code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
namespace CirrusSearch\Search;
use CirrusSearch\Search\Fetch\FetchPhaseConfigBuilder;
use Elastica\ResultSet as ElasticaResultSet;
/**
* Result type for a full text search.
*/
final class FullTextResultsType extends BaseResultsType {
/**
* @var bool
*/
private $searchContainedSyntax;
/**
* @var FetchPhaseConfigBuilder
*/
private $fetchPhaseBuilder;
/**
* @var TitleHelper
*/
private $titleHelper;
/**
* @var string[] list of extra fields to extract
*/
private $extraFieldsToExtract;
/**
* @param FetchPhaseConfigBuilder $fetchPhaseBuilder
* @param bool $searchContainedSyntax
* @param TitleHelper $titleHelper
* @param string[] $extraFieldsToExtract
*/
public function __construct(
FetchPhaseConfigBuilder $fetchPhaseBuilder,
$searchContainedSyntax,
TitleHelper $titleHelper,
array $extraFieldsToExtract = []
) {
$this->fetchPhaseBuilder = $fetchPhaseBuilder;
$this->searchContainedSyntax = $searchContainedSyntax;
$this->titleHelper = $titleHelper;
$this->extraFieldsToExtract = $extraFieldsToExtract;
}
/**
* @return false|string|array corresponding to Elasticsearch source filtering syntax
*/
public function getSourceFiltering() {
return array_merge(
parent::getSourceFiltering(),
[ 'redirect.*', 'timestamp', 'text_bytes' ],
$this->extraFieldsToExtract
);
}
/**
* @return array
*/
public function getStoredFields() {
return [ "text.word_count" ]; // word_count is only a stored field and isn't part of the source.
}
/**
* Setup highlighting.
* Don't fragment title because it is small.
* Get just one fragment from the text because that is all we will display.
* Get one fragment from redirect title and heading each or else they
* won't be sorted by score.
*
* @param array $extraHighlightFields (deprecated and ignored)
* @return array|null of highlighting configuration
*/
public function getHighlightingConfiguration( array $extraHighlightFields = [] ) {
$this->fetchPhaseBuilder->configureDefaultFullTextFields();
return $this->fetchPhaseBuilder->buildHLConfig();
}
/**
* @param ElasticaResultSet $result
* @return CirrusSearchResultSet
*/
public function transformElasticsearchResult( ElasticaResultSet $result ) {
// Should we make this a concrete class?
return new class( $this->titleHelper, $this->fetchPhaseBuilder, $result, $this->searchContainedSyntax, $this->extraFieldsToExtract )
extends BaseCirrusSearchResultSet {
/** @var TitleHelper */
private $titleHelper;
/** @var FullTextCirrusSearchResultBuilder */
private $resultBuilder;
/** @var ElasticaResultSet */
private $results;
/** @var bool */
private $searchContainedSyntax;
public function __construct(
TitleHelper $titleHelper,
FetchPhaseConfigBuilder $builder,
ElasticaResultSet $results,
$searchContainedSyntax,
array $extraFieldsToExtract
) {
$this->titleHelper = $titleHelper;
$this->resultBuilder = new FullTextCirrusSearchResultBuilder( $this->titleHelper,
$builder->getHLFieldsPerTargetAndPriority(), $extraFieldsToExtract );
$this->results = $results;
$this->searchContainedSyntax = $searchContainedSyntax;
}
/**
* @inheritDoc
*/
protected function transformOneResult( \Elastica\Result $result ) {
return $this->resultBuilder->build( $result );
}
/**
* @return \Elastica\ResultSet|null
*/
public function getElasticaResultSet() {
return $this->results;
}
/**
* @inheritDoc
*/
public function searchContainedSyntax() {
return $this->searchContainedSyntax;
}
protected function getTitleHelper(): TitleHelper {
return $this->titleHelper;
}
};
}
/**
* @param FetchPhaseConfigBuilder $builder
* @return FullTextResultsType
*/
public function withFetchPhaseBuilder( FetchPhaseConfigBuilder $builder ): FullTextResultsType {
return new self( $builder, $this->searchContainedSyntax, $this->titleHelper );
}
/**
* @return CirrusSearchResultSet
*/
public function createEmptyResult() {
return BaseCirrusSearchResultSet::emptyResultSet();
}
}
| wikimedia/mediawiki-extensions-CirrusSearch | includes/Search/FullTextResultsType.php | PHP | gpl-2.0 | 4,137 |
namespace L2dotNET.GameService.network.l2send
{
class AutoAttackStop : GameServerNetworkPacket
{
private int sId;
public AutoAttackStop(int sId)
{
this.sId = sId;
}
protected internal override void write()
{
writeC(0x2c);
writeD(sId);
}
}
}
| domis045/L2dotNET | src/L2dotNET.Game/network/serverpackets/AutoAttackStop.cs | C# | gpl-2.0 | 350 |
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest20813")
public class BenchmarkTest20813 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request );
String param = scr.getTheValue("foo");
String bar = doSomething(param);
String a1 = "";
String a2 = "";
String osName = System.getProperty("os.name");
if (osName.indexOf("Windows") != -1) {
a1 = "cmd.exe";
a2 = "/c";
} else {
a1 = "sh";
a2 = "-c";
}
String[] args = {a1, a2, "echo", bar};
String[] argsEnv = { "foo=bar" };
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec(args, argsEnv);
org.owasp.benchmark.helpers.Utils.printOSCommandResults(p);
} catch (IOException e) {
System.out.println("Problem executing cmdi - TestCase");
throw new ServletException(e);
}
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
java.util.List<String> valuesList = new java.util.ArrayList<String>( );
valuesList.add("safe");
valuesList.add( param );
valuesList.add( "moresafe" );
valuesList.remove(0); // remove the 1st safe value
String bar = valuesList.get(0); // get the param value
return bar;
}
}
| iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest20813.java | Java | gpl-2.0 | 2,749 |
/**
* Created by herve on 10/11/15.
*/
function ajax_exercises_by_muscles(muscle) {
$("#loader").show();
$("#loader-message").show();
$.ajax({
url : "/exercises/muscles/ajax-exercises-by-muscles/", // the endpoint
type : "POST", // http method
data : { muscle : muscle }, // data sent with the post request
// handle a successful response
success : function(json) {
json = JSON.stringify(json);
json = JSON.parse(json);
$("#loader").hide();
$("#loader-message").hide();
$("#exercises-count").text(json.count);
$("#exercises-count").attr('href', json.link);
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
};
| 4383/street-workout-database | sport/web/static/js/ajax.js | JavaScript | gpl-2.0 | 926 |
require 'rails_helper'
RSpec.describe Category, type: :model do
let(:category) { create(:category) }
it 'is valid factory for :category' do
expect(category).to be_valid
end
it 'is check empty category name' do
category = build(:category, name: nil)
category.valid?
expect(category.errors[:name]).to include("can't be blank")
end
it 'is check category name limit with 255 chars' do
category = build(:category, name: 's' * 256)
category.valid?
expect(category.errors[:name]).to include('is too long (maximum is 255 characters)')
end
it 'is check empty category uri' do
category = build(:category, uri: nil)
category.valid?
expect(category.errors[:uri]).to include("can't be blank")
end
it 'is check category uri limit with 64 chars' do
category = build(:category, uri: 's' * 65)
category.valid?
expect(category.errors[:uri]).to include('is too long (maximum is 64 characters)')
end
it 'is check uniq values of category uri' do
create(:category, uri: 'cars')
category = build(:category, uri: 'cars')
category.valid?
expect(category.errors[:uri]).to include('has already been taken')
end
it 'is check subcategory should be destroyed when category deleted' do
parent_category = create(:category)
create(:subcategory, category: parent_category)
expect { parent_category.destroy }.to change(Subcategory, :count).by(-1)
end
end
| ufacode/wenternet | spec/models/category_spec.rb | Ruby | gpl-2.0 | 1,438 |
<form role="search" method="get" id="searchform" class="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<div>
<input type="submit" id="searchsubmit" value="<?php echo esc_attr_x( 'Search', 'submit button' ); ?>" />
<label class="screen-reader-text" for="s"><?php _x( 'Search for:', 'label' ); ?></label>
<input id="autocomplete" title="type "a"" type="text" value="<?php echo get_search_query(); ?>" name="s" id="s" placeholder=" Help you find anything?" />
</div>
</form> | Kitzo/door-fellowship | wp-content/themes/chris-base-theme/searchform.php | PHP | gpl-2.0 | 506 |
require 'vx/container_connector'
require 'vx/instrumentation'
require 'active_support/notifications'
$stdout.puts ' --> initializing Vx::ContainerConnector'
Vx::ContainerConnector.instrumenter = ActiveSupport::Notifications
| pacoguzman/vx-worker | lib/vx/worker/initializers/containers.rb | Ruby | gpl-2.0 | 226 |
import React from "react";
import { connect } from "react-redux";
import { TimeMode, AppState, Dispatch } from "../../types";
import { getTimeObj } from "../../utils";
import * as Actions from "../../actionCreators";
import * as Selectors from "../../selectors";
import { TIME_MODE } from "../../constants";
interface StateProps {
timeElapsed: number;
duration: number;
timeMode: TimeMode;
}
interface DispatchProps {
toggleTimeMode(): void;
}
const Time = ({
timeElapsed,
duration,
timeMode,
toggleTimeMode,
}: StateProps & DispatchProps) => {
const seconds =
timeMode === TIME_MODE.ELAPSED ? timeElapsed : duration - timeElapsed;
const timeObj = getTimeObj(seconds);
return (
<div id="time" onClick={toggleTimeMode} className="countdown">
{timeMode === TIME_MODE.REMAINING && <div id="minus-sign" />}
<div
id="minute-first-digit"
className={`digit digit-${timeObj.minutesFirstDigit}`}
/>
<div
id="minute-second-digit"
className={`digit digit-${timeObj.minutesSecondDigit}`}
/>
<div
id="second-first-digit"
className={`digit digit-${timeObj.secondsFirstDigit}`}
/>
<div
id="second-second-digit"
className={`digit digit-${timeObj.secondsSecondDigit}`}
/>
</div>
);
};
const mapStateToProps = (state: AppState): StateProps => {
const timeElapsed = Selectors.getTimeElapsed(state);
const duration = Selectors.getDuration(state);
const { timeMode } = state.media;
return { timeElapsed, duration: duration || 0, timeMode };
};
const mapDispatchToProps = (dispatch: Dispatch): DispatchProps => ({
toggleTimeMode: () => dispatch(Actions.toggleTimeMode()),
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Time);
| mazhar266/mazhar266.github.io | webamp/js/components/MainWindow/Time.tsx | TypeScript | gpl-2.0 | 1,798 |
<?php
/* This file is part of a copyrighted work; it is distributed with NO WARRANTY.
* See the file COPYRIGHT.html for more details.
*/
require_once("../shared/common.php");
$tab = "admin";
$nav = "materials";
$restrictInDemo = true;
require_once("../shared/logincheck.php");
require_once("../classes/DmQuery.php");
/*
require_once("../classes/CheckoutPrivsQuery.php"); //add jalg de la version openbiblio 7.1
require_once("../classes/MaterialFieldQuery.php"); //add jalg de la version openbiblio 7.1
*/
require_once("../functions/errorFuncs.php");
require_once("../classes/Localize.php");
$loc = new Localize(OBIB_LOCALE,$tab);
#****************************************************************************
#* Checking for query string. Go back to material type list if none found.
#****************************************************************************
if (!isset($_GET["code"])){
header("Location: ../admin/materials_list.php");
exit();
}
$code = $_GET["code"];
$description = $_GET["desc"];
#**************************************************************************
#* Delete row
#**************************************************************************
$dmQ = new DmQuery();
$dmQ->connect();
$dmQ->delete("material_type_dm",$code);
$dmQ->close();
/*
//add jalg de la version openbiblio 7.1
$checkoutPrivsQ = new CheckoutPrivsQuery();
$checkoutPrivsQ->connect();
$checkoutPrivsQ->delete_by_material_cd($code);
$checkoutPrivsQ->close();
$materialFieldQ = new MaterialFieldQuery();
$materialFieldQ->connect();
$materialFieldQ->deleteCustomField($code);
$materialFieldQ->close();
//add jalg de la version openbiblio 7.1
*/
#**************************************************************************
#* Show success page
#**************************************************************************
require_once("../shared/header.php");
?>
<?php echo $loc->getText("admin_materials_delMaterialType"); ?>
<?php echo H($description);?><?php echo $loc->getText("admin_materials_delMaterialdeleted"); ?>
<br><br>
<a href="../admin/materials_list.php"><?php echo $loc->getText("admin_materials_Return"); ?></a>
<?php require_once("../shared/footer.php");
| uniedpa/biblioteca | admin/materials_del.php | PHP | gpl-2.0 | 2,251 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Random mutator based on C. Miller 'algorithm' for Nightmare Fuzzing Project.
Created on Sun May 12 10:57:06 2013
@author: joxean
"""
import sys
import math
import random
#-----------------------------------------------------------------------
class CCMillerMutator(object):
def __init__(self, buf, skip=5):
self.buf = buf
self.skip = 5
def mutate(self):
buf = self.buf
fuzz_factor = len(buf)/500.
if fuzz_factor < 1:
fuzz_factor = 1
numwrites = random.randrange(math.ceil((float(len(buf)) / fuzz_factor)))+1
#print "Total of %d" % numwrites
diff = []
for j in range(numwrites):
rbyte = random.randrange(256)
rn = random.randrange(len(buf))
rtotal = random.randint(0, 16)
c = "%c" % rbyte
buf = buf[:rn-1] + c*rtotal + buf[rn+rtotal:]
diff.append("%d, %d" % (rn, rtotal))
return buf, diff
#-----------------------------------------------------------------------
def main(template, output):
mut = CCMillerMutator(open(template, "rb").read())
buf, diff = mut.mutate()
f = open(output, "wb")
f.write(buf)
f.close()
diff.sort()
f = open(output + ".diff", "wb")
f.write("# Original file created by 'CMiller Mutator Rep' was %s\n" % template)
f.write("\n".join(diff))
f.close()
#-----------------------------------------------------------------------
def usage():
print "Usage:", sys.argv[0], "<template> <output filename>"
if __name__ == "__main__":
if len(sys.argv) != 3:
usage()
else:
main(sys.argv[1], sys.argv[2])
| joxeankoret/nightmare | mutators/cmiller_mutator_rep.py | Python | gpl-2.0 | 1,588 |
/* class for generating random sample data*/
public class ValueGenerator {
private static String[] values = {
"elephant","giraffe","monkey","cheetah","dog","cat","tiger",
"mouse","tortoise","shark","whale","salmon","deer","wolf",
"grizzlybear","fox","snake","worm","fly","bee","hornet"
};
public static String[] getNewStringArray(){
int size = (int)(Math.random()*20 +1);
String[] arr = new String[size];
for(int i=0; i<size;++i){
arr[i] = getNewString();
}
return arr;
}
public static String getNewString(){
int index = (int)(Math.random()*values.length);
return values[index];
}
public static int getNewInt(){
return (int)(Math.random()*100);
}
public static Integer[] getNewIntArray(){
int size = (int)(Math.random()*20 +1);
Integer[] arr = new Integer[size];
for(int i=0; i<size;++i){
arr[i] = getNewInt();
}
return arr;
}
public static double getNewDouble(){
//round double to ##.###
return Math.floor(Math.random()*100000 ) / 1000;
}
public static Double[] getNewDoubleArray(){
int size = (int)(Math.random()*20 +1);
Double[] arr = new Double[size];
for(int i=0; i<size;++i){
arr[i] = getNewDouble();
}
return arr;
}
}
| DB-SE/isp2014.marcus.kamieth | Algorithms_DataStructures_RTVar/src/ValueGenerator.java | Java | gpl-2.0 | 1,197 |
//=============================================================================
// YHTTPD
// Helper
//=============================================================================
// c
#include <cstdio> // printf prototype.
#include <cstdlib> // calloc and free prototypes.
#include <cstring> // str* and memset prototypes.
#include <cstdarg>
#include <sstream>
#include <iomanip>
#include <unistd.h>
// yhttpd
#include <yconfig.h>
#include <tuxboxapi/controlapi.h>
#include "ytypes_globals.h"
#include "helper.h"
#include "ylogging.h"
//=============================================================================
// Integers
//=============================================================================
//-------------------------------------------------------------------------
// Check and set integer inside boundaries (min, max)
//-------------------------------------------------------------------------
int minmax(int value, int min, int max) {
if (value < min)
return min;
if (value > max)
return max;
return value;
}
//=============================================================================
// Date & Time
//=============================================================================
//-------------------------------------------------------------------------
// Check and set Date/Time (tm*) inside boundaries
//-------------------------------------------------------------------------
void correctTime(struct tm *zt) {
zt->tm_year = minmax(zt->tm_year, 0, 129);
zt->tm_mon = minmax(zt->tm_mon, 0, 11);
zt->tm_mday = minmax(zt->tm_mday, 1, 31); //-> eine etwas laxe pruefung, aber mktime biegt das wieder grade
zt->tm_hour = minmax(zt->tm_hour, 0, 23);
zt->tm_min = minmax(zt->tm_min, 0, 59);
zt->tm_sec = minmax(zt->tm_sec, 0, 59);
zt->tm_isdst = -1;
}
//=============================================================================
// Strings
//=============================================================================
//-------------------------------------------------------------------------
// Integer to Hexadecimal-String
//-------------------------------------------------------------------------
std::string itoh(unsigned int conv) {
return string_printf("0x%06x", conv);
}
//-------------------------------------------------------------------------
// Integer to String
//-------------------------------------------------------------------------
std::string itoa(unsigned int conv) {
return string_printf("%u", conv);
}
//-------------------------------------------------------------------------
// convert timer_t to "<hour>:<minutes>" String
//-------------------------------------------------------------------------
std::string timeString(time_t time) {
char tmp[7] = { '\0' };
struct tm *tm = localtime(&time);
if (strftime(tmp, 6, "%H:%M", tm))
return std::string(tmp);
else
return std::string("??:??");
}
//-------------------------------------------------------------------------
// Printf and return formatet String. Buffer-save!
// max length up to bufferlen -> then snip
//-------------------------------------------------------------------------
std::string string_printf(const char *fmt, ...) {
va_list arglist;
const int bufferlen = 4*1024;
char buffer[bufferlen] = {0};
va_start(arglist, fmt);
vsnprintf(buffer, bufferlen, fmt, arglist);
va_end(arglist);
return std::string(buffer);
}
//-------------------------------------------------------------------------
// ySplitString: spit string "str" in two strings "left" and "right" at
// one of the chars in "delimiter" returns true if delimiter found
//-------------------------------------------------------------------------
bool ySplitString(std::string str, std::string delimiter, std::string& left,
std::string& right) {
std::string::size_type pos;
if ((pos = str.find_first_of(delimiter)) != std::string::npos) {
left = str.substr(0, pos);
right = str.substr(pos + 1, str.length() - (pos + 1));
} else {
left = str; //default if not found
right = "";
}
return (pos != std::string::npos);
}
//-------------------------------------------------------------------------
// ySplitString: spit string "str" in two strings "left" and "right" at
// one of the chars in "delimiter" returns true if delimiter found
//-------------------------------------------------------------------------
bool ySplitStringExact(std::string str, std::string delimiter,
std::string& left, std::string& right) {
std::string::size_type pos;
if ((pos = str.find(delimiter)) != std::string::npos) {
left = str.substr(0, pos);
right = str.substr(pos + delimiter.length(), str.length() - (pos
+ delimiter.length()));
} else {
left = str; //default if not found
right = "";
}
return (pos != std::string::npos);
}
//-------------------------------------------------------------------------
// ySplitStringRight: spit string "str" in two strings "left" and "right" at
// one of the chars in "delimiter" returns true if delimiter found
//-------------------------------------------------------------------------
bool ySplitStringLast(std::string str, std::string delimiter,
std::string& left, std::string& right) {
std::string::size_type pos;
if ((pos = str.find_last_of(delimiter)) != std::string::npos) {
left = str.substr(0, pos);
right = str.substr(pos + 1, str.length() - (pos + 1));
} else {
left = str; //default if not found
right = "";
}
return (pos != std::string::npos);
}
//-------------------------------------------------------------------------
// ySplitStringVector: spit string "str" and build vector of strings
//-------------------------------------------------------------------------
CStringArray ySplitStringVector(std::string str, std::string delimiter) {
std::string left, right, rest;
bool found;
CStringArray split;
rest = str;
do {
found = ySplitString(rest, delimiter, left, right);
split.push_back(left);
rest = right;
} while (found);
return split;
}
//-------------------------------------------------------------------------
// trim whitespaces
//-------------------------------------------------------------------------
std::string trim(std::string const& source, char const* delims) {
std::string result(source);
std::string::size_type index = result.find_last_not_of(delims);
if (index != std::string::npos)
result.erase(++index);
index = result.find_first_not_of(delims);
if (index != std::string::npos)
result.erase(0, index);
else
result.erase();
return result;
}
//-------------------------------------------------------------------------
// replace all occurrences find_what
//-------------------------------------------------------------------------
void replace(std::string &str, const std::string &find_what,
const std::string &replace_with) {
std::string::size_type pos = 0;
while ((pos = str.find(find_what, pos)) != std::string::npos) {
str.erase(pos, find_what.length());
str.insert(pos, replace_with);
pos += replace_with.length();
}
}
//-------------------------------------------------------------------------
// equal-function for case insensitive compare
//-------------------------------------------------------------------------
bool nocase_compare(char c1, char c2) {
return toupper(c1) == toupper(c2);
}
//-----------------------------------------------------------------------------
// Decode URLEncoded std::string
//-----------------------------------------------------------------------------
std::string decodeString(std::string encodedString) {
const char *string = encodedString.c_str();
unsigned int count = 0;
char hex[3] = { '\0' };
unsigned long iStr;
std::string result = "";
count = 0;
while (count < encodedString.length()) /* use the null character as a loop terminator */
{
if (string[count] == '%' && count + 2 < encodedString.length()) {
hex[0] = string[count + 1];
hex[1] = string[count + 2];
hex[2] = '\0';
iStr = strtoul(hex, NULL, 16); /* convert to Hex char */
result += (char) iStr;
count += 3;
} else if (string[count] == '+') {
result += ' ';
count++;
} else {
result += string[count];
count++;
}
} /* end of while loop */
return result;
}
//-----------------------------------------------------------------------------
// HTMLEncode std::string
//-----------------------------------------------------------------------------
std::string encodeString(const std::string &decodedString)
{
std::string result="";
char buf[10]= {0};
for (unsigned int i=0; i<decodedString.length(); i++)
{
const char one_char = decodedString[i];
if (isalnum(one_char)) {
result += one_char;
} else {
snprintf(buf,sizeof(buf), "&#%d;",(unsigned char) one_char);
result +=buf;
}
}
result+='\0';
result.reserve();
return result;
}
//-----------------------------------------------------------------------------
// returns string in lower case
//-----------------------------------------------------------------------------
std::string string_tolower(std::string str) {
for (unsigned int i = 0; i < str.length(); i++)
str[i] = tolower(str[i]);
return str;
}
//-----------------------------------------------------------------------------
// write string to a file
//-----------------------------------------------------------------------------
bool write_to_file(std::string filename, std::string content, bool append) {
FILE *fd = NULL;
if ((fd = fopen(filename.c_str(), append ? "a" : "w")) != NULL) // open file
{
fwrite(content.c_str(), content.length(), 1, fd);
fflush(fd); // flush and close file
fclose(fd);
return true;
} else
return false;
}
//-----------------------------------------------------------------------------
// JSON: create pair string "<_key>". "<_value>"
// Handle wrong quotes
//-----------------------------------------------------------------------------
std::string json_out_quote_convert(std::string _str) {
replace(_str, "\"", "\'");
return _str;
}
//-----------------------------------------------------------------------------
// JSON: create pair string "<_key>". "<_value>"
// Handle wrong quotes
//-----------------------------------------------------------------------------
std::string json_out_pair(std::string _key, std::string _value) {
replace(_key, "\"", "");
replace(_value, "\"", "\'");
return "\"" + _key + "\": " + "\"" + _value + "\"";
}
//-----------------------------------------------------------------------------
// JSON: create success return string
//-----------------------------------------------------------------------------
std::string json_out_success(std::string _result) {
return "{\"success\": \"true\", \"data\":{" + _result + "}}";
}
//-----------------------------------------------------------------------------
// JSON: create success return string
//-----------------------------------------------------------------------------
std::string json_out_error(std::string _error) {
return "{\"success\": \"false\", \"error\":{\"text\": \"" + _error + "\"}}";
}
//-----------------------------------------------------------------------------
// JSON: convert string to JSON-String
//-----------------------------------------------------------------------------
std::string json_convert_string(std::string value)
{
std::string result;
for (size_t i = 0; i < value.length(); i++)
{
unsigned char c = unsigned(value[i]);
switch(c)
{
case '\"':
result += "\\\"";
break;
case '\\':
result += "\\\\";
break;
case '\b':
result += "\\b";
break;
case '\f':
result += "\\f";
break;
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
default:
if ( isControlCharacter( c ) )
{
std::ostringstream oss;
oss << "\\u" << std::hex << std::uppercase << std::setfill('0') << std::setw(4) << static_cast<int>(c);
result += oss.str();
}
else
{
result += c;
}
break;
}
}
return result;
}
#if 0
std::string json_convert_string(std::string s) {
std::stringstream ss;
for (size_t i = 0; i < s.length(); ) {
unsigned char ch = unsigned(s[i]);
if(ch == 0x0d){
ss << "\\u000d";
i++;
continue;
}
if(ch == 0x0a){
ss << "\\u000a";
i++;
continue;
}
if(ch < '\x20' || ch == '\\' || ch == '"' || ch >= '\x80') {
unsigned long unicode = 0;
size_t todo = 0;
if (ch <= 0xBF) {
}
else if (ch <= 0xDF) {
unicode = ch & 0x1F;
todo = 1;
}
else if (ch <= 0xEF) {
unicode = ch & 0x0F;
todo = 2;
}
else if (ch <= 0xF7) {
unicode = ch & 0x07;
todo = 3;
}
for (size_t j = 0; j < todo; ++j){
++i;
unicode <<= 6;
unicode += unsigned(s[i]) & 0x3F;
}
if (unicode <= 0xFFFF)
{
ss << "\\u" << std::setfill('0') << std::setw(4) << std::hex << unicode;
}else
{
unicode -= 0x10000;
ss << "\\u" << std::setfill('0') << std::setw(4) << std::hex << ((unicode >> 10) + 0xD800);
ss << "\\u" << std::setfill('0') << std::setw(4) << std::hex << ((unicode & 0x3FF) + 0xDC00);
}
}
else {
ss << s[i];
}
++i;
}
return ss.str();
}
#endif // 0
std::string yExecuteScript(std::string cmd) {
#if HAVE_SPARK_HARDWARE || HAVE_DUCKBOX_HARDWARE
const char *fbshot = "Y_Tools fbshot fb /";
int len = strlen(fbshot);
if (!strncmp(cmd.c_str(), fbshot, len))
return CFrameBuffer::getInstance()->OSDShot(cmd.substr(len - 1)) ? "" : "error";
#endif
std::string script, para, result;
bool found = false;
//aprintf("%s: %s\n", __func__, cmd.c_str());
// split script and parameters
int pos;
if ((pos = cmd.find_first_of(" ")) > 0) {
script = cmd.substr(0, pos);
para = cmd.substr(pos + 1, cmd.length() - (pos + 1)); // snip
} else
script = cmd;
// get file
std::string fullfilename;
script += ".sh"; //add script extention
char cwd[255];
getcwd(cwd, 254);
for (unsigned int i = 0; i < CControlAPI::PLUGIN_DIR_COUNT && !found; i++) {
fullfilename = CControlAPI::PLUGIN_DIRS[i] + "/" + script;
FILE *test = fopen(fullfilename.c_str(), "r"); // use fopen: popen does not work
if (test != NULL) {
fclose(test);
chdir(CControlAPI::PLUGIN_DIRS[i].c_str());
FILE *f = popen((fullfilename + " " + para).c_str(), "r"); //execute
if (f != NULL) {
found = true;
char output[1024];
while (fgets(output, 1024, f)) // get script output
result += output;
pclose(f);
}
}
}
chdir(cwd);
if (!found) {
printf("%s: script %s not found in:\n", __func__, script.c_str());
for (unsigned int i = 0; i < CControlAPI::PLUGIN_DIR_COUNT; i++) {
printf("\t%s\n", CControlAPI::PLUGIN_DIRS[i].c_str());
}
result = "error";
}
return result;
}
| j00zek/j00zeks-neutrino-mp-cst-next | src/nhttpd/yhttpd_core/helper.cpp | C++ | gpl-2.0 | 14,657 |
<?php
/**
* @version SEBLOD 3.x Core ~ $Id: _debug.php sebastienheraud $
* @package SEBLOD (App Builder & CCK) // SEBLOD nano (Form Builder)
* @url http://www.seblod.com
* @editor Octopoos - www.octopoos.com
* @copyright Copyright (C) 2009 - 2016 SEBLOD. All Rights Reserved.
* @license GNU General Public License version 2 or later; see _LICENSE.php
**/
defined( '_JEXEC' ) or die;
// Init
jimport( 'joomla.error.profiler' );
$db = JFactory::getDbo();
$config = JCckDev::init();
$cck = JCckDev::preload( array( '' ) );
$doc = JFactory::getDocument();
$profiler = new JProfiler();
// -- DEBUG:START -- //
$js = '';
$js2 = '';
$js_script = '';
$js_script = JURI::root( true ).$js_script;
echo '<br /><div style="color: #999999; font-size: 10px; font-weight: bold;">-------- Debug --------<br />';
// -------- -------- -------- -------- -------- -------- -------- -------- //
$n = 10000;
$profiler = new JProfiler();
for ( $i = 0; $i < $n; $i++ ) {
//
}
$profiler_res = $profiler->mark( 'afterDebug' );
// -------- -------- -------- -------- -------- -------- -------- -------- //
if ( $js_script ) {
$doc->addScript( $js_script );
}
if ( $js || $js2 ) {
echo '<input text id="toto" name="toto" value="" />'.'<input text id="toto2" name="toto2" value="" />';
$doc->addScriptDeclaration( 'jQuery(document).ready(function($) {' . $js . '});' . $js2 );
}
echo '<br />'. $profiler_res . '<br />-------- Debug --------<br /></div>';
// -- DEBUG:END -- //
/*
$log = JLog::addLogger( array( 'format'=>'{DATE}\t{TIME}\t{LEVEL}\t{CODE}\t{MESSAGE}', 'text_file'=>'com_cck.php' ) );
*/ | klas/SEBLOD | administrator/components/com_cck/helpers/scripts/_debug.php | PHP | gpl-2.0 | 1,658 |
/*
* Copyright (c) 2021, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.hosted;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.graalvm.nativeimage.hosted.Feature;
import org.graalvm.nativeimage.impl.ConfigurationCondition;
import com.oracle.svm.core.TypeResult;
public abstract class ConditionalConfigurationRegistry {
private final Map<String, List<Runnable>> pendingReachabilityHandlers = new ConcurrentHashMap<>();
protected void registerConditionalConfiguration(ConfigurationCondition condition, Runnable runnable) {
if (ConfigurationCondition.alwaysTrue().equals(condition)) {
/* analysis optimization to include new types as early as possible */
runnable.run();
} else {
List<Runnable> handlers = pendingReachabilityHandlers.computeIfAbsent(condition.getTypeName(), key -> new ArrayList<>());
handlers.add(runnable);
}
}
public void flushConditionalConfiguration(Feature.BeforeAnalysisAccess b) {
for (Map.Entry<String, List<Runnable>> reachabilityEntry : pendingReachabilityHandlers.entrySet()) {
TypeResult<Class<?>> typeResult = ((FeatureImpl.BeforeAnalysisAccessImpl) b).getImageClassLoader().findClass(reachabilityEntry.getKey());
b.registerReachabilityHandler(access -> reachabilityEntry.getValue().forEach(Runnable::run), typeResult.get());
}
pendingReachabilityHandlers.clear();
}
public void flushConditionalConfiguration(Feature.DuringAnalysisAccess b) {
if (!pendingReachabilityHandlers.isEmpty()) {
b.requireAnalysisIteration();
}
flushConditionalConfiguration((Feature.BeforeAnalysisAccess) b);
}
}
| smarr/Truffle | substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/ConditionalConfigurationRegistry.java | Java | gpl-2.0 | 2,958 |
<?php
/**
* @package Blue Hat CDN
* @version 2.9.4
* @copyright (C) Copyright 2006-2014 Blue Hat Network, BlueHatNetwork.com. All rights reserved.
* @license GNU/GPL http://www.gnu.org/licenses/gpl-3.0.txt
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/>.
*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
class BlueHatNetworkCommon
{
private static $_getWebsiteOwnerEmailAddress;
public static function isValidEmailAddress($emailAddress)
{
if(!class_exists('BlueHatNetworkFactory')) require BHN_PLUGIN_ADMIN_ROOT.DIRECTORY_SEPARATOR.'lib'.DIRECTORY_SEPARATOR.'factory.php';
if(BlueHatNetworkFactory::isWordPress())
{
return is_email($emailAddress);
}
elseif(BlueHatNetworkFactory::isJoomla())
{
jimport('joomla.mail.helper');
return JMailHelper::isEmailAddress($emailAddress);
}
}
public static function getWebsiteOwnerEmailAddress()
{
if(!empty(self::$_getWebsiteOwnerEmailAddress)) return self::$_getWebsiteOwnerEmailAddress;
if(!class_exists('BlueHatNetworkFactory')) require BHN_PLUGIN_ADMIN_ROOT.DIRECTORY_SEPARATOR.'lib'.DIRECTORY_SEPARATOR.'factory.php';
if(BlueHatNetworkFactory::isWordPress())
{
self::$_getWebsiteOwnerEmailAddress = get_bloginfo('admin_email');
}
elseif(BlueHatNetworkFactory::isJoomla())
{
$config =& JFactory::getConfig();
if(method_exists($config, 'getValue'))
{
self::$_getWebsiteOwnerEmailAddress = $config->getValue('config.mailfrom');
}
else
{
self::$_getWebsiteOwnerEmailAddress = $config->get('mailfrom');
}
}
return self::$_getWebsiteOwnerEmailAddress;
}
public static function mkdir($dirPath)
{
if(!class_exists('BlueHatNetworkFactory')) require BHN_PLUGIN_ADMIN_ROOT.DIRECTORY_SEPARATOR.'lib'.DIRECTORY_SEPARATOR.'factory.php';
if(BlueHatNetworkFactory::isWordPress())
{
return wp_mkdir_p($dirPath);
}
elseif(BlueHatNetworkFactory::isJoomla())
{
jimport('joomla.filesystem.folder');
return JFolder::create($dirPath);
}
}
public static function humanReadableFilesize($size)
{
$mod = 1024;
$units = explode(' ', 'Bytes KB MB GB TB PB');
for($i = 0; $size > $mod; $i++)
{
$size /= $mod;
}
return round($size, 2).' '.$units[$i];
}
public static function getFileExt($file)
{
return substr($file, strrpos($file, '.')+1);
}
public static function isWindows()
{
if(strncasecmp(PHP_OS, 'WIN', 3) == 0)
{
return true;
}
else
{
return false;
}
}
public static function extractGzipFile($gzipFilePath)
{
if(!is_file($gzipFilePath)) return false;
// Raising this value may increase performance
$buffer_size = 4096; // read 4kb at a time
$out_file_name = preg_replace('@\.gz$@i', '', $gzipFilePath, 1);
// Open our files (in binary mode)
$file = gzopen($gzipFilePath, 'rb');
$out_file = fopen($out_file_name, 'wb');
// Keep repeating until the end of the input file
while(!gzeof($file))
{
// Read buffer-size bytes
// Both fwrite and gzread and binary-safe
fwrite($out_file, gzread($file, $buffer_size));
}
// Files are done, close files
fclose($out_file);
gzclose($file);
}
} | dialoquad/dialoquad | wp-content/plugins/blue-hat-cdn/lib/common.php | PHP | gpl-2.0 | 3,884 |
<?php
// Checking if visitor is connected
$connected = false;
$is_admin = false;
if ( !empty($_SESSION['member'])) {
$connected = true;
$stmt = $PDO->prepare('SELECT members_id FROM admins WHERE id=1');
$stmt->execute();
$rslt = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$members_id = explode(',', $rslt['members_id']);
if ( in_array($_SESSION['member']['id'], $members_id) )
$is_admin = true; // Visitor is an admin
}
// Global settings
error_reporting(0);
// Define path
define( 'PATH', '/TSBlog/' ); // Default : "/"
// Gettings configs
$stmt = $PDO->prepare('SELECT * FROM config WHERE id=1');
$stmt->execute();
$rslt = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
define( 'MAX_SIZE_PICTURE', $rslt['maxsize'] ); // Limit of file's size 4 Mo
define( 'SITE_NAME', $rslt['sitename'] ); // Site name
define( 'PHONE_NUMBER', $rslt['phonenumber'] ); // Your phone number
define ('EMAIL_ADRESS', $rslt['email'] ); // Email adress
define('ABOUT', $rslt['aboutme'] ); // About me
// List of months
$mois = array('01'=>$lang15,
'02'=>$lang16,
'03'=>$lang17,
'04'=>$lang18,
'05'=>$lang19,
'06'=>$lang20,
'07'=>$lang21,
'08'=>$lang22,
'09'=>$lang23,
'10'=>$lang24,
'11'=>$lang25,
'12'=>$lang26);
?> | Tunisia-Sat/TSBlog | config/config.php | PHP | gpl-2.0 | 1,343 |
using System;
using System.Diagnostics;
using System.Resources;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using HTTPServer.Resources;
namespace HTTPServer
{
public partial class App : Application
{
/// <summary>
///提供对电话应用程序的根框架的轻松访问。
/// </summary>
/// <returns>电话应用程序的根框架。</returns>
public static PhoneApplicationFrame RootFrame { get; private set; }
/// <summary>
/// Application 对象的构造函数。
/// </summary>
public App()
{
// 未捕获的异常的全局处理程序。
UnhandledException += Application_UnhandledException;
// 标准 XAML 初始化
InitializeComponent();
// 特定于电话的初始化
InitializePhoneApplication();
// 语言显示初始化
InitializeLanguage();
// 调试时显示图形分析信息。
if (Debugger.IsAttached)
{
// 显示当前帧速率计数器。
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// 显示在每个帧中重绘的应用程序区域。
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// 启用非生产分析可视化模式,
// 该模式显示递交给 GPU 的包含彩色重叠区的页面区域。
//Application.Current.Host.Settings.EnableCacheVisualization = true;
// 通过禁用以下对象阻止在调试过程中关闭屏幕
// 应用程序的空闲检测。
// 注意: 仅在调试模式下使用此设置。禁用用户空闲检测的应用程序在用户不使用电话时将继续运行
// 并且消耗电池电量。
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
}
// 应用程序启动(例如,从“开始”菜单启动)时执行的代码
// 此代码在重新激活应用程序时不执行
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
// 激活应用程序(置于前台)时执行的代码
// 此代码在首次启动应用程序时不执行
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}
// 停用应用程序(发送到后台)时执行的代码
// 此代码在应用程序关闭时不执行
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// 应用程序关闭(例如,用户点击“后退”)时执行的代码
// 此代码在停用应用程序时不执行
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// 导航失败时执行的代码
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (Debugger.IsAttached)
{
// 导航已失败;强行进入调试器
Debugger.Break();
}
}
// 出现未处理的异常时执行的代码
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
// 出现未处理的异常;强行进入调试器
Debugger.Break();
}
}
#region 电话应用程序初始化
// 避免双重初始化
private bool phoneApplicationInitialized = false;
// 请勿向此方法中添加任何其他代码
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// 创建框架但先不将它设置为 RootVisual;这允许初始
// 屏幕保持活动状态,直到准备呈现应用程序时。
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// 处理导航故障
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// 在下一次导航中处理清除 BackStack 的重置请求,
RootFrame.Navigated += CheckForResetNavigation;
// 确保我们未再次初始化
phoneApplicationInitialized = true;
}
// 请勿向此方法中添加任何其他代码
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// 设置根视觉效果以允许应用程序呈现
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// 删除此处理程序,因为不再需要它
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
private void CheckForResetNavigation(object sender, NavigationEventArgs e)
{
// 如果应用程序收到“重置”导航,则需要进行检查
// 以确定是否应重置页面堆栈
if (e.NavigationMode == NavigationMode.Reset)
RootFrame.Navigated += ClearBackStackAfterReset;
}
private void ClearBackStackAfterReset(object sender, NavigationEventArgs e)
{
// 取消注册事件,以便不再调用该事件
RootFrame.Navigated -= ClearBackStackAfterReset;
// 只为“新建”(向前)和“刷新”导航清除堆栈
if (e.NavigationMode != NavigationMode.New && e.NavigationMode != NavigationMode.Refresh)
return;
// 为了获得 UI 一致性,请清除整个页面堆栈
while (RootFrame.RemoveBackEntry() != null)
{
; // 不执行任何操作
}
}
#endregion
// 初始化应用程序在其本地化资源字符串中定义的字体和排列方向。
//
// 若要确保应用程序的字体与受支持的语言相符,并确保
// 这些语言的 FlowDirection 都采用其传统方向,ResourceLanguage
// 应该初始化每个 resx 文件中的 ResourceFlowDirection,以便将这些值与以下对象匹配
// 文件的区域性。例如:
//
// AppResources.es-ES.resx
// ResourceLanguage 的值应为“es-ES”
// ResourceFlowDirection 的值应为“LeftToRight”
//
// AppResources.ar-SA.resx
// ResourceLanguage 的值应为“ar-SA”
// ResourceFlowDirection 的值应为“RightToLeft”
//
// 有关本地化 Windows Phone 应用程序的详细信息,请参见 http://go.microsoft.com/fwlink/?LinkId=262072。
//
private void InitializeLanguage()
{
try
{
// 将字体设置为与由以下对象定义的显示语言匹配
// 每种受支持的语言的 ResourceLanguage 资源字符串。
//
// 如果显示出现以下情况,则回退到非特定语言的字体
// 手机的语言不受支持。
//
// 如果命中编译器错误,则表示以下对象中缺少 ResourceLanguage
// 资源文件。
RootFrame.Language = XmlLanguage.GetLanguage(AppResources.ResourceLanguage);
// 根据以下条件设置根框架下的所有元素的 FlowDirection
// 每个以下对象的 ResourceFlowDirection 资源字符串上的
// 受支持的语言。
//
// 如果命中编译器错误,则表示以下对象中缺少 ResourceFlowDirection
// 资源文件。
FlowDirection flow = (FlowDirection)Enum.Parse(typeof(FlowDirection), AppResources.ResourceFlowDirection);
RootFrame.FlowDirection = flow;
}
catch
{
// 如果此处导致了异常,则最可能的原因是
// ResourceLangauge 未正确设置为受支持的语言
// 代码或 ResourceFlowDirection 设置为 LeftToRight 以外的值
// 或 RightToLeft。
if (Debugger.IsAttached)
{
Debugger.Break();
}
throw;
}
}
}
} | sintrb/WindowsPhoneHTTPServer | App.xaml.cs | C# | gpl-2.0 | 8,746 |
package com.arantius.tivocommander.rpc.request;
import com.arantius.tivocommander.rpc.MindRpc;
public class Unsubscribe extends MindRpcRequest {
public Unsubscribe(String subscriptionId) {
super("unsubscribe");
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
mDataMap.put("subscriptionId", subscriptionId);
}
}
| arantius/TiVo-Commander | src/com/arantius/tivocommander/rpc/request/Unsubscribe.java | Java | gpl-2.0 | 330 |
/* -----------------------------------------------------------------------------------------------------------
Software License for The Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android
© Copyright 1995 - 2012 Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V.
All rights reserved.
Copyright (C) 2012 Sony Mobile Communications AB.
1. INTRODUCTION
The Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software that implements
the MPEG Advanced Audio Coding ("AAC") encoding and decoding scheme for digital audio.
This FDK AAC Codec software is intended to be used on a wide variety of Android devices.
AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient general perceptual
audio codecs. AAC-ELD is considered the best-performing full-bandwidth communications codec by
independent studies and is widely deployed. AAC has been standardized by ISO and IEC as part
of the MPEG specifications.
Patent licenses for necessary patent claims for the FDK AAC Codec (including those of Fraunhofer)
may be obtained through Via Licensing (www.vialicensing.com) or through the respective patent owners
individually for the purpose of encoding or decoding bit streams in products that are compliant with
the ISO/IEC MPEG audio standards. Please note that most manufacturers of Android devices already license
these patent claims through Via Licensing or directly from the patent owners, and therefore FDK AAC Codec
software may already be covered under those patent licenses when it is used for those licensed purposes only.
Commercially-licensed AAC software libraries, including floating-point versions with enhanced sound quality,
are also available from Fraunhofer. Users are encouraged to check the Fraunhofer website for additional
applications information and documentation.
2. COPYRIGHT LICENSE
Redistribution and use in source and binary forms, with or without modification, are permitted without
payment of copyright license fees provided that you satisfy the following conditions:
You must retain the complete text of this software license in redistributions of the FDK AAC Codec or
your modifications thereto in source code form.
You must retain the complete text of this software license in the documentation and/or other materials
provided with redistributions of the FDK AAC Codec or your modifications thereto in binary form.
You must make available free of charge copies of the complete source code of the FDK AAC Codec and your
modifications thereto to recipients of copies in binary form.
The name of Fraunhofer may not be used to endorse or promote products derived from this library without
prior written permission.
You may not charge copyright license fees for anyone to use, copy or distribute the FDK AAC Codec
software or your modifications thereto.
Your modified versions of the FDK AAC Codec must carry prominent notices stating that you changed the software
and the date of any change. For modified versions of the FDK AAC Codec, the term
"Fraunhofer FDK AAC Codec Library for Android" must be replaced by the term
"Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android."
3. NO PATENT LICENSE
NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without limitation the patents of Fraunhofer,
ARE GRANTED BY THIS SOFTWARE LICENSE. Fraunhofer provides no warranty of patent non-infringement with
respect to this software.
You may use this FDK AAC Codec software or modifications thereto only for purposes that are authorized
by appropriate patent licenses.
4. DISCLAIMER
This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright holders and contributors
"AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, including but not limited to the implied warranties
of merchantability and fitness for a particular purpose. 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), arising in any way out of the use of this software, even if
advised of the possibility of such damage.
5. CONTACT INFORMATION
Fraunhofer Institute for Integrated Circuits IIS
Attention: Audio and Multimedia Departments - FDK AAC LL
Am Wolfsmantel 33
91058 Erlangen, Germany
www.iis.fraunhofer.de/amm
amm-info@iis.fraunhofer.de
----------------------------------------------------------------------------------------------------------- */
/******************************** Fraunhofer IIS ***************************
Author(s): Arthur Tritthart
Description: (ARM optimised) LPP transposer subroutines
******************************************************************************/
#if defined(__arm__)
#define FUNCTION_LPPTRANSPOSER_func1
#ifdef FUNCTION_LPPTRANSPOSER_func1
/* Note: This code requires only 43 cycles per iteration instead of 61 on ARM926EJ-S */
__attribute__ ((noinline)) static void lppTransposer_func1(
FIXP_DBL *lowBandReal,
FIXP_DBL *lowBandImag,
FIXP_DBL **qmfBufferReal,
FIXP_DBL **qmfBufferImag,
int loops,
int hiBand,
int dynamicScale,
int descale,
FIXP_SGL a0r,
FIXP_SGL a0i,
FIXP_SGL a1r,
FIXP_SGL a1i)
{
FIXP_DBL real1, real2, imag1, imag2, accu1, accu2;
real2 = lowBandReal[-2];
real1 = lowBandReal[-1];
imag2 = lowBandImag[-2];
imag1 = lowBandImag[-1];
for(int i=0; i < loops; i++)
{
accu1 = fMultDiv2( a0r,real1);
accu2 = fMultDiv2( a0i,imag1);
accu1 = fMultAddDiv2(accu1,a1r,real2);
accu2 = fMultAddDiv2(accu2,a1i,imag2);
real2 = fMultDiv2( a1i,real2);
accu1 = accu1 - accu2;
accu1 = accu1 >> dynamicScale;
accu2 = fMultAddDiv2(real2,a1r,imag2);
real2 = real1;
imag2 = imag1;
accu2 = fMultAddDiv2(accu2,a0i,real1);
real1 = lowBandReal[i];
accu2 = fMultAddDiv2(accu2,a0r,imag1);
imag1 = lowBandImag[i];
accu2 = accu2 >> dynamicScale;
accu1 <<= 1;
accu2 <<= 1;
qmfBufferReal[i][hiBand] = accu1 + (real1>>descale);
qmfBufferImag[i][hiBand] = accu2 + (imag1>>descale);
}
}
#endif /* #ifdef FUNCTION_LPPTRANSPOSER_func1 */
#endif /* __arm__ */
| percy-g2/Novathor_xperia_u8500 | 6.2.A.1.100/external/aac/libSBRdec/src/arm/lpp_tran_arm.cpp | C++ | gpl-2.0 | 6,494 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2008-2020 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2020 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.web.rest.v1;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.EnumUtils;
import org.opennms.core.criteria.CriteriaBuilder;
import org.opennms.netmgt.dao.api.AcknowledgmentDao;
import org.opennms.netmgt.dao.api.AlarmDao;
import org.opennms.netmgt.model.AckAction;
import org.opennms.netmgt.model.OnmsAcknowledgment;
import org.opennms.netmgt.model.OnmsAlarm;
import org.opennms.netmgt.model.OnmsAlarmCollection;
import org.opennms.netmgt.model.TroubleTicketState;
import org.opennms.netmgt.model.alarm.AlarmSummary;
import org.opennms.netmgt.model.alarm.AlarmSummaryCollection;
import org.opennms.web.rest.support.MultivaluedMapImpl;
import org.opennms.web.rest.support.SecurityHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component("alarmRestService")
@Path("alarms")
public class AlarmRestService extends AlarmRestServiceBase {
@Autowired
private AlarmDao m_alarmDao;
@Autowired
private AcknowledgmentDao m_ackDao;
/**
* <p>
* getAlarm
* </p>
*
* @param alarmId
* a {@link java.lang.String} object.
* @return a {@link org.opennms.netmgt.model.OnmsAlarm} object.
*/
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML})
@Path("{alarmId}")
@Transactional
public Response getAlarm(@Context SecurityContext securityContext, @PathParam("alarmId") final String alarmId) {
SecurityHelper.assertUserReadCredentials(securityContext);
if ("summaries".equals(alarmId)) {
final List<AlarmSummary> collection = m_alarmDao.getNodeAlarmSummaries();
return collection == null ? Response.status(Status.NOT_FOUND).build() : Response.ok(new AlarmSummaryCollection(collection)).build();
} else {
final OnmsAlarm alarm = m_alarmDao.get(Integer.valueOf(alarmId));
return alarm == null ? Response.status(Status.NOT_FOUND).build() : Response.ok(alarm).build();
}
}
/**
* <p>
* getCount
* </p>
*
* @return a {@link java.lang.String} object.
*/
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("count")
@Transactional
public String getCount(@Context SecurityContext securityContext) {
SecurityHelper.assertUserReadCredentials(securityContext);
return Integer.toString(m_alarmDao.countAll());
}
/**
* <p>
* getAlarms
* </p>
*
* @return a {@link org.opennms.netmgt.model.OnmsAlarmCollection} object.
*/
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML})
@Transactional
public OnmsAlarmCollection getAlarms(@Context final SecurityContext securityContext, @Context final UriInfo uriInfo) {
SecurityHelper.assertUserReadCredentials(securityContext);
final CriteriaBuilder builder = getCriteriaBuilder(uriInfo.getQueryParameters(), false);
builder.distinct();
final OnmsAlarmCollection coll = new OnmsAlarmCollection(m_alarmDao.findMatching(builder.toCriteria()));
// For getting totalCount
coll.setTotalCount(m_alarmDao.countMatching(builder.count().toCriteria()));
return coll;
}
/**
* <p>
* updateAlarm
* </p>
*
* @param alarmId
* a {@link java.lang.String} object.
* @param ack
* a {@link java.lang.Boolean} object.
*/
@PUT
@Path("{alarmId}")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Transactional
public Response updateAlarm(@Context final SecurityContext securityContext, @PathParam("alarmId") final Integer alarmId, final MultivaluedMapImpl formProperties) {
writeLock();
try {
if (alarmId == null) {
return getBadRequestResponse("Unable to determine alarm ID to update based on query path.");
}
final String ackValue = formProperties.getFirst("ack");
formProperties.remove("ack");
final String escalateValue = formProperties.getFirst("escalate");
formProperties.remove("escalate");
final String clearValue = formProperties.getFirst("clear");
formProperties.remove("clear");
final String ackUserValue = formProperties.getFirst("ackUser");
formProperties.remove("ackUser");
final String ticketIdValue = formProperties.getFirst("ticketId");
formProperties.remove("ticketId");
final String ticketStateValue = formProperties.getFirst("ticketState");
formProperties.remove("ticketState");
final OnmsAlarm alarm = m_alarmDao.get(alarmId);
if (alarm == null) {
return getBadRequestResponse("Unable to locate alarm with ID '" + alarmId + "'");
}
boolean alarmUpdated = false;
if (StringUtils.isNotBlank(ticketIdValue)) {
alarmUpdated = true;
alarm.setTTicketId(ticketIdValue);
}
if (EnumUtils.isValidEnum(TroubleTicketState.class, ticketStateValue)) {
alarmUpdated = true;
alarm.setTTicketState(TroubleTicketState.valueOf(ticketStateValue));
}
if (alarmUpdated) {
m_alarmDao.saveOrUpdate(alarm);
}
final String ackUser = ackUserValue == null ? securityContext.getUserPrincipal().getName() : ackUserValue;
if (ackUser != null && StringUtils.isNotBlank(ackUser)) {
SecurityHelper.assertUserEditCredentials(securityContext, ackUser);
}
final OnmsAcknowledgment acknowledgement = new OnmsAcknowledgment(alarm, ackUser);
acknowledgement.setAckAction(AckAction.UNSPECIFIED);
boolean isProcessAck = false;
if (ackValue != null) {
isProcessAck = true;
if (Boolean.parseBoolean(ackValue)) {
acknowledgement.setAckAction(AckAction.ACKNOWLEDGE);
} else {
acknowledgement.setAckAction(AckAction.UNACKNOWLEDGE);
}
} else if (escalateValue != null) {
isProcessAck = true;
if (Boolean.parseBoolean(escalateValue)) {
acknowledgement.setAckAction(AckAction.ESCALATE);
}
} else if (clearValue != null) {
isProcessAck = true;
if (Boolean.parseBoolean(clearValue)) {
acknowledgement.setAckAction(AckAction.CLEAR);
}
}
if (isProcessAck) {
m_ackDao.processAck(acknowledgement);
m_ackDao.flush();
}
return Response.noContent().build();
} finally {
writeUnlock();
}
}
/**
* <p>
* updateAlarms
* </p>
*
* @param formProperties
* a {@link org.opennms.web.rest.support.MultivaluedMapImpl} object.
*/
@PUT
@Transactional
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response updateAlarms(@Context final SecurityContext securityContext, final MultivaluedMapImpl formProperties) {
writeLock();
try {
final String ackValue = formProperties.getFirst("ack");
formProperties.remove("ack");
final String escalateValue = formProperties.getFirst("escalate");
formProperties.remove("escalate");
final String clearValue = formProperties.getFirst("clear");
formProperties.remove("clear");
final CriteriaBuilder builder = getCriteriaBuilder(formProperties, false);
builder.distinct();
builder.limit(0);
builder.offset(0);
final String ackUser = formProperties.containsKey("ackUser") ? formProperties.getFirst("ackUser") : securityContext.getUserPrincipal().getName();
formProperties.remove("ackUser");
SecurityHelper.assertUserEditCredentials(securityContext, ackUser);
final List<OnmsAlarm> alarms = m_alarmDao.findMatching(builder.toCriteria());
for (final OnmsAlarm alarm : alarms) {
final OnmsAcknowledgment acknowledgement = new OnmsAcknowledgment(alarm, ackUser);
acknowledgement.setAckAction(AckAction.UNSPECIFIED);
if (ackValue != null) {
if (Boolean.parseBoolean(ackValue)) {
acknowledgement.setAckAction(AckAction.ACKNOWLEDGE);
} else {
acknowledgement.setAckAction(AckAction.UNACKNOWLEDGE);
}
} else if (escalateValue != null) {
if (Boolean.parseBoolean(escalateValue)) {
acknowledgement.setAckAction(AckAction.ESCALATE);
}
} else if (clearValue != null) {
if (Boolean.parseBoolean(clearValue)) {
acknowledgement.setAckAction(AckAction.CLEAR);
}
} else {
throw getException(Status.BAD_REQUEST, "Must supply one of the 'ack', 'escalate', or 'clear' parameters, set to either 'true' or 'false'.");
}
m_ackDao.processAck(acknowledgement);
}
return alarms == null || alarms.isEmpty() ? Response.notModified().build() : Response.noContent().build();
} finally {
writeUnlock();
}
}
}
| jeffgdotorg/opennms | opennms-webapp-rest/src/main/java/org/opennms/web/rest/v1/AlarmRestService.java | Java | gpl-2.0 | 11,406 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VDS.RDF.Query.Expressions.Functions.Leviathan.Numeric.Trigonometry
{
/// <summary>
/// Represents the Leviathan lfn:cot() or lfn:cot-1 function
/// </summary>
public class CotangentFunction
: BaseTrigonometricFunction
{
private bool _inverse = false;
private static Func<double, double> _cotangent = (d => (Math.Cos(d) / Math.Sin(d)));
private static Func<double, double> _arccotangent = (d => Math.Atan(1 / d));
/// <summary>
/// Creates a new Leviathan Cotangent Function
/// </summary>
/// <param name="expr">Expression</param>
public CotangentFunction(ISparqlExpression expr)
: base(expr, _cotangent) { }
/// <summary>
/// Creates a new Leviathan Cotangent Function
/// </summary>
/// <param name="expr">Expression</param>
/// <param name="inverse">Whether this should be the inverse function</param>
public CotangentFunction(ISparqlExpression expr, bool inverse)
: base(expr)
{
this._inverse = inverse;
if (this._inverse)
{
this._func = _arccotangent;
}
else
{
this._func = _cotangent;
}
}
/// <summary>
/// Gets the String representation of the function
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (this._inverse)
{
return "<" + LeviathanFunctionFactory.LeviathanFunctionsNamespace + LeviathanFunctionFactory.TrigCotanInv + ">(" + this._expr.ToString() + ")";
}
else
{
return "<" + LeviathanFunctionFactory.LeviathanFunctionsNamespace + LeviathanFunctionFactory.TrigCotan + ">(" + this._expr.ToString() + ")";
}
}
/// <summary>
/// Gets the Functor of the Expression
/// </summary>
public override string Functor
{
get
{
if (this._inverse)
{
return LeviathanFunctionFactory.LeviathanFunctionsNamespace + LeviathanFunctionFactory.TrigCotanInv;
}
else
{
return LeviathanFunctionFactory.LeviathanFunctionsNamespace + LeviathanFunctionFactory.TrigCotan;
}
}
}
/// <summary>
/// Transforms the Expression using the given Transformer
/// </summary>
/// <param name="transformer">Expression Transformer</param>
/// <returns></returns>
public override ISparqlExpression Transform(IExpressionTransformer transformer)
{
return new CotangentFunction(transformer.Transform(this._expr), this._inverse);
}
}
}
| jmahmud/RDFer | RDFerSolution/dotNetRdf/Query/Expressions/Functions/Leviathan/Numeric/Trigonometry/CotangentFunction.cs | C# | gpl-2.0 | 2,997 |
// $ANTLR 2.7.0a11: "antlr.g" -> "ANTLRLexer.java"$
package antlr;
public interface ANTLRTokenTypes {
int EOF = 1;
int NULL_TREE_LOOKAHEAD = 3;
int LITERAL_tokens = 4;
int LITERAL_header = 5;
int STRING_LITERAL = 6;
int ACTION = 7;
int DOC_COMMENT = 8;
int LITERAL_lexclass = 9;
int LITERAL_class = 10;
int LITERAL_extends = 11;
int LITERAL_Lexer = 12;
int LITERAL_TreeParser = 13;
int OPTIONS = 14;
int ASSIGN = 15;
int SEMI = 16;
int RCURLY = 17;
int LITERAL_charVocabulary = 18;
int CHAR_LITERAL = 19;
int INT = 20;
int OR = 21;
int RANGE = 22;
int TOKENS = 23;
int TOKEN_REF = 24;
int OPEN_ELEMENT_OPTION = 25;
int CLOSE_ELEMENT_OPTION = 26;
int LPAREN = 27;
int RULE_REF = 28;
int RPAREN = 29;
int LITERAL_Parser = 30;
int LITERAL_protected = 31;
int LITERAL_public = 32;
int LITERAL_private = 33;
int BANG = 34;
int ARG_ACTION = 35;
int LITERAL_returns = 36;
int COLON = 37;
int LITERAL_exception = 38;
int LITERAL_catch = 39;
int NOT_OP = 40;
int SEMPRED = 41;
int TREE_BEGIN = 42;
int QUESTION = 43;
int STAR = 44;
int PLUS = 45;
int IMPLIES = 46;
int CARET = 47;
int WILDCARD = 48;
int LITERAL_options = 49;
int WS = 50;
int COMMENT = 51;
int SL_COMMENT = 52;
int ML_COMMENT = 53;
int COMMA = 54;
int ESC = 55;
int DIGIT = 56;
int XDIGIT = 57;
int VOCAB = 58;
int NESTED_ARG_ACTION = 59;
int NESTED_ACTION = 60;
int WS_LOOP = 61;
int INTERNAL_RULE_REF = 62;
int WS_OPT = 63;
int NOT_USEFUL = 64;
}
| dbenn/cgp | lib/antlr-2.7.0/antlr/ANTLRTokenTypes.java | Java | gpl-2.0 | 1,472 |
package Common.Loggers;
import Common.FuncInterfaces.*;
import Common.Interfaces.ILogger;
import java.io.*;
import static Common.Utils.StringUtils.LineBreak;
import static Common.Utils.TimeUtils.nowTime;
import static java.lang.String.format;
/**
* Created by roman.i on 25.09.2014.
*/
public class DefaultLogger implements ILogger {
public FuncT<String> LogFileFormat;
private static String LogRecordTemplate = LineBreak + "[%s] %s: %s" + LineBreak;
private FuncTTT<String, String, String> LogRecord = (String s1, String s2) -> format(LogRecordTemplate, s1, nowTime("yyyy-MM-dd HH:mm:ss.S"), s2);
public FuncT<String> LogDirectoryRoot = () -> ".Logs/";
public boolean CreateFoldersForLogTypes = true;
public static String getValidUrl(String logPath)
{
if (logPath == null || logPath.equals(""))
return "";
String result = logPath.replace("/", "\\");
if (result.charAt(1) != ':')
if (result.substring(0, 3).equals("..\\"))
result = result.substring(2);
if (result.charAt(0) != '\\')
result = "\\" + result;
return (result.charAt(result.length() - 1) == '\\')
? result
: result + "\\";
}
public File getFile(String fileName) throws Exception {
File file = new File(".");
String current = file.getCanonicalPath();
String logDirectory = current + getValidUrl(LogDirectoryRoot.invoke()) + (CreateFoldersForLogTypes ? fileName + "s\\" : "");
return new File(logDirectory + format(LogFileFormat.invoke(), fileName));
}
public void createDirFile(File file) throws IOException {
file.getParentFile().mkdirs();
if (!file.exists())
file.createNewFile();
}
private void InLog(String fileName, String typeName, String msg) throws Exception {
File file = getFile(fileName);
createDirFile(file);
writeInFile(file, LogRecord.invoke(typeName, msg));
}
private void writeInFile(File file, String msg) throws Exception {
FileWriter fw = new FileWriter(file, true);
fw.write(msg);
fw.close();
}
public void Event(String msg) throws Exception {
InLog("Event", "Event", msg);
}
public void Error(String msg) throws Exception {
InLog("Error", "Error", msg);
InLog("Event", "Error", msg);
}
}
| elv1s42/VIQAUITestingTool | Java/src/main/java/Common/Loggers/DefaultLogger.java | Java | gpl-2.0 | 2,428 |
<?php
//-
$ranges=Array(
"3573547008" => array("3573612543","ES"),
"3573612544" => array("3573743615","GB"),
"3573743616" => array("3573809151","CH"),
"3573809152" => array("3573874687","ES"),
"3573874688" => array("3573878783","PL"),
"3573878784" => array("3573882879","RU"),
"3573882880" => array("3573884927","DK"),
"3573884928" => array("3573886975","PL"),
"3573886976" => array("3573889023","RU"),
"3573889024" => array("3573891071","HR"),
"3573891072" => array("3573893119","NL"),
"3573893120" => array("3573897215","RU"),
"3573897216" => array("3573899263","GB"),
"3573899264" => array("3573903359","RU"),
"3573903360" => array("3573905407","SI"),
"3573905408" => array("3573909503","RU"),
"3573909504" => array("3573913599","PL"),
"3573913600" => array("3573915647","CH"),
"3573915648" => array("3573917695","RU"),
"3573917696" => array("3573919743","SA"),
"3573919744" => array("3573921791","GB"),
"3573921792" => array("3573923839","RU"),
"3573923840" => array("3573925887","UA"),
"3573925888" => array("3573929983","PL"),
"3573929984" => array("3573938175","RU"),
"3573938176" => array("3573940223","PL"),
"3573940224" => array("3574005759","PS"),
"3574005760" => array("3574071295","CY"),
"3574071296" => array("3574136831","IL"),
"3574136832" => array("3574169599","DE"),
"3574169600" => array("3574202367","ES"),
"3574202368" => array("3574267903","NL"),
"3574267904" => array("3574333439","FR"),
"3574333440" => array("3574398975","EU"),
"3574398976" => array("3574464511","PT"),
"3574464512" => array("3574530047","TR"),
"3574530048" => array("3574595583","SE"),
"3574595584" => array("3574603775","FR"),
"3574603776" => array("3574611967","BG"),
"3574611968" => array("3574628351","HU"),
"3574628352" => array("3574661119","GR"),
"3574661120" => array("3574693887","NL"),
"3574693888" => array("3574726655","PL"),
"3574726656" => array("3574792191","GB"),
"3574792192" => array("3574824959","CZ"),
"3574824960" => array("3574857727","GB"),
"3574857728" => array("3574923263","DE"),
"3574923264" => array("3574939647","RU"),
"3574939648" => array("3574956031","SE"),
"3574956032" => array("3574972415","IT"),
"3574972416" => array("3574988799","LV"),
"3574988800" => array("3575054335","PT"),
"3575054336" => array("3575119871","DE"),
"3575119872" => array("3575185407","RU"),
"3575185408" => array("3575250943","PL"),
"3575250944" => array("3575316479","IT"),
"3575316480" => array("3575349247","RU"),
"3575349248" => array("3575382015","ES"),
"3575382016" => array("3575447551","FI"),
"3575447552" => array("3575513087","CZ"),
"3575513088" => array("3575545855","PT"),
"3575545856" => array("3575562239","FR"),
"3575562240" => array("3575578623","DE"),
"3575578624" => array("3575644159","BE"),
"3575644160" => array("3575709695","DK"),
"3575709696" => array("3575742463","AT"),
"3575742464" => array("3575775231","RU"),
"3575775232" => array("3575824383","NL"),
"3575824384" => array("3575832575","KW"),
"3575832576" => array("3575840767","NL"),
"3575840768" => array("3575873535","GB"),
"3575873536" => array("3575906303","EE"),
"3575906304" => array("3575971839","FR"),
"3575971840" => array("3576037375","ES"),
"3576037376" => array("3576102911","EU"),
"3576102912" => array("3576135679","GB"),
"3576135680" => array("3576168447","DE"),
"3576168448" => array("3576266751","GB"),
"3576266752" => array("3576299519","FR"),
"3576299520" => array("3576365055","AE"),
"3576365056" => array("3576430591","TR"),
"3576430592" => array("3576496127","FR"),
"3576496128" => array("3576561663","IT"),
"3576561664" => array("3576627199","NL"),
"3576627200" => array("3576692735","AT"),
"3576692736" => array("3576758271","GB"),
"3576758272" => array("3576823807","BE"),
"3576823808" => array("3576889343","SE"),
"3576889344" => array("3576954879","NL"),
"3576954880" => array("3576987647","NO"),
"3576987648" => array("3577020415","GB"),
"3577020416" => array("3577085951","NL"),
"3577085952" => array("3577151487","DE"),
"3577151488" => array("3577167871","FR"),
"3577167872" => array("3577184255","ET"),
"3577184256" => array("3577217023","CH"),
"3577217024" => array("3577282559","FR"),
"3577282560" => array("3577348095","IL"),
"3577348096" => array("3577413631","PT"),
"3577413632" => array("3577479167","RU"),
"3577479168" => array("3577544703","ES"),
"3577544704" => array("3577610239","DE"),
"3577610240" => array("3577675775","EU"),
"3577675776" => array("3577741311","PT"),
"3577741312" => array("3578003455","SE"),
"3578003456" => array("3578265599","DE"),
"3578265600" => array("3578331135","GB"),
"3578331136" => array("3578339327","PL"),
"3578339328" => array("3578347519","ES"),
"3578347520" => array("3578363903","DE"),
"3578363904" => array("3578396671","NL"),
"3578396672" => array("3578462207","TR"),
"3578462208" => array("3578527743","NL"),
"3578527744" => array("3578658815","PL"),
"3578658816" => array("3578724351","GB"),
"3578724352" => array("3578732543","RU"),
"3578732544" => array("3578740735","IE"),
"3578740736" => array("3578757119","RU"),
"3578757120" => array("3578822655","SE"),
"3578822656" => array("3578855423","RU"),
"3578855424" => array("3578888191","GB"),
"3578888192" => array("3578920959","SK"),
"3578920960" => array("3578986495","IT"),
"3578986496" => array("3579002879","DE"),
"3579002880" => array("3579019263","GB"),
"3579019264" => array("3579052031","DK"),
"3579052032" => array("3579117567","NL"),
"3579117568" => array("3579183103","RU"),
"3579183104" => array("3579248639","GB"),
"3579248640" => array("3579346943","RU"),
"3579346944" => array("3579445247","SE"),
"3579445248" => array("3579478015","AT"),
"3579478016" => array("3579527167","FR"),
"3579527168" => array("3579543551","BA"),
"3579543552" => array("3579576319","BG"),
"3579576320" => array("3579609087","IT"),
"3579609088" => array("3579641855","PL"),
"3579641856" => array("3579707391","NL"),
"3579707392" => array("3579723775","ES"),
"3579723776" => array("3579740159","AT"),
"3579740160" => array("3579772927","IE"),
"3579772928" => array("3579838463","DE"),
"3579838464" => array("3580100607","ES"),
"3580100608" => array("3580362751","SE"),
"3580362752" => array("3580624895","GB"),
"3580624896" => array("3580626943","RU"),
"3580626944" => array("3580628991","PL"),
"3580628992" => array("3580631039","RU"),
"3580631040" => array("3580633087","NL"),
"3580633088" => array("3580635135","RU"),
"3580635136" => array("3580637183","UA"),
"3580637184" => array("3580639231","KZ"),
"3580639232" => array("3580641279","PL"),
"3580641280" => array("3580643327","FR"),
"3580643328" => array("3580645375","UA"),
"3580645376" => array("3580647423","PL"),
"3580647424" => array("3580649471","DE"),
"3580649472" => array("3580651519","SE"),
"3580651520" => array("3580653567","NL"),
"3580653568" => array("3580655615","PL"),
"3580655616" => array("3580657663","SK"),
"3580657664" => array("3580663807","RU"),
"3580663808" => array("3580665855","PL"),
"3580665856" => array("3580667903","CZ"),
"3580667904" => array("3580669951","RU"),
"3580669952" => array("3580671999","UA"),
"3580672000" => array("3580682239","RU"),
"3580682240" => array("3580684287","PL"),
"3580684288" => array("3580686335","FR"),
"3580686336" => array("3580688383","BG"),
"3580688384" => array("3580698623","RU"),
"3580698624" => array("3580702719","PL"),
"3580702720" => array("3580710911","RU"),
"3580710912" => array("3580715007","UA"),
"3580715008" => array("3580719103","RU"),
"3580719104" => array("3580723199","NL"),
"3580723200" => array("3580727295","UA"),
"3580727296" => array("3580731391","RU"),
"3580731392" => array("3580739583","RO"),
"3580739584" => array("3580743679","RU"),
"3580743680" => array("3580751871","UA"),
"3580751872" => array("3580755967","IR"),
"3580755968" => array("3580772351","RU"),
"3580772352" => array("3580780543","LV"),
"3580780544" => array("3580805119","UA"),
"3580805120" => array("3580821503","RU"),
"3580821504" => array("3580837887","FR"),
"3580837888" => array("3580887039","UA"),
"3580887040" => array("3581149183","SE"),
"3581149184" => array("3581280255","EU"),
"3581280256" => array("3581411327","BE"),
"3581411328" => array("3581673471","GB"),
"3581673472" => array("3581935615","NL"),
"3581935616" => array("3581943807","RU"),
"3581943808" => array("3581951999","FR"),
"3581952000" => array("3581960191","TR"),
"3581960192" => array("3581976575","DE"),
"3581976576" => array("3581984767","NO"),
"3581984768" => array("3581992959","RU"),
"3581992960" => array("3582001151","GB"),
"3582001152" => array("3582009343","DK"),
"3582009344" => array("3582017535","RU"),
"3582017536" => array("3582025727","GB"),
"3582025728" => array("3582033919","RU"),
"3582033920" => array("3582042111","CZ"),
"3582042112" => array("3582050303","ES"),
"3582050304" => array("3582058495","NL"),
"3582058496" => array("3582066687","AT"),
"3582066688" => array("3582074879","UA"),
"3582074880" => array("3582083071","GB"),
"3582083072" => array("3582091263","BG"),
"3582091264" => array("3582099455","QA"),
"3582099456" => array("3582107647","GB"),
"3582107648" => array("3582115839","NL"),
"3582115840" => array("3582124031","SE"),
"3582124032" => array("3582132223","FI"),
"3582132224" => array("3582140415","RU"),
"3582140416" => array("3582148607","GE"),
"3582148608" => array("3582156799","EG"),
"3582156800" => array("3582164991","GB"),
"3582164992" => array("3582173183","SE"),
"3582173184" => array("3582181375","GB"),
"3582181376" => array("3582197759","DE"),
"3582197760" => array("3582205951","DK"),
"3582205952" => array("3582214143","AE"),
"3582214144" => array("3582222335","RU"),
"3582222336" => array("3582230527","SE"),
"3582230528" => array("3582238719","BE"),
"3582238720" => array("3582255103","NL"),
"3582255104" => array("3582263295","KW"),
"3582263296" => array("3582271487","ME"),
"3582271488" => array("3582279679","NL"),
"3582279680" => array("3582287871","GB"),
"3582287872" => array("3582296063","DE"),
"3582296064" => array("3582304255","GB"),
"3582304256" => array("3582312447","UA"),
"3582312448" => array("3582320639","JE"),
"3582320640" => array("3582328831","CH"),
"3582328832" => array("3582337023","HU"),
"3582337024" => array("3582345215","ES"),
"3582345216" => array("3582353407","IT"),
"3582353408" => array("3582361599","SE"),
"3582361600" => array("3582377983","PL"),
"3582377984" => array("3582386175","RU"),
"3582386176" => array("3582394367","NL"),
"3582394368" => array("3582402559","DE"),
"3582402560" => array("3582410751","PL"),
"3582410752" => array("3582435327","RU"),
"3582435328" => array("3582443519","MK"),
"3582443520" => array("3582451711","DE"),
"3582451712" => array("3582459903","LU"),
"3582459904" => array("3582468095","NL"),
"3582468096" => array("3582476287","SE"),
"3582476288" => array("3582484479","DE"),
"3582484480" => array("3582492671","CI"),
"3582492672" => array("3582509055","IT"),
"3582509056" => array("3582517247","SA"),
"3582517248" => array("3582525439","PL"),
"3582525440" => array("3582533631","GB"),
"3582533632" => array("3582541823","BG"),
"3582541824" => array("3582550015","US"),
"3582550016" => array("3582558207","RS"),
"3582558208" => array("3582566399","MC"),
"3582566400" => array("3582574591","EU"),
"3582574592" => array("3582582783","DE"),
"3582582784" => array("3582590975","RU"),
"3582590976" => array("3582599167","FR"),
"3582599168" => array("3582607359","DE"),
"3582607360" => array("3582615551","RU"),
"3582615552" => array("3582623743","GB"),
"3582623744" => array("3582631935","FI"),
"3582631936" => array("3582640127","NO"),
"3582640128" => array("3582648319","RU"),
"3582648320" => array("3582656511","PT"),
"3582656512" => array("3582664703","ES"),
"3582664704" => array("3582672895","JO"),
"3582672896" => array("3582681087","DE"),
"3582681088" => array("3582689279","FR"),
"3582689280" => array("3582697471","DE"),
"3582697472" => array("3582705663","FI"),
"3582705664" => array("3582722047","TR"),
"3582722048" => array("3582730239","IT"),
"3582730240" => array("3582738431","ES"),
"3582738432" => array("3582746623","DK"),
"3582746624" => array("3582754815","RU"),
"3582754816" => array("3582763007","GR"),
"3582763008" => array("3582771199","FI"),
"3582771200" => array("3582779391","CY"),
"3582779392" => array("3582787583","RU"),
"3582787584" => array("3582795775","PT"),
"3582795776" => array("3582803967","ES"),
"3582803968" => array("3582812159","SE"),
"3582812160" => array("3582820351","FI"),
"3582820352" => array("3582828543","RU"),
"3582828544" => array("3582836735","KZ"),
"3582836736" => array("3582853119","RU"),
"3582853120" => array("3582861311","SE"),
"3582861312" => array("3582869503","RU"),
"3582869504" => array("3582877695","NO"),
"3582877696" => array("3582885887","AT"),
"3582885888" => array("3582894079","TR"),
"3582894080" => array("3582902271","CH"),
"3582902272" => array("3582910463","RU"),
"3582910464" => array("3582918655","SI"),
"3582918656" => array("3582926847","GB"),
"3582926848" => array("3582935039","ES"),
"3582935040" => array("3582943231","SI"),
"3582943232" => array("3582951423","AT"),
"3582951424" => array("3582959615","GB"),
"3582959616" => array("3582967807","FI"),
"3582967808" => array("3582975999","DE"),
"3582976000" => array("3582984191","TR"),
"3582984192" => array("3582992383","DE"),
"3582992384" => array("3583000575","ES"),
"3583000576" => array("3583008767","IT"),
"3583008768" => array("3583016959","TR"),
"3583016960" => array("3583025151","CH"),
"3583025152" => array("3583033343","IT"),
"3583033344" => array("3583041535","FR"),
"3583041536" => array("3583049727","NL"),
"3583049728" => array("3583066111","RU"),
"3583066112" => array("3583074303","DE"),
"3583074304" => array("3583082495","BG"),
"3583082496" => array("3583090687","KG"),
"3583090688" => array("3583098879","NO"),
"3583098880" => array("3583107071","FI"),
"3583107072" => array("3583115263","AT"),
"3583115264" => array("3583123455","CH"),
"3583123456" => array("3583131647","PL"),
"3583131648" => array("3583139839","SE"),
"3583139840" => array("3583148031","DE"),
"3583148032" => array("3583164415","GB"),
"3583164416" => array("3583172607","PT"),
"3583172608" => array("3583188991","DE"),
"3583188992" => array("3583197183","RU"),
"3583197184" => array("3583205375","KE"),
"3583205376" => array("3583213567","HR"),
"3583213568" => array("3583221759","IR"),
"3583221760" => array("3583229951","AT"),
"3583229952" => array("3583238143","RU"),
"3583238144" => array("3583246335","GB"),
"3583246336" => array("3583254527","RU"),
"3583254528" => array("3583262719","GB"),
"3583262720" => array("3583270911","TR"),
"3583270912" => array("3583287295","DE"),
"3583287296" => array("3583295487","RU"),
"3583295488" => array("3583303679","ES"),
"3583303680" => array("3583311871","NL"),
"3583311872" => array("3583320063","RU"),
"3583320064" => array("3583328255","HR"),
"3583328256" => array("3583336447","DE"),
"3583336448" => array("3583344639","ME"),
"3583344640" => array("3583352831","BG"),
"3583352832" => array("3583361023","CY"),
"3583361024" => array("3583369215","IT"),
"3583369216" => array("3583377407","ES"),
"3583377408" => array("3583385599","AT"),
"3583385600" => array("3583393791","DK"),
"3583393792" => array("3583401983","RU"),
"3583401984" => array("3583410175","KE"),
"3583410176" => array("3583418367","SE"),
"3583418368" => array("3583426559","TN"),
"3583426560" => array("3583434751","CI"),
"3583434752" => array("3583442943","AT"),
"3583442944" => array("3583451135","UA"),
"3583451136" => array("3583459327","IL"),
"3583459328" => array("3583467519","CZ"),
"3583467520" => array("3583475711","ES"),
"3583475712" => array("3583483903","NO"),
"3583483904" => array("3583492095","FR"),
"3583492096" => array("3583508479","SK"),
"3583508480" => array("3583516671","FR"),
"3583516672" => array("3583524863","GB"),
"3583524864" => array("3583533055","EG"),
"3583533056" => array("3583541247","DE"),
"3583541248" => array("3583549439","RU"),
"3583549440" => array("3583557631","NL"),
"3583557632" => array("3583565823","IT"),
"3583565824" => array("3583574015","GB"),
"3583574016" => array("3583582207","NO"),
"3583582208" => array("3583590399","AT"),
"3583590400" => array("3583598591","DE"),
"3583598592" => array("3583606783","SE"),
"3583606784" => array("3583639551","TR"),
"3583639552" => array("3583647743","AZ"),
"3583647744" => array("3583655935","EG"),
"3583655936" => array("3583664127","SN"),
"3583664128" => array("3583680511","RO"),
"3583680512" => array("3583688703","RU"),
"3583688704" => array("3583696895","UA"),
"3583696896" => array("3583705087","NL"),
"3583705088" => array("3583713279","UA"),
"3583713280" => array("3583721471","CZ"),
"3583721472" => array("3583729663","DE"),
"3583729664" => array("3583737855","TR"),
"3583737856" => array("3583746047","EU"),
"3583746048" => array("3583754239","PL"),
"3583754240" => array("3583762431","RU"),
"3583762432" => array("3583770623","CZ"),
"3583770624" => array("3583778815","NL"),
"3583778816" => array("3583787007","IT"),
"3583787008" => array("3583795199","UA"),
"3583795200" => array("3583803391","PL"),
"3583803392" => array("3583811583","RU"),
"3583811584" => array("3583819775","DE"),
"3583819776" => array("3583827967","RU"),
"3583827968" => array("3583836159","CH"),
"3583836160" => array("3583844351","DE"),
"3583844352" => array("3583852543","KZ"),
"3583852544" => array("3583860735","FI"),
"3583860736" => array("3583868927","HU"),
"3583868928" => array("3583877119","AT"),
"3583877120" => array("3583885311","RO"),
"3583885312" => array("3583893503","GE"),
"3583893504" => array("3583901695","SI"),
"3583901696" => array("3583909887","RU"),
"3583909888" => array("3583918079","SE"),
"3583918080" => array("3583926271","IT"),
"3583926272" => array("3583934463","DE"),
"3583934464" => array("3583942655","CH"),
"3583942656" => array("3583950847","EG"),
"3583950848" => array("3583959039","PL"),
"3583959040" => array("3583967231","NO"),
"3583967232" => array("3583975423","NL"),
"3583975424" => array("3583983615","LT"),
"3583983616" => array("3583999999","RU"),
"3584000000" => array("3584008191","IE"),
"3584008192" => array("3584016383","DK"),
"3584016384" => array("3584024575","RU"),
"3584024576" => array("3584032767","UA"),
"3584032768" => array("3584040959","DE"),
"3584040960" => array("3584049151","CH"),
"3584049152" => array("3584057343","DE"),
"3584057344" => array("3584065535","GB"),
"3584065536" => array("3584073727","UA"),
"3584073728" => array("3584081919","SK"),
"3584081920" => array("3584098303","NL"),
"3584098304" => array("3584106495","SI"),
"3584106496" => array("3584114687","FI"),
"3584114688" => array("3584122879","GB"),
"3584122880" => array("3584131071","PL"),
"3584131072" => array("3584139263","TR"),
"3584139264" => array("3584147455","NO"),
"3584147456" => array("3584155647","FR"),
"3584155648" => array("3584163839","NO"),
"3584163840" => array("3584172031","CH"),
"3584172032" => array("3584180223","FR"),
"3584180224" => array("3584188415","AT"),
"3584188416" => array("3584196607","GB"),
"3584196608" => array("3584204799","DE"),
"3584204800" => array("3584212991","NL"),
"3584212992" => array("3584221183","ES"),
"3584221184" => array("3584229375","NO"),
"3584229376" => array("3584245759","HU"),
"3584245760" => array("3584253951","NL"),
"3584253952" => array("3584262143","ME"),
"3584262144" => array("3584270335","SE"),
"3584270336" => array("3584278527","FR"),
"3584278528" => array("3584286719","GB"),
"3584286720" => array("3584303103","AT"),
"3584303104" => array("3584311295","ES"),
"3584311296" => array("3584319487","DE"),
"3584319488" => array("3584327679","LT"),
"3584327680" => array("3584335871","DE"),
"3584335872" => array("3584344063","ES"),
"3584344064" => array("3584352255","SE"),
"3584352256" => array("3584360447","RO"),
"3584360448" => array("3584368639","GB"),
"3584368640" => array("3584376831","LB"),
"3584376832" => array("3584393215","DE"),
"3584393216" => array("3584401407","GB"),
"3584401408" => array("3584409599","MT"),
"3584409600" => array("3584417791","RU"),
"3584417792" => array("3584434175","GB"),
"3584434176" => array("3584442367","LU"),
"3584442368" => array("3584450559","GB"),
"3584450560" => array("3584458751","EU"),
"3584458752" => array("3584466943","SA"),
"3584466944" => array("3584475135","NO"),
"3584475136" => array("3584483327","FR"),
"3584483328" => array("3584491519","DE"),
"3584491520" => array("3584499711","BG"),
"3584499712" => array("3584507903","RU"),
"3584507904" => array("3584516095","GB"),
"3584516096" => array("3584524287","NO"),
"3584524288" => array("3584532479","IS"),
"3584532480" => array("3584540671","DE"),
"3584540672" => array("3584548863","RU"),
"3584548864" => array("3584557055","ES"),
"3584557056" => array("3584565247","EE"),
"3584565248" => array("3584573439","RU"),
"3584573440" => array("3584589823","DE"),
"3584589824" => array("3584598015","RU"),
"3584598016" => array("3584606207","CZ"),
"3584606208" => array("3584614399","DE"),
"3584614400" => array("3584622591","IE"),
"3584622592" => array("3584630783","FI"),
"3584630784" => array("3584638975","BG"),
"3584638976" => array("3584647167","UA"),
"3584647168" => array("3584655359","LU"),
"3584655360" => array("3584663551","CY"),
"3584663552" => array("3584671743","FR"),
"3584671744" => array("3584688127","NL"),
"3584688128" => array("3584696319","GB"),
"3584696320" => array("3584704511","ES"),
"3584704512" => array("3584720895","RU"),
"3584720896" => array("3584729087","GB"),
"3584729088" => array("3584737279","DE"),
"3584737280" => array("3584745471","GR"),
"3584745472" => array("3584753663","DK"),
"3584753664" => array("3584770047","RU"),
"3584770048" => array("3584778239","NL"),
"3584778240" => array("3584786431","IT"),
"3584786432" => array("3584794623","NL"),
"3584794624" => array("3584802815","IT"),
"3584802816" => array("3584811007","GB"),
"3584811008" => array("3584819199","ES"),
"3584819200" => array("3584827391","RU"),
"3584827392" => array("3584835583","ES"),
"3584835584" => array("3584843775","AZ"),
"3584843776" => array("3584851967","DE"),
"3584860160" => array("3584868351","PL"),
"3584868352" => array("3584876543","NO"),
"3584876544" => array("3584884735","SI"),
"3584884736" => array("3584892927","DE"),
"3584892928" => array("3584901119","IL"),
"3584901120" => array("3584909311","AT"),
"3584909312" => array("3584917503","IT"),
"3584917504" => array("3584925695","FI"),
"3584925696" => array("3584933887","CH"),
"3584933888" => array("3584942079","SE"),
"3584942080" => array("3584950271","DK"),
"3584950272" => array("3584958463","UA"),
"3584958464" => array("3584966655","DE"),
"3584966656" => array("3584974847","DK"),
"3584974848" => array("3584983039","FR"),
"3584983040" => array("3584991231","NL"),
"3584991232" => array("3584999423","IT"),
"3584999424" => array("3585007615","GB"),
"3585007616" => array("3585015807","AT"),
"3585015808" => array("3585023999","IT"),
"3585024000" => array("3585032191","CZ"),
"3585032192" => array("3585048575","LV"),
"3585048576" => array("3585056767","GB"),
"3585056768" => array("3585064959","LB"),
"3585064960" => array("3585081343","GB"),
"3585081344" => array("3585114111","IR"),
"3585114112" => array("3585122303","IS"),
"3585122304" => array("3585130495","ES"),
"3585130496" => array("3585138687","FR"),
"3585138688" => array("3585146879","RU"),
"3585146880" => array("3585155071","RO"),
"3585155072" => array("3585163263","GB"),
"3585163264" => array("3585171455","BE"),
"3585171456" => array("3585179647","RU"),
"3585179648" => array("3585196031","BE"),
"3585196032" => array("3585204223","ES"),
"3585204224" => array("3585212415","GB"),
"3585212416" => array("3585220607","DE"),
"3585220608" => array("3585228799","RU"),
"3585228800" => array("3585236991","DE"),
"3585236992" => array("3585245183","HU"),
"3585245184" => array("3585253375","GB"),
"3585253376" => array("3585261567","DE"),
"3585261568" => array("3585269759","IT"),
"3585269760" => array("3585277951","SY"),
"3585277952" => array("3585286143","SE"),
"3585286144" => array("3585294335","NO"),
"3585294336" => array("3585302527","DE"),
"3585302528" => array("3585310719","ES"),
"3585310720" => array("3585318911","DE"),
"3585318912" => array("3585327103","DZ"),
"3585327104" => array("3585335295","NL"),
"3585335296" => array("3585343487","UA"),
"3585343488" => array("3585351679","EE"),
"3585351680" => array("3585359871","CZ"),
"3585359872" => array("3585368063","SE"),
"3585368064" => array("3585376255","LV"),
"3585376256" => array("3585384447","PL"),
"3585384448" => array("3585392639","CH"),
"3585392640" => array("3585400831","RU"),
"3585400832" => array("3585409023","FR"),
"3585409024" => array("3585417215","RU"),
"3585417216" => array("3585425407","BE"),
"3585425408" => array("3585433599","ES"),
"3585433600" => array("3585441791","IS"),
"3585441792" => array("3585449983","SK"),
"3585449984" => array("3585458175","SA"),
"3585458176" => array("3585466367","HU"),
"3585466368" => array("3585474559","EG"),
"3585474560" => array("3585482751","DE"),
"3585482752" => array("3585490943","FR"),
"3585490944" => array("3585499135","IT"),
"3585499136" => array("3585515519","DE"),
"3585515520" => array("3585523711","RU"),
"3585523712" => array("3585531903","LV"),
"3585531904" => array("3585540095","AT"),
"3585540096" => array("3585548287","DE"),
"3585548288" => array("3585556479","RU"),
"3585556480" => array("3585564671","DE"),
"3585564672" => array("3585572863","RU"),
"3585572864" => array("3585581055","IT"),
"3585581056" => array("3585597439","DE"),
"3585597440" => array("3585605631","RU"),
"3585605632" => array("3585613823","PL"),
"3585613824" => array("3585622015","EE"),
"3585622016" => array("3585630207","RU"),
"3585630208" => array("3585638399","RS"),
"3585638400" => array("3585646591","RU"),
"3585646592" => array("3585654783","SA"),
"3585654784" => array("3585662975","NO"),
"3585662976" => array("3585671167","BY"),
"3585671168" => array("3585679359","SE"),
"3585679360" => array("3585687551","FI"),
"3585687552" => array("3585695743","DE"),
"3585695744" => array("3585703935","GB"),
"3585703936" => array("3585712127","DE"),
"3585712128" => array("3585720319","AT"),
"3585720320" => array("3585728511","GB"),
"3585728512" => array("3585736703","SE"),
"3585736704" => array("3585744895","HR"),
"3585744896" => array("3585753087","FR"),
"3585753088" => array("3585761279","PL"),
"3585761280" => array("3585769471","UA"),
"3585769472" => array("3585777663","TR"),
"3585777664" => array("3585785855","JO"),
"3585785856" => array("3585794047","UA"),
"3585794048" => array("3585802239","FI"),
"3585802240" => array("3585810431","IT"),
"3585810432" => array("3585818623","GB"),
"3585818624" => array("3585826815","DE"),
"3585826816" => array("3585835007","RU"),
"3585835008" => array("3585843199","US"),
"3585843200" => array("3585851391","NO"),
"3585851392" => array("3585859583","SE"),
"3585859584" => array("3585867775","DE"),
"3585867776" => array("3585875967","NO"),
"3585875968" => array("3585884159","CH"),
"3585884160" => array("3585892351","IQ"),
"3585892352" => array("3585900543","DE"),
"3585900544" => array("3585908735","NO"),
"3585908736" => array("3585916927","FR"),
"3585916928" => array("3585925119","IT"),
"3585925120" => array("3585933311","CH"),
"3585933312" => array("3585941503","NL"),
"3585941504" => array("3585949695","PL"),
"3585949696" => array("3585957887","KW"),
"3585957888" => array("3585966079","SE"),
"3585966080" => array("3585974271","CH"),
"3585974272" => array("3585982463","BE"),
"3585982464" => array("3585998847","RU"),
"3585998848" => array("3586007039","ES"),
"3586007040" => array("3586015231","LT"),
"3586015232" => array("3586023423","FR"),
"3586023424" => array("3586031615","IS"),
"3586031616" => array("3586039807","IE"),
"3586039808" => array("3586047999","GB"),
"3586048000" => array("3586056191","PT"),
"3586056192" => array("3586072575","RU"),
"3586072576" => array("3586088959","DE"),
"3586088960" => array("3586097151","CZ"),
"3586097152" => array("3586105343","HR"),
"3586113536" => array("3586121727","BG"),
"3586121728" => array("3586129919","IE"),
"3586129920" => array("3586146303","CZ"),
"3586146304" => array("3586162687","PL"),
"3586162688" => array("3586179071","FI"),
"3586179072" => array("3586195455","ES"),
"3586195456" => array("3586203647","RU"),
"3586203648" => array("3586211839","ZA"),
"3586211840" => array("3586228223","CH"),
"3586228224" => array("3586244607","BE"),
"3586244608" => array("3586260991","NL"),
"3586260992" => array("3586277375","ES"),
"3586277376" => array("3586293759","TR"),
"3586293760" => array("3586310143","ES"),
"3586310144" => array("3586326527","CZ"),
"3586326528" => array("3586342911","IR"),
"3586342912" => array("3586359295","ES"),
"3586359296" => array("3586375679","PL"),
"3586375680" => array("3586392063","CZ"),
"3586392064" => array("3586408447","NL"),
"3586408448" => array("3586424831","BA"),
"3586424832" => array("3586441215","CH"),
"3586441216" => array("3586457599","DE"),
"3586457600" => array("3586473983","NL"),
"3586473984" => array("3586490367","HU"),
"3586490368" => array("3586506751","LT"),
"3586506752" => array("3586523135","NL"),
"3586523136" => array("3586555903","DE"),
"3586555904" => array("3586572287","IT"),
"3586572288" => array("3586588671","RS"),
"3586588672" => array("3586596863","IT"),
"3586596864" => array("3586605055","GB"),
"3586605056" => array("3586621439","SE"),
"3586621440" => array("3586637823","GB"),
"3586637824" => array("3586654207","PL"),
"3586654208" => array("3586662399","GE"),
"3586662400" => array("3586670591","UA"),
"3586670592" => array("3586686975","IE"),
"3586686976" => array("3586703359","SE"),
"3586703360" => array("3586719743","CH"),
"3586719744" => array("3586752511","ES"),
"3586752512" => array("3586785279","NL"),
"3586785280" => array("3586793471","OM"),
"3586793472" => array("3586801663","CH"),
"3586801664" => array("3586818047","HR"),
"3586818048" => array("3586834431","IE"),
"3586834432" => array("3586850815","DE"),
"3586850816" => array("3586867199","NO"),
"3586867200" => array("3586883583","FR"),
"3586883584" => array("3586899967","IT"),
"3586899968" => array("3586916351","DE"),
"3586916352" => array("3586924543","IT"),
"3586924544" => array("3586932735","AX"),
"3586932736" => array("3586949119","LB"),
"3586949120" => array("3586965503","SE"),
"3586965504" => array("3586981887","NL"),
"3586981888" => array("3586998271","IT"),
"3586998272" => array("3587006463","PT"),
"3587006464" => array("3587014655","FR"),
"3587014656" => array("3587055615","GB"),
"3587055616" => array("3587063807","UZ"),
"3587063808" => array("3587080191","NL"),
"3587080192" => array("3587088383","GB"),
"3587088384" => array("3587096575","DE"),
"3587096576" => array("3587121151","NL"),
"3587121152" => array("3587129343","AL"),
"3587129344" => array("3587145727","NL"),
"3587145728" => array("3587162111","CY"),
"3587162112" => array("3587178495","IR"),
"3587178496" => array("3587186687","AT"),
"3587186688" => array("3587194879","DE"),
"3587194880" => array("3587211263","GB"),
"3587211264" => array("3587219455","AT"),
"3587219456" => array("3587227647","RU"),
"3587227648" => array("3587244031","GB"),
"3587244032" => array("3587260415","IT"),
"3587260416" => array("3587284991","DE"),
"3587284992" => array("3587309567","IT"),
"3587309568" => array("3587325951","GB"),
"3587325952" => array("3587342335","RU"),
"3587342336" => array("3587358719","CZ"),
"3587358720" => array("3587375103","SA"),
"3587375104" => array("3587383295","TR"),
"3587383296" => array("3587391487","CZ"),
"3587391488" => array("3587407871","KZ"),
"3587407872" => array("3587424255","BE"),
"3587424256" => array("3587440639","DE"),
"3587440640" => array("3587457023","SE"),
"3587457024" => array("3587473407","GB"),
"3587473408" => array("3587489791","IT"),
"3587489792" => array("3587506175","EG"),
"3587506176" => array("3587538943","IT"),
"3587538944" => array("3587547135","IS"),
"3587547136" => array("3587555327","CH"),
"3587555328" => array("3587571711","BE"),
"3587571712" => array("3587579903","DE"),
"3587579904" => array("3587588095","BE"),
"3587588096" => array("3587596287","BG"),
"3587596288" => array("3587604479","NL"),
"3587604480" => array("3587620863","FI"),
"3587620864" => array("3587637247","SE"),
"3587637248" => array("3587653631","FR"),
"3587653632" => array("3587670015","SK"),
"3587670016" => array("3587702783","IT"),
"3587702784" => array("3587710975","DE"),
"3587710976" => array("3587719167","CZ"),
"3587719168" => array("3587735551","PL"),
"3587735552" => array("3587751935","GB"),
"3587751936" => array("3587768319","FI"),
"3587768320" => array("3587776511","DE"),
"3587776512" => array("3587784703","IR"),
"3587784704" => array("3587801087","DE"),
"3587801088" => array("3587817471","IT"),
"3587817472" => array("3587833855","MT"),
"3587833856" => array("3587842047","DE"),
"3587842048" => array("3587850239","IT"),
"3587850240" => array("3587866623","PL"),
"3587866624" => array("3587874815","FR"),
"3587874816" => array("3587883007","DE"),
"3587883008" => array("3587915775","GB"),
"3587915776" => array("3587932159","EE"),
"3587932160" => array("3587948543","BE"),
"3587948544" => array("3587964927","RU"),
"3587964928" => array("3587981311","ES"),
"3587981312" => array("3587997695","IS"),
"3587997696" => array("3588014079","DE"),
"3588014080" => array("3588030463","CZ"),
"3588030464" => array("3588046847","RU"),
"3588046848" => array("3588063231","DE"),
"3588063232" => array("3588071423","CH"),
"3588071424" => array("3588079615","GB"),
"3588079616" => array("3588095999","CH"),
"3588096000" => array("3588104191","NL"),
"3588104192" => array("3588112383","BG"),
"3588112384" => array("3588128767","FR"),
"3588128768" => array("3588145151","HU"),
"3588145152" => array("3588153343","PL"),
"3588153344" => array("3588161535","RU"),
"3588161536" => array("3588227071","FR"),
"3588227072" => array("3588292607","BE"),
"3588292608" => array("3588308991","AT"),
"3588308992" => array("3588325375","NO"),
"3588325376" => array("3588333567","GB"),
"3588333568" => array("3588341759","FR"),
"3588341760" => array("3588358143","IT"),
"3588358144" => array("3588374527","BG"),
"3588374528" => array("3588390911","SE"),
"3588390912" => array("3588407295","LT"),
"3588407296" => array("3588423679","CZ"),
"3588423680" => array("3588440063","ES"),
"3588440064" => array("3588456447","PL"),
"3588456448" => array("3588464639","NL"),
"3588464640" => array("3588472831","AT"),
"3588472832" => array("3588489215","UA"),
"3588489216" => array("3588505599","FR"),
"3588505600" => array("3588521983","RU"),
"3588521984" => array("3588538367","PT"),
"3588538368" => array("3588554751","GB"),
"3588554752" => array("3588571135","AT"),
"3588571136" => array("3588587519","GB"),
"3588587520" => array("3588603903","ES"),
"3588603904" => array("3588620287","SI"),
"3588620288" => array("3588628479","SA"),
"3588628480" => array("3588636671","CH"),
"3588636672" => array("3588653055","UZ"),
"3588653056" => array("3588661247","IT"),
"3588661248" => array("3588669439","NO"),
"3588669440" => array("3588685823","GB"),
"3588685824" => array("3588702207","UA"),
"3588702208" => array("3588718591","ES"),
"3588718592" => array("3588734975","BG"),
"3588734976" => array("3588751359","PL"),
"3588751360" => array("3588767743","TR"),
"3588767744" => array("3588784127","GB"),
"3588784128" => array("3588800511","CH"),
"3588800512" => array("3588816895","RU"),
"3588816896" => array("3588833279","IT"),
"3588833280" => array("3588849663","RO"),
"3588849664" => array("3588857855","IE"),
"3588857856" => array("3588866047","IR"),
"3588866048" => array("3588882431","NL"),
"3588882432" => array("3588890623","RU"),
"3588890624" => array("3588898815","GB"),
"3588898816" => array("3588915199","NO"),
"3588915200" => array("3588931583","IT"),
"3588931584" => array("3588947967","RU"),
"3588947968" => array("3588964351","GB"),
"3588964352" => array("3588997119","CZ"),
"3588997120" => array("3589013503","AT"),
"3589013504" => array("3589021695","ES"),
"3589021696" => array("3589029887","SA"),
"3589029888" => array("3589046271","NL"),
"3589046272" => array("3589079039","NO"),
"3589079040" => array("3589128191","DK"),
"3589128192" => array("3589144575","GB"),
"3589144576" => array("3589152767","UA"),
"3589152768" => array("3589160959","DE"),
"3589160960" => array("3589177343","PL"),
"3589177344" => array("3589193727","TR"),
"3589193728" => array("3589210111","SE"),
"3589210112" => array("3589226495","NL"),
"3589226496" => array("3589242879","NO"),
"3589242880" => array("3589259263","NL"),
"3589259264" => array("3589275647","DE"),
"3589275648" => array("3589292031","RS"),
"3589292032" => array("3589308415","AT"),
"3589308416" => array("3589324799","DE"),
"3589324800" => array("3589341183","BG"),
"3589341184" => array("3589373951","PL"),
"3589373952" => array("3589390335","DE"),
"3589390336" => array("3589423103","RU"),
"3589423104" => array("3589439487","GB"),
"3589439488" => array("3589455871","SE"),
"3589455872" => array("3589472255","RU"),
"3589472256" => array("3589488639","TR"),
"3589488640" => array("3589505023","RU"),
"3589505024" => array("3589521407","FI"),
"3589521408" => array("3589537791","IT"),
"3589537792" => array("3589545983","FR"),
"3589545984" => array("3589554175","DE"),
"3589554176" => array("3589570559","PS"),
"3589570560" => array("3589586943","GB"),
"3589586944" => array("3589603327","RS"),
"3589603328" => array("3589668863","FR"),
"3589668864" => array("3589677055","RU"),
"3589677056" => array("3589685247","FR"),
"3589685248" => array("3589718015","GB"),
"3589718016" => array("3589734399","BE"),
"3589734400" => array("3589742591","EG"),
"3589742592" => array("3589767167","NL"),
"3589767168" => array("3589816319","RU"),
"3589816320" => array("3589832703","EU"),
"3589832704" => array("3589849087","TR"),
"3589849088" => array("3589865471","GB"),
"3589865472" => array("3589881855","GR"),
"3589881856" => array("3589890047","NL"),
"3589890048" => array("3589931007","GB"),
"3589931008" => array("3589947391","SI"),
"3589947392" => array("3589963775","FI"),
"3589963776" => array("3589980159","ES"),
"3589980160" => array("3589996543","CZ"),
"3589996544" => array("3590012927","GB"),
"3590012928" => array("3590029311","BE"),
"3590029312" => array("3590045695","FR"),
"3590045696" => array("3590062079","RU"),
"3590062080" => array("3590078463","DE"),
"3590078464" => array("3590094847","RU"),
"3590094848" => array("3590111231","DE"),
"3590111232" => array("3590127615","LT"),
"3590127616" => array("3590143999","GB"),
"3590144000" => array("3590160383","SI"),
"3590160384" => array("3590176767","GB"),
"3590176768" => array("3590193151","HU"),
"3590193152" => array("3590201343","IT"),
"3590201344" => array("3590209535","DE"),
"3590209536" => array("3590225919","ES"),
"3590225920" => array("3590234111","TR"),
"3590234112" => array("3590242303","GB"),
"3590242304" => array("3590258687","IE"),
"3590258688" => array("3590291455","IT"),
"3590291456" => array("3590299647","EG"),
"3590299648" => array("3590307839","FI"),
"3590307840" => array("3590324223","GB"),
);
?> | hodorogandrei/contesteasyplatform | admiasi/include/ip2country_files/213.php | PHP | gpl-2.0 | 38,880 |
def float_example():
a = -10
print a.__float__()
print float(a)
if __name__ == '__main__':
float_example() | ramesharpu/python | basic-coding/built-in-functions/float.py | Python | gpl-2.0 | 124 |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2001 David R. Hampton
# Copyright (C) 2001-2006 Donald N. Allingham
# Copyright (C) 2007 Brian G. Matherly
# Copyright (C) 2010 Jakim Friant
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from gramps.gen.utils.grampslocale import GrampsLocale
from gramps.gen.display.name import NameDisplay
from gramps.gen.config import config
#-------------------------------------------------------------------------
#
# Report
#
#-------------------------------------------------------------------------
class Report:
"""
The Report base class. This is a base class for generating
customized reports. It cannot be used as is, but it can be easily
sub-classed to create a functional report generator.
"""
def __init__(self, database, options_class, user):
self.database = database
self.options_class = options_class
self._user = user
self.doc = options_class.get_document()
creator = database.get_researcher().get_name()
self.doc.set_creator(creator)
output = options_class.get_output()
if output:
self.standalone = True
self.doc.open(options_class.get_output())
else:
self.standalone = False
def begin_report(self):
pass
def set_locale(self, language):
"""
Set the translator to one selected with
stdoptions.add_localization_option().
"""
if language == GrampsLocale.DEFAULT_TRANSLATION_STR:
language = None
locale = GrampsLocale(lang=language)
self._ = locale.translation.sgettext
self._get_date = locale.get_date
self._get_type = locale.get_type
self._ldd = locale.date_displayer
self._name_display = NameDisplay(locale) # a legacy/historical name
self._name_display.set_name_format(self.database.name_formats)
fmt_default = config.get('preferences.name-format')
self._name_display.set_default_format(fmt_default)
return locale
def write_report(self):
pass
def end_report(self):
if self.standalone:
self.doc.close()
| beernarrd/gramps | gramps/gen/plug/report/_reportbase.py | Python | gpl-2.0 | 3,048 |
<?php
// Search
// Wp Estate Pack
global $row_number_col;
get_header();
$options = wpestate_page_details('');
$unit_class = "col-md-6";
$row_number_col=6;
if($options['content_class'] == "col-md-12"){
$unit_class="col-md-4";
$row_number_col=4;
}
$row_number_col=4;
?>
<div class="row content-fixed">
<?php get_template_part('templates/breadcrumbs'); ?>
<div class=" col-md-12 ">
<div class="blog_list_wrapper row">
<?php
if (have_posts()){
print ' <h1 class="entry-title-search">'. esc_html__( 'Search Results for: ','wpestate');print '"' . get_search_query() . '"'.'</h1>';
while (have_posts()) : the_post();
get_template_part('templates/blog_unit');
endwhile;
}else{
?>
<h1 class="entry-title-search"><?php esc_html_e( 'We didn\'t find any results. Please try again with different search parameters. ', 'wpestate' ); ?></h1>
<form method="get" class="searchform" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input type="text" class="form-control search_res_form" name="s" id="s" value="<?php esc_attr (esc_html_e( 'Type Keyword', 'wpestate' )); ?>" />
<input type="submit" id="submit-form" class="wpb_btn-info wpb_regularsize wpestate_vc_button vc_button" value="<?php esc_attr ( esc_html_e( 'Search', 'wpestate') ); ?>">
</form>
<?php
}
wp_reset_query();
?>
</div>
<?php kriesi_pagination('', $range = 2); ?>
</div><!-- end 8col container-->
<?php // include(locate_template('sidebar.php')); ?>
</div>
<?php get_footer(); ?> | riddya85/rentail_upwrk | wp-content/themes/wprentals/search.php | PHP | gpl-2.0 | 1,879 |
from distutils.core import setup
setup(
name='tinyfsm',
version='0.1',
packages=[''],
url='https://github.com/tonyfunc/tinyfsm',
license='GNU Library',
author='tony',
author_email='me@tonyfunc.com',
description='A tiny implementation of Finite State Machine in Python.'
)
| tonyfunc/tinyfsm | setup.py | Python | gpl-2.0 | 305 |
package cn.guoyukun.demo.cts.dao;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.stereotype.Repository;
@Repository
public class DealerDao extends BaseDao{
private static final String _TABLE_NAME = "dealer";
private static final String _PK_NAME = "JXSDM";
@Override
protected String getTableName() {
return _TABLE_NAME;
}
@Override
protected String getPKName() {
return _PK_NAME;
}
public void add(Map <String,Object> info){
super.getJdbcTemplate().update("insert into dealer (" +
"JXSDM," +
"JXSMC," +
"SYB," +
"SHENG," +
"SHI," +
"QY," +
"SFTY" +
") values(?,?,?,?,?,?,?)",
info.get("JXSDM"),
info.get("JXSMC"),
info.get("SYB"),
info.get("SHENG"),
info.get("SHI"),
info.get("QY"),
info.get("SFTY")
);
}
public void edit(Map <String,Object> info){
super.getJdbcTemplate().update("update dealer set "+
"JXSMC=?,"+
"SYB=?,"+
"SHENG=?,"+
"SHI=?,"+
"QY=?,"+
"SFTY=?"+
" where JXSMC=?",
info.get("JXSMC"),
info.get("SYB"),
info.get("SHENG"),
info.get("SHI"),
info.get("QY"),
info.get("SFTY"),
info.get("JXSDM")
);
}
}
| gyk001/demo-cts | src/main/java/cn/guoyukun/demo/cts/dao/DealerDao.java | Java | gpl-2.0 | 1,189 |
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Falla extends Model{
protected $fillable = ['name', 'address', 'status'];
public function objections(){
return $this->hasMany('App\Models\Objection', 'id_falla');
}
public function fools(){
return $this->belongsToMany('App\Models\User', 'objections', 'id_falla', 'id_user');
}
} | victorarcasrios/fallas | app/Models/Falla.php | PHP | gpl-2.0 | 367 |
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under the GNU Public Licence, v2 or any higher version
#
# Please cite your use of MDAnalysis in published work:
#
# R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler,
# D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein.
# MDAnalysis: A Python package for the rapid analysis of molecular dynamics
# simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th
# Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy.
# doi: 10.25080/majora-629e541a-00e
#
# N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein.
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#
"""Water dynamics analysis --- :mod:`MDAnalysis.analysis.waterdynamics`
=======================================================================
:Author: Alejandro Bernardin
:Year: 2014-2015
:Copyright: GNU Public License v3
.. versionadded:: 0.11.0
This module provides functions to analize water dynamics trajectories and water
interactions with other molecules. The functions in this module are: water
orientational relaxation (WOR) [Yeh1999]_, hydrogen bond lifetimes (HBL)
[Rapaport1983]_, angular distribution (AD) [Grigera1995]_, mean square
displacement (MSD) [Brodka1994]_ and survival probability (SP) [Liu2004]_.
For more information about this type of analysis please refer to
[Araya-Secchi2014]_ (water in a protein cavity) and [Milischuk2011]_ (water in
a nanopore).
.. rubric:: References
.. [Rapaport1983] D.C. Rapaport (1983): Hydrogen bonds in water, Molecular
Physics: An International Journal at the Interface Between
Chemistry and Physics, 50:5, 1151-1162.
.. [Yeh1999] Yu-ling Yeh and Chung-Yuan Mou (1999). Orientational Relaxation
Dynamics of Liquid Water Studied by Molecular Dynamics Simulation,
J. Phys. Chem. B 1999, 103, 3699-3705.
.. [Grigera1995] Raul Grigera, Susana G. Kalko and Jorge Fischbarg
(1995). Wall-Water Interface. A Molecular Dynamics Study,
Langmuir 1996,12,154-158
.. [Liu2004] Pu Liu, Edward Harder, and B. J. Berne (2004).On the Calculation
of Diffusion Coefficients in Confined Fluids and Interfaces with
an Application to the Liquid-Vapor Interface of Water,
J. Phys. Chem. B 2004, 108, 6595-6602.
.. [Brodka1994] Aleksander Brodka (1994). Diffusion in restricted volume,
Molecular Physics, 1994, Vol. 82, No. 5, 1075-1078.
.. [Araya-Secchi2014] Araya-Secchi, R., Tomas Perez-Acle, Seung-gu Kang, Tien
Huynh, Alejandro Bernardin, Yerko Escalona, Jose-Antonio
Garate, Agustin D. Martinez, Isaac E. Garcia, Juan
C. Saez, Ruhong Zhou (2014). Characterization of a novel
water pocket inside the human Cx26 hemichannel
structure. Biophysical journal, 107(3), 599-612.
.. [Milischuk2011] Anatoli A. Milischuk and Branka M. Ladanyi. Structure and
dynamics of water confined in silica
nanopores. J. Chem. Phys. 135, 174709 (2011); doi:
10.1063/1.3657408
Example use of the analysis classes
-----------------------------------
HydrogenBondLifetimes
~~~~~~~~~~~~~~~~~~~~~
To analyse hydrogen bond lifetime, use
:meth:`MDAnalysis.analysis.hydrogenbonds.hbond_analysis.HydrogenBondAnalysis.liftetime`.
See Also
--------
:mod:`MDAnalysis.analysis.hydrogenbonds.hbond_analysis`
WaterOrientationalRelaxation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Analyzing water orientational relaxation (WOR)
:class:`WaterOrientationalRelaxation`. In this case we are analyzing "how fast"
water molecules are rotating/changing direction. If WOR is very stable we can
assume that water molecules are rotating/changing direction very slow, on the
other hand, if WOR decay very fast, we can assume that water molecules are
rotating/changing direction very fast::
import MDAnalysis
from MDAnalysis.analysis.waterdynamics import WaterOrientationalRelaxation as WOR
u = MDAnalysis.Universe(pdb, trajectory)
select = "byres name OH2 and sphzone 6.0 protein and resid 42"
WOR_analysis = WOR(universe, select, 0, 1000, 20)
WOR_analysis.run()
time = 0
#now we print the data ready to plot. The first two columns are WOR_OH vs t plot,
#the second two columns are WOR_HH vs t graph and the third two columns are WOR_dip vs t graph
for WOR_OH, WOR_HH, WOR_dip in WOR_analysis.timeseries:
print("{time} {WOR_OH} {time} {WOR_HH} {time} {WOR_dip}".format(time=time, WOR_OH=WOR_OH, WOR_HH=WOR_HH,WOR_dip=WOR_dip))
time += 1
#now, if we want, we can plot our data
plt.figure(1,figsize=(18, 6))
#WOR OH
plt.subplot(131)
plt.xlabel('time')
plt.ylabel('WOR')
plt.title('WOR OH')
plt.plot(range(0,time),[column[0] for column in WOR_analysis.timeseries])
#WOR HH
plt.subplot(132)
plt.xlabel('time')
plt.ylabel('WOR')
plt.title('WOR HH')
plt.plot(range(0,time),[column[1] for column in WOR_analysis.timeseries])
#WOR dip
plt.subplot(133)
plt.xlabel('time')
plt.ylabel('WOR')
plt.title('WOR dip')
plt.plot(range(0,time),[column[2] for column in WOR_analysis.timeseries])
plt.show()
where t0 = 0, tf = 1000 and dtmax = 20. In this way we create 20 windows
timesteps (20 values in the x axis), the first window is created with 1000
timestep average (1000/1), the second window is created with 500 timestep
average(1000/2), the third window is created with 333 timestep average (1000/3)
and so on.
AngularDistribution
~~~~~~~~~~~~~~~~~~~
Analyzing angular distribution (AD) :class:`AngularDistribution` for OH vector,
HH vector and dipole vector. It returns a line histogram with vector
orientation preference. A straight line in the output plot means no
preferential orientation in water molecules. In this case we are analyzing if
water molecules have some orientational preference, in this way we can see if
water molecules are under an electric field or if they are interacting with
something (residue, protein, etc)::
import MDAnalysis
from MDAnalysis.analysis.waterdynamics import AngularDistribution as AD
u = MDAnalysis.Universe(pdb, trajectory)
selection = "byres name OH2 and sphzone 6.0 (protein and (resid 42 or resid 26) )"
bins = 30
AD_analysis = AD(universe,selection,bins)
AD_analysis.run()
#now we print data ready to graph. The first two columns are P(cos(theta)) vs cos(theta) for OH vector ,
#the seconds two columns are P(cos(theta)) vs cos(theta) for HH vector and thirds two columns
#are P(cos(theta)) vs cos(theta) for dipole vector
for bin in range(bins):
print("{AD_analysisOH} {AD_analysisHH} {AD_analysisDip}".format(AD_analysis.graph0=AD_analysis.graph[0][bin], AD_analysis.graph1=AD_analysis.graph[1][bin],AD_analysis.graph2=AD_analysis.graph[2][bin]))
#and if we want to graph our results
plt.figure(1,figsize=(18, 6))
#AD OH
plt.subplot(131)
plt.xlabel('cos theta')
plt.ylabel('P(cos theta)')
plt.title('PDF cos theta for OH')
plt.plot([float(column.split()[0]) for column in AD_analysis.graph[0][:-1]],[float(column.split()[1]) for column in AD_analysis.graph[0][:-1]])
#AD HH
plt.subplot(132)
plt.xlabel('cos theta')
plt.ylabel('P(cos theta)')
plt.title('PDF cos theta for HH')
plt.plot([float(column.split()[0]) for column in AD_analysis.graph[1][:-1]],[float(column.split()[1]) for column in AD_analysis.graph[1][:-1]])
#AD dip
plt.subplot(133)
plt.xlabel('cos theta')
plt.ylabel('P(cos theta)')
plt.title('PDF cos theta for dipole')
plt.plot([float(column.split()[0]) for column in AD_analysis.graph[2][:-1]],[float(column.split()[1]) for column in AD_analysis.graph[2][:-1]])
plt.show()
where `P(cos(theta))` is the angular distribution or angular probabilities.
MeanSquareDisplacement
~~~~~~~~~~~~~~~~~~~~~~
Analyzing mean square displacement (MSD) :class:`MeanSquareDisplacement` for
water molecules. In this case we are analyzing the average distance that water
molecules travels inside protein in XYZ direction (cylindric zone of radius
11[nm], Zmax 4.0[nm] and Zmin -8.0[nm]). A strong rise mean a fast movement of
water molecules, a weak rise mean slow movement of particles::
import MDAnalysis
from MDAnalysis.analysis.waterdynamics import MeanSquareDisplacement as MSD
u = MDAnalysis.Universe(pdb, trajectory)
select = "byres name OH2 and cyzone 11.0 4.0 -8.0 protein"
MSD_analysis = MSD(universe, select, 0, 1000, 20)
MSD_analysis.run()
#now we print data ready to graph. The graph
#represents MSD vs t
time = 0
for msd in MSD_analysis.timeseries:
print("{time} {msd}".format(time=time, msd=msd))
time += 1
#Plot
plt.xlabel('time')
plt.ylabel('MSD')
plt.title('MSD')
plt.plot(range(0,time),MSD_analysis.timeseries)
plt.show()
.. _SP-examples:
SurvivalProbability
~~~~~~~~~~~~~~~~~~~
Analyzing survival probability (SP) :class:`SurvivalProbability` of molecules.
In this case we are analyzing how long water molecules remain in a
sphere of radius 12.3 centered in the geometrical center of resid 42 and 26.
A slow decay of SP means a long permanence time of water molecules in
the zone, on the other hand, a fast decay means a short permanence time::
import MDAnalysis
from MDAnalysis.analysis.waterdynamics import SurvivalProbability as SP
import matplotlib.pyplot as plt
universe = MDAnalysis.Universe(pdb, trajectory)
select = "byres name OH2 and sphzone 12.3 (resid 42 or resid 26) "
sp = SP(universe, select, verbose=True)
sp.run(start=0, stop=101, tau_max=20)
tau_timeseries = sp.tau_timeseries
sp_timeseries = sp.sp_timeseries
# print in console
for tau, sp in zip(tau_timeseries, sp_timeseries):
print("{time} {sp}".format(time=tau, sp=sp))
# plot
plt.xlabel('Time')
plt.ylabel('SP')
plt.title('Survival Probability')
plt.plot(tau_timeseries, sp_timeseries)
plt.show()
One should note that the `stop` keyword as used in the above example has an
`exclusive` behaviour, i.e. here the final frame used will be 100 not 101.
This behaviour is aligned with :class:`AnalysisBase` but currently differs from
other :mod:`MDAnalysis.analysis.waterdynamics` classes, which all exhibit
`inclusive` behaviour for their final frame selections.
Another example applies to the situation where you work with many different "residues".
Here we calculate the SP of a potassium ion around each lipid in a membrane and
average the results. In this example, if the SP analysis were run without treating each lipid
separately, potassium ions may hop from one lipid to another and still be counted as remaining
in the specified region. That is, the survival probability of the potassium ion around the
entire membrane will be calculated.
Note, for this example, it is advisable to use `Universe(in_memory=True)` to ensure that the
simulation is not being reloaded into memory for each lipid::
import MDAnalysis as mda
from MDAnalysis.analysis.waterdynamics import SurvivalProbability as SP
import numpy as np
u = mda.Universe("md.gro", "md100ns.xtc", in_memory=True)
lipids = u.select_atoms('resname LIPIDS')
joined_sp_timeseries = [[] for _ in range(20)]
for lipid in lipids.residues:
print("Lipid ID: %d" % lipid.resid)
select = "resname POTASSIUM and around 3.5 (resid %d and name O13 O14) " % lipid.resid
sp = SP(u, select, verbose=True)
sp.run(tau_max=20)
# Raw SP points for each tau:
for sps, new_sps in zip(joined_sp_timeseries, sp.sp_timeseries_data):
sps.extend(new_sps)
# average all SP datapoints
sp_data = [np.mean(sp) for sp in joined_sp_timeseries]
for tau, sp in zip(range(1, tau_max + 1), sp_data):
print("{time} {sp}".format(time=tau, sp=sp))
.. _Output:
Output
------
WaterOrientationalRelaxation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Water orientational relaxation (WOR) data is returned per window timestep,
which is stored in :attr:`WaterOrientationalRelaxation.timeseries`::
results = [
[ # time t0
<WOR_OH>, <WOR_HH>, <WOR_dip>
],
[ # time t1
<WOR_OH>, <WOR_HH>, <WOR_dip>
],
...
]
AngularDistribution
~~~~~~~~~~~~~~~~~~~
Angular distribution (AD) data is returned per vector, which is stored in
:attr:`AngularDistribution.graph`. In fact, AngularDistribution returns a
histogram::
results = [
[ # OH vector values
# the values are order in this way: <x_axis y_axis>
<cos_theta0 ang_distr0>, <cos_theta1 ang_distr1>, ...
],
[ # HH vector values
<cos_theta0 ang_distr0>, <cos_theta1 ang_distr1>, ...
],
[ # dip vector values
<cos_theta0 ang_distr0>, <cos_theta1 ang_distr1>, ...
],
]
MeanSquareDisplacement
~~~~~~~~~~~~~~~~~~~~~~
Mean Square Displacement (MSD) data is returned in a list, which each element
represents a MSD value in its respective window timestep. Data is stored in
:attr:`MeanSquareDisplacement.timeseries`::
results = [
#MSD values orders by window timestep
<MSD_t0>, <MSD_t1>, ...
]
SurvivalProbability
~~~~~~~~~~~~~~~~~~~
Survival Probability (SP) computes two lists: a list of taus (:attr:`SurvivalProbability.tau_timeseries`) and a list of
the corresponding survival probabilities (:attr:`SurvivalProbability.sp_timeseries`).
results = [ tau1, tau2, ..., tau_n ], [ sp_tau1, sp_tau2, ..., sp_tau_n]
Additionally, a list :attr:`SurvivalProbability.sp_timeseries_data`, is provided which contains
a list of all SPs calculated for each tau. This can be used to compute the distribution or time dependence of SP, etc.
Classes
--------
.. autoclass:: WaterOrientationalRelaxation
:members:
:inherited-members:
.. autoclass:: AngularDistribution
:members:
:inherited-members:
.. autoclass:: MeanSquareDisplacement
:members:
:inherited-members:
.. autoclass:: SurvivalProbability
:members:
:inherited-members:
"""
from MDAnalysis.lib.correlations import autocorrelation, correct_intermittency
import MDAnalysis.analysis.hbonds
from itertools import zip_longest
import logging
import warnings
import numpy as np
logger = logging.getLogger('MDAnalysis.analysis.waterdynamics')
from MDAnalysis.lib.log import ProgressBar
class WaterOrientationalRelaxation(object):
r"""Water orientation relaxation analysis
Function to evaluate the Water Orientational Relaxation proposed by Yu-ling
Yeh and Chung-Yuan Mou [Yeh1999_]. WaterOrientationalRelaxation indicates
"how fast" water molecules are rotating or changing direction. This is a
time correlation function given by:
.. math::
C_{\hat u}(\tau)=\langle \mathit{P}_2[\mathbf{\hat{u}}(t_0)\cdot\mathbf{\hat{u}}(t_0+\tau)]\rangle
where :math:`P_2=(3x^2-1)/2` is the second-order Legendre polynomial and :math:`\hat{u}` is
a unit vector along HH, OH or dipole vector.
Parameters
----------
universe : Universe
Universe object
selection : str
Selection string for water [‘byres name OH2’].
t0 : int
frame where analysis begins
tf : int
frame where analysis ends
dtmax : int
Maximum dt size, `dtmax` < `tf` or it will crash.
.. versionadded:: 0.11.0
.. versionchanged:: 1.0.0
Changed `selection` keyword to `select`
"""
def __init__(self, universe, select, t0, tf, dtmax, nproc=1):
self.universe = universe
self.selection = select
self.t0 = t0
self.tf = tf
self.dtmax = dtmax
self.nproc = nproc
self.timeseries = None
def _repeatedIndex(self, selection, dt, totalFrames):
"""
Indicates the comparation between all the t+dt.
The results is a list of list with all the repeated index per frame
(or time).
Ex: dt=1, so compare frames (1,2),(2,3),(3,4)...
Ex: dt=2, so compare frames (1,3),(3,5),(5,7)...
Ex: dt=3, so compare frames (1,4),(4,7),(7,10)...
"""
rep = []
for i in range(int(round((totalFrames - 1) / float(dt)))):
if (dt * i + dt < totalFrames):
rep.append(self._sameMolecTandDT(
selection, dt * i, (dt * i) + dt))
return rep
def _getOneDeltaPoint(self, universe, repInd, i, t0, dt):
"""
Gives one point to calculate the mean and gets one point of the plot
C_vect vs t.
Ex: t0=1 and tau=1 so calculate the t0-tau=1-2 intervale.
Ex: t0=5 and tau=3 so calcultate the t0-tau=5-8 intervale.
i = come from getMeanOnePoint (named j) (int)
"""
valOH = 0
valHH = 0
valdip = 0
n = 0
for j in range(len(repInd[i]) // 3):
begj = 3 * j
universe.trajectory[t0]
Ot0 = repInd[i][begj]
H1t0 = repInd[i][begj + 1]
H2t0 = repInd[i][begj + 2]
OHVector0 = H1t0.position - Ot0.position
HHVector0 = H1t0.position - H2t0.position
dipVector0 = ((H1t0.position + H2t0.position) * 0.5) - Ot0.position
universe.trajectory[t0 + dt]
Otp = repInd[i][begj]
H1tp = repInd[i][begj + 1]
H2tp = repInd[i][begj + 2]
OHVectorp = H1tp.position - Otp.position
HHVectorp = H1tp.position - H2tp.position
dipVectorp = ((H1tp.position + H2tp.position) * 0.5) - Otp.position
normOHVector0 = np.linalg.norm(OHVector0)
normOHVectorp = np.linalg.norm(OHVectorp)
normHHVector0 = np.linalg.norm(HHVector0)
normHHVectorp = np.linalg.norm(HHVectorp)
normdipVector0 = np.linalg.norm(dipVector0)
normdipVectorp = np.linalg.norm(dipVectorp)
unitOHVector0 = [OHVector0[0] / normOHVector0,
OHVector0[1] / normOHVector0,
OHVector0[2] / normOHVector0]
unitOHVectorp = [OHVectorp[0] / normOHVectorp,
OHVectorp[1] / normOHVectorp,
OHVectorp[2] / normOHVectorp]
unitHHVector0 = [HHVector0[0] / normHHVector0,
HHVector0[1] / normHHVector0,
HHVector0[2] / normHHVector0]
unitHHVectorp = [HHVectorp[0] / normHHVectorp,
HHVectorp[1] / normHHVectorp,
HHVectorp[2] / normHHVectorp]
unitdipVector0 = [dipVector0[0] / normdipVector0,
dipVector0[1] / normdipVector0,
dipVector0[2] / normdipVector0]
unitdipVectorp = [dipVectorp[0] / normdipVectorp,
dipVectorp[1] / normdipVectorp,
dipVectorp[2] / normdipVectorp]
valOH += self.lg2(np.dot(unitOHVector0, unitOHVectorp))
valHH += self.lg2(np.dot(unitHHVector0, unitHHVectorp))
valdip += self.lg2(np.dot(unitdipVector0, unitdipVectorp))
n += 1
return (valOH/n, valHH/n, valdip/n) if n > 0 else (0, 0, 0)
def _getMeanOnePoint(self, universe, selection1, selection_str, dt,
totalFrames):
"""
This function gets one point of the plot C_vec vs t. It uses the
_getOneDeltaPoint() function to calculate the average.
"""
repInd = self._repeatedIndex(selection1, dt, totalFrames)
sumsdt = 0
n = 0.0
sumDeltaOH = 0.0
sumDeltaHH = 0.0
sumDeltadip = 0.0
for j in range(totalFrames // dt - 1):
a = self._getOneDeltaPoint(universe, repInd, j, sumsdt, dt)
sumDeltaOH += a[0]
sumDeltaHH += a[1]
sumDeltadip += a[2]
sumsdt += dt
n += 1
# if no water molecules remain in selection, there is nothing to get
# the mean, so n = 0.
return (sumDeltaOH / n, sumDeltaHH / n, sumDeltadip / n) if n > 0 else (0, 0, 0)
def _sameMolecTandDT(self, selection, t0d, tf):
"""
Compare the molecules in the t0d selection and the t0d+dt selection and
select only the particles that are repeated in both frame. This is to
consider only the molecules that remains in the selection after the dt
time has elapsed.
The result is a list with the indexs of the atoms.
"""
a = set(selection[t0d])
b = set(selection[tf])
sort = sorted(list(a.intersection(b)))
return sort
def _selection_serial(self, universe, selection_str):
selection = []
for ts in ProgressBar(universe.trajectory, verbose=True,
total=universe.trajectory.n_frames):
selection.append(universe.select_atoms(selection_str))
return selection
@staticmethod
def lg2(x):
"""Second Legendre polynomial"""
return (3*x*x - 1)/2
def run(self, **kwargs):
"""Analyze trajectory and produce timeseries"""
# All the selection to an array, this way is faster than selecting
# later.
if self.nproc == 1:
selection_out = self._selection_serial(
self.universe, self.selection)
else:
# selection_out = self._selection_parallel(self.universe,
# self.selection, self.nproc)
# parallel selection to be implemented
selection_out = self._selection_serial(
self.universe, self.selection)
self.timeseries = []
for dt in list(range(1, self.dtmax + 1)):
output = self._getMeanOnePoint(
self.universe, selection_out, self.selection, dt, self.tf)
self.timeseries.append(output)
class AngularDistribution(object):
r"""Angular distribution function analysis
The angular distribution function (AD) is defined as the distribution
probability of the cosine of the :math:`\theta` angle formed by the OH
vector, HH vector or dipolar vector of water molecules and a vector
:math:`\hat n` parallel to chosen axis (z is the default value). The cosine
is define as :math:`\cos \theta = \hat u \cdot \hat n`, where :math:`\hat
u` is OH, HH or dipole vector. It creates a histogram and returns a list
of lists, see Output_. The AD is also know as Angular Probability (AP).
Parameters
----------
universe : Universe
Universe object
select : str
Selection string to evaluate its angular distribution ['byres name OH2']
bins : int (optional)
Number of bins to create the histogram by means of :func:`numpy.histogram`
axis : {'x', 'y', 'z'} (optional)
Axis to create angle with the vector (HH, OH or dipole) and calculate
cosine theta ['z'].
.. versionadded:: 0.11.0
.. versionchanged:: 1.0.0
Changed `selection` keyword to `select`
"""
def __init__(self, universe, select, bins=40, nproc=1, axis="z"):
self.universe = universe
self.selection_str = select
self.bins = bins
self.nproc = nproc
self.axis = axis
self.graph = None
def _getCosTheta(self, universe, selection, axis):
valOH = []
valHH = []
valdip = []
i = 0
while i <= (len(selection) - 1):
universe.trajectory[i]
line = selection[i].positions
Ot0 = line[::3]
H1t0 = line[1::3]
H2t0 = line[2::3]
OHVector0 = H1t0 - Ot0
HHVector0 = H1t0 - H2t0
dipVector0 = (H1t0 + H2t0) * 0.5 - Ot0
unitOHVector0 = OHVector0 / \
np.linalg.norm(OHVector0, axis=1)[:, None]
unitHHVector0 = HHVector0 / \
np.linalg.norm(HHVector0, axis=1)[:, None]
unitdipVector0 = dipVector0 / \
np.linalg.norm(dipVector0, axis=1)[:, None]
j = 0
while j < len(line) / 3:
if axis == "z":
valOH.append(unitOHVector0[j][2])
valHH.append(unitHHVector0[j][2])
valdip.append(unitdipVector0[j][2])
elif axis == "x":
valOH.append(unitOHVector0[j][0])
valHH.append(unitHHVector0[j][0])
valdip.append(unitdipVector0[j][0])
elif axis == "y":
valOH.append(unitOHVector0[j][1])
valHH.append(unitHHVector0[j][1])
valdip.append(unitdipVector0[j][1])
j += 1
i += 1
return (valOH, valHH, valdip)
def _getHistogram(self, universe, selection, bins, axis):
"""
This function gets a normalized histogram of the cos(theta) values. It
return a list of list.
"""
a = self._getCosTheta(universe, selection, axis)
cosThetaOH = a[0]
cosThetaHH = a[1]
cosThetadip = a[2]
lencosThetaOH = len(cosThetaOH)
lencosThetaHH = len(cosThetaHH)
lencosThetadip = len(cosThetadip)
histInterval = bins
histcosThetaOH = np.histogram(cosThetaOH, histInterval, density=True)
histcosThetaHH = np.histogram(cosThetaHH, histInterval, density=True)
histcosThetadip = np.histogram(cosThetadip, histInterval, density=True)
return (histcosThetaOH, histcosThetaHH, histcosThetadip)
def _hist2column(self, aList):
"""
This function transform from the histogram format
to a column format.
"""
a = []
for x in zip_longest(*aList, fillvalue="."):
a.append(" ".join(str(i) for i in x))
return a
def run(self, **kwargs):
"""Function to evaluate the angular distribution of cos(theta)"""
if self.nproc == 1:
selection = self._selection_serial(
self.universe, self.selection_str)
else:
# not implemented yet
# selection = self._selection_parallel(self.universe,
# self.selection_str,self.nproc)
selection = self._selection_serial(
self.universe, self.selection_str)
self.graph = []
output = self._getHistogram(
self.universe, selection, self.bins, self.axis)
# this is to format the exit of the file
# maybe this output could be improved
listOH = [list(output[0][1]), list(output[0][0])]
listHH = [list(output[1][1]), list(output[1][0])]
listdip = [list(output[2][1]), list(output[2][0])]
self.graph.append(self._hist2column(listOH))
self.graph.append(self._hist2column(listHH))
self.graph.append(self._hist2column(listdip))
def _selection_serial(self, universe, selection_str):
selection = []
for ts in ProgressBar(universe.trajectory, verbose=True,
total=universe.trajectory.n_frames):
selection.append(universe.select_atoms(selection_str))
return selection
class MeanSquareDisplacement(object):
r"""Mean square displacement analysis
Function to evaluate the Mean Square Displacement (MSD_). The MSD gives the
average distance that particles travels. The MSD is given by:
.. math::
\langle\Delta r(t)^2\rangle = 2nDt
where :math:`r(t)` is the position of particle in time :math:`t`,
:math:`\Delta r(t)` is the displacement after time lag :math:`t`,
:math:`n` is the dimensionality, in this case :math:`n=3`,
:math:`D` is the diffusion coefficient and :math:`t` is the time.
.. _MSD: http://en.wikipedia.org/wiki/Mean_squared_displacement
Parameters
----------
universe : Universe
Universe object
select : str
Selection string for water [‘byres name OH2’].
t0 : int
frame where analysis begins
tf : int
frame where analysis ends
dtmax : int
Maximum dt size, `dtmax` < `tf` or it will crash.
.. versionadded:: 0.11.0
.. versionchanged:: 1.0.0
Changed `selection` keyword to `select`
"""
def __init__(self, universe, select, t0, tf, dtmax, nproc=1):
self.universe = universe
self.selection = select
self.t0 = t0
self.tf = tf
self.dtmax = dtmax
self.nproc = nproc
self.timeseries = None
def _repeatedIndex(self, selection, dt, totalFrames):
"""
Indicate the comparation between all the t+dt.
The results is a list of list with all the repeated index per frame
(or time).
- Ex: dt=1, so compare frames (1,2),(2,3),(3,4)...
- Ex: dt=2, so compare frames (1,3),(3,5),(5,7)...
- Ex: dt=3, so compare frames (1,4),(4,7),(7,10)...
"""
rep = []
for i in range(int(round((totalFrames - 1) / float(dt)))):
if (dt * i + dt < totalFrames):
rep.append(self._sameMolecTandDT(
selection, dt * i, (dt * i) + dt))
return rep
def _getOneDeltaPoint(self, universe, repInd, i, t0, dt):
"""
Gives one point to calculate the mean and gets one point of the plot
C_vect vs t.
- Ex: t0=1 and dt=1 so calculate the t0-dt=1-2 interval.
- Ex: t0=5 and dt=3 so calcultate the t0-dt=5-8 interva
i = come from getMeanOnePoint (named j) (int)
"""
valO = 0
n = 0
for j in range(len(repInd[i]) // 3):
begj = 3 * j
universe.trajectory[t0]
# Plus zero is to avoid 0to be equal to 0tp
Ot0 = repInd[i][begj].position + 0
universe.trajectory[t0 + dt]
# Plus zero is to avoid 0to be equal to 0tp
Otp = repInd[i][begj].position + 0
# position oxygen
OVector = Ot0 - Otp
# here it is the difference with
# waterdynamics.WaterOrientationalRelaxation
valO += np.dot(OVector, OVector)
n += 1
# if no water molecules remain in selection, there is nothing to get
# the mean, so n = 0.
return valO/n if n > 0 else 0
def _getMeanOnePoint(self, universe, selection1, selection_str, dt,
totalFrames):
"""
This function gets one point of the plot C_vec vs t. It's uses the
_getOneDeltaPoint() function to calculate the average.
"""
repInd = self._repeatedIndex(selection1, dt, totalFrames)
sumsdt = 0
n = 0.0
sumDeltaO = 0.0
valOList = []
for j in range(totalFrames // dt - 1):
a = self._getOneDeltaPoint(universe, repInd, j, sumsdt, dt)
sumDeltaO += a
valOList.append(a)
sumsdt += dt
n += 1
# if no water molecules remain in selection, there is nothing to get
# the mean, so n = 0.
return sumDeltaO/n if n > 0 else 0
def _sameMolecTandDT(self, selection, t0d, tf):
"""
Compare the molecules in the t0d selection and the t0d+dt selection and
select only the particles that are repeated in both frame. This is to
consider only the molecules that remains in the selection after the dt
time has elapsed. The result is a list with the indexs of the atoms.
"""
a = set(selection[t0d])
b = set(selection[tf])
sort = sorted(list(a.intersection(b)))
return sort
def _selection_serial(self, universe, selection_str):
selection = []
for ts in ProgressBar(universe.trajectory, verbose=True,
total=universe.trajectory.n_frames):
selection.append(universe.select_atoms(selection_str))
return selection
def run(self, **kwargs):
"""Analyze trajectory and produce timeseries"""
# All the selection to an array, this way is faster than selecting
# later.
if self.nproc == 1:
selection_out = self._selection_serial(
self.universe, self.selection)
else:
# parallel not yet implemented
# selection = selection_parallel(universe, selection_str, nproc)
selection_out = self._selection_serial(
self.universe, self.selection)
self.timeseries = []
for dt in list(range(1, self.dtmax + 1)):
output = self._getMeanOnePoint(
self.universe, selection_out, self.selection, dt, self.tf)
self.timeseries.append(output)
class SurvivalProbability(object):
r"""
Survival Probability (SP) gives the probability for a group of particles to remain in a certain region.
The SP is given by:
.. math::
P(\tau) = \frac1T \sum_{t=1}^T \frac{N(t,t+\tau)}{N(t)}
where :math:`T` is the maximum time of simulation, :math:`\tau` is the
timestep, :math:`N(t)` the number of particles at time :math:`t`, and
:math:`N(t, t+\tau)` is the number of particles at every frame from :math:`t` to `\tau`.
Parameters
----------
universe : Universe
Universe object
select : str
Selection string; any selection is allowed. With this selection you
define the region/zone where to analyze, e.g.: "resname SOL and around 5 (resid 10)". See `SP-examples`_.
verbose : Boolean, optional
When True, prints progress and comments to the console.
Notes
-----
Currently :class:`SurvivalProbability` is the only on in
:mod:`MDAnalysis.analysis.waterdynamics` to support an `exclusive`
behaviour (i.e. similar to the current behaviour of :class:`AnalysisBase`
to the `stop` keyword passed to :meth:`SurvivalProbability.run`. Unlike
other :mod:`MDAnalysis.analysis.waterdynamics` final frame definitions
which are `inclusive`.
.. versionadded:: 0.11.0
.. versionchanged:: 1.0.0
Using the MDAnalysis.lib.correlations.py to carry out the intermittency
and autocorrelation calculations.
Changed `selection` keyword to `select`.
Removed support for the deprecated `t0`, `tf`, and `dtmax` keywords.
These should instead be passed to :meth:`SurvivalProbability.run` as
the `start`, `stop`, and `tau_max` keywords respectively.
The `stop` keyword as passed to :meth:`SurvivalProbability.run` has now
changed behaviour and will act in an `exclusive` manner (instead of it's
previous `inclusive` behaviour),
"""
def __init__(self, universe, select, verbose=False):
self.universe = universe
self.selection = select
self.verbose = verbose
def run(self, tau_max=20, start=None, stop=None, step=None, residues=False,
intermittency=0, verbose=False):
"""
Computes and returns the Survival Probability (SP) timeseries
Parameters
----------
start : int, optional
Zero-based index of the first frame to be analysed, Default: None
(first frame).
stop : int, optional
Zero-based index of the last frame to be analysed (exclusive),
Default: None (last frame).
step : int, optional
Jump every `step`-th frame. This is compatible but independant of
the taus used, and it is good to consider using the `step` equal
to `tau_max` to remove the overlap. Note that `step` and `tau_max`
work consistently with intermittency. Default: None
(use every frame).
tau_max : int, optional
Survival probability is calculated for the range
1 <= `tau` <= `tau_max`.
residues : Boolean, optional
If true, the analysis will be carried out on the residues
(.resids) rather than on atom (.ids). A single atom is sufficient
to classify the residue as within the distance.
intermittency : int, optional
The maximum number of consecutive frames for which an atom can
leave but be counted as present if it returns at the next frame.
An intermittency of `0` is equivalent to a continuous survival
probability, which does not allow for the leaving and returning of
atoms. For example, for `intermittency=2`, any given atom may leave
a region of interest for up to two consecutive frames yet be
treated as being present at all frames. The default is continuous
(0).
verbose : Boolean, optional
Print the progress to the console.
Returns
-------
tau_timeseries : list
tau from 1 to `tau_max`. Saved in the field tau_timeseries.
sp_timeseries : list
survival probability for each value of `tau`. Saved in the field
sp_timeseries.
sp_timeseries_data: list
raw datapoints from which the average is taken (sp_timeseries).
Time dependancy and distribution can be extracted.
.. versionchanged:: 1.0.0
To math other analysis methods, the `stop` keyword is now exclusive
rather than inclusive.
"""
start, stop, step = self.universe.trajectory.check_slice_indices(
start,
stop,
step
)
if tau_max > (stop - start):
raise ValueError("Too few frames selected for given tau_max.")
# preload the frames (atom IDs) to a list of sets
self._selected_ids = []
# fixme - to parallise: the section should be rewritten so that this loop only creates a list of indices,
# on which the parallel _single_frame can be applied.
# skip frames that will not be used in order to improve performance
# because AtomGroup.select_atoms is the most expensive part of this calculation
# Example: step 5 and tau 2: LLLSS LLLSS, ... where L = Load, and S = Skip
# Intermittency means that we have to load the extra frames to know if the atom is actually missing.
# Say step=5 and tau=1, intermittency=0: LLSSS LLSSS
# Say step=5 and tau=1, intermittency=1: LLLSL LLLSL
frame_loaded_counter = 0
# only for the first window (frames before t are not used)
frames_per_window = tau_max + 1 + intermittency
# This number will apply after the first windows was loaded
frames_per_window_subsequent = (tau_max + 1) + (2 * intermittency)
num_frames_to_skip = max(step - frames_per_window_subsequent, 0)
frame_no = start
while frame_no < stop: # we have already added 1 to stop, therefore <
if num_frames_to_skip != 0 and frame_loaded_counter == frames_per_window:
logger.info("Skipping the next %d frames:", num_frames_to_skip)
frame_no += num_frames_to_skip
frame_loaded_counter = 0
# Correct the number of frames to be loaded after the first window (which starts at t=0, and
# intermittency does not apply to the frames before)
frames_per_window = frames_per_window_subsequent
continue
# update the frame number
self.universe.trajectory[frame_no]
logger.info("Loading frame: %d", self.universe.trajectory.frame)
atoms = self.universe.select_atoms(self.selection)
# SP of residues or of atoms
ids = atoms.residues.resids if residues else atoms.ids
self._selected_ids.append(set(ids))
frame_no += 1
frame_loaded_counter += 1
# adjust for the frames that were not loaded (step>tau_max + 1),
# and for extra frames that were loaded (intermittency)
window_jump = step - num_frames_to_skip
self._intermittent_selected_ids = correct_intermittency(self._selected_ids, intermittency=intermittency)
tau_timeseries, sp_timeseries, sp_timeseries_data = autocorrelation(self._intermittent_selected_ids,
tau_max, window_jump)
# warn the user if the NaN are found
if all(np.isnan(sp_timeseries[1:])):
logger.warning('NaN Error: Most likely data was not found. Check your atom selections. ')
# user can investigate the distribution and sample size
self.sp_timeseries_data = sp_timeseries_data
self.tau_timeseries = tau_timeseries
self.sp_timeseries = sp_timeseries
return self
| MDAnalysis/mdanalysis | package/MDAnalysis/analysis/waterdynamics.py | Python | gpl-2.0 | 41,156 |
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;
var beerSchema = new Schema({
name: String,
categoryId: ObjectId,
description: String,
stars: Number,
categoryIdString: String
});
var Beer = mongoose.model('Beer', beerSchema);
module.exports = Beer;
| HomeTap/HomeTap | models/beer.js | JavaScript | gpl-2.0 | 318 |
// $Id: DeploymentDiagramRenderer.java 7783 2005-02-20 21:55:19Z linus $
// Copyright (c) 2003-2005 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.uml.diagram.deployment.ui;
import java.util.Collection;
import java.util.Map;
import org.apache.log4j.Logger;
import org.argouml.model.Model;
import org.argouml.uml.diagram.UmlDiagramRenderer;
import org.argouml.uml.diagram.static_structure.ui.CommentEdge;
import org.argouml.uml.diagram.static_structure.ui.FigClass;
import org.argouml.uml.diagram.static_structure.ui.FigComment;
import org.argouml.uml.diagram.static_structure.ui.FigEdgeNote;
import org.argouml.uml.diagram.static_structure.ui.FigInterface;
import org.argouml.uml.diagram.static_structure.ui.FigLink;
import org.argouml.uml.diagram.ui.FigAssociation;
import org.argouml.uml.diagram.ui.FigAssociationClass;
import org.argouml.uml.diagram.ui.FigAssociationEnd;
import org.argouml.uml.diagram.ui.FigDependency;
import org.argouml.uml.diagram.ui.FigGeneralization;
import org.argouml.uml.diagram.ui.FigNodeAssociation;
import org.tigris.gef.base.Layer;
import org.tigris.gef.graph.GraphModel;
import org.tigris.gef.presentation.FigEdge;
import org.tigris.gef.presentation.FigNode;
/**
* This class defines a renderer object for UML Deployment Diagrams.
*
*/
public class DeploymentDiagramRenderer extends UmlDiagramRenderer {
/**
* Logger.
*/
private static final Logger LOG =
Logger.getLogger(DeploymentDiagramRenderer.class);
/**
* Return a Fig that can be used to represent the given node.
*
* @see org.tigris.gef.graph.GraphNodeRenderer#getFigNodeFor(
* org.tigris.gef.graph.GraphModel, org.tigris.gef.base.Layer,
* java.lang.Object, java.util.Map)
*/
public FigNode getFigNodeFor(
GraphModel gm,
Layer lay,
Object node,
Map styleAttributes) {
if (Model.getFacade().isANode(node)) {
return new FigMNode(gm, node);
} else if (Model.getFacade().isAAssociation(node)) {
return new FigNodeAssociation(gm, node);
} else if (Model.getFacade().isANodeInstance(node)) {
return new FigMNodeInstance(gm, node);
} else if (Model.getFacade().isAComponent(node)) {
return new FigComponent(gm, node);
} else if (Model.getFacade().isAComponentInstance(node)) {
return new FigComponentInstance(gm, node);
} else if (Model.getFacade().isAClass(node)) {
return new FigClass(gm, node);
} else if (Model.getFacade().isAInterface(node)) {
return new FigInterface(gm, node);
} else if (Model.getFacade().isAObject(node)) {
return new FigObject(gm, node);
} else if (Model.getFacade().isAComment(node)) {
return new FigComment(gm, node);
}
LOG.debug("TODO: DeploymentDiagramRenderer getFigNodeFor");
return null;
}
/**
* Return a Fig that can be used to represent the given edge.
*
* @see org.tigris.gef.graph.GraphEdgeRenderer#getFigEdgeFor(
* org.tigris.gef.graph.GraphModel, org.tigris.gef.base.Layer,
* java.lang.Object, java.util.Map)
*/
public FigEdge getFigEdgeFor(
GraphModel gm,
Layer lay,
Object edge,
Map styleAttributes) {
if (Model.getFacade().isAAssociationClass(edge)) {
FigAssociationClass ascCFig = new FigAssociationClass(edge, lay);
return ascCFig;
} else if (Model.getFacade().isAAssociation(edge)) {
Object asc = /*(MAssociation)*/ edge;
FigAssociation ascFig = new FigAssociation(asc, lay);
return ascFig;
} else if (Model.getFacade().isAAssociationEnd(edge)) {
FigAssociationEnd asend = new FigAssociationEnd(edge, lay);
Model.getFacade().getAssociation(edge);
FigNode associationFN =
(FigNode) lay.presentationFor(Model
.getFacade().getAssociation(edge));
FigNode classifierFN =
(FigNode) lay.presentationFor(Model
.getFacade().getType(edge));
asend.setSourcePortFig(associationFN);
asend.setSourceFigNode(associationFN);
asend.setDestPortFig(classifierFN);
asend.setDestFigNode(classifierFN);
return asend;
}
if (Model.getFacade().isALink(edge)) {
Object lnk = /*(MLink)*/ edge;
FigLink lnkFig = new FigLink(lnk);
Collection linkEnds = Model.getFacade().getConnections(lnk);
if (linkEnds == null) {
LOG.debug("null linkRoles....");
}
Object[] leArray = linkEnds.toArray();
Object fromEnd = leArray[0];
Object fromInst = Model.getFacade().getInstance(fromEnd);
Object toEnd = leArray[1];
Object toInst = Model.getFacade().getInstance(toEnd);
FigNode fromFN = (FigNode) lay.presentationFor(fromInst);
FigNode toFN = (FigNode) lay.presentationFor(toInst);
lnkFig.setSourcePortFig(fromFN);
lnkFig.setSourceFigNode(fromFN);
lnkFig.setDestPortFig(toFN);
lnkFig.setDestFigNode(toFN);
return lnkFig;
}
if (Model.getFacade().isADependency(edge)) {
Object dep = /*(MDependency)*/ edge;
FigDependency depFig = new FigDependency(dep);
Object supplier =
((Model.getFacade().getSuppliers(dep).toArray())[0]);
Object client =
((Model.getFacade().getClients(dep).toArray())[0]);
FigNode supFN = (FigNode) lay.presentationFor(supplier);
FigNode cliFN = (FigNode) lay.presentationFor(client);
depFig.setSourcePortFig(cliFN);
depFig.setSourceFigNode(cliFN);
depFig.setDestPortFig(supFN);
depFig.setDestFigNode(supFN);
depFig.getFig().setDashed(true);
return depFig;
}
if (Model.getFacade().isAGeneralization(edge)) {
Object gen = /*(MGeneralization)*/ edge;
FigGeneralization genFig = new FigGeneralization(gen, lay);
return genFig;
}
if (edge instanceof CommentEdge) {
return new FigEdgeNote(edge, lay);
}
return null;
}
static final long serialVersionUID = 8002278834226522224L;
}
| carvalhomb/tsmells | sample/argouml/argouml/org/argouml/uml/diagram/deployment/ui/DeploymentDiagramRenderer.java | Java | gpl-2.0 | 7,999 |
#!/usr/bin/env python
# encoding: utf-8
import sys
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--m_number", dest = "m", help = "pleaer enter the m...", type = int)
parser.add_argument("-n", "--n_number", dest = "n", help = "pleaer enter the n...", type = int)
args = parser.parse_args()
print "%d ^ %d = %d" % (args.m, args.n, args.m ** args.n) | gatieme/AderXCoding | language/python/argparse/m-n3.py | Python | gpl-2.0 | 435 |
/***************************************************************************
testqgslayoutcontext.cpp
------------------------
begin : November 2014
copyright : (C) 2014 by Nyall Dawson
email : nyall dot dawson at gmail dot com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgslayoutrendercontext.h"
#include "qgslayoutreportcontext.h"
#include "qgis.h"
#include "qgsfeature.h"
#include "qgsvectorlayer.h"
#include "qgsgeometry.h"
#include "qgsproject.h"
#include "qgslayout.h"
#include "qgsexpressionutils.h"
#include <QObject>
#include "qgstest.h"
#include <QtTest/QSignalSpy>
class TestQgsLayoutContext: public QObject
{
Q_OBJECT
private slots:
void initTestCase();// will be called before the first testfunction is executed.
void cleanupTestCase();// will be called after the last testfunction was executed.
void init();// will be called before each testfunction is executed.
void cleanup();// will be called after every testfunction.
void creation(); //test creation of QgsLayout
void flags(); //test QgsLayout flags
void feature();
void layer();
void dpi();
void renderContextFlags();
void boundingBoxes();
void exportLayer();
void geometry();
void scales();
private:
QString mReport;
};
void TestQgsLayoutContext::initTestCase()
{
mReport = QStringLiteral( "<h1>Layout Context Tests</h1>\n" );
}
void TestQgsLayoutContext::cleanupTestCase()
{
QString myReportFile = QDir::tempPath() + QDir::separator() + "qgistest.html";
QFile myFile( myReportFile );
if ( myFile.open( QIODevice::WriteOnly | QIODevice::Append ) )
{
QTextStream myQTextStream( &myFile );
myQTextStream << mReport;
myFile.close();
}
}
void TestQgsLayoutContext::init()
{
}
void TestQgsLayoutContext::cleanup()
{
}
void TestQgsLayoutContext::creation()
{
QgsLayoutRenderContext *context = new QgsLayoutRenderContext( nullptr );
QVERIFY( context );
delete context;
}
void TestQgsLayoutContext::flags()
{
QgsLayoutRenderContext context( nullptr );
QSignalSpy spyFlagsChanged( &context, &QgsLayoutRenderContext::flagsChanged );
//test getting and setting flags
context.setFlags( QgsLayoutRenderContext::Flags( QgsLayoutRenderContext::FlagAntialiasing | QgsLayoutRenderContext::FlagUseAdvancedEffects ) );
// default flags, so should be no signal
QCOMPARE( spyFlagsChanged.count(), 0 );
QVERIFY( context.flags() == ( QgsLayoutRenderContext::FlagAntialiasing | QgsLayoutRenderContext::FlagUseAdvancedEffects ) );
QVERIFY( context.testFlag( QgsLayoutRenderContext::FlagAntialiasing ) );
QVERIFY( context.testFlag( QgsLayoutRenderContext::FlagUseAdvancedEffects ) );
QVERIFY( ! context.testFlag( QgsLayoutRenderContext::FlagDebug ) );
context.setFlag( QgsLayoutRenderContext::FlagDebug );
QCOMPARE( spyFlagsChanged.count(), 1 );
QVERIFY( context.testFlag( QgsLayoutRenderContext::FlagDebug ) );
context.setFlag( QgsLayoutRenderContext::FlagDebug, false );
QCOMPARE( spyFlagsChanged.count(), 2 );
QVERIFY( ! context.testFlag( QgsLayoutRenderContext::FlagDebug ) );
context.setFlag( QgsLayoutRenderContext::FlagDebug, false ); //no change
QCOMPARE( spyFlagsChanged.count(), 2 );
context.setFlags( QgsLayoutRenderContext::FlagDebug );
QCOMPARE( spyFlagsChanged.count(), 3 );
}
void TestQgsLayoutContext::feature()
{
QgsLayoutReportContext context( nullptr );
//test removing feature
context.setFeature( QgsFeature() );
QVERIFY( !context.feature().isValid() );
//test setting/getting feature
QgsFeature testFeature;
testFeature.initAttributes( 1 );
testFeature.setAttribute( 0, "Test" );
context.setFeature( testFeature );
QCOMPARE( context.feature().attribute( 0 ), testFeature.attribute( 0 ) );
}
void TestQgsLayoutContext::layer()
{
QgsLayoutReportContext context( nullptr );
//test clearing layer
context.setLayer( nullptr );
QVERIFY( !context.layer() );
//test setting/getting layer
QgsVectorLayer *layer = new QgsVectorLayer( QStringLiteral( "Point?field=id_a:integer" ), QStringLiteral( "A" ), QStringLiteral( "memory" ) );
context.setLayer( layer );
QCOMPARE( context.layer(), layer );
//clear layer
context.setLayer( nullptr );
QVERIFY( !context.layer() );
QgsLayout l( QgsProject::instance() );
l.reportContext().setLayer( layer );
//test that expression context created for layout contains report context layer scope
QgsExpressionContext expContext = l.createExpressionContext();
QCOMPARE( QgsExpressionUtils::getVectorLayer( expContext.variable( "layer" ), nullptr ), layer );
delete layer;
}
void TestQgsLayoutContext::dpi()
{
QgsLayoutRenderContext context( nullptr );
QSignalSpy spyDpiChanged( &context, &QgsLayoutRenderContext::dpiChanged );
context.setDpi( 600 );
QCOMPARE( context.dpi(), 600.0 );
QCOMPARE( context.measurementConverter().dpi(), 600.0 );
QCOMPARE( spyDpiChanged.count(), 1 );
context.setDpi( 600 );
QCOMPARE( spyDpiChanged.count(), 1 );
context.setDpi( 6000 );
QCOMPARE( spyDpiChanged.count(), 2 );
}
void TestQgsLayoutContext::renderContextFlags()
{
QgsLayoutRenderContext context( nullptr );
context.setFlags( 0 );
QgsRenderContext::Flags flags = context.renderContextFlags();
QVERIFY( !( flags & QgsRenderContext::Antialiasing ) );
QVERIFY( !( flags & QgsRenderContext::UseAdvancedEffects ) );
QVERIFY( ( flags & QgsRenderContext::ForceVectorOutput ) );
context.setFlag( QgsLayoutRenderContext::FlagAntialiasing );
flags = context.renderContextFlags();
QVERIFY( ( flags & QgsRenderContext::Antialiasing ) );
QVERIFY( !( flags & QgsRenderContext::UseAdvancedEffects ) );
QVERIFY( ( flags & QgsRenderContext::ForceVectorOutput ) );
context.setFlag( QgsLayoutRenderContext::FlagUseAdvancedEffects );
flags = context.renderContextFlags();
QVERIFY( ( flags & QgsRenderContext::Antialiasing ) );
QVERIFY( ( flags & QgsRenderContext::UseAdvancedEffects ) );
QVERIFY( ( flags & QgsRenderContext::ForceVectorOutput ) );
}
void TestQgsLayoutContext::boundingBoxes()
{
QgsLayoutRenderContext context( nullptr );
context.setBoundingBoxesVisible( false );
QVERIFY( !context.boundingBoxesVisible() );
context.setBoundingBoxesVisible( true );
QVERIFY( context.boundingBoxesVisible() );
}
void TestQgsLayoutContext::exportLayer()
{
QgsLayoutRenderContext context( nullptr );
// must default to -1
QCOMPARE( context.currentExportLayer(), -1 );
context.setCurrentExportLayer( 1 );
QCOMPARE( context.currentExportLayer(), 1 );
}
void TestQgsLayoutContext::geometry()
{
QgsProject p;
QgsLayout l( &p );
QgsLayoutReportContext context( &l );
// no feature set
QVERIFY( context.currentGeometry().isNull() );
QVERIFY( context.currentGeometry( QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:3111" ) ) ).isNull() );
// no layer set
QgsFeature f;
f.setGeometry( QgsGeometry::fromWkt( QStringLiteral( "LineString( 144 -38, 145 -39 )" ) ) );
context.setFeature( f );
QCOMPARE( context.currentGeometry().asWkt(), f.geometry().asWkt() );
QVERIFY( context.currentGeometry( QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:3111" ) ) ).isNull() );
//with layer
QgsVectorLayer *layer = new QgsVectorLayer( QStringLiteral( "Point?crs=EPSG:4326&field=id_a:integer" ), QStringLiteral( "A" ), QStringLiteral( "memory" ) );
context.setLayer( layer );
QCOMPARE( context.currentGeometry().asWkt(), f.geometry().asWkt() );
QVERIFY( !context.currentGeometry( QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:3111" ) ) ).isNull() );
QCOMPARE( context.currentGeometry( QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:3111" ) ) ).asWkt( 0 ), QStringLiteral( "LineString (2412169 2388563, 2500000 2277996)" ) );
// should be cached
QCOMPARE( context.currentGeometry( QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:3111" ) ) ).asWkt( 0 ), QStringLiteral( "LineString (2412169 2388563, 2500000 2277996)" ) );
// layer crs
QCOMPARE( context.currentGeometry( layer->crs() ).asWkt(), f.geometry().asWkt() );
// clear cache
QgsFeature f2;
context.setFeature( f2 );
QVERIFY( context.currentGeometry().isNull() );
QVERIFY( context.currentGeometry( QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:3111" ) ) ).isNull() );
delete layer;
}
void TestQgsLayoutContext::scales()
{
QVector< qreal > scales;
scales << 1 << 15 << 5 << 10;
QgsLayoutReportContext context( nullptr );
context.setPredefinedScales( scales );
// should be sorted
QCOMPARE( context.predefinedScales(), QVector< qreal >() << 1 << 5 << 10 << 15 );
}
QGSTEST_MAIN( TestQgsLayoutContext )
#include "testqgslayoutcontext.moc"
| CS-SI/QGIS | tests/src/core/testqgslayoutcontext.cpp | C++ | gpl-2.0 | 9,396 |
var winston = require('winston');
var WinstonFileTransport = winston.transports.File,
WinstonConsoleTransport = winston.transports.Console;
configLevel();
exports = winston;
module.exports = winston;
global.logs = winston;
exports.configLevel = configLevel;
function configLevel(config) {
winston.clear();
config = config || {};
var logLevel = 'debug';
if (config.runMode === 'beta') {
logLevel = 'info';
} else if (config.runMode === 'production') {
logLevel = 'error';
}
winston.add(WinstonConsoleTransport, {
timestamp: true,
colorize: true,
level: logLevel
});
winston.add(WinstonFileTransport, {
name: 'file#out',
timestamp: true,
colorize: true,
filename: 'logs/api_' + process.env.MODE + '_out.log',
maxsize: 10485760,// maxsize: 10mb
maxFiles: 20,
level: logLevel,
json: false
});
winston.add(WinstonFileTransport, {
name: 'file#err',
timestamp: true,
colorize: true,
filename: 'logs/api_' + process.env.MODE + '_err.log',
maxsize: 10485760,// maxsize: 10mb
maxFiles: 20,
level: 'error',
json: false
});
}
| CaptureYou/captureyou-www | general/log.js | JavaScript | gpl-2.0 | 1,136 |
<?php
/**
* File containing the eZDiffEngine class.
*
* @copyright Copyright (C) 1999-2012 eZ Systems AS. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
* @version 2012.5
* @package lib
*/
/*!
\class eZDiffEngine ezdiffengine.php
\abstract
\ingroup eZDiff
\brief eZDiff provides an access point the diff system
The eZDiffEngine class is an abstract class, providing interface and shared code
for the different available DiffEngine.
*/
class eZDiffEngine
{
/*!
This method must be overridden for each implementation of eZDiffEngine. This is the function
which created the object containing the detected changes in the data set.
*/
function createDifferenceObject( $fromData, $toData )
{
}
/// \privatesection
public $DiffMode;
}
?>
| pauletienney/siliconnexion | lib/ezdiff/classes/ezdiffengine.php | PHP | gpl-2.0 | 850 |
/*
* Kexi Report Plugin
* Copyright (C) 2007-2009 by Adam Pigg (adam@piggz.co.uk)
*
* This 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 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "kexisourceselector.h"
#include <kpushbutton.h>
#include <klineedit.h>
#include <QLabel>
#include <klocale.h>
#include <kdebug.h>
#include <QDomElement>
#include "KexiDataSourceComboBox.h"
#include <kexiproject.h>
//#define NO_EXTERNAL_SOURCES
#ifdef NO_EXTERNAL_SOURCES
#ifdef __GNUC__
#warning enable external data sources for 2.3
#else
#pragma WARNING( enable external data sources for 2.3 )
#endif
#endif
class KexiSourceSelector::Private
{
public:
Private()
: kexiDBData(0)
{
}
~Private()
{
delete kexiDBData;
#ifndef KEXI_MOBILE
delete kexiMigrateData;
#endif
}
KexiDB::Connection *conn;
QVBoxLayout *layout;
QComboBox *sourceType;
KexiDataSourceComboBox *internalSource;
KLineEdit *externalSource;
KPushButton *setData;
KexiDBReportData *kexiDBData;
#ifndef KEXI_MOBILE
KexiMigrateReportData *kexiMigrateData;
#endif
};
KexiSourceSelector::KexiSourceSelector(KexiProject* project, QWidget* parent)
: QWidget(parent)
, d(new Private)
{
d->conn = project->dbConnection();
d->kexiDBData = 0;
#ifndef KEXI_MOBILE
d->kexiMigrateData = 0;
#endif
d->layout = new QVBoxLayout(this);
d->sourceType = new QComboBox(this);
d->internalSource = new KexiDataSourceComboBox(this);
d->internalSource->setProject(project);
d->externalSource = new KLineEdit(this);
d->setData = new KPushButton(i18n("Set Data"));
connect(d->setData, SIGNAL(clicked()), this, SLOT(setDataClicked()));
d->sourceType->addItem(i18n("Internal"), QVariant("internal"));
d->sourceType->addItem(i18n("External"), QVariant("external"));
#ifndef NO_EXTERNAL_SOURCES
//!@TODO enable when adding external data
d->layout->addWidget(new QLabel(i18n("Source Type:"), this));
d->layout->addWidget(d->sourceType);
d->layout->addSpacing(10);
#else
d->sourceType->setVisible(false);
d->externalSource->setVisible(false);
#endif
d->layout->addWidget(new QLabel(i18n("Internal Source:"), this));
d->layout->addWidget(d->internalSource);
d->layout->addSpacing(10);
#ifndef NO_EXTERNAL_SOURCES
d->layout->addWidget(new QLabel(i18n("External Source:"), this));
d->layout->addWidget(d->externalSource);
#endif
d->layout->addSpacing(20);
d->layout->addWidget(d->setData);
d->layout->addStretch();
setLayout(d->layout);
}
KexiSourceSelector::~KexiSourceSelector()
{
delete d;
}
void KexiSourceSelector::setConnectionData(QDomElement c)
{
if (c.attribute("type") == "internal") {
d->sourceType->setCurrentIndex(d->sourceType->findData("internal"));
d->internalSource->setCurrentIndex(d->internalSource->findText(c.attribute("source")));
}
if (c.attribute("type") == "external") {
d->sourceType->setCurrentIndex(d->sourceType->findText("external"));
d->externalSource->setText(c.attribute("source"));
}
emit(setData(sourceData()));
}
QDomElement KexiSourceSelector::connectionData()
{
kDebug();
QDomDocument dd;
QDomElement conndata = dd.createElement("connection");
#ifndef NO_EXTERNAL_SOURCES
//!@TODO Make a better gui for selecting external data source
conndata.setAttribute("type", d->sourceType->itemData(d->sourceType->currentIndex()).toString());
if (d->sourceType->itemData(d->sourceType->currentIndex()).toString() == "internal") {
conndata.setAttribute("source", d->internalSource->currentText());
} else {
conndata.setAttribute("source", d->externalSource->text());
}
#else
conndata.setAttribute("type", "internal");
conndata.setAttribute("source", d->internalSource->currentText());
#endif
return conndata;
}
KoReportData* KexiSourceSelector::sourceData()
{
if (d->kexiDBData) {
delete d->kexiDBData;
d->kexiDBData = 0;
}
#ifndef KEXI_MOBILE
if (d->kexiMigrateData) {
delete d->kexiMigrateData;
d->kexiMigrateData = 0;
}
#endif
//!@TODO Fix when enable external data
#ifndef NO_EXTERNAL_SOURCES
if (d->sourceType->itemData(d->sourceType->currentIndex()).toString() == "internal" && d->internalSource->isSelectionValid()) {
d->kexiDBData = new KexiDBReportData(d->internalSource->selectedName(), d->internalSource->selectedPartClass(), d->conn);
return d->kexiDBData;
}
#ifndef KEXI_MOBILE
if (d->sourceType->itemData(d->sourceType->currentIndex()).toString() == "external") {
d->kexiMigrateData = new KexiMigrateReportData(d->externalSource->text());
return d->kexiMigrateData;
}
#endif
#else
if (d->internalSource->isSelectionValid()) {
d->kexiDBData = new KexiDBReportData(d->internalSource->selectedName(), d->conn);
return d->kexiDBData;
}
#endif
return 0;
}
void KexiSourceSelector::setDataClicked()
{
emit(setData(sourceData()));
}
| donniexyz/calligra | kexi/plugins/reports/kexisourceselector.cpp | C++ | gpl-2.0 | 5,620 |
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include "vm_local.h"
#include <stdint.h>
#define PAD(base, alignment) (((base)+(alignment)-1) & ~((alignment)-1))
#define PADLEN(base, alignment) (PAD((base), (alignment)) - (base))
#define PADP(base, alignment) ((void *) PAD((intptr_t) (base), (alignment)))
#define ARRAY_LEN(x) (sizeof(x) / sizeof(*(x)))
//#define DEBUG_VM
#ifdef DEBUG_VM
static char *opnames[256] = {
"OP_UNDEF",
"OP_IGNORE",
"OP_BREAK",
"OP_ENTER",
"OP_LEAVE",
"OP_CALL",
"OP_PUSH",
"OP_POP",
"OP_CONST",
"OP_LOCAL",
"OP_JUMP",
//-------------------
"OP_EQ",
"OP_NE",
"OP_LTI",
"OP_LEI",
"OP_GTI",
"OP_GEI",
"OP_LTU",
"OP_LEU",
"OP_GTU",
"OP_GEU",
"OP_EQF",
"OP_NEF",
"OP_LTF",
"OP_LEF",
"OP_GTF",
"OP_GEF",
//-------------------
"OP_LOAD1",
"OP_LOAD2",
"OP_LOAD4",
"OP_STORE1",
"OP_STORE2",
"OP_STORE4",
"OP_ARG",
"OP_BLOCK_COPY",
//-------------------
"OP_SEX8",
"OP_SEX16",
"OP_NEGI",
"OP_ADD",
"OP_SUB",
"OP_DIVI",
"OP_DIVU",
"OP_MODI",
"OP_MODU",
"OP_MULI",
"OP_MULU",
"OP_BAND",
"OP_BOR",
"OP_BXOR",
"OP_BCOM",
"OP_LSH",
"OP_RSHI",
"OP_RSHU",
"OP_NEGF",
"OP_ADDF",
"OP_SUBF",
"OP_DIVF",
"OP_MULF",
"OP_CVIF",
"OP_CVFI"
};
#endif
#if idppc
//FIXME: these, um... look the same to me
#if defined(__GNUC__)
static ID_INLINE unsigned int loadWord(void *addr) {
unsigned int word;
asm("lwbrx %0,0,%1" : "=r" (word) : "r" (addr));
return word;
}
#else
static ID_INLINE unsigned int __lwbrx(register void *addr,
register int offset) {
register unsigned int word;
asm("lwbrx %0,%2,%1" : "=r" (word) : "r" (addr), "b" (offset));
return word;
}
#define loadWord(addr) __lwbrx(addr,0)
#endif
#else
static ID_INLINE int loadWord(void *addr) {
int word;
memcpy(&word, addr, 4);
return LittleLong(word);
}
#endif
char *VM_Indent( vm_t *vm ) {
static char *string = " ";
if ( vm->callLevel > 20 ) {
return string;
}
return string + 2 * ( 20 - vm->callLevel );
}
void VM_StackTrace( vm_t *vm, int programCounter, int programStack ) {
int count;
count = 0;
do {
Com_Printf( "%s\n", VM_ValueToSymbol( vm, programCounter ) );
programStack = *(int *)&vm->dataBase[programStack+4];
programCounter = *(int *)&vm->dataBase[programStack];
} while ( programCounter != -1 && ++count < 32 );
}
/*
====================
VM_PrepareInterpreter
====================
*/
void VM_PrepareInterpreter( vm_t *vm, vmHeader_t *header ) {
int op;
int byte_pc;
int int_pc;
byte *code;
int instruction;
int *codeBase;
vm->codeBase = (byte *)Hunk_Alloc( vm->codeLength*4, h_high ); // we're now int aligned
// memcpy( vm->codeBase, (byte *)header + header->codeOffset, vm->codeLength );
// we don't need to translate the instructions, but we still need
// to find each instructions starting point for jumps
int_pc = byte_pc = 0;
instruction = 0;
code = (byte *)header + header->codeOffset;
codeBase = (int *)vm->codeBase;
// Copy and expand instructions to words while building instruction table
while ( instruction < header->instructionCount ) {
vm->instructionPointers[ instruction ] = int_pc;
instruction++;
op = (int)code[ byte_pc ];
codeBase[int_pc] = op;
if(byte_pc > header->codeLength)
Com_Error(ERR_DROP, "VM_PrepareInterpreter: pc > header->codeLength");
byte_pc++;
int_pc++;
// these are the only opcodes that aren't a single byte
switch ( op ) {
case OP_ENTER:
case OP_CONST:
case OP_LOCAL:
case OP_LEAVE:
case OP_EQ:
case OP_NE:
case OP_LTI:
case OP_LEI:
case OP_GTI:
case OP_GEI:
case OP_LTU:
case OP_LEU:
case OP_GTU:
case OP_GEU:
case OP_EQF:
case OP_NEF:
case OP_LTF:
case OP_LEF:
case OP_GTF:
case OP_GEF:
case OP_BLOCK_COPY:
codeBase[int_pc] = loadWord(&code[byte_pc]);
byte_pc += 4;
int_pc++;
break;
case OP_ARG:
codeBase[int_pc] = (int)code[byte_pc];
byte_pc++;
int_pc++;
break;
default:
break;
}
}
int_pc = 0;
instruction = 0;
// Now that the code has been expanded to int-sized opcodes, we'll translate instruction index
//into an index into codeBase[], which contains opcodes and operands.
while ( instruction < header->instructionCount ) {
op = codeBase[ int_pc ];
instruction++;
int_pc++;
switch ( op ) {
// These ops need to translate addresses in jumps from instruction index to int index
case OP_EQ:
case OP_NE:
case OP_LTI:
case OP_LEI:
case OP_GTI:
case OP_GEI:
case OP_LTU:
case OP_LEU:
case OP_GTU:
case OP_GEU:
case OP_EQF:
case OP_NEF:
case OP_LTF:
case OP_LEF:
case OP_GTF:
case OP_GEF:
if(codeBase[int_pc] < 0 || codeBase[int_pc] > vm->instructionCount)
Com_Error(ERR_DROP, "VM_PrepareInterpreter: Jump to invalid instruction number");
// codeBase[pc] is the instruction index. Convert that into an offset into
//the int-aligned codeBase[] by the lookup table.
codeBase[int_pc] = vm->instructionPointers[codeBase[int_pc]];
int_pc++;
break;
// These opcodes have an operand that isn't an instruction index
case OP_ENTER:
case OP_CONST:
case OP_LOCAL:
case OP_LEAVE:
case OP_BLOCK_COPY:
case OP_ARG:
int_pc++;
break;
default:
break;
}
}
}
/*
==============
VM_Call
Upon a system call, the stack will look like:
sp+32 parm1
sp+28 parm0
sp+24 return stack
sp+20 return address
sp+16 local1
sp+14 local0
sp+12 arg1
sp+8 arg0
sp+4 return stack
sp return address
An interpreted function will immediately execute
an OP_ENTER instruction, which will subtract space for
locals from sp
==============
*/
#define DEBUGSTR va("%s%i", VM_Indent(vm), opStackOfs)
int VM_CallInterpreted( vm_t *vm, int *args ) {
byte stack[OPSTACK_SIZE + 15];
int *opStack;
uint8_t opStackOfs;
int programCounter;
int programStack;
int stackOnEntry;
byte *image;
int *codeImage;
int v1;
int dataMask;
int arg;
#ifdef DEBUG_VM
vmSymbol_t *profileSymbol;
#endif
// interpret the code
vm->currentlyInterpreting = qtrue;
// we might be called recursively, so this might not be the very top
programStack = stackOnEntry = vm->programStack;
#ifdef DEBUG_VM
profileSymbol = VM_ValueToFunctionSymbol( vm, 0 );
// uncomment this for debugging breakpoints
vm->breakFunction = 0;
#endif
// set up the stack frame
image = vm->dataBase;
codeImage = (int *)vm->codeBase;
dataMask = vm->dataMask;
programCounter = 0;
programStack -= ( 8 + 4 * MAX_VMMAIN_ARGS );
for ( arg = 0; arg < MAX_VMMAIN_ARGS; arg++ )
*(int *)&image[ programStack + 8 + arg * 4 ] = args[ arg ];
*(int *)&image[ programStack + 4 ] = 0; // return stack
*(int *)&image[ programStack ] = -1; // will terminate the loop on return
VM_Debug(0);
// leave a free spot at start of stack so
// that as long as opStack is valid, opStack-1 will
// not corrupt anything
opStack = (int *)PADP(stack, 16);
*opStack = 0xDEADBEEF;
opStackOfs = 0;
// vm_debugLevel=2;
// main interpreter loop, will exit when a LEAVE instruction
// grabs the -1 program counter
#define r2 codeImage[programCounter]
while ( 1 ) {
int opcode, r0, r1;
// unsigned int r2;
nextInstruction:
r0 = opStack[opStackOfs];
r1 = opStack[(uint8_t) (opStackOfs - 1)];
nextInstruction2:
#ifdef DEBUG_VM
if ( (unsigned)programCounter >= vm->codeLength ) {
Com_Error( ERR_DROP, "VM pc out of range" );
return 0;
}
if ( programStack <= vm->stackBottom ) {
Com_Error( ERR_DROP, "VM stack overflow" );
return 0;
}
if ( programStack & 3 ) {
Com_Error( ERR_DROP, "VM program stack misaligned" );
return 0;
}
if ( vm_debugLevel > 1 ) {
Com_Printf( "%s %s\n", DEBUGSTR, opnames[opcode] );
}
profileSymbol->profileCount++;
#endif
opcode = codeImage[ programCounter++ ];
switch ( opcode ) {
#ifdef DEBUG_VM
default:
Com_Error( ERR_DROP, "Bad VM instruction" ); // this should be scanned on load!
return 0;
#endif
case OP_BREAK:
vm->breakCount++;
goto nextInstruction2;
case OP_CONST:
opStackOfs++;
r1 = r0;
r0 = opStack[opStackOfs] = r2;
programCounter += 1;
goto nextInstruction2;
case OP_LOCAL:
opStackOfs++;
r1 = r0;
r0 = opStack[opStackOfs] = r2+programStack;
programCounter += 1;
goto nextInstruction2;
case OP_LOAD4:
#ifdef DEBUG_VM
if(opStack[opStackOfs] & 3)
{
Com_Error( ERR_DROP, "OP_LOAD4 misaligned" );
return 0;
}
#endif
r0 = opStack[opStackOfs] = *(int *) &image[r0 & dataMask & ~3 ];
goto nextInstruction2;
case OP_LOAD2:
r0 = opStack[opStackOfs] = *(unsigned short *)&image[ r0&dataMask&~1 ];
goto nextInstruction2;
case OP_LOAD1:
r0 = opStack[opStackOfs] = image[ r0&dataMask ];
goto nextInstruction2;
case OP_STORE4:
*(int *)&image[ r1&(dataMask & ~3) ] = r0;
opStackOfs -= 2;
goto nextInstruction;
case OP_STORE2:
*(short *)&image[ r1&(dataMask & ~1) ] = r0;
opStackOfs -= 2;
goto nextInstruction;
case OP_STORE1:
image[ r1&dataMask ] = r0;
opStackOfs -= 2;
goto nextInstruction;
case OP_ARG:
// single byte offset from programStack
*(int *)&image[ (codeImage[programCounter] + programStack)&dataMask&~3 ] = r0;
opStackOfs--;
programCounter += 1;
goto nextInstruction;
case OP_BLOCK_COPY:
VM_BlockCopy(r1, r0, r2);
programCounter += 1;
opStackOfs -= 2;
goto nextInstruction;
case OP_CALL:
// save current program counter
*(int *)&image[ programStack ] = programCounter;
// jump to the location on the stack
programCounter = r0;
opStackOfs--;
if ( programCounter < 0 ) {
// system call
int r;
// int temp;
#ifdef DEBUG_VM
int stomped;
if ( vm_debugLevel ) {
Com_Printf( "%s---> systemcall(%i)\n", DEBUGSTR, -1 - programCounter );
}
#endif
// save the stack to allow recursive VM entry
// temp = vm->callLevel;
vm->programStack = programStack - 4;
#ifdef DEBUG_VM
stomped = *(int *)&image[ programStack + 4 ];
#endif
*(int *)&image[ programStack + 4 ] = -1 - programCounter;
//VM_LogSyscalls( (int *)&image[ programStack + 4 ] );
{
// the vm has ints on the stack, we expect
// pointers so we might have to convert it
if (sizeof(intptr_t) != sizeof(int)) {
intptr_t argarr[ MAX_VMSYSCALL_ARGS ];
int *imagePtr = (int *)&image[ programStack ];
int i;
for (i = 0; i < ARRAY_LEN(argarr); ++i) {
argarr[i] = *(++imagePtr);
}
r = vm->systemCall( argarr );
} else {
intptr_t* argptr = (intptr_t *)&image[ programStack + 4 ];
r = vm->systemCall( argptr );
}
}
#ifdef DEBUG_VM
// this is just our stack frame pointer, only needed
// for debugging
*(int *)&image[ programStack + 4 ] = stomped;
#endif
// save return value
opStackOfs++;
opStack[opStackOfs] = r;
programCounter = *(int *)&image[ programStack ];
// vm->callLevel = temp;
#ifdef DEBUG_VM
if ( vm_debugLevel ) {
Com_Printf( "%s<--- %s\n", DEBUGSTR, VM_ValueToSymbol( vm, programCounter ) );
}
#endif
} else if ( (unsigned)programCounter >= vm->instructionCount ) {
Com_Error( ERR_DROP, "VM program counter out of range in OP_CALL" );
return 0;
} else {
programCounter = vm->instructionPointers[ programCounter ];
}
goto nextInstruction;
// push and pop are only needed for discarded or bad function return values
case OP_PUSH:
opStackOfs++;
goto nextInstruction;
case OP_POP:
opStackOfs--;
goto nextInstruction;
case OP_ENTER:
#ifdef DEBUG_VM
profileSymbol = VM_ValueToFunctionSymbol( vm, programCounter );
#endif
// get size of stack frame
v1 = r2;
programCounter += 1;
programStack -= v1;
#ifdef DEBUG_VM
// save old stack frame for debugging traces
*(int *)&image[programStack+4] = programStack + v1;
if ( vm_debugLevel ) {
Com_Printf( "%s---> %s\n", DEBUGSTR, VM_ValueToSymbol( vm, programCounter - 5 ) );
if ( vm->breakFunction && programCounter - 5 == vm->breakFunction ) {
// this is to allow setting breakpoints here in the debugger
vm->breakCount++;
// vm_debugLevel = 2;
// VM_StackTrace( vm, programCounter, programStack );
}
// vm->callLevel++;
}
#endif
goto nextInstruction;
case OP_LEAVE:
// remove our stack frame
v1 = r2;
programStack += v1;
// grab the saved program counter
programCounter = *(int *)&image[ programStack ];
#ifdef DEBUG_VM
profileSymbol = VM_ValueToFunctionSymbol( vm, programCounter );
if ( vm_debugLevel ) {
// vm->callLevel--;
Com_Printf( "%s<--- %s\n", DEBUGSTR, VM_ValueToSymbol( vm, programCounter ) );
}
#endif
// check for leaving the VM
if ( programCounter == -1 ) {
goto done;
} else if ( (unsigned)programCounter >= vm->codeLength ) {
Com_Error( ERR_DROP, "VM program counter out of range in OP_LEAVE" );
return 0;
}
goto nextInstruction;
/*
===================================================================
BRANCHES
===================================================================
*/
case OP_JUMP:
if ( (unsigned)r0 >= vm->instructionCount )
{
Com_Error( ERR_DROP, "VM program counter out of range in OP_JUMP" );
return 0;
}
programCounter = vm->instructionPointers[ r0 ];
opStackOfs--;
goto nextInstruction;
case OP_EQ:
opStackOfs -= 2;
if ( r1 == r0 ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_NE:
opStackOfs -= 2;
if ( r1 != r0 ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_LTI:
opStackOfs -= 2;
if ( r1 < r0 ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_LEI:
opStackOfs -= 2;
if ( r1 <= r0 ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_GTI:
opStackOfs -= 2;
if ( r1 > r0 ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_GEI:
opStackOfs -= 2;
if ( r1 >= r0 ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_LTU:
opStackOfs -= 2;
if ( ((unsigned)r1) < ((unsigned)r0) ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_LEU:
opStackOfs -= 2;
if ( ((unsigned)r1) <= ((unsigned)r0) ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_GTU:
opStackOfs -= 2;
if ( ((unsigned)r1) > ((unsigned)r0) ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_GEU:
opStackOfs -= 2;
if ( ((unsigned)r1) >= ((unsigned)r0) ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_EQF:
opStackOfs -= 2;
if(((float *) opStack)[(uint8_t) (opStackOfs + 1)] == ((float *) opStack)[(uint8_t) (opStackOfs + 2)])
{
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_NEF:
opStackOfs -= 2;
if(((float *) opStack)[(uint8_t) (opStackOfs + 1)] != ((float *) opStack)[(uint8_t) (opStackOfs + 2)])
{
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_LTF:
opStackOfs -= 2;
if(((float *) opStack)[(uint8_t) (opStackOfs + 1)] < ((float *) opStack)[(uint8_t) (opStackOfs + 2)])
{
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_LEF:
opStackOfs -= 2;
if(((float *) opStack)[(uint8_t) ((uint8_t) (opStackOfs + 1))] <= ((float *) opStack)[(uint8_t) ((uint8_t) (opStackOfs + 2))])
{
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_GTF:
opStackOfs -= 2;
if(((float *) opStack)[(uint8_t) (opStackOfs + 1)] > ((float *) opStack)[(uint8_t) (opStackOfs + 2)])
{
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_GEF:
opStackOfs -= 2;
if(((float *) opStack)[(uint8_t) (opStackOfs + 1)] >= ((float *) opStack)[(uint8_t) (opStackOfs + 2)])
{
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
//===================================================================
case OP_NEGI:
opStack[opStackOfs] = -r0;
goto nextInstruction;
case OP_ADD:
opStackOfs--;
opStack[opStackOfs] = r1 + r0;
goto nextInstruction;
case OP_SUB:
opStackOfs--;
opStack[opStackOfs] = r1 - r0;
goto nextInstruction;
case OP_DIVI:
opStackOfs--;
opStack[opStackOfs] = r1 / r0;
goto nextInstruction;
case OP_DIVU:
opStackOfs--;
opStack[opStackOfs] = ((unsigned) r1) / ((unsigned) r0);
goto nextInstruction;
case OP_MODI:
opStackOfs--;
opStack[opStackOfs] = r1 % r0;
goto nextInstruction;
case OP_MODU:
opStackOfs--;
opStack[opStackOfs] = ((unsigned) r1) % ((unsigned) r0);
goto nextInstruction;
case OP_MULI:
opStackOfs--;
opStack[opStackOfs] = r1 * r0;
goto nextInstruction;
case OP_MULU:
opStackOfs--;
opStack[opStackOfs] = ((unsigned) r1) * ((unsigned) r0);
goto nextInstruction;
case OP_BAND:
opStackOfs--;
opStack[opStackOfs] = ((unsigned) r1) & ((unsigned) r0);
goto nextInstruction;
case OP_BOR:
opStackOfs--;
opStack[opStackOfs] = ((unsigned) r1) | ((unsigned) r0);
goto nextInstruction;
case OP_BXOR:
opStackOfs--;
opStack[opStackOfs] = ((unsigned) r1) ^ ((unsigned) r0);
goto nextInstruction;
case OP_BCOM:
opStack[opStackOfs] = ~((unsigned) r0);
goto nextInstruction;
case OP_LSH:
opStackOfs--;
opStack[opStackOfs] = r1 << r0;
goto nextInstruction;
case OP_RSHI:
opStackOfs--;
opStack[opStackOfs] = r1 >> r0;
goto nextInstruction;
case OP_RSHU:
opStackOfs--;
opStack[opStackOfs] = ((unsigned) r1) >> r0;
goto nextInstruction;
case OP_NEGF:
((float *) opStack)[opStackOfs] = -((float *) opStack)[opStackOfs];
goto nextInstruction;
case OP_ADDF:
opStackOfs--;
((float *) opStack)[opStackOfs] = ((float *) opStack)[opStackOfs] + ((float *) opStack)[(uint8_t) (opStackOfs + 1)];
goto nextInstruction;
case OP_SUBF:
opStackOfs--;
((float *) opStack)[opStackOfs] = ((float *) opStack)[opStackOfs] - ((float *) opStack)[(uint8_t) (opStackOfs + 1)];
goto nextInstruction;
case OP_DIVF:
opStackOfs--;
((float *) opStack)[opStackOfs] = ((float *) opStack)[opStackOfs] / ((float *) opStack)[(uint8_t) (opStackOfs + 1)];
goto nextInstruction;
case OP_MULF:
opStackOfs--;
((float *) opStack)[opStackOfs] = ((float *) opStack)[opStackOfs] * ((float *) opStack)[(uint8_t) (opStackOfs + 1)];
goto nextInstruction;
case OP_CVIF:
((float *) opStack)[opStackOfs] = (float) opStack[opStackOfs];
goto nextInstruction;
case OP_CVFI:
opStack[opStackOfs] = Q_ftol(((float *) opStack)[opStackOfs]);
goto nextInstruction;
case OP_SEX8:
opStack[opStackOfs] = (signed char) opStack[opStackOfs];
goto nextInstruction;
case OP_SEX16:
opStack[opStackOfs] = (short) opStack[opStackOfs];
goto nextInstruction;
}
}
done:
vm->currentlyInterpreting = qfalse;
if (opStackOfs != 1 || *opStack != 0xDEADBEEF)
Com_Error(ERR_DROP, "Interpreter error: opStack[0] = %X, opStackOfs = %d", opStack[0], opStackOfs);
vm->programStack = stackOnEntry;
// return the result
return opStack[opStackOfs];
}
| ensiform/jk2mv | src/qcommon/vm_interpreted.cpp | C++ | gpl-2.0 | 21,435 |
# F3AT - Flumotion Asynchronous Autonomous Agent Toolkit
# Copyright (C) 2010,2011 Flumotion Services, S.A.
# 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# See "LICENSE.GPL" in the source distribution for more information.
# Headers in this file shall remain intact.
# -*- coding: utf-8 -*-
# -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
import uuid
import time
from twisted.internet import defer
from zope.interface import implements
from feat.agents.base import descriptor, requester, replier, replay
from feat.agencies import message, retrying
from feat.interface.agency import ExecMode
from feat.database.interface import NotFoundError
from feat.interface.requests import RequestState
from feat.interface.protocols import ProtocolFailed, IInterest, InterestType
from feat.test import common, dummies #don't remove dummies, it defines adapter
class DummyRequester(requester.BaseRequester):
protocol_id = 'dummy-request'
timeout = 2
@replay.entry_point
def initiate(self, state, argument):
state._got_response = False
msg = message.RequestMessage()
msg.payload = argument
state.medium.request(msg)
@replay.entry_point
def got_reply(self, state, message):
state._got_response = True
return message.payload
@replay.immutable
def _get_medium(self, state):
self.log(state)
return state.medium
@replay.immutable
def got_response(self, state):
return state._got_response
class DummyReplier(replier.BaseReplier):
protocol_id = 'dummy-request'
@replay.entry_point
def requested(self, state, request):
state.agent.got_payload = request.payload
state.medium.reply(message.ResponseMessage(payload=request.payload))
class DummyInterest(object):
implements(IInterest)
def __init__(self):
self.protocol_type = "Contract"
self.protocol_id = "some-contract"
self.interest_type = InterestType.public
self.initiator = message.Announcement
class TestDependencies(common.TestCase, common.AgencyTestHelper):
@defer.inlineCallbacks
def setUp(self):
yield common.TestCase.setUp(self)
yield common.AgencyTestHelper.setUp(self)
def testGettingModes(self):
self.assertEqual(ExecMode.test, self.agency.get_mode('unknown'))
self.agency.set_mode('something', ExecMode.production)
self.assertEqual(ExecMode.production,
self.agency.get_mode('something'))
self.agency._set_default_mode(ExecMode.production)
self.assertEqual(ExecMode.production,
self.agency.get_mode('unknown'))
class TestAgencyAgent(common.TestCase, common.AgencyTestHelper):
timeout = 3
protocol_type = 'Request'
protocol_id = 'dummy-request'
@defer.inlineCallbacks
def setUp(self):
yield common.TestCase.setUp(self)
yield common.AgencyTestHelper.setUp(self)
desc = yield self.doc_factory(descriptor.Descriptor)
self.agent = yield self.agency.start_agent(desc)
self.assertEqual(1, self.agent.get_descriptor().instance_id)
self.endpoint, self.queue = self.setup_endpoint()
def testJoinShard(self):
messaging = self.agent._messaging
self.assertTrue(len(messaging.get_bindings('lobby')) > 1)
self.agent.leave_shard('lobby')
self.assertEqual(0, len(messaging.get_bindings('lobby')))
@defer.inlineCallbacks
def testSwitchingShardRebinding(self):
messaging = self.agent._messaging
initial = len(messaging.get_bindings('lobby'))
interest = DummyInterest()
self.agent.register_interest(interest)
self.assertEqual(initial + 1, len(messaging.get_bindings('lobby')))
yield self.agent.leave_shard('lobby')
self.assertEqual(0, len(messaging.get_bindings('lobby')))
yield self.agent.join_shard('new shard')
self.assertEqual(initial + 1,
len(messaging.get_bindings('new shard')))
self.assertEqual(0, len(messaging.get_bindings('lobby')))
@defer.inlineCallbacks
def testUpdateDocument(self):
desc = self.agent.get_descriptor()
self.assertIsInstance(desc, descriptor.Descriptor)
def update_fun(desc):
desc.shard = 'changed'
yield self.agent.update_descriptor(update_fun)
self.assertEqual('changed', self.agent._descriptor.shard)
def testRegisterTwice(self):
self.assertTrue(self.agent.register_interest(DummyReplier))
self.failIf(self.agent.register_interest(DummyReplier))
def testRegisteringAndRevokeReplier(self):
self.agent.register_interest(DummyReplier)
self.assertTrue('Request' in self.agent._interests)
self.assertTrue('dummy-request' in self.agent._interests['Request'])
self.agent.revoke_interest(DummyReplier)
self.assertFalse('dummy-request' in self.agent._interests['Request'])
#calling once again nothing bad should happened
req = self.agent.revoke_interest(DummyReplier)
self.assertFalse(req)
def tesGetingRequestWithoutInterest(self):
'''Current implementation just ignores such events. Update this test
in case we decide to do sth else'''
key = (self.agent.get_descriptor()).doc_id
msg = message.RequestMessage()
return self.recv_msg(msg, self.endpoint, key)
@defer.inlineCallbacks
def testTerminatingTheAgent(self):
# make him have running retrying request (covers all the hard cases)
d = self.cb_after(None, self.agent, 'initiate_protocol')
factory = retrying.RetryingProtocolFactory(DummyRequester)
self.agent.initiate_protocol(factory, self.endpoint, None)
yield d
yield self.agent._terminate()
self.assertCalled(self.agent.agent, 'shutdown')
doc_id = self.agent._descriptor.doc_id
d = self.agency._database.get_connection().get_document(doc_id)
self.assertFailure(d, NotFoundError)
yield d
self.assertEqual(0, len(self.agency._agents))
@common.attr(timescale=0.05)
class TestRequests(common.TestCase, common.AgencyTestHelper):
timeout = 3
protocol_type = 'Request'
protocol_id = 'dummy-request'
@defer.inlineCallbacks
def setUp(self):
yield common.TestCase.setUp(self)
yield common.AgencyTestHelper.setUp(self)
desc = yield self.doc_factory(descriptor.Descriptor)
self.agent = yield self.agency.start_agent(desc)
self.endpoint, self.queue = self.setup_endpoint()
def testRequester(self):
d = self.queue.get()
payload = 5
self.requester =\
self.agent.initiate_protocol(DummyRequester,
self.endpoint, payload)
self.medium = self.requester._get_medium()
self.finished = self.requester.notify_finish()
self.assertIsInstance(self.finished, defer.Deferred)
def assertsOnMessage(message):
desc = self.agent.get_descriptor()
self.assertEqual(desc.shard, \
message.reply_to.route)
self.assertEqual(desc.doc_id, \
message.reply_to.key)
self.assertEqual('Request', message.protocol_type)
self.assertEqual('dummy-request', message.protocol_id)
self.assertEqual(payload, message.payload)
self.assertTrue(message.expiration_time is not None)
guid = message.sender_id
self.assertEqual(guid, str(guid))
self.assertEqual(RequestState.requested, self.medium.state)
return guid, message
d.addCallback(assertsOnMessage)
def assertsOnAgency((guid, msg, )):
self.log('%r', self.agent._protocols.keys())
self.assertTrue(guid in self.agent._protocols.keys())
protocol = self.agent._protocols[guid]
self.assertEqual('AgencyRequester', protocol.__class__.__name__)
return guid, msg
d.addCallback(assertsOnAgency)
def mimicReceivingResponse((guid, msg, )):
response = message.ResponseMessage()
self.reply(response, self.endpoint, msg)
return guid
d.addCallback(mimicReceivingResponse)
d.addCallback(lambda _: self.finished)
def assertGotResponseAndTerminated(guid):
self.assertFalse(guid in self.agent._protocols.keys())
self.assertTrue(self.requester.got_response)
d.addCallback(assertGotResponseAndTerminated)
return d
@common.attr(timeout=10)
@defer.inlineCallbacks
def testRequestTimeout(self):
payload = 5
self.requester =\
yield self.agent.initiate_protocol(DummyRequester,
self.endpoint, payload)
self.medium = self.requester._get_medium()
self.finished = self.requester.notify_finish()
self.assertFailure(self.finished, ProtocolFailed)
yield self.finished
guid = self.medium.guid
self.assertFalse(guid in self.agent._protocols.keys())
self.assertFalse(self.requester.got_response())
self.assertEqual(RequestState.closed, self.medium.state)
msg = yield self.queue.get()
self.assertIsInstance(msg, message.RequestMessage)
def testReplierReplies(self):
self.agent.register_interest(DummyReplier)
key = (self.agent.get_descriptor()).doc_id
req = self._build_req_msg(self.endpoint)
d = self.recv_msg(req, self.endpoint, key)
d.addCallback(lambda _: self.queue.get())
def assert_on_msg(msg):
self.assertEqual('dummy-request', msg.protocol_id)
d.addCallback(assert_on_msg)
return d
def testNotProcessingExpiredRequests(self):
self.agent.register_interest(DummyReplier)
self.agent.agent.got_payload = False
key = (self.agent.get_descriptor()).doc_id
# define false sender, he will get the response later
req = self._build_req_msg(self.endpoint)
expiration_time = time.time() - 1
d = self.recv_msg(req, self.endpoint, key, expiration_time)
def asserts_after_procesing(return_value):
self.log(return_value)
self.assertFalse(return_value)
self.assertEqual(False, self.agent.agent.got_payload)
d.addCallback(asserts_after_procesing)
return d
@defer.inlineCallbacks
def testTwoAgentsTalking(self):
receiver = self.agent
desc = yield self.doc_factory(descriptor.Descriptor)
sender = yield self.agency.start_agent(desc)
receiver.register_interest(DummyReplier)
requester = sender.initiate_protocol(DummyRequester, receiver, 1)
r = yield requester.notify_finish()
self.assertEqual(1, r)
self.assertTrue(requester.got_response)
self.assertEqual(1, receiver.agent.got_payload)
def _build_req_msg(self, recp):
r = message.RequestMessage()
r.guid = str(uuid.uuid1())
r.traversal_id = str(uuid.uuid1())
r.payload = 10
return r
| f3at/feat | src/feat/test/test_agencies_emu_agency.py | Python | gpl-2.0 | 11,954 |
<?php
if ( ! class_exists( 'Redux_Validation_not_empty' ) ) {
class Redux_Validation_not_empty {
/**
* Field Constructor.
* Required - must call the parent constructor, then assign field and value to vars, and obviously call the render field function
*
* @since ReduxFramework 1.0.0
*/
function __construct( $parent, $field, $value, $current ) {
$this->parent = $parent;
$this->field = $field;
$this->field['msg'] = ( isset( $this->field['msg'] ) ) ? $this->field['msg'] : __( 'This field cannot be empty. Please provide a value.', 'helpme' );
$this->value = $value;
$this->current = $current;
$this->validate();
} //function
/**
* Field Render Function.
* Takes the vars and outputs the HTML for the field in the settings
*
* @since ReduxFramework 1.0.0
*/
function validate() {
if ( ! isset( $this->value ) || empty( $this->value ) ) {
$this->value = ( isset( $this->current ) ) ? $this->current : '';
$this->error = $this->field;
}
} //function
} //class
} | wanmendoza/fundecan | wp-content/themes/helpme/includes/framework/ReduxCore/inc/validation/not_empty/validation_not_empty.php | PHP | gpl-2.0 | 1,384 |
package iptat.util;
public interface Observer {
public void update(int state);
}
| AlexandruGhergut/IPTAT | src/iptat/util/Observer.java | Java | gpl-2.0 | 83 |
/*
* Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Battlefield.h"
#include "BattlefieldMgr.h"
#include "Battleground.h"
#include "BattlegroundPackets.h"
#include "CellImpl.h"
#include "CreatureTextMgr.h"
#include "DB2Stores.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "Group.h"
#include "GroupMgr.h"
#include "Log.h"
#include "Map.h"
#include "MapManager.h"
#include "MiscPackets.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "WorldSession.h"
#include "WorldStatePackets.h"
#include <G3D/g3dmath.h>
Battlefield::Battlefield()
{
_scriptType = ZONE_SCRIPT_TYPE_BATTLEFIELD;
m_Timer = 0;
m_IsEnabled = true;
m_isActive = false;
m_DefenderTeam = TEAM_NEUTRAL;
m_TypeId = 0;
m_BattleId = 0;
m_ZoneId = 0;
m_Map = nullptr;
m_MapId = 0;
m_MaxPlayer = 0;
m_MinPlayer = 0;
m_MinLevel = 0;
m_BattleTime = 0;
m_NoWarBattleTime = 0;
m_RestartAfterCrash = 0;
m_TimeForAcceptInvite = 20;
m_uiKickDontAcceptTimer = 1000;
m_uiKickAfkPlayersTimer = 1000;
m_LastResurrectTimer = 30 * IN_MILLISECONDS;
m_StartGroupingTimer = 0;
m_StartGrouping = false;
}
Battlefield::~Battlefield()
{
for (BfCapturePointMap::iterator itr = m_capturePoints.begin(); itr != m_capturePoints.end(); ++itr)
delete itr->second;
for (GraveyardVect::const_iterator itr = m_GraveyardList.begin(); itr != m_GraveyardList.end(); ++itr)
delete *itr;
}
// Called when a player enters the zone
void Battlefield::HandlePlayerEnterZone(Player* player, Area* /*zone*/)
{
// If battle is started,
// If not full of players > invite player to join the war
// If full of players > announce to player that BF is full and kick him after a few second if he desn't leave
if (IsWarTime())
{
if (m_PlayersInWar[player->GetTeamId()].size() + m_InvitedPlayers[player->GetTeamId()].size() < m_MaxPlayer) // Vacant spaces
InvitePlayerToWar(player);
else // No more vacant places
{
/// @todo Send a packet to announce it to player
m_PlayersWillBeKick[player->GetTeamId()][player->GetGUID()] = time(nullptr) + 10;
InvitePlayerToQueue(player);
}
}
else
{
// If time left is < 15 minutes invite player to join queue
if (m_Timer <= m_StartGroupingTimer)
InvitePlayerToQueue(player);
}
// Add player in the list of player in zone
m_players[player->GetTeamId()].insert(player->GetGUID());
OnPlayerEnterZone(player);
}
// Called when a player leave the zone
void Battlefield::HandlePlayerLeaveZone(Player* player, Area* /*zone*/)
{
if (IsWarTime())
{
// If the player is participating to the battle
if (m_PlayersInWar[player->GetTeamId()].find(player->GetGUID()) != m_PlayersInWar[player->GetTeamId()].end())
{
m_PlayersInWar[player->GetTeamId()].erase(player->GetGUID());
player->GetSession()->SendBfLeaveMessage(GetQueueId(), GetState(), player->GetZoneId() == GetZoneId());
if (Group* group = player->GetGroup()) // Remove the player from the raid group
group->RemoveMember(player->GetGUID());
OnPlayerLeaveWar(player);
}
}
for (BfCapturePointMap::iterator itr = m_capturePoints.begin(); itr != m_capturePoints.end(); ++itr)
itr->second->HandlePlayerLeave(player);
m_InvitedPlayers[player->GetTeamId()].erase(player->GetGUID());
m_PlayersWillBeKick[player->GetTeamId()].erase(player->GetGUID());
m_players[player->GetTeamId()].erase(player->GetGUID());
SendRemoveWorldStates(player);
RemovePlayerFromResurrectQueue(player->GetGUID());
OnPlayerLeaveZone(player);
}
bool Battlefield::Update(uint32 diff)
{
if (m_Timer <= diff)
{
// Battlefield ends on time
if (IsWarTime())
EndBattle(true);
else // Time to start a new battle!
StartBattle();
}
else
m_Timer -= diff;
// Invite players a few minutes before the battle's beginning
if (!IsWarTime() && !m_StartGrouping && m_Timer <= m_StartGroupingTimer)
{
m_StartGrouping = true;
InvitePlayersInZoneToQueue();
OnStartGrouping();
}
bool objective_changed = false;
if (IsWarTime())
{
if (m_uiKickAfkPlayersTimer <= diff)
{
m_uiKickAfkPlayersTimer = 1000;
KickAfkPlayers();
}
else
m_uiKickAfkPlayersTimer -= diff;
// Kick players who chose not to accept invitation to the battle
if (m_uiKickDontAcceptTimer <= diff)
{
time_t now = time(nullptr);
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
for (PlayerTimerMap::iterator itr = m_InvitedPlayers[team].begin(); itr != m_InvitedPlayers[team].end(); ++itr)
if (itr->second <= now)
KickPlayerFromBattlefield(itr->first);
InvitePlayersInZoneToWar();
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
for (PlayerTimerMap::iterator itr = m_PlayersWillBeKick[team].begin(); itr != m_PlayersWillBeKick[team].end(); ++itr)
if (itr->second <= now)
KickPlayerFromBattlefield(itr->first);
m_uiKickDontAcceptTimer = 1000;
}
else
m_uiKickDontAcceptTimer -= diff;
for (BfCapturePointMap::iterator itr = m_capturePoints.begin(); itr != m_capturePoints.end(); ++itr)
if (itr->second->Update(diff))
objective_changed = true;
}
if (m_LastResurrectTimer <= diff)
{
for (uint8 i = 0; i < m_GraveyardList.size(); i++)
if (GetGraveyardById(i))
m_GraveyardList[i]->Resurrect();
m_LastResurrectTimer = RESURRECTION_INTERVAL;
}
else
m_LastResurrectTimer -= diff;
return objective_changed;
}
void Battlefield::InvitePlayersInZoneToQueue()
{
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
for (auto itr = m_players[team].begin(); itr != m_players[team].end(); ++itr)
if (Player* player = ObjectAccessor::FindPlayer(*itr))
InvitePlayerToQueue(player);
}
void Battlefield::InvitePlayerToQueue(Player* player)
{
if (m_PlayersInQueue[player->GetTeamId()].count(player->GetGUID()))
return;
if (m_PlayersInQueue[player->GetTeamId()].size() <= m_MinPlayer || m_PlayersInQueue[GetOtherTeam(player->GetTeamId())].size() >= m_MinPlayer)
player->GetSession()->SendBfInvitePlayerToQueue(GetQueueId(), GetState());
}
void Battlefield::InvitePlayersInQueueToWar()
{
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
{
for (auto itr = m_PlayersInQueue[team].begin(); itr != m_PlayersInQueue[team].end(); ++itr)
{
if (Player* player = ObjectAccessor::FindPlayer(*itr))
{
if (m_PlayersInWar[player->GetTeamId()].size() + m_InvitedPlayers[player->GetTeamId()].size() < m_MaxPlayer)
InvitePlayerToWar(player);
else
{
//Full
}
}
}
m_PlayersInQueue[team].clear();
}
}
void Battlefield::InvitePlayersInZoneToWar()
{
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
{
for (auto itr = m_players[team].begin(); itr != m_players[team].end(); ++itr)
{
if (Player* player = ObjectAccessor::FindPlayer(*itr))
{
if (m_PlayersInWar[player->GetTeamId()].count(player->GetGUID()) || m_InvitedPlayers[player->GetTeamId()].count(player->GetGUID()))
continue;
if (m_PlayersInWar[player->GetTeamId()].size() + m_InvitedPlayers[player->GetTeamId()].size() < m_MaxPlayer)
InvitePlayerToWar(player);
else // Battlefield is full of players
m_PlayersWillBeKick[player->GetTeamId()][player->GetGUID()] = time(nullptr) + 10;
}
}
}
}
uint64 Battlefield::GetQueueId() const
{
return MAKE_PAIR64(m_BattleId | 0x20000, 0x1F100000);
}
void Battlefield::InvitePlayerToWar(Player* player)
{
if (!player)
return;
/// @todo needed ?
if (player->IsInFlight())
return;
if (player->InArena() || player->GetBattleground())
{
m_PlayersInQueue[player->GetTeamId()].erase(player->GetGUID());
return;
}
// If the player does not match minimal level requirements for the battlefield, kick him
if (player->getLevel() < m_MinLevel)
{
if (m_PlayersWillBeKick[player->GetTeamId()].count(player->GetGUID()) == 0)
m_PlayersWillBeKick[player->GetTeamId()][player->GetGUID()] = time(nullptr) + 10;
return;
}
// Check if player is not already in war
if (m_PlayersInWar[player->GetTeamId()].count(player->GetGUID()) || m_InvitedPlayers[player->GetTeamId()].count(player->GetGUID()))
return;
m_PlayersWillBeKick[player->GetTeamId()].erase(player->GetGUID());
m_InvitedPlayers[player->GetTeamId()][player->GetGUID()] = time(nullptr) + m_TimeForAcceptInvite;
player->GetSession()->SendBfInvitePlayerToWar(GetQueueId(), m_ZoneId, m_TimeForAcceptInvite);
}
void Battlefield::InitStalker(uint32 entry, Position const& pos)
{
if (Creature* creature = SpawnCreature(entry, pos))
StalkerGuid = creature->GetGUID();
else
TC_LOG_ERROR("bg.battlefield", "Battlefield::InitStalker: Could not spawn Stalker (Creature entry %u), zone messages will be unavailable!", entry);
}
void Battlefield::KickAfkPlayers()
{
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
for (auto itr = m_PlayersInWar[team].begin(); itr != m_PlayersInWar[team].end(); ++itr)
if (Player* player = ObjectAccessor::FindPlayer(*itr))
if (player->isAFK())
KickPlayerFromBattlefield(*itr);
}
void Battlefield::KickPlayerFromBattlefield(ObjectGuid guid)
{
if (Player* player = ObjectAccessor::FindPlayer(guid))
if (player->GetZoneId() == GetZoneId())
player->TeleportTo(KickPosition);
}
void Battlefield::StartBattle()
{
if (m_isActive)
return;
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
{
m_PlayersInWar[team].clear();
m_Groups[team].clear();
}
m_Timer = m_BattleTime;
m_isActive = true;
InvitePlayersInZoneToWar();
InvitePlayersInQueueToWar();
OnBattleStart();
}
void Battlefield::EndBattle(bool endByTimer)
{
if (!m_isActive)
return;
m_isActive = false;
m_StartGrouping = false;
if (!endByTimer)
SetDefenderTeam(GetAttackerTeam());
OnBattleEnd(endByTimer);
// Reset battlefield timer
m_Timer = m_NoWarBattleTime;
SendInitWorldStatesToAll();
}
void Battlefield::DoPlaySoundToAll(uint32 soundID)
{
BroadcastPacketToWar(WorldPackets::Misc::PlaySound(ObjectGuid::Empty, soundID).Write());
}
bool Battlefield::HasPlayer(Player* player) const
{
return m_players[player->GetTeamId()].find(player->GetGUID()) != m_players[player->GetTeamId()].end();
}
// Called in WorldSession::HandleBfQueueInviteResponse
void Battlefield::PlayerAcceptInviteToQueue(Player* player)
{
// Add player in queue
m_PlayersInQueue[player->GetTeamId()].insert(player->GetGUID());
// Send notification
player->GetSession()->SendBfQueueInviteResponse(GetQueueId(), m_ZoneId, GetState());
}
// Called in WorldSession::HandleBfExitRequest
void Battlefield::AskToLeaveQueue(Player* player)
{
// Remove player from queue
m_PlayersInQueue[player->GetTeamId()].erase(player->GetGUID());
}
// Called in WorldSession::HandleHearthAndResurrect
void Battlefield::PlayerAskToLeave(Player* player)
{
// Player leaving Wintergrasp, teleport to Dalaran.
// ToDo: confirm teleport destination.
player->TeleportTo(571, 5804.1499f, 624.7710f, 647.7670f, 1.6400f);
}
// Called in WorldSession::HandleBfEntryInviteResponse
void Battlefield::PlayerAcceptInviteToWar(Player* player)
{
if (!IsWarTime())
return;
if (AddOrSetPlayerToCorrectBfGroup(player))
{
player->GetSession()->SendBfEntered(GetQueueId(), player->GetZoneId() != GetZoneId(), player->GetTeamId() == GetAttackerTeam());
m_PlayersInWar[player->GetTeamId()].insert(player->GetGUID());
m_InvitedPlayers[player->GetTeamId()].erase(player->GetGUID());
if (player->isAFK())
player->ToggleAFK();
OnPlayerJoinWar(player); //for scripting
}
}
void Battlefield::TeamCastSpell(TeamId team, int32 spellId)
{
if (spellId > 0)
{
for (auto itr = m_PlayersInWar[team].begin(); itr != m_PlayersInWar[team].end(); ++itr)
if (Player* player = ObjectAccessor::FindPlayer(*itr))
player->CastSpell(player, uint32(spellId), true);
}
else
{
for (auto itr = m_PlayersInWar[team].begin(); itr != m_PlayersInWar[team].end(); ++itr)
if (Player* player = ObjectAccessor::FindPlayer(*itr))
player->RemoveAuraFromStack(uint32(-spellId));
}
}
void Battlefield::BroadcastPacketToZone(WorldPacket const* data) const
{
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
for (auto itr = m_players[team].begin(); itr != m_players[team].end(); ++itr)
if (Player* player = ObjectAccessor::FindPlayer(*itr))
player->SendDirectMessage(data);
}
void Battlefield::BroadcastPacketToQueue(WorldPacket const* data) const
{
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
for (auto itr = m_PlayersInQueue[team].begin(); itr != m_PlayersInQueue[team].end(); ++itr)
if (Player* player = ObjectAccessor::FindConnectedPlayer(*itr))
player->SendDirectMessage(data);
}
void Battlefield::BroadcastPacketToWar(WorldPacket const* data) const
{
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
for (auto itr = m_PlayersInWar[team].begin(); itr != m_PlayersInWar[team].end(); ++itr)
if (Player* player = ObjectAccessor::FindPlayer(*itr))
player->SendDirectMessage(data);
}
void Battlefield::SendWarning(uint8 id, WorldObject const* target /*= nullptr*/)
{
if (Creature* stalker = GetCreature(StalkerGuid))
sCreatureTextMgr->SendChat(stalker, id, target);
}
void Battlefield::SendUpdateWorldState(uint32 variable, uint32 value, bool hidden /*= false*/)
{
WorldPackets::WorldState::UpdateWorldState worldstate;
worldstate.VariableID = variable;
worldstate.Value = value;
worldstate.Hidden = hidden;
BroadcastPacketToZone(worldstate.Write());
}
void Battlefield::AddCapturePoint(BfCapturePoint* cp)
{
Battlefield::BfCapturePointMap::iterator i = m_capturePoints.find(cp->GetCapturePointEntry());
if (i != m_capturePoints.end())
{
TC_LOG_ERROR("bg.battlefield", "Battlefield::AddCapturePoint: CapturePoint %u already exists!", cp->GetCapturePointEntry());
delete i->second;
}
m_capturePoints[cp->GetCapturePointEntry()] = cp;
}
BfCapturePoint* Battlefield::GetCapturePoint(uint32 entry) const
{
Battlefield::BfCapturePointMap::const_iterator itr = m_capturePoints.find(entry);
if (itr != m_capturePoints.end())
return itr->second;
return nullptr;
}
void Battlefield::RegisterZone(uint32 zoneId)
{
sBattlefieldMgr->AddZone(zoneId, this);
}
void Battlefield::HideNpc(Creature* creature)
{
creature->CombatStop();
creature->SetReactState(REACT_PASSIVE);
creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE);
creature->DisappearAndDie();
creature->SetVisible(false);
}
void Battlefield::ShowNpc(Creature* creature, bool aggressive)
{
creature->SetVisible(true);
creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE);
if (!creature->IsAlive())
creature->Respawn(true);
if (aggressive)
creature->SetReactState(REACT_AGGRESSIVE);
else
{
creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
creature->SetReactState(REACT_PASSIVE);
}
}
// ****************************************************
// ******************* Group System *******************
// ****************************************************
Group* Battlefield::GetFreeBfRaid(TeamId TeamId)
{
for (auto itr = m_Groups[TeamId].begin(); itr != m_Groups[TeamId].end(); ++itr)
if (Group* group = sGroupMgr->GetGroupByGUID(*itr))
if (!group->IsFull())
return group;
return nullptr;
}
Group* Battlefield::GetGroupPlayer(ObjectGuid guid, TeamId TeamId)
{
for (auto itr = m_Groups[TeamId].begin(); itr != m_Groups[TeamId].end(); ++itr)
if (Group* group = sGroupMgr->GetGroupByGUID(*itr))
if (group->IsMember(guid))
return group;
return nullptr;
}
bool Battlefield::AddOrSetPlayerToCorrectBfGroup(Player* player)
{
if (!player->IsInWorld())
return false;
if (Group* group = player->GetGroup())
group->RemoveMember(player->GetGUID());
Group* group = GetFreeBfRaid(player->GetTeamId());
if (!group)
{
group = new Group;
group->SetBattlefieldGroup(this);
group->Create(player);
sGroupMgr->AddGroup(group);
m_Groups[player->GetTeamId()].insert(group->GetGUID());
}
else if (group->IsMember(player->GetGUID()))
{
uint8 subgroup = group->GetMemberGroup(player->GetGUID());
player->SetBattlegroundOrBattlefieldRaid(group, subgroup);
}
else
group->AddMember(player);
return true;
}
//***************End of Group System*******************
//*****************************************************
//***************Spirit Guide System*******************
//*****************************************************
//--------------------
//-Battlefield Method-
//--------------------
BfGraveyard* Battlefield::GetGraveyardById(uint32 id) const
{
if (id < m_GraveyardList.size())
{
if (BfGraveyard* graveyard = m_GraveyardList.at(id))
return graveyard;
else
TC_LOG_ERROR("bg.battlefield", "Battlefield::GetGraveyardById Id:%u does not exist.", id);
}
else
TC_LOG_ERROR("bg.battlefield", "Battlefield::GetGraveyardById Id:%u could not be found.", id);
return nullptr;
}
WorldSafeLocsEntry const* Battlefield::GetClosestGraveYard(Player* player)
{
BfGraveyard* closestGY = nullptr;
float maxdist = -1;
for (uint8 i = 0; i < m_GraveyardList.size(); i++)
{
if (m_GraveyardList[i])
{
if (m_GraveyardList[i]->GetControlTeamId() != player->GetTeamId())
continue;
float dist = m_GraveyardList[i]->GetDistance(player);
if (dist < maxdist || maxdist < 0)
{
closestGY = m_GraveyardList[i];
maxdist = dist;
}
}
}
if (closestGY)
return sWorldSafeLocsStore.LookupEntry(closestGY->GetGraveyardId());
return nullptr;
}
void Battlefield::AddPlayerToResurrectQueue(ObjectGuid npcGuid, ObjectGuid playerGuid)
{
for (uint8 i = 0; i < m_GraveyardList.size(); i++)
{
if (!m_GraveyardList[i])
continue;
if (m_GraveyardList[i]->HasNpc(npcGuid))
{
m_GraveyardList[i]->AddPlayer(playerGuid);
break;
}
}
}
void Battlefield::RemovePlayerFromResurrectQueue(ObjectGuid playerGuid)
{
for (uint8 i = 0; i < m_GraveyardList.size(); i++)
{
if (!m_GraveyardList[i])
continue;
if (m_GraveyardList[i]->HasPlayer(playerGuid))
{
m_GraveyardList[i]->RemovePlayer(playerGuid);
break;
}
}
}
void Battlefield::SendAreaSpiritHealerQueryOpcode(Player* player, ObjectGuid const& guid)
{
WorldPackets::Battleground::AreaSpiritHealerTime areaSpiritHealerTime;
areaSpiritHealerTime.HealerGuid = guid;
areaSpiritHealerTime.TimeLeft = m_LastResurrectTimer;
player->SendDirectMessage(areaSpiritHealerTime.Write());
}
// ----------------------
// - BfGraveyard Method -
// ----------------------
BfGraveyard::BfGraveyard(Battlefield* battlefield)
{
m_Bf = battlefield;
m_GraveyardId = 0;
m_ControlTeam = TEAM_NEUTRAL;
}
void BfGraveyard::Initialize(TeamId startControl, uint32 graveyardId)
{
m_ControlTeam = startControl;
m_GraveyardId = graveyardId;
}
void BfGraveyard::SetSpirit(Creature* spirit, TeamId team)
{
if (!spirit)
{
TC_LOG_ERROR("bg.battlefield", "BfGraveyard::SetSpirit: Invalid Spirit.");
return;
}
m_SpiritGuide[team] = spirit->GetGUID();
spirit->SetReactState(REACT_PASSIVE);
}
float BfGraveyard::GetDistance(Player* player)
{
WorldSafeLocsEntry const* safeLoc = sWorldSafeLocsStore.LookupEntry(m_GraveyardId);
return player->GetDistance2d(safeLoc->Loc.X, safeLoc->Loc.Y);
}
void BfGraveyard::AddPlayer(ObjectGuid playerGuid)
{
if (!m_ResurrectQueue.count(playerGuid))
{
m_ResurrectQueue.insert(playerGuid);
if (Player* player = ObjectAccessor::FindPlayer(playerGuid))
player->CastSpell(player, SPELL_WAITING_FOR_RESURRECT, true);
}
}
void BfGraveyard::RemovePlayer(ObjectGuid playerGuid)
{
m_ResurrectQueue.erase(m_ResurrectQueue.find(playerGuid));
if (Player* player = ObjectAccessor::FindPlayer(playerGuid))
player->RemoveAurasDueToSpell(SPELL_WAITING_FOR_RESURRECT);
}
void BfGraveyard::Resurrect()
{
if (m_ResurrectQueue.empty())
return;
for (GuidSet::const_iterator itr = m_ResurrectQueue.begin(); itr != m_ResurrectQueue.end(); ++itr)
{
// Get player object from his guid
Player* player = ObjectAccessor::FindPlayer(*itr);
if (!player)
continue;
// Check if the player is in world and on the good graveyard
if (player->IsInWorld())
if (Creature* spirit = m_Bf->GetCreature(m_SpiritGuide[m_ControlTeam]))
spirit->CastSpell(spirit, SPELL_SPIRIT_HEAL, true);
// Resurrect player
player->CastSpell(player, SPELL_RESURRECTION_VISUAL, true);
player->ResurrectPlayer(1.0f);
player->CastSpell(player, 6962, true);
player->CastSpell(player, SPELL_SPIRIT_HEAL_MANA, true);
player->SpawnCorpseBones(false);
}
m_ResurrectQueue.clear();
}
// For changing graveyard control
void BfGraveyard::GiveControlTo(TeamId team)
{
// Guide switching
// Note: Visiblity changes are made by phasing
/*if (m_SpiritGuide[1 - team])
m_SpiritGuide[1 - team]->SetVisible(false);
if (m_SpiritGuide[team])
m_SpiritGuide[team]->SetVisible(true);*/
m_ControlTeam = team;
// Teleport to other graveyard, player witch were on this graveyard
RelocateDeadPlayers();
}
void BfGraveyard::RelocateDeadPlayers()
{
WorldSafeLocsEntry const* closestGrave = nullptr;
for (GuidSet::const_iterator itr = m_ResurrectQueue.begin(); itr != m_ResurrectQueue.end(); ++itr)
{
Player* player = ObjectAccessor::FindPlayer(*itr);
if (!player)
continue;
if (closestGrave)
player->TeleportTo(player->GetMapId(), closestGrave->Loc.X, closestGrave->Loc.Y, closestGrave->Loc.Z, player->GetOrientation());
else
{
closestGrave = m_Bf->GetClosestGraveYard(player);
if (closestGrave)
player->TeleportTo(player->GetMapId(), closestGrave->Loc.X, closestGrave->Loc.Y, closestGrave->Loc.Z, player->GetOrientation());
}
}
}
bool BfGraveyard::HasNpc(ObjectGuid guid)
{
if (!m_SpiritGuide[TEAM_ALLIANCE] || !m_SpiritGuide[TEAM_HORDE])
return false;
if (!m_Bf->GetCreature(m_SpiritGuide[TEAM_ALLIANCE]) ||
!m_Bf->GetCreature(m_SpiritGuide[TEAM_HORDE]))
return false;
return (m_SpiritGuide[TEAM_ALLIANCE] == guid || m_SpiritGuide[TEAM_HORDE] == guid);
}
// *******************************************************
// *************** End Spirit Guide system ***************
// *******************************************************
// ********************** Misc ***************************
// *******************************************************
Creature* Battlefield::SpawnCreature(uint32 entry, Position const& pos)
{
//Get map object
Map* map = sMapMgr->CreateBaseMap(m_MapId);
if (!map)
{
TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnCreature: Can't create creature entry: %u, map not found.", entry);
return nullptr;
}
if (!sObjectMgr->GetCreatureTemplate(entry))
{
TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnCreature: entry %u does not exist.", entry);
return nullptr;
}
Creature* creature = Creature::CreateCreature(entry, map, pos);
if (!creature)
{
TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnCreature: Can't create creature entry: %u", entry);
return nullptr;
}
creature->SetHomePosition(pos);
// Set creature in world
map->AddToMap(creature);
creature->setActive(true);
return creature;
}
// Method for spawning gameobject on map
GameObject* Battlefield::SpawnGameObject(uint32 entry, Position const& pos, QuaternionData const& rot)
{
// Get map object
Map* map = sMapMgr->CreateBaseMap(m_MapId);
if (!map)
{
TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnGameObject: Can't create GameObject (Entry: %u). Map not found.", entry);
return nullptr;
}
if (!sObjectMgr->GetGameObjectTemplate(entry))
{
TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnGameObject: GameObject template %u not found in database! Battlefield not created!", entry);
return nullptr;
}
// Create gameobject
GameObject* go = GameObject::CreateGameObject(entry, map, pos, rot, 255, GO_STATE_READY);
if (!go)
{
TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnGameObject: Could not create gameobject template %u! Battlefield has not been created!", entry);
return nullptr;
}
// Add to world
map->AddToMap(go);
go->setActive(true);
return go;
}
Creature* Battlefield::GetCreature(ObjectGuid guid)
{
if (!m_Map)
return nullptr;
return m_Map->GetCreature(guid);
}
GameObject* Battlefield::GetGameObject(ObjectGuid guid)
{
if (!m_Map)
return nullptr;
return m_Map->GetGameObject(guid);
}
// *******************************************************
// ******************* CapturePoint **********************
// *******************************************************
BfCapturePoint::BfCapturePoint(Battlefield* battlefield) : m_Bf(battlefield), m_capturePointGUID()
{
m_team = TEAM_NEUTRAL;
m_value = 0;
m_minValue = 0.0f;
m_maxValue = 0.0f;
m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_NEUTRAL;
m_OldState = BF_CAPTUREPOINT_OBJECTIVESTATE_NEUTRAL;
m_capturePointEntry = 0;
m_neutralValuePct = 0;
m_maxSpeed = 0;
}
bool BfCapturePoint::HandlePlayerEnter(Player* player)
{
if (!m_capturePointGUID.IsEmpty())
{
if (GameObject* capturePoint = m_Bf->GetGameObject(m_capturePointGUID))
{
player->SendUpdateWorldState(capturePoint->GetGOInfo()->controlZone.worldState1, 1);
player->SendUpdateWorldState(capturePoint->GetGOInfo()->controlZone.worldstate2, uint32(ceil((m_value + m_maxValue) / (2 * m_maxValue) * 100.0f)));
player->SendUpdateWorldState(capturePoint->GetGOInfo()->controlZone.worldstate3, m_neutralValuePct);
}
}
return m_activePlayers[player->GetTeamId()].insert(player->GetGUID()).second;
}
GuidSet::iterator BfCapturePoint::HandlePlayerLeave(Player* player)
{
if (!m_capturePointGUID.IsEmpty())
if (GameObject* capturePoint = m_Bf->GetGameObject(m_capturePointGUID))
player->SendUpdateWorldState(capturePoint->GetGOInfo()->controlZone.worldState1, 0);
GuidSet::iterator current = m_activePlayers[player->GetTeamId()].find(player->GetGUID());
if (current == m_activePlayers[player->GetTeamId()].end())
return current; // return end()
m_activePlayers[player->GetTeamId()].erase(current++);
return current;
}
void BfCapturePoint::SendChangePhase()
{
if (!m_capturePointGUID)
return;
if (GameObject* capturePoint = m_Bf->GetGameObject(m_capturePointGUID))
{
// send this too, sometimes the slider disappears, dunno why :(
SendUpdateWorldState(capturePoint->GetGOInfo()->controlZone.worldState1, 1);
// send these updates to only the ones in this objective
SendUpdateWorldState(capturePoint->GetGOInfo()->controlZone.worldstate2, (uint32)std::ceil((m_value + m_maxValue) / (2 * m_maxValue) * 100.0f));
// send this too, sometimes it resets :S
SendUpdateWorldState(capturePoint->GetGOInfo()->controlZone.worldstate3, m_neutralValuePct);
}
}
bool BfCapturePoint::SetCapturePointData(GameObject* capturePoint)
{
ASSERT(capturePoint);
TC_LOG_DEBUG("bg.battlefield", "Creating capture point %u", capturePoint->GetEntry());
m_capturePointGUID = capturePoint->GetGUID();
m_capturePointEntry = capturePoint->GetEntry();
// check info existence
GameObjectTemplate const* goinfo = capturePoint->GetGOInfo();
if (goinfo->type != GAMEOBJECT_TYPE_CONTROL_ZONE)
{
TC_LOG_ERROR("misc", "OutdoorPvP: GO %u is not a capture point!", capturePoint->GetEntry());
return false;
}
// get the needed values from goinfo
m_maxValue = goinfo->controlZone.maxTime;
m_maxSpeed = m_maxValue / (goinfo->controlZone.minTime ? goinfo->controlZone.minTime : 60);
m_neutralValuePct = goinfo->controlZone.neutralPercent;
m_minValue = m_maxValue * goinfo->controlZone.neutralPercent / 100;
if (m_team == TEAM_ALLIANCE)
{
m_value = m_maxValue;
m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_ALLIANCE;
}
else
{
m_value = -m_maxValue;
m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_HORDE;
}
return true;
}
GameObject* BfCapturePoint::GetCapturePointGo()
{
return m_Bf->GetGameObject(m_capturePointGUID);
}
bool BfCapturePoint::DelCapturePoint()
{
if (!m_capturePointGUID.IsEmpty())
{
if (GameObject* capturePoint = m_Bf->GetGameObject(m_capturePointGUID))
{
capturePoint->SetRespawnTime(0); // not save respawn time
capturePoint->Delete();
capturePoint = nullptr;
}
m_capturePointGUID.Clear();
}
return true;
}
bool BfCapturePoint::Update(uint32 diff)
{
if (!m_capturePointGUID)
return false;
if (GameObject* capturePoint = m_Bf->GetGameObject(m_capturePointGUID))
{
float radius = capturePoint->GetGOInfo()->controlZone.radius;
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
{
for (GuidSet::iterator itr = m_activePlayers[team].begin(); itr != m_activePlayers[team].end();)
{
if (Player* player = ObjectAccessor::FindPlayer(*itr))
{
if (!capturePoint->IsWithinDistInMap(player, radius) || !player->IsOutdoorPvPActive())
itr = HandlePlayerLeave(player);
else
++itr;
}
else
++itr;
}
}
std::list<Player*> players;
Trinity::AnyPlayerInObjectRangeCheck checker(capturePoint, radius);
Trinity::PlayerListSearcher<Trinity::AnyPlayerInObjectRangeCheck> searcher(capturePoint, players, checker);
Cell::VisitWorldObjects(capturePoint, searcher, radius);
for (std::list<Player*>::iterator itr = players.begin(); itr != players.end(); ++itr)
if ((*itr)->IsOutdoorPvPActive())
if (m_activePlayers[(*itr)->GetTeamId()].insert((*itr)->GetGUID()).second)
HandlePlayerEnter(*itr);
}
// get the difference of numbers
float fact_diff = ((float) m_activePlayers[TEAM_ALLIANCE].size() - (float) m_activePlayers[TEAM_HORDE].size()) * diff / BATTLEFIELD_OBJECTIVE_UPDATE_INTERVAL;
if (G3D::fuzzyEq(fact_diff, 0.0f))
return false;
uint32 Challenger = 0;
float maxDiff = m_maxSpeed * diff;
if (fact_diff < 0)
{
// horde is in majority, but it's already horde-controlled -> no change
if (m_State == BF_CAPTUREPOINT_OBJECTIVESTATE_HORDE && m_value <= -m_maxValue)
return false;
if (fact_diff < -maxDiff)
fact_diff = -maxDiff;
Challenger = HORDE;
}
else
{
// ally is in majority, but it's already ally-controlled -> no change
if (m_State == BF_CAPTUREPOINT_OBJECTIVESTATE_ALLIANCE && m_value >= m_maxValue)
return false;
if (fact_diff > maxDiff)
fact_diff = maxDiff;
Challenger = ALLIANCE;
}
float oldValue = m_value;
TeamId oldTeam = m_team;
m_OldState = m_State;
m_value += fact_diff;
if (m_value < -m_minValue) // red
{
if (m_value < -m_maxValue)
m_value = -m_maxValue;
m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_HORDE;
m_team = TEAM_HORDE;
}
else if (m_value > m_minValue) // blue
{
if (m_value > m_maxValue)
m_value = m_maxValue;
m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_ALLIANCE;
m_team = TEAM_ALLIANCE;
}
else if (oldValue * m_value <= 0) // grey, go through mid point
{
// if challenger is ally, then n->a challenge
if (Challenger == ALLIANCE)
m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_NEUTRAL_ALLIANCE_CHALLENGE;
// if challenger is horde, then n->h challenge
else if (Challenger == HORDE)
m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_NEUTRAL_HORDE_CHALLENGE;
m_team = TEAM_NEUTRAL;
}
else // grey, did not go through mid point
{
// old phase and current are on the same side, so one team challenges the other
if (Challenger == ALLIANCE && (m_OldState == BF_CAPTUREPOINT_OBJECTIVESTATE_HORDE || m_OldState == BF_CAPTUREPOINT_OBJECTIVESTATE_NEUTRAL_HORDE_CHALLENGE))
m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_HORDE_ALLIANCE_CHALLENGE;
else if (Challenger == HORDE && (m_OldState == BF_CAPTUREPOINT_OBJECTIVESTATE_ALLIANCE || m_OldState == BF_CAPTUREPOINT_OBJECTIVESTATE_NEUTRAL_ALLIANCE_CHALLENGE))
m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_ALLIANCE_HORDE_CHALLENGE;
m_team = TEAM_NEUTRAL;
}
if (G3D::fuzzyNe(m_value, oldValue))
SendChangePhase();
if (m_OldState != m_State)
{
//TC_LOG_ERROR("bg.battlefield", "%u->%u", m_OldState, m_State);
if (oldTeam != m_team)
ChangeTeam(oldTeam);
return true;
}
return false;
}
void BfCapturePoint::SendUpdateWorldState(uint32 field, uint32 value)
{
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
for (GuidSet::iterator itr = m_activePlayers[team].begin(); itr != m_activePlayers[team].end(); ++itr) // send to all players present in the area
if (Player* player = ObjectAccessor::FindPlayer(*itr))
player->SendUpdateWorldState(field, value);
}
void BfCapturePoint::SendObjectiveComplete(uint32 id, ObjectGuid guid)
{
uint8 team;
switch (m_State)
{
case BF_CAPTUREPOINT_OBJECTIVESTATE_ALLIANCE:
team = TEAM_ALLIANCE;
break;
case BF_CAPTUREPOINT_OBJECTIVESTATE_HORDE:
team = TEAM_HORDE;
break;
default:
return;
}
// send to all players present in the area
for (GuidSet::iterator itr = m_activePlayers[team].begin(); itr != m_activePlayers[team].end(); ++itr)
if (Player* player = ObjectAccessor::FindPlayer(*itr))
player->KilledMonsterCredit(id, guid);
}
bool BfCapturePoint::IsInsideObjective(Player* player) const
{
return m_activePlayers[player->GetTeamId()].find(player->GetGUID()) != m_activePlayers[player->GetTeamId()].end();
}
| conan513/SingleCore_TC | src/server/game/Battlefield/Battlefield.cpp | C++ | gpl-2.0 | 37,310 |
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
import {AjaxResponse} from 'TYPO3/CMS/Core/Ajax/AjaxResponse';
import AjaxRequest = require('TYPO3/CMS/Core/Ajax/AjaxRequest');
import javaScriptHandler = require('TYPO3/CMS/Core/JavaScriptHandler');
import Notification = require('../../Notification');
import Utility = require('../../Utility');
interface Context {
config: Object;
hmac: string;
}
interface Message {
title: string;
message: string;
}
export interface AjaxDispatcherResponse {
hasErrors: boolean;
messages: Message[];
stylesheetFiles: string[];
inlineData: object;
requireJsModules: string[];
scriptCall: string[];
scriptItems?: any[];
}
export class AjaxDispatcher {
private readonly objectGroup: string = null;
constructor(objectGroup: string) {
this.objectGroup = objectGroup;
}
public newRequest(endpoint: string): AjaxRequest {
return new AjaxRequest(endpoint);
}
/**
* @param {String} routeName
*/
public getEndpoint(routeName: string): string {
if (typeof TYPO3.settings.ajaxUrls[routeName] !== 'undefined') {
return TYPO3.settings.ajaxUrls[routeName];
}
throw 'Undefined endpoint for route "' + routeName + '"';
}
public send(request: AjaxRequest, params: Array<string>): Promise<any> {
const sentRequest = request.post(this.createRequestBody(params)).then(async (response: AjaxResponse): Promise<any> => {
return this.processResponse(await response.resolve());
});
sentRequest.catch((reason: Error): void => {
Notification.error('Error ' + reason.message);
});
return sentRequest;
}
private createRequestBody(input: Array<string>): { [key: string]: string } {
const body: { [key: string]: string } = {};
for (let i = 0; i < input.length; i++) {
body['ajax[' + i + ']'] = input[i];
}
body['ajax[context]'] = JSON.stringify(this.getContext());
return body;
}
private getContext(): Context {
let context: Context;
if (typeof TYPO3.settings.FormEngineInline.config[this.objectGroup] !== 'undefined'
&& typeof TYPO3.settings.FormEngineInline.config[this.objectGroup].context !== 'undefined'
) {
context = TYPO3.settings.FormEngineInline.config[this.objectGroup].context;
}
return context;
}
private processResponse(json: AjaxDispatcherResponse): AjaxDispatcherResponse {
if (json.hasErrors) {
for (const message of json.messages) {
Notification.error(message.title, message.message);
}
}
// If there are elements they should be added to the <HEAD> tag (e.g. for RTEhtmlarea):
if (json.stylesheetFiles) {
for (const [index, stylesheetFile] of json.stylesheetFiles.entries()) {
if (!stylesheetFile) {
break;
}
const element = document.createElement('link');
element.rel = 'stylesheet';
element.type = 'text/css';
element.href = stylesheetFile;
document.querySelector('head').appendChild(element);
delete json.stylesheetFiles[index];
}
}
if (typeof json.inlineData === 'object') {
TYPO3.settings.FormEngineInline = Utility.mergeDeep(TYPO3.settings.FormEngineInline, json.inlineData);
}
if (json.scriptItems instanceof Array && json.scriptItems.length > 0) {
javaScriptHandler.processItems(json.scriptItems, true);
}
// @todo deprecate or remove with TYPO3 v12.0
if (typeof json.requireJsModules === 'object') {
for (let requireJsModule of json.requireJsModules) {
new Function(requireJsModule)();
}
}
// TODO: This is subject to be removed
// @todo deprecate or remove with TYPO3 v12.0
if (json.scriptCall && json.scriptCall.length > 0) {
for (const scriptCall of json.scriptCall) {
// eslint-disable-next-line no-eval
eval(scriptCall);
}
}
return json;
}
}
| stweil/TYPO3.CMS | Build/Sources/TypeScript/backend/Resources/Public/TypeScript/FormEngine/InlineRelation/AjaxDispatcher.ts | TypeScript | gpl-2.0 | 4,280 |
// *************************************************************************
//
// Copyright 2004-2010 Bruno PAGES .
//
// This file is part of the BOUML Uml Toolkit.
//
// 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.
//
// e-mail : bouml@free.fr
// home : http://bouml.free.fr
//
// *************************************************************************
#include <stdio.h>
#include "UmlDrag.h"
#include "BrowserNode.h"
const QString UmlDrag::Key = "Bouml/";
QString UmlDrag::postfix;
bool UmlDrag::ro;
UmlDrag::UmlDrag(BrowserNode * bn, QWidget * parent, const char * name)
: QStoredDrag(UmlDrag::Key + bn->drag_key(), parent, name) {
// stay in the same application : can use address directly
QByteArray a(sizeof(bn));
memcpy(a.data(), &bn, sizeof(bn));
setEncodedData(a);
postfix = bn->drag_postfix();
ro = ((bn->parent() != 0) &&
!((BrowserNode *) bn->parent())->is_writable());
}
bool UmlDrag::canDecode(QDragMoveEvent * e, UmlCode type,
bool withpostfix, bool evenro)
{
if (ro && ! evenro)
return FALSE;
return (e->source() != 0) &&
e->provides((withpostfix) ? UmlDrag::Key + QString::number(type) + postfix
: UmlDrag::Key + QString::number(type));
}
bool UmlDrag::canDecode(QDragMoveEvent * e, const QString & type)
{
return !ro && (e->source() != 0) && e->provides(UmlDrag::Key + type);
}
BrowserNode * UmlDrag::decode(QDropEvent * e, UmlCode type,
bool withpostfix)
{
QByteArray payload =
e->data((withpostfix) ? UmlDrag::Key + QString::number(type) + postfix
: UmlDrag::Key + QString::number(type));
if (payload.size()) {
e->accept();
BrowserNode * bn;
memcpy(&bn, payload.data(), sizeof(bn));
return bn;
}
return 0;
}
BrowserNode * UmlDrag::decode(QDropEvent * e, const QString & type)
{
QByteArray payload = e->data(UmlDrag::Key + type);
if (payload.size()) {
e->accept();
BrowserNode * bn;
memcpy(&bn, payload.data(), sizeof(bn));
return bn;
}
return 0;
}
| gregsmirnov/bouml | src/misc/UmlDrag.cpp | C++ | gpl-2.0 | 2,695 |
<?php
/**
*
* Ajax Shoutbox extension for the phpBB Forum Software package.
*
* @copyright (c) 2014 Paul Sohier <http://www.ajax-shoutbox.com>
* @license GNU General Public License, version 2 (GPL-2.0)
*
* Translated By : Bassel Taha Alhitary - www.alhitary.net
*/
/**
* DO NOT CHANGE
*/
if (!defined('IN_PHPBB'))
{
exit;
}
if (empty($lang) || !is_array($lang))
{
$lang = array();
}
// DEVELOPERS PLEASE NOTE
//
// All language files should use UTF-8 as their encoding and the files must not contain a BOM.
//
// Placeholders can now contain order information, e.g. instead of
// 'Page %s of %s' you can (and should) write 'Page %1$s of %2$s', this allows
// translators to re-order the output of data while ensuring it remains correct
//
// You do not need this where single placeholders are used, e.g. 'Message %d' is fine
// equally where a string contains only two placeholders which are used to wrap text
// in a url you again do not need to specify an order e.g., 'Click %sHERE%s' is fine
//
// Some characters you may want to copy&paste:
// ’ » “ ” …
//
$lang = array_merge(
$lang, array(
'AJAX_SHOUTBOX' => 'الدردشة أجاكس',
'AJAX_SHOUTBOX_MESSAGE' => 'ارسل رسالتك',
'AJAX_SHOUTBOX_ONLY_AJAX' => 'المعذرة , يجب تفعيل الجافا سكربت لكي تعمل هذه الدردشة.',
'AJAX_SHOUTBOX_NO_PERMISSION' => 'لا توجد صلاحية لتنفيذ هذا الأمر',
'AJAX_SHOUTBOX_MESSAGE_EMPTY' => 'الرسالة فارغة',
'AJAX_SHOUTBOX_ERROR' => 'خطأ',
'AJAX_SHOUTBOX_MISSING_ID' => 'لا يُمكن حذف المشاركة',
'AJAX_SHOUTBOX_NO_SUCH_POST' => 'لا يُمكن العثور على المشاركة',
'AJAX_SHOUTBOX_PUSH_NOT_AVAIL' => 'الخدمة عير متوفرة حالياً',
'AJAXSHOUTBOX_BOARD_DATE_FORMAT' => 'My shoutbox date format',
'AJAXSHOUTBOX_BOARD_DATE_FORMAT_EXPLAIN' => 'Specify a date format for just the shoutbox. You should not use a relative date format.',
)
);
| Galixte/ajax-shoutbox-ext | language/ar/ajax_shoutbox.php | PHP | gpl-2.0 | 2,096 |
<?php
/*
$Id: tax_classes.php 1692 2012-02-26 01:26:50Z michael.oscmax@gmail.com $
osCmax e-Commerce
http://www.oscmax.com
Copyright 2000 - 2011 osCmax
Released under the GNU General Public License
*/
define('HEADING_TITLE', 'Tipos de impuestos');
define('TABLE_HEADING_TAX_CLASSES', 'Tipos de impuestos');
define('TABLE_HEADING_ACTION', 'Acción');
define('TEXT_INFO_EDIT_INTRO', 'Realiza los cambios necesarios');
define('TEXT_INFO_CLASS_TITLE', 'Nombre del impuesto:');
define('TEXT_INFO_CLASS_DESCRIPTION', 'Descripción:');
define('TEXT_INFO_DATE_ADDED', 'Fecha creación:');
define('TEXT_INFO_LAST_MODIFIED', 'Última modificación:');
define('TEXT_INFO_INSERT_INTRO', 'Introduce los datos del nuevo tipo de impuesto');
define('TEXT_INFO_DELETE_INTRO', '¿Seguro que quieres eliminar este tipo de impuesto?');
define('TEXT_INFO_HEADING_NEW_TAX_CLASS', 'Nuevo tipo de impuesto');
define('TEXT_INFO_HEADING_EDIT_TAX_CLASS', 'Editar tipo de impuesto');
define('TEXT_INFO_HEADING_DELETE_TAX_CLASS', 'Eliminar tipo de impuesto');
?> | arnabnaha/NHCPharmacy | catalog/admin/includes/languages/espanol/tax_classes.php | PHP | gpl-2.0 | 1,041 |
/* $Id: tag.hpp 55984 2013-01-01 09:34:55Z mordante $ */
/*
Copyright (C) 2011 - 2013 by Sytyi Nick <nsytyi@gmail.com>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* @file
* This file contains objects "tag" and "key", which are used to store
* information about tags and keys while annotation parsing.
*/
#ifndef TOOLS_SCHEMA_TAG_HPP_INCLUDED
#define TOOLS_SCHEMA_TAG_HPP_INCLUDED
#include <algorithm>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
class config;
namespace schema_validation{
/**
* class_key is used to save the information about one key.
* Key has next info: name, type, default value or key is mandatory.
*/
class class_key{
public:
class_key():name_(""),type_(""),default_("\"\""),mandatory_(false)
{ }
class_key(const std::string & name,
const std::string &type,
const std::string &def="\"\"")
: name_(name)
, type_(type)
, default_(def)
, mandatory_(def.empty())
{
}
class_key(const config&);
const std::string & get_name() const{
return name_ ;
}
const std::string & get_type() const{
return type_ ;
}
const std::string & get_default() const{
return default_;
}
bool is_mandatory () const{
return mandatory_ ;
}
void set_name(const std::string& name){
name_ = name;
}
void set_type(const std::string& type){
type_ = type;
}
void set_default(const std::string& def){
default_ = def;
if (def.empty()){
mandatory_ = true;
}
}
void set_mandatory(bool mandatory){
mandatory_ = mandatory;
}
/** is used to print key info
* the format is next
* [key]
* name="name"
* type="type"
* default="default"
* mandatory="true/false"
* [/key]
*/
void print(std::ostream& os,int level) const;
/**
*Compares keys by name. Used in std::sort, i.e.
*/
bool operator < ( const class_key& k) const{
return (get_name() < k.get_name());
}
private:
/** Name of key*/
std::string name_;
/** Type of key*/
std::string type_;
/** Default value*/
std::string default_;
/** Shows, if key is a mandatory key.*/
bool mandatory_;
};
/**
* Stores information about tag.
* Each tags is an element of great tag tree. This tree is close to filesystem:
* you can use links and special include directory global/
* Normally root is not mentioned in path.
* Each tag has name, minimum and maximum occasions number,
* and lists of subtags, keys and links.
*/
class class_tag{
public:
typedef std::map<std::string,class_tag> tag_map;
typedef std::pair<std::string,class_tag> tag_map_value;
typedef std::map<std::string,class_key> key_map;
typedef std::pair<std::string,class_key> key_map_value;
typedef std::map<std::string,std::string> link_map;
typedef std::pair<std::string,std::string> link_map_value;
typedef key_map::iterator key_iterator;
typedef std::pair<key_iterator,key_iterator> all_key_iterators;
typedef key_map::const_iterator const_key_iterator;
typedef std::pair<const_key_iterator,const_key_iterator>
all_const_key_iterators;
typedef tag_map::iterator tag_iterator;
typedef std::pair<tag_iterator,tag_iterator> all_tag_iterators;
typedef tag_map::const_iterator const_tag_iterator;
typedef std::pair<const_tag_iterator,const_tag_iterator>
all_const_tag_iterators;
typedef link_map::iterator link_iterator;
typedef std::pair<link_iterator,link_iterator> all_link_iterators;
typedef link_map::const_iterator const_link_iterator;
typedef std::pair<const_link_iterator,const_link_iterator>
all_const_link_iterators;
class_tag()
: name_("")
, min_(0)
, max_(0)
, super_("")
, tags_()
, keys_()
, links_()
{
}
class_tag(const std::string & name,
int min,
int max,
const std::string & super=""
)
: name_(name)
, min_(min)
, max_(max)
, super_(super)
, tags_()
, keys_()
, links_()
{
}
class_tag(const config&);
~class_tag(){ }
/** Prints information about tag to outputstream, recursively
* is used to print tag info
* the format is next
* [tag]
* subtags
* keys
* name="name"
* min="min"
* max="max"
* [/tag]
*/
void print(std::ostream& os);
const std::string & get_name() const{
return name_ ;
}
int get_min() const{
return min_;
}
int get_max() const{
return max_;
}
const std::string & get_super() const{
return super_ ;
}
bool is_extension() const{
return ! super_.empty();
}
void set_name(const std::string& name){
name_ = name;
}
void set_min(int o){
min_ = o;
}
void set_max(int o){
max_ = o;
}
void set_min( std::string const& s){
std::istringstream i(s);
if (!(i >> min_)){
min_ = 0;
}
}
void set_max( std::string const & s){
std::istringstream i(s);
if (!(i >> max_)){
max_ = 0;
}
}
void set_super(std::string const & s){
super_= s;
}
void add_key(const class_key& new_key){
keys_.insert(key_map_value(new_key.get_name(),new_key));
}
void add_tag(const class_tag& new_tag){
tags_.insert(tag_map_value(new_tag.name_,new_tag));
}
void add_link(const std::string & link);
/**
* Tags are usually organized in tree.
* This fuction helps to add tag to his exact place in tree
* @param path - path in subtree to exact place of tag
* @param tag - tag to add
* @param root - root of schema tree - use to support of adding to link.
* Path is getting shotter and shoter with each call.
* Path schould look like tag1/tag2/parent/ Slash at end is mandatory.
*/
void add_tag (const std::string & path,const class_tag & tag,
class_tag &root);
bool operator < ( const class_tag& t) const{
return name_ < t.name_;
}
bool operator == (const class_tag & other) const {
return name_ == other.name_;
}
/**
* Returns pointer to child key
*/
const class_key * find_key(const std::string & name) const;
/**
* Returns pointer to child link
*/
const std::string * find_link(const std::string & name) const;
/**
* Returns pointer to tag using full path to it.
* Also work with links
*/
const class_tag * find_tag(const std::string & fullpath,
const class_tag & root) const;
/**
* Calls the expansion on each child
*/
void expand_all(class_tag &root);
all_const_tag_iterators tags() const{
return all_const_tag_iterators(tags_.begin(),tags_.end());
}
all_const_key_iterators keys() const{
return all_const_key_iterators(keys_.begin(),keys_.end());
}
all_const_link_iterators links() const{
return all_const_link_iterators(links_.begin(),links_.end());
}
void remove_key_by_name(const std::string &name){
keys_.erase (name);
}
/** Removes all keys with this type. Works recursively */
void remove_keys_by_type(const std::string &type);
#ifdef _MSC_VER
// MSVC throws an error if this method is private.
// so, define it as public to prevent that. The error is:
// error C2248: 'schema_validation::class_tag::find_tag' : cannot
// access private member declared in class 'schema_validation::class_tag'
class_tag * find_tag(const std::string & fullpath,
class_tag & root) ;
#endif
// class_tag & operator= (class_tag const& );
private:
/** name of tag*/
std::string name_;
/** number of minimum occasions*/
int min_;
/** number of maximum occasions*/
int max_;
/**
* name of tag to extend "super-tag"
* Extension is smth like inheritance and is used in case
* when you need to use another tag with all his
* keys, childs, etc. But you also want to allow extra subtags of that tags,
* so just linking that tag wouldn't help at all.
*/
std::string super_;
/** children tags*/
tag_map tags_;
/** keys*/
key_map keys_;
/** links to possible children. */
link_map links_;
/**
* the same as class_tag::print(std::ostream&)
* but indents different levels with step space.
* @param os stream to print
* @param level current level of indentation
* @param step step to next indent
*/
void printl(std::ostream &os,int level, int step = 4);
#ifndef _MSC_VER
// this is complementary with the above #ifdef for the MSVC error
class_tag * find_tag(const std::string & fullpath,
class_tag & root) ;
#endif
void add_tags (const tag_map & list){
tags_.insert(list.begin(),list.end());
}
void add_keys (const key_map & list){
keys_.insert(list.begin(),list.end());
}
void add_links (const link_map & list){
links_.insert(list.begin(),list.end());
}
/**
* Copies tags, keys and links of tag to this
*/
void append_super(const class_tag & tag,const std::string & super);
/**
* Expands all "super" copying their data to this.
*/
void expand(class_tag & root);
};
}
#endif // TOOLS_SCHEMA_TAG_HPP_INCLUDED
| RushilPatel/BattleForWesnoth | src/tools/schema/tag.hpp | C++ | gpl-2.0 | 9,062 |
<?php
require_once("include/config.php");
require_once("include/functions.php");
if(!isset($_SESSION['logat'])) $_SESSION['logat'] = 'Nu';
if($_SESSION['logat'] == 'Da')
{
if(isset($_SESSION['nume']) && ctype_alnum($_SESSION['nume']))
$setid = $_SESSION['userid'];
if(isset($setid))
{
if($_SESSION['global']==1 ? $acces=1 : $acces=check_perm("Editare pagini"));
if($acces!=1)
header('Location: http://'.$_SERVER["SERVER_NAME"].'/admiasi/index.php');
}
else
header('Location: http://'.$_SERVER["SERVER_NAME"].'/admiasi/index.php');
if(isset($_POST['submit']))
{
$id = make_safe($_GET['id']);
$galt = make_safe($_POST['galt']);
$link = $_POST['link'];
if(!validateURL($link))
$mesaj = "Adresă web invalidă.";
else
{
$sql="UPDATE `gallery` SET galt='$galt', link='$link' WHERE id='$id'";
mysql_query($sql);
$mesaj = "Datele au fost actualizate!";
}
}
if(isset($_GET['id']) && is_numeric($_GET['id']))
{
$sql = "SELECT * FROM `gallery` WHERE id=".$_GET['id']."";
$result = mysql_query($sql);
if(mysql_num_rows($result)>0)
{
$rand = mysql_fetch_object($result);
$id = $rand -> id;
$galt = $rand -> galt;
$link = $rand -> link;
}
else
$nuexista = 1;
}
else
header('Location: http://'.$_SERVER["SERVER_NAME"].'/admiasi/editare-sponsori.php');
?>
<!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 profile="http://gmpg.org/xfn/11">
<?php include("include/headerinfoadm.php");?>
<link rel="stylesheet" type="text/css" href="js/formValidator/validationEngine.jquery.css" />
</head>
<body>
<div id="contain">
<div id="main">
<?php include("include/headeradm.php");?>
<div id="pagecontent">
<div id="pcontent_f"></div>
<?php if(!isset($nuexista))
{
?>
<br/>
<a href="editare-galerie.php"><img src="images/back.png" class="midalign"/></a> <a href="editare-galerie.php">Înapoi la pagina de administrare a galeriei foto</a>
<br/><br/>
<?php
display_message($mesaj);
?>
<b>Editare imagine galerie foto:</b><br/><br/>
<form action="editare-foto.php?id=<?php echo $_GET['id'];?>" method="post" id="validate">
<input type="hidden" name="token" value="<?php echo $_SESSION['token'] ?>" />
Text alternativ imagine:
<input name="galt" type="text" value="<?php if(isset($galt)) echo $galt?>" class="stfield"/>
<br/><br/>
Link imagine:
<input name="link" type="text" value="<?php if(isset($link)) echo $link?>" class="stfield" data-validation-engine="validate[custom[url]]"/>
<br /><br />
<input name="submit" type="submit" value="Actualizare imagine" />
</form>
<? } else {?>
Comentariul pe care aţi încercat să îl accesaţi nu există!
<?php } ?>
</div>
<?php include("include/footeradm.php");?>
</div>
</div>
<script type="text/javascript" src="js/formValidator/jquery.validationEngine.js"></script>
<script type="text/javascript" src="js/formValidator/jquery.validationEngine-ro.js" charset="utf-8"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#validate").validationEngine();
});
</script>
</body>
</html>
<?php
} else {
header('Location: http://'.$_SERVER["SERVER_NAME"].'/admiasi/index.php');
}
?> | hodorogandrei/contesteasyplatform | admiasi/editare-foto.php | PHP | gpl-2.0 | 4,821 |
using System.ComponentModel;
using System.Windows;
namespace Filewatcher.GUI
{
public partial class MacroView
{
public string Value { get; set; }
public MacroView()
{
InitializeComponent();
InitalizeExitRequest();
InitializeLocation();
}
private void InitalizeExitRequest()
{
var currDataContext = DataContext as MacroViewModel;
if (currDataContext == null) return;
currDataContext.ExitRequest += (s, eArgs) =>
{
if (eArgs.DialogResult)
Value = eArgs.Value.ToString();
DialogResult = eArgs.DialogResult;
Close();
};
}
private void InitializeLocation()
{
if (Properties.Settings.Default.MACROVIEW_LEFT > 0)
Left = Properties.Settings.Default.MACROVIEW_LEFT;
if (Properties.Settings.Default.MACROVIEW_TOP > 0)
Top = Properties.Settings.Default.MACROVIEW_TOP;
}
private void WindowClosing(object sender, CancelEventArgs e)
{
Properties.Settings.Default.MACROVIEW_LEFT = Left;
Properties.Settings.Default.MACROVIEW_TOP = Top;
Properties.Settings.Default.Save();
}
}
}
| bajak/luba-filewatcher | GUI/Views/MacroView.xaml.cs | C# | gpl-2.0 | 1,364 |
<?php
// ============================================================+
// File name : example_045.php
// Begin : 2008-03-04
// Last Update : 2011-04-15
//
// Description : Example 045 for TCPDF class
// Bookmarks and Table of Content
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// Manor Coach House, Church Hill
// Aldershot, Hants, GU12 4RQ
// UK
// www.tecnick.com
// info@tecnick.com
// ============================================================+
/**
* Creates an example PDF TEST document using TCPDF
*
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Bookmarks and Table of Content
* @author Nicola Asuni
* @since 2008-03-04
*/
require_once ('../config/lang/eng.php');
require_once ('../tcpdf.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 045');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE . ' 045', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(
PDF_FONT_NAME_MAIN,
'',
PDF_FONT_SIZE_MAIN
));
$pdf->setFooterFont(Array(
PDF_FONT_NAME_DATA,
'',
PDF_FONT_SIZE_DATA
));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings
$pdf->setLanguageArray($l);
// ---------------------------------------------------------
// set font
$pdf->SetFont('times', 'B', 20);
// add a page
$pdf->AddPage();
// set a bookmark for the current position
$pdf->Bookmark('Chapter 1', 0, 0, '', 'B', array(
0,
64,
128
));
// print a line using Cell()
$pdf->Cell(0, 10, 'Chapter 1', 0, 1, 'L');
$pdf->AddPage();
$pdf->Bookmark('Paragraph 1.1', 1, 0, '', '', array(
128,
0,
0
));
$pdf->Cell(0, 10, 'Paragraph 1.1', 0, 1, 'L');
$pdf->AddPage();
$pdf->Bookmark('Paragraph 1.2', 1, 0, '', '', array(
128,
0,
0
));
$pdf->Cell(0, 10, 'Paragraph 1.2', 0, 1, 'L');
$pdf->AddPage();
$pdf->Bookmark('Sub-Paragraph 1.2.1', 2, 0, '', 'I', array(
0,
128,
0
));
$pdf->Cell(0, 10, 'Sub-Paragraph 1.2.1', 0, 1, 'L');
$pdf->AddPage();
$pdf->Bookmark('Paragraph 1.3', 1, 0, '', '', array(
128,
0,
0
));
$pdf->Cell(0, 10, 'Paragraph 1.3', 0, 1, 'L');
// add some pages and bookmarks
for ($i = 2; $i < 12; $i ++) {
$pdf->AddPage();
$pdf->Bookmark('Chapter ' . $i, 0, 0, '', 'B', array(
0,
64,
128
));
$pdf->Cell(0, 10, 'Chapter ' . $i, 0, 1, 'L');
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
// add a new page for TOC
$pdf->addTOCPage();
// write the TOC title
$pdf->SetFont('times', 'B', 16);
$pdf->MultiCell(0, 0, 'Table Of Content', 0, 'C', 0, 1, '', '', true, 0);
$pdf->Ln();
$pdf->SetFont('dejavusans', '', 12);
// add a simple Table Of Content at first page
// (check the example n. 59 for the HTML version)
$pdf->addTOC(1, 'courier', '.', 'INDEX', 'B', array(
128,
0,
0
));
// end of TOC page
$pdf->endTOCPage();
// ---------------------------------------------------------
// Close and output PDF document
$pdf->Output('example_045.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+
| memoupao/Fondo-Simon | lib/tcpdf/examples/example_045.php | PHP | gpl-2.0 | 3,857 |
package de.amshaegar.economy.http;
import java.io.IOException;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpServer;
import de.amshaegar.economy.EcoFlow;
public class WebInterface {
private HttpServer server;
public WebInterface(int port) throws IOException {
server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext("/", new TemplateHttpHandler());
server.createContext("/auth", new AuthHttpHandler());
server.createContext("/intern", new InternHttpHandler());
server.createContext("/intern/ajax", new AjaxHttpHandler());
server.start();
EcoFlow.getPlugin().getLogger().info(String.format("Web interface started on port %d", server.getAddress().getPort()));
}
public void stop() {
server.stop(0);
}
}
| AmShaegar13/EcoFlow | src/de/amshaegar/economy/http/WebInterface.java | Java | gpl-2.0 | 780 |
<?php
/**
* Auto Amazon Links
*
* Generates links of Amazon products just coming out today. You just pick categories and they appear even in JavaScript disabled browsers.
*
* https://en.michaeluno.jp/amazon-auto-links/
* Copyright (c) 2013-2021 Michael Uno
*/
/**
* A scratch class to delete a database table.
*
* @since 4.3.5
*/
class AmazonAutoLinks_Run_Database_Delete_aal_products extends AmazonAutoLinks_Scratch_Base {
/**
* @purpose Deletes the task table and version option.
* @return boolean
*/
public function scratch_uninstall() {
$_oTaskTable = new AmazonAutoLinks_DatabaseTable_aal_products;
$_oTaskTable->uninstall();
return ! $_oTaskTable->tableExists();
}
} | michaeluno/amazon-auto-links | include/core/component/test/run/delete/database/aal_products/AmazonAutoLinks_Run_Database_Delete_aal_products.php | PHP | gpl-2.0 | 745 |
<div class="footer-social">
<div class="container">
<div class="row">
<div class="col-sm-6">
<h3 style="margin-top:8px; font-weight:300;"></h3>
</div>
<div class="col-sm-1">
<div class="social">
<div class="social-icon"><a href="#"><i class="icon-twitter"></i></a></div>
</div>
</div><!--/1-->
<div class="col-sm-1">
<div class="social">
<div class="social-icon"><a href="#"><i class="icon-facebook"></i></a></div>
</div>
</div><!--/1-->
<div class="col-sm-1">
<div class="social">
<div class="social-icon"><a href="#"><i class="icon-google-plus"></i></a></div>
</div>
</div><!--/1-->
<div class="col-sm-1">
<div class="social">
<div class="social-icon"><a href="#"><i class="icon-linkedin"></i></a></div>
</div>
</div><!--/1-->
</div>
</div>
</div>
<footer class="footer" role="contentinfo">
<div class="container">
<div id="inner-footer" class="wrap clearfix">
<nav role="navigation">
<div class="row">
<div class="col-md-3 col-sm-3">
<?php bones_footer_links(); ?>
</div><!--/3-->
<div class="col-md-3 col-sm-3">
<?php bones_footer_links_2(); ?>
</div><!--/3-->
<div class="col-md-3 col-sm-3">
<?php bones_footer_links_3(); ?>
</div><!--/3-->
<div class="col-md-3 col-sm-3">
<h4>About Us</h4>
<p>Helping our clients grow - with responsible, ethical, and technological leadership. TRUEBADORE is poised to humanize the experience of using technology for meaningful business purposes. TRUEBADORE focuses on aligning aesthetic intelligence and technical prowess so that people will be delighted - not disillusioned - by the new reality that every business is a software business.</p>
</div><!--/3-->
</div>
</nav>
</div> <!-- end #inner-footer -->
</div> <!-- end .container -->
</footer> <!-- end footer -->
<div class="footer-copyright">
<div class="container">
<div class="row">
<div class="col-md-10">
<p class="source-org copyright">© <?php echo date('Y'); ?> <?php bloginfo( 'name' ); ?>. All Rights Reserved.</p>
</div>
<div class="col-md-2">
<a href="#">Back to Top <i class="icon-arrow-up"></i></a>
</div>
</div>
</div>
</div>
</div> <!-- end .wrapper -->
<!-- all js scripts are loaded in library/bones.php -->
<?php wp_footer(); ?>
</body>
</html> <!-- end page. what a ride! -->
| truebadore/tba | wp-content/themes/cloudhost/footer.php | PHP | gpl-2.0 | 3,013 |
<?php
if ( !defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
/**
* Manages image sizes settings
*
* Here image sizes settings are defined and managed.
*
* @version 1.1.4
* @package ecommerce-product-catalog/functions
* @author Norbert Dreszer
*/
add_action( 'admin_init', 'ic_add_wp_screens_settings' );
function ic_add_wp_screens_settings() {
add_settings_section( 'default', __( 'Product Catalog Images', 'ecommerce-product-catalog' ), 'ic_catalog_image_sizes_settings', 'media' );
}
function ic_catalog_image_sizes_settings() {
$images = ic_get_catalog_image_sizes();
?>
<table class="form-table">
<tbody>
<tr>
<th scope="row"><?php _e( 'Catalog Single Page Image', 'ecommerce-product-catalog' ) ?></th>
<td><fieldset><legend class="screen-reader-text"><span>Large size</span></legend>
<label for="product_page_image_w"><?php _e( 'Max Width' ) ?></label>
<input name="catalog_image_sizes[product_page_image_w]" type="number" step="1" min="0" id="product_page_image_w" value="<?php echo $images[ 'product_page_image_w' ] ?>" class="small-text">
<label for="product_page_image_h"><?php _e( 'Max Height' ) ?></label>
<input name="catalog_image_sizes[product_page_image_h]" type="number" step="1" min="0" id="product_page_image_h" value="<?php echo $images[ 'product_page_image_h' ] ?>" class="small-text">
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _e( 'Catalog Category Page Image', 'ecommerce-product-catalog' ) ?></th>
<td><fieldset><legend class="screen-reader-text"><span>Large size</span></legend>
<label for="product_category_page_image_w"><?php _e( 'Max Width' ) ?></label>
<input name="catalog_image_sizes[product_category_page_image_w]" type="number" step="1" min="0" id="product_category_page_image_w" value="<?php echo $images[ 'product_category_page_image_w' ] ?>" class="small-text">
<label for="product_category_page_image_h"><?php _e( 'Max Height' ) ?></label>
<input name="catalog_image_sizes[product_category_page_image_h]" type="number" step="1" min="0" id="product_category_page_image_h" value="<?php echo $images[ 'product_category_page_image_h' ] ?>" class="small-text">
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _e( 'Modern Grid Image', 'ecommerce-product-catalog' ) ?></th>
<td><fieldset><legend class="screen-reader-text"><span>Large size</span></legend>
<label for="modern_grid_image_w"><?php _e( 'Max Width' ) ?></label>
<input name="catalog_image_sizes[modern_grid_image_w]" type="number" step="1" min="0" id="product_page_image_w" value="<?php echo $images[ 'modern_grid_image_w' ] ?>" class="small-text">
<label for="modern_grid_image_h"><?php _e( 'Max Height' ) ?></label>
<input name="catalog_image_sizes[modern_grid_image_h]" type="number" step="1" min="0" id="product_page_image_h" value="<?php echo $images[ 'modern_grid_image_h' ] ?>" class="small-text"><br>
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _e( 'Classic Grid Image', 'ecommerce-product-catalog' ) ?></th>
<td><fieldset><legend class="screen-reader-text"><span><?php _e( 'Classic Grid Image', 'ecommerce-product-catalog' ) ?></span></legend>
<label for="classic_grid_image_w"><?php _e( 'Max Width' ) ?></label>
<input name="catalog_image_sizes[classic_grid_image_w]" type="number" step="1" min="0" id="product_page_image_w" value="<?php echo $images[ 'classic_grid_image_w' ] ?>" class="small-text">
<label for="classic_grid_image_h"><?php _e( 'Max Height' ) ?></label>
<input name="catalog_image_sizes[classic_grid_image_h]" type="number" step="1" min="0" id="product_page_image_h" value="<?php echo $images[ 'classic_grid_image_h' ] ?>" class="small-text">
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _e( 'Classic List Image', 'ecommerce-product-catalog' ) ?></th>
<td><fieldset><legend class="screen-reader-text"><span><?php _e( 'Classic List Image', 'ecommerce-product-catalog' ) ?></span></legend>
<label for="classic_list_image_w"><?php _e( 'Max Width' ) ?></label>
<input name="catalog_image_sizes[classic_list_image_w]" type="number" step="1" min="0" id="product_page_image_w" value="<?php echo $images[ 'classic_list_image_w' ] ?>" class="small-text">
<label for="classic_list_image_h"><?php _e( 'Max Height' ) ?></label>
<input name="catalog_image_sizes[classic_list_image_h]" type="number" step="1" min="0" id="product_page_image_h" value="<?php echo $images[ 'classic_list_image_h' ] ?>" class="small-text">
</fieldset></td>
</tr>
<?php do_action( 'catalog_image_sizes_settings', $images ) ?>
</tbody>
</table>
<?php
}
function ic_get_default_catalog_image_sizes() {
$image_sizes[ 'product_page_image_w' ] = 600;
$image_sizes[ 'product_page_image_h' ] = 600;
$image_sizes[ 'product_category_page_image_w' ] = 600;
$image_sizes[ 'product_category_page_image_h' ] = 600;
$image_sizes[ 'classic_grid_image_w' ] = 600;
$image_sizes[ 'classic_grid_image_h' ] = 600;
$image_sizes[ 'classic_list_image_w' ] = 280;
$image_sizes[ 'classic_list_image_h' ] = 160;
$image_sizes[ 'modern_grid_image_w' ] = 600;
$image_sizes[ 'modern_grid_image_h' ] = 384;
return apply_filters( 'default_catalog_image_sizes', $image_sizes );
}
/**
* Returns catalog image sizes array
*
* @return type
*/
function ic_get_catalog_image_sizes() {
$image_sizes = ic_get_global( 'catalog_image_sizes' );
if ( !$image_sizes ) {
$default = ic_get_default_catalog_image_sizes();
$image_sizes = wp_parse_args( get_option( 'catalog_image_sizes', $default ), $default );
ic_save_global( 'catalog_image_sizes', $image_sizes );
}
return $image_sizes;
}
add_action( 'product-settings-list', 'ic_register_image_setting' );
/**
* Registers catalog image sizes
*
*/
function ic_register_image_setting() {
register_setting( 'media', 'catalog_image_sizes' );
}
add_action( 'after_setup_theme', 'ic_add_catalog_image_sizes' );
/**
* Adds image size for classic grid product listing
*
*/
function ic_add_catalog_image_sizes() {
$image_sizes = ic_get_catalog_image_sizes();
add_image_size( 'classic-grid-listing', $image_sizes[ 'classic_grid_image_w' ], $image_sizes[ 'classic_grid_image_h' ] );
add_image_size( 'classic-list-listing', $image_sizes[ 'classic_list_image_w' ], $image_sizes[ 'classic_list_image_h' ] );
add_image_size( 'modern-grid-listing', $image_sizes[ 'modern_grid_image_w' ], $image_sizes[ 'modern_grid_image_h' ], true );
add_image_size( 'product-page-image', $image_sizes[ 'product_page_image_w' ], $image_sizes[ 'product_page_image_h' ] );
add_image_size( 'product-category-page-image', $image_sizes[ 'product_category_page_image_w' ], $image_sizes[ 'product_category_page_image_h' ] );
do_action( 'add_catalog_image_sizes', $image_sizes );
}
/**
* Generates image size settings table tr
*
* @param type $label
* @param type $name
*/
function ic_image_sizes_settings_tr( $label, $name ) {
$images = ic_get_catalog_image_sizes();
?>
<tr>
<th scope="row"><?php echo $label ?></th>
<td><fieldset><legend class="screen-reader-text"><span><?php echo $label ?></span></legend>
<label for="<?php echo $name . '_w' ?>"><?php _e( 'Max Width' ) ?></label>
<input name="catalog_image_sizes[<?php echo $name ?>_w]" type="number" step="1" min="0" id="<?php echo $name ?>_w" value="<?php echo $images[ $name . '_w' ] ?>" class="small-text">
<label for="<?php echo $name . '_h' ?>"><?php _e( 'Max Height' ) ?></label>
<input name="catalog_image_sizes[<?php echo $name ?>_h]" type="number" step="1" min="0" id="<?php echo $name ?>_h" value="<?php echo $images[ $name . '_h' ] ?>" class="small-text">
</fieldset></td>
</tr><?php
}
| impleCode/ecommerce-product-catalog | includes/settings/image-sizes.php | PHP | gpl-2.0 | 7,783 |
package com.tacohen.killbots.Logic;
import android.util.Pair;
public class GridDimensions {
public static Pair<Integer, Integer> gridDimensions;
public static int width;
public static int height;
public static Pair<Integer, Integer> getGridDimensions() {
return gridDimensions;
}
public static void setGridDimensions(Pair<Integer, Integer> gridDimensions) {
GridDimensions.gridDimensions = gridDimensions;
}
public static int getWidth() {
return width;
}
public static void setWidth(int width) {
GridDimensions.width = width;
}
public static int getHeight() {
return height;
}
public static void setHeight(int height) {
GridDimensions.height = height;
}
}
| Tacohen/Killbots | Killbots/src/com/tacohen/killbots/Logic/GridDimensions.java | Java | gpl-2.0 | 692 |
<?php
/*
* Plugin Name: Permalink Redirect
* Plugin URI: http://scott.yang.id.au/code/permalink-redirect/
* Description: Permalink Redirect ensures that pages and entries are always accessed via the permalink. Otherwise, a 301 redirect will be issued.
* Version: 2.0.5
* Author: Scott Yang
* Author URI: http://scott.yang.id.au/
*/
class YLSY_PermalinkRedirect {
function admin_menu() {
add_options_page('Permalink Redirect Manager', 'Permalink Redirect', 5,
'permalink-redirect', array($this, 'admin_page'));
}
function admin_page() {
global $wp_version;
// If we are updating, we will flush all the rewrite rules to force the
// old structure to be added.
if (isset($_GET['updated']) ||
isset($_GET['settings-updated'])) {
$this->regenerate_rules();
}
$options = array('feedburner', 'feedburnerbrand', 'hostname',
'oldstruct', 'skip', 'newpath');
$optionvars = array();
foreach ($options as $option) {
$$option = get_option("permalink_redirect_$option");
if (!$$option) {
$$option = ($option == 'feedburnerbrand') ?
'feeds.feedburner.com' : '';
}
if ($wp_version < '2' && !$$option) {
add_option("permalink_redirect_$option", $$option);
}
$optionvars[] = "permalink_redirect_$option";
}
$home = parse_url(get_option('home'));
?>
<div class="wrap">
<h2>Permalink Redirect Manager</h2>
<form action="options.php" method="post">
<fieldset class="options">
<legend>Paths to be skipped</legend>
<p>Separate each entry with a new line. Matched with regular expression.</p>
<textarea name="permalink_redirect_skip" style="width:98%;" rows="5"><?php echo htmlspecialchars($skip); ?></textarea>
<legend style="padding-top:20px">Path pairs to redirect from and to</legend>
<p>Separate each entry with a new line. Each line is [from]<spaces>[to].</p>
<textarea name="permalink_redirect_newpath" style="width:98%;" rows="5"><?php echo htmlspecialchars($newpath); ?></textarea>
<table class="optiontable" style="padding-top:20px">
<tr valign="top">
<th scope="row">Old Permalink Structures:</th>
<td><textarea name="permalink_redirect_oldstruct" id="permalink_redirect_oldstruct" style="width:98%" rows="3"><?php echo htmlspecialchars($oldstruct); ?></textarea><br/><small><a href="http://codex.wordpress.org/Using_Permalinks">Available tags</a>. One Permalink Structure per line. Current permalink structure: <a href="#" onclick="document.getElementById('permalink_redirect_oldstruct').value = '<?php echo htmlspecialchars(get_option('permalink_structure')); ?>';return false;"><code><?php echo htmlspecialchars(get_option('permalink_structure')); ?></code></a></small></td>
</tr>
<tr>
<th scope="row">FeedBurner Redirect:</th>
<td>http://<input name="permalink_redirect_feedburnerbrand" type="text" id="permalink_redirect_feedburnerbrand" value="<?php print htmlspecialchars($feedburnerbrand); ?>" size="20"/>/<input name="permalink_redirect_feedburner" type="text" id="permalink_redirect_feedburner" value="<?php echo htmlspecialchars($feedburner) ?>" size="20" /></td>
</tr>
<tr>
<th scope="row">Hostname Redirect:</th>
<td><input name="permalink_redirect_hostname" type="checkbox" id="permalink_redirect_hostname" value="1"<?php if ($hostname) { ?> checked="checked"<?php } ?>/> Redirect if hostname is not <code><?php echo htmlspecialchars($home['host']); ?></code>.</td>
</tr>
</table>
</fieldset>
<p class="submit">
<input type="submit" name="Submit" value="<?php _e('Update Options') ?> »" />
<input type="hidden" name="action" value="update" />
<input type="hidden" name="page_options" value="<?php echo join(',', $optionvars); ?>"/>
<?php if (function_exists('wp_nonce_field')) { wp_nonce_field('update-options'); } ?>
</p>
</form>
</div>
<?php
}
function check_hostname() {
if (! get_option('permalink_redirect_hostname')) {
return false;
}
$requested = $_SERVER['HTTP_HOST'];
$home = parse_url(get_option('home'));
return $requested != $home['host'];
}
function execute() {
global $wp_query;
$this->execute2($wp_query);
}
function execute2($query, $testold=true) {
$req_uri = $_SERVER['REQUEST_URI'];
if ($query->is_trackback ||
$query->is_search ||
$query->is_comments_popup ||
$query->is_robots ||
$this->is_skip($req_uri))
{
return;
}
$this->redirect_newpath($req_uri);
$this->redirect_feedburner($query);
if ($query->is_404) {
if ($testold) {
$this->redirect_old_permalink($req_uri);
}
return;
}
if (($req_uri = @parse_url($_SERVER['REQUEST_URI'])) === false) {
return;
}
$req_path = $req_uri['path'];
$new_uri = $this->guess_permalink($query);
if (!$new_uri) {
return;
}
$permalink = @parse_url($new_uri);
// WP2.1: If a static page has been set as the front-page, we'll get
// empty string here.
if (!$permalink['path']) {
$permalink['path'] = '/';
}
if (($req_path != $permalink['path']) || $this->check_hostname()) {
wp_redirect($new_uri, 301);
}
}
function guess_permalink($query) {
$haspost = count($query->posts) > 0;
$has_ut = function_exists('user_trailingslashit');
if (get_query_var('m')) {
// Handling special case with '?m=yyyymmddHHMMSS'
// Since there is no code for producing the archive links for
// is_time, we will give up and not trying any redirection.
$m = preg_replace('/[^0-9]/', '', get_query_var('m'));
switch (strlen($m)) {
case 4: // Yearly
$link = get_year_link($m);
break;
case 6: // Monthly
$link = get_month_link(substr($m, 0, 4), substr($m, 4, 2));
break;
case 8: // Daily
$link = get_day_link(substr($m, 0, 4), substr($m, 4, 2),
substr($m, 6, 2));
break;
default:
return false;
}
} elseif (($query->is_single || $query->is_page) && $haspost) {
$post = $query->posts[0];
$link = get_permalink($post->ID);
$page = get_query_var('page');
if ($page && $page > 1) {
$link = trailingslashit($link) . "$page";
if ($has_ut) {
$link = user_trailingslashit($link, 'paged');
} else {
$link .= '/';
}
}
// WP2.2: In Wordpress 2.2+ is_home() returns false and is_page()
// returns true if front page is a static page.
if ($query->is_page && ('page' == get_option('show_on_front')) &&
$post->ID == get_option('page_on_front'))
{
$link = trailingslashit($link);
}
} elseif ($query->is_author && $haspost) {
global $wp_version;
if ($wp_version >= '2') {
$author = get_userdata(get_query_var('author'));
if ($author === false)
return false;
if (function_exists('get_author_posts_url')) {
$link = get_author_posts_url($author->ID,
$author->user_nicename);
} else {
$link = get_author_link(false, $author->ID,
$author->user_nicename);
}
// XXX: get_author_link seems to always return one with
// trailing slash. We have to call user_trailingslashit to
// make it right.
if ($has_ut) {
$link = user_trailingslashit($link);
}
} else {
// XXX: get_author_link() bug in WP 1.5.1.2
// s/author_nicename/user_nicename/
global $cache_userdata;
$userid = get_query_var('author');
$link = get_author_link(false, $userid,
$cache_userdata[$userid]->user_nicename);
}
} elseif ($query->is_category && $haspost) {
$link = get_category_link(get_query_var('cat'));
} elseif ($query->is_tag && $haspost) {
$link = get_tag_link(get_query_var('tag_id'));
} elseif ($query->is_day && $haspost) {
$link = get_day_link(get_query_var('year'),
get_query_var('monthnum'),
get_query_var('day'));
} elseif ($query->is_month && $haspost) {
$link = get_month_link(get_query_var('year'),
get_query_var('monthnum'));
} elseif ($query->is_year && $haspost) {
$link = get_year_link(get_query_var('year'));
} elseif ($query->is_home) {
// WP2.1: Handling "Posts page" option. In WordPress 2.1 is_home()
// returns true and is_page() returns false if home page has been
// set to a page, and we are getting the permalink of that page
// here.
if ((get_option('show_on_front') == 'page') &&
($pageid = get_option('page_for_posts')))
{
$link = trailingslashit(get_permalink($pageid));
} else {
$link = trailingslashit(get_option('home'));
}
} else {
return false;
}
if ($query->is_paged) {
$paged = get_query_var('paged');
if ($paged) {
$link = trailingslashit($link) . "page/$paged";
if ($has_ut) {
$link = user_trailingslashit($link, 'paged');
} else {
$link .= '/';
}
}
}
if ($query->is_feed) {
$link = trailingslashit($link) . 'feed';
if ($has_ut) {
$link = user_trailingslashit($link, 'feed');
} else {
$link .= '/';
}
}
return $link;
}
function is_feedburner() {
return strncmp('FeedBurner/', $_SERVER['HTTP_USER_AGENT'], 11) == 0;
}
function is_skip($path) {
$permalink_redirect_skip = get_option('permalink_redirect_skip');
$permalink_redirect_skip = explode("\n", $permalink_redirect_skip);
// Apply 'permalink_redirect_skip' filter so other plugins can
// customise the skip behaviour. (Denis de Bernardy @ 2006-04-23)
$permalink_redirect_skip = apply_filters('permalink_redirect_skip',
$permalink_redirect_skip);
foreach ($permalink_redirect_skip as $skip) {
$skip = trim($skip);
if ($skip && ereg($skip, $path))
return true;
}
return false;
}
function redirect_feedburner($query) {
// Check whether we need to do redirect for FeedBurner.
// NOTE this might not always get executed. For feeds,
// WP::send_headers() might send back a 304 before template_redirect
// action can be called.
global $withcomments;
if ($query->is_feed && !$query->is_archive && !$withcomments) {
if (($feedburner = get_option('permalink_redirect_feedburner')) &&
(strncmp('FeedBurner/', $_SERVER['HTTP_USER_AGENT'], 11) != 0))
{
$brand = get_option('permalink_redirect_feedburnerbrand');
$brand = $brand ? $brand : 'feeds.feedburner.com';
wp_redirect("http://$brand/$feedburner", 302);
}
}
}
// Static page redirect contributed by Sergey Menshikov.
function redirect_newpath($path) {
if ($newpathlist = get_option('permalink_redirect_newpath')) {
$newpathlist = explode("\n", $newpathlist);
foreach ($newpathlist as $newpath) {
$pair = preg_split('/\s+/', trim($newpath));
if ($pair[0] == $path) {
wp_redirect($pair[1], 301);
}
}
}
}
/**
* Called when the main execute function gets a 404 to check against old
* permalink structures and perform redirect if an old post can be
* matched.
*/
function redirect_old_permalink($req_uri) {
global $wp_query, $wp_rewrite;
global $wp_version;
$rules = get_option('permalink_redirect_rules');
if (!$rules) {
return;
}
// Backing up the rewrite object for you, imperative programmers!
$wp_rewrite_old = $wp_rewrite;
// Unsetting the globals. Argh! Evil global variables!
foreach ($wp_query->query_vars as $key => $val) {
unset($GLOBALS[$key]);
}
// Going through the rules.
foreach ($rules as $rules2) {
$wp2 = new WP();
$wp_rewrite = new YLSY_Rewrite();
$wp_rewrite->index = $wp_rewrite_old->index;
$wp_rewrite->rules = $rules2;
$wp2->parse_request();
if (isset($wp2->query_vars['error']) &&
($wp2->query_vars['error'] == 404))
{
continue;
}
$query = new WP_Query();
if ($wp_version >= '2.1') {
$posts = $query->query($wp2->query_vars);
} else {
$wp2->build_query_string();
$posts = $query->query($wp2->query_string);
}
if (count($posts) > 0) {
$wp_rewrite = $wp_rewrite_old;
$this->execute2($query, false);
return;
}
}
// Restoring global variables. We don't bother to reset the other
// variables as we are going to do a 404 anyway.
$wp_rewrite = $wp_rewrite_old;
}
/**
* This function is called after someone saved the old permalink
* structure. It will create cached version of rewrite rules from the
* old structure.
*/
function regenerate_rules() {
global $wp_rewrite;
$oldstruct = get_option('permalink_redirect_oldstruct');
if ($oldstruct) {
$rules = array();
$oldstruct = explode("\n", $oldstruct);
foreach ($oldstruct as $item) {
$rules2 = $wp_rewrite->generate_rewrite_rule(trim($item),
false, false, false, true);
$rules3 = array();
foreach ($rules2 as $match => $query) {
$query = preg_replace('/\$(\d+)/', '\$matches[\1]', $query);
$rules3[$match] = $query;
}
$rules[] = $rules3;
}
update_option('permalink_redirect_rules', $rules);
} else {
delete_option('permalink_redirect_rules');
}
}
}
/**
* I am a dummy class to simulate the WP_Rewite class, but only has one
* method implemented.
*/
class YLSY_Rewrite {
function wp_rewrite_rules() {
return $this->rules;
}
}
if (!function_exists('wp_redirect')) {
function wp_redirect($location, $status=302) {
global $is_IIS;
$location = apply_filters('wp_redirect', $location, $status);
$status = apply_filters('wp_redirect_status', $status, $location);
if (!$location)
return false;
if (function_exists('wp_sanitize_redirect')) {
$location = wp_sanitize_redirect($location);
}
if ($is_IIS) {
header("Refresh: 0;url=$location");
} else {
status_header($status);
header("Location: $location");
}
}
}
$_permalink_redirect = new YLSY_PermalinkRedirect();
add_action('admin_menu', array($_permalink_redirect, 'admin_menu'));
add_action('template_redirect', array($_permalink_redirect, 'execute'));
| amejias101/wordpress | wp-content/plugins/ylsy_permalink_redirect.php | PHP | gpl-2.0 | 16,822 |
//http://codeforces.com/problemset/problem/670/D2
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define printv(data) for(auto& e:data) cout<<e<<","; cout<<endl;
#define sortv(data) std::sort(data.begin(),data.end());
#define rsortv(data) std::sort(data.rbegin(),data.rend());
#define fori(start,end) for(size_t i{start};i<end;i++)
#define forj(start,end) for(size_t j{start};j<end;j++)
#define foralli(data) fori(0,data.size())
constexpr size_t min(size_t a,size_t b){ return a<b?a:b; }
constexpr size_t max(size_t a,size_t b){ return a>b?a:b; }
using ll = long long;
using vll = std::vector<ll>;
#define get(var_name) ll var_name{0}; cin >> var_name;
#define readv(start,end,vec_name) std::vector<ll> vec_name(end); for(size_t i{start};i<end;i++) cin>>vec_name[i];
constexpr ll BIGLL{ std::numeric_limits<ll>::max() };
constexpr ll LL10{ 10000000000 + 1 };
bool check(vll cookie,vll ingred,ll k,ll num){
foralli(cookie){
ll delta = ingred[i] - cookie[i]*num;
if(delta<0){
delta*=-1;
if(delta<=k){
k -= delta;
}else{
return false;
}
}
}
return true;
}
int main()
{
ios_base::sync_with_stdio(false);
get(n);
get(k);
readv(0,n,cookie);
readv(0,n,ingred);
ll l{0},r{LL10};
while(l<=r){
ll m{(l+r)/2};
if(check(cookie,ingred,k,m)){
l = m + 1;
}else{
r = m - 1;
}
}
cout<<r<<endl;
return 0;
}
| fjanisze/Problems | D2MagicPowder.cpp | C++ | gpl-2.0 | 1,543 |
function fileQueueError(file, errorCode, message) {
try {
var imageName = "error.gif";
var errorName = "";
if (errorCode === SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) {
errorName = "You have attempted to queue too many files.";
}
if (errorName !== "") {
alert(errorName);
return;
}
switch (errorCode) {
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
imageName = "zerobyte.gif";
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
imageName = "toobig.gif";
break;
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
default:
alert(message);
break;
}
addImage(images_filepath + imageName);
} catch (ex) {
this.debug(ex);
}
}
function fileDialogComplete(numFilesSelected, numFilesQueued) {
try {
if (numFilesQueued > 0) {
this.startUpload();
}
} catch (ex) {
this.debug(ex);
}
}
function uploadProgress(file, bytesLoaded) {
try {
var percent = Math.ceil((bytesLoaded / file.size) * 100);
var progress = new FileProgress(file, this.customSettings.upload_target);
progress.setProgress(percent);
if (percent === 100) {
progress.setStatus("Creating thumbnail...");
progress.toggleCancel(false, this);
} else {
progress.setStatus("Uploading...");
progress.toggleCancel(true, this);
}
} catch (ex) {
this.debug(ex);
}
}
function uploadSuccess(file, serverData) {
try {
var progress = new FileProgress(file, this.customSettings.upload_target);
if (serverData.substring(0, 7) === "FILEID:") {
addImage(serverData.substring(7),serverData.substring(7));
progress.setStatus("Thumbnail Created.");
progress.toggleCancel(false);
} else {
addImage(images_filepath+"error.gif");
progress.setStatus("Error.");
progress.toggleCancel(false);
alert(serverData);
}
} catch (ex) {
this.debug(ex);
}
}
function uploadComplete(file) {
try {
/* I want the next upload to continue automatically so I'll call startUpload here */
if (this.getStats().files_queued > 0) {
this.startUpload();
} else {
var progress = new FileProgress(file, this.customSettings.upload_target);
progress.setComplete();
progress.setStatus("All images received.");
progress.toggleCancel(false);
}
} catch (ex) {
this.debug(ex);
}
}
function uploadError(file, errorCode, message) {
var imageName = "error.gif";
var progress;
try {
switch (errorCode) {
case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
try {
progress = new FileProgress(file, this.customSettings.upload_target);
progress.setCancelled();
progress.setStatus("Cancelled");
progress.toggleCancel(false);
}
catch (ex1) {
this.debug(ex1);
}
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
try {
progress = new FileProgress(file, this.customSettings.upload_target);
progress.setCancelled();
progress.setStatus("Stopped");
progress.toggleCancel(true);
}
catch (ex2) {
this.debug(ex2);
}
case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
imageName = "uploadlimit.gif";
break;
default:
alert(message);
break;
}
addImage(images_filepath + imageName);
} catch (ex3) {
this.debug(ex3);
}
}
function addImage(src,image_id) {
var newImg = document.createElement("img");
newImg.setAttribute('id', image_id);
newImg.style.margin = "5px";
newImg.style.width='110px';
newImg.style.height='130px';
var newDiv = document.createElement("div");
newDiv.setAttribute('id', 'div_'+image_id);
newDiv.setAttribute('class', 'imageBox_label2');
document.getElementById("thumbnails").appendChild(newDiv);
document.getElementById('div_'+image_id).appendChild(newImg);
if (newImg.filters) {
try {
newImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0;
} catch (e) {
// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
newImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')';
}
} else {
newImg.style.opacity = 0;
}
newImg.onload = function () {
fadeIn(newImg, 0);
};
newImg.src = src;
//create a tag
div = document.getElementById('div_'+image_id);
var newlink = document.createElement('a');
newlink.setAttribute('id', 'a_photo_'+image_id);
newlink.setAttribute('href', 'javascript:void(0);');
newlink.setAttribute('onclick', 'javascript:removePhoto("","'+image_id+'")');
newlink.innerHTML = '<img src="'+img_delete+'" class="img_delete2" alt="" >';
div.appendChild(newlink);
}
function fadeIn(element, opacity) {
var reduceOpacityBy = 5;
var rate = 30; // 15 fps
if (opacity < 100) {
opacity += reduceOpacityBy;
if (opacity > 100) {
opacity = 100;
}
if (element.filters) {
try {
element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity;
} catch (e) {
// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')';
}
} else {
element.style.opacity = opacity / 100;
}
}
if (opacity < 100) {
setTimeout(function () {
fadeIn(element, opacity);
}, rate);
}
}
/* ******************************************
* FileProgress Object
* Control object for displaying file info
* ****************************************** */
function FileProgress(file, targetID) {
this.fileProgressID = "divFileProgress";
this.fileProgressWrapper = document.getElementById(this.fileProgressID);
if (!this.fileProgressWrapper) {
this.fileProgressWrapper = document.createElement("div");
this.fileProgressWrapper.className = "progressWrapper";
this.fileProgressWrapper.id = this.fileProgressID;
this.fileProgressElement = document.createElement("div");
this.fileProgressElement.className = "progressContainer";
var progressCancel = document.createElement("a");
progressCancel.className = "progressCancel";
progressCancel.href = "#";
progressCancel.style.visibility = "hidden";
progressCancel.appendChild(document.createTextNode(" "));
var progressText = document.createElement("div");
progressText.className = "progressName";
progressText.appendChild(document.createTextNode(file.name));
var progressBar = document.createElement("div");
progressBar.className = "progressBarInProgress";
var progressStatus = document.createElement("div");
progressStatus.className = "progressBarStatus";
progressStatus.innerHTML = " ";
this.fileProgressElement.appendChild(progressCancel);
this.fileProgressElement.appendChild(progressText);
this.fileProgressElement.appendChild(progressStatus);
this.fileProgressElement.appendChild(progressBar);
this.fileProgressWrapper.appendChild(this.fileProgressElement);
document.getElementById(targetID).appendChild(this.fileProgressWrapper);
fadeIn(this.fileProgressWrapper, 0);
} else {
this.fileProgressElement = this.fileProgressWrapper.firstChild;
this.fileProgressElement.childNodes[1].firstChild.nodeValue = file.name;
}
this.height = this.fileProgressWrapper.offsetHeight;
}
FileProgress.prototype.setProgress = function (percentage) {
this.fileProgressElement.className = "progressContainer green";
this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
this.fileProgressElement.childNodes[3].style.width = percentage + "%";
};
FileProgress.prototype.setComplete = function () {
this.fileProgressElement.className = "progressContainer blue";
this.fileProgressElement.childNodes[3].className = "progressBarComplete";
this.fileProgressElement.childNodes[3].style.width = "";
};
FileProgress.prototype.setError = function () {
this.fileProgressElement.className = "progressContainer red";
this.fileProgressElement.childNodes[3].className = "progressBarError";
this.fileProgressElement.childNodes[3].style.width = "";
};
FileProgress.prototype.setCancelled = function () {
this.fileProgressElement.className = "progressContainer";
this.fileProgressElement.childNodes[3].className = "progressBarError";
this.fileProgressElement.childNodes[3].style.width = "";
};
FileProgress.prototype.setStatus = function (status) {
this.fileProgressElement.childNodes[2].innerHTML = status;
};
FileProgress.prototype.toggleCancel = function (show, swfuploadInstance) {
this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
if (swfuploadInstance) {
var fileID = this.fileProgressID;
this.fileProgressElement.childNodes[0].onclick = function () {
swfuploadInstance.cancelUpload(fileID);
return false;
};
}
};
| vapvarun/MicrocerptBIZ | wp-content/plugins/PlusOnett/monetize/add_post/image_uploader/swfupload/handlers.js | JavaScript | gpl-2.0 | 8,928 |
/**
* Copyright (C) 2012-2016 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as publishedby the Free
* Software Foundation.
*
* If the program is linked with libraries which are licensed under one of the
* following licenses, the combination of the program with the linked library is
* not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed under
* the aforementioned licenses, is permitted by the copyright holders if the
* distribution is compliant with both the GNU General Public License version 2
* and the aforementioned licenses.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*/
package org.n52.server.da.oxf;
import org.n52.oxf.sos.adapter.ISOSRequestBuilder;
import org.n52.oxf.sos.adapter.SOSRequestBuilderFactory;
import org.n52.oxf.sos.util.SosUtil;
public class SosRequestBuilderFactory {
public static ISOSRequestBuilder createRequestBuilder(String serviceVersion) {
if (SosUtil.isVersion100(serviceVersion)) {
return new SOSRequestBuilder_100_OXFExtension();
} else if (SosUtil.isVersion200(serviceVersion)) {
return new SOSRequestBuilder_200_OXFExtension();
} else {
return SOSRequestBuilderFactory.generateRequestBuilder(serviceVersion);
}
}
}
| ridoo/SensorWebClient | sensorwebclient-api/src/main/java/org/n52/server/da/oxf/SosRequestBuilderFactory.java | Java | gpl-2.0 | 1,956 |
<?php
/* define package */
define('PKG_NAME', 'VoteForms');
define('PKG_NAME_LOWER', strtolower(PKG_NAME));
define('PKG_VERSION', '2.0.5');
define('PKG_RELEASE', 'beta');
define('PKG_AUTO_INSTALL', true);
/* define paths */
if (isset($_SERVER['MODX_BASE_PATH'])) {
define('MODX_BASE_PATH', $_SERVER['MODX_BASE_PATH']);
}
elseif (file_exists(dirname(dirname(dirname(__FILE__))) . '/core')) {
define('MODX_BASE_PATH', dirname(dirname(dirname(__FILE__))) . '/');
}
else {
define('MODX_BASE_PATH', dirname(dirname(dirname(dirname(__FILE__)))) . '/');
}
define('MODX_CORE_PATH', MODX_BASE_PATH . 'core/');
define('MODX_MANAGER_PATH', MODX_BASE_PATH . 'manager/');
define('MODX_CONNECTORS_PATH', MODX_BASE_PATH . 'connectors/');
define('MODX_ASSETS_PATH', MODX_BASE_PATH . 'assets/');
/* define urls */
define('MODX_BASE_URL', '/');
define('MODX_CORE_URL', MODX_BASE_URL . 'core/');
define('MODX_MANAGER_URL', MODX_BASE_URL . 'manager/');
define('MODX_CONNECTORS_URL', MODX_BASE_URL . 'connectors/');
define('MODX_ASSETS_URL', MODX_BASE_URL . 'assets/');
/* define build options */
define('BUILD_MENU_UPDATE', true);
define('BUILD_ACTION_UPDATE', true);
define('BUILD_SETTING_UPDATE', true);
define('BUILD_CHUNK_UPDATE', true);
define('BUILD_SNIPPET_UPDATE', true);
define('BUILD_PLUGIN_UPDATE', true);
//define('BUILD_EVENT_UPDATE', true);
//define('BUILD_POLICY_UPDATE', true);
//define('BUILD_POLICY_TEMPLATE_UPDATE', true);
//define('BUILD_PERMISSION_UPDATE', true);
if (!empty($_GET['development'])) {
define('PKG_NAMESPACE_PATH', '{base_path}' . PKG_NAME . '/core/components/' . PKG_NAME_LOWER . '/');
define('PKG_CORE_PATH', MODX_BASE_PATH . PKG_NAME . '/core/components/' . PKG_NAME_LOWER . '/');
define('PKG_STATIC_PATH', PKG_NAME . '/core/components/' . PKG_NAME_LOWER);
define('PKG_ASSETS_URL', '/' . PKG_NAME .'/assets/components/' . PKG_NAME_LOWER . '/');
define('BUILD_CHUNK_STATIC', true);
define('BUILD_SNIPPET_STATIC', true);
define('BUILD_PLUGIN_STATIC', true);
} else {
define('PKG_NAMESPACE_PATH', '{core_path}components/' . PKG_NAME_LOWER . '/');
define('PKG_CORE_PATH', '{core_path}components/' . PKG_NAME_LOWER . '/');
define('PKG_STATIC_PATH', 'core/components/' . PKG_NAME_LOWER);
define('PKG_ASSETS_URL', '{assets_url}components/' . PKG_NAME_LOWER . '/');
define('BUILD_CHUNK_STATIC', false);
define('BUILD_SNIPPET_STATIC', false);
define('BUILD_PLUGIN_STATIC', false);
}
$BUILD_RESOLVERS = array(
'tables',
'chunks',
'setup',
); | me6iaton/VoteForms | _build/build.config.php | PHP | gpl-2.0 | 2,496 |
//
// ID Engine
// ID_IN.c - Input Manager
// v1.0d1
// By Jason Blochowiak
//
//
// This module handles dealing with the various input devices
//
// Depends on: Memory Mgr (for demo recording), Sound Mgr (for timing stuff),
// User Mgr (for command line parms)
//
// Globals:
// LastScan - The keyboard scan code of the last key pressed
// LastASCII - The ASCII value of the last key pressed
// DEBUG - there are more globals
//
#include "wl_def.h"
void IN_GetJoyDelta(int *dx,int *dy) { (void)dx; (void)dy; }
/*
=============================================================================
GLOBAL VARIABLES
=============================================================================
*/
#ifdef USE_SDL
//
// configuration variables
//
boolean MousePresent;
boolean forcegrabmouse;
// Global variables
volatile boolean Keyboard[SDLK_LAST];
volatile boolean Paused;
volatile char LastASCII;
volatile ScanCode LastScan;
//KeyboardDef KbdDefs = {0x1d,0x38,0x47,0x48,0x49,0x4b,0x4d,0x4f,0x50,0x51};
static KeyboardDef KbdDefs = {
sc_Control, // button0
sc_Alt, // button1
sc_Home, // upleft
sc_UpArrow, // up
sc_PgUp, // upright
sc_LeftArrow, // left
sc_RightArrow, // right
sc_End, // downleft
sc_DownArrow, // down
sc_PgDn // downright
};
static SDL_Joystick *Joystick;
int JoyNumButtons;
static int JoyNumHats;
static bool GrabInput = false;
/*
=============================================================================
LOCAL VARIABLES
=============================================================================
*/
byte ASCIINames[] = // Unshifted ASCII for scan codes // TODO: keypad
{
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,8 ,9 ,0 ,0 ,0 ,13 ,0 ,0 , // 0
0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,27 ,0 ,0 ,0 , // 1
' ',0 ,0 ,0 ,0 ,0 ,0 ,39 ,0 ,0 ,'*','+',',','-','.','/', // 2
'0','1','2','3','4','5','6','7','8','9',0 ,';',0 ,'=',0 ,0 , // 3
'`','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o', // 4
'p','q','r','s','t','u','v','w','x','y','z','[',92 ,']',0 ,0 , // 5
0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , // 6
0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 // 7
};
byte ShiftNames[] = // Shifted ASCII for scan codes
{
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,8 ,9 ,0 ,0 ,0 ,13 ,0 ,0 , // 0
0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,27 ,0 ,0 ,0 , // 1
' ',0 ,0 ,0 ,0 ,0 ,0 ,34 ,0 ,0 ,'*','+','<','_','>','?', // 2
')','!','@','#','$','%','^','&','*','(',0 ,':',0 ,'+',0 ,0 , // 3
'~','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', // 4
'P','Q','R','S','T','U','V','W','X','Y','Z','{','|','}',0 ,0 , // 5
0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , // 6
0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 // 7
};
byte SpecialNames[] = // ASCII for 0xe0 prefixed codes
{
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , // 0
0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,13 ,0 ,0 ,0 , // 1
0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , // 2
0 ,0 ,0 ,0 ,0 ,'/',0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , // 3
0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , // 4
0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , // 5
0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 , // 6
0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 // 7
};
static boolean IN_Started;
static Direction DirTable[] = // Quick lookup for total direction
{
dir_NorthWest, dir_North, dir_NorthEast,
dir_West, dir_None, dir_East,
dir_SouthWest, dir_South, dir_SouthEast
};
///////////////////////////////////////////////////////////////////////////
//
// INL_GetMouseButtons() - Gets the status of the mouse buttons from the
// mouse driver
//
///////////////////////////////////////////////////////////////////////////
static int
INL_GetMouseButtons(void)
{
int buttons = SDL_GetMouseState(NULL, NULL);
int middlePressed = buttons & SDL_BUTTON(SDL_BUTTON_MIDDLE);
int rightPressed = buttons & SDL_BUTTON(SDL_BUTTON_RIGHT);
buttons &= ~(SDL_BUTTON(SDL_BUTTON_MIDDLE) | SDL_BUTTON(SDL_BUTTON_RIGHT));
if(middlePressed) buttons |= 1 << 2;
if(rightPressed) buttons |= 1 << 1;
return buttons;
}
///////////////////////////////////////////////////////////////////////////
//
// IN_GetJoyDelta() - Returns the relative movement of the specified
// joystick (from +/-127)
//
///////////////////////////////////////////////////////////////////////////
void IN_GetJoyDelta(int *dx,int *dy)
{
if(!Joystick)
{
*dx = *dy = 0;
return;
}
SDL_JoystickUpdate();
#ifdef _arch_dreamcast
int x = 0;
int y = 0;
#else
int x = SDL_JoystickGetAxis(Joystick, 0) >> 8;
int y = SDL_JoystickGetAxis(Joystick, 1) >> 8;
#endif
if(param_joystickhat != -1)
{
uint8_t hatState = SDL_JoystickGetHat(Joystick, param_joystickhat);
if(hatState & SDL_HAT_RIGHT)
x += 127;
else if(hatState & SDL_HAT_LEFT)
x -= 127;
if(hatState & SDL_HAT_DOWN)
y += 127;
else if(hatState & SDL_HAT_UP)
y -= 127;
if(x < -128) x = -128;
else if(x > 127) x = 127;
if(y < -128) y = -128;
else if(y > 127) y = 127;
}
*dx = x;
*dy = y;
}
///////////////////////////////////////////////////////////////////////////
//
// IN_GetJoyFineDelta() - Returns the relative movement of the specified
// joystick without dividing the results by 256 (from +/-127)
//
///////////////////////////////////////////////////////////////////////////
void IN_GetJoyFineDelta(int *dx, int *dy)
{
if(!Joystick)
{
*dx = 0;
*dy = 0;
return;
}
SDL_JoystickUpdate();
int x = SDL_JoystickGetAxis(Joystick, 0);
int y = SDL_JoystickGetAxis(Joystick, 1);
if(x < -128) x = -128;
else if(x > 127) x = 127;
if(y < -128) y = -128;
else if(y > 127) y = 127;
*dx = x;
*dy = y;
}
/*
===================
=
= IN_JoyButtons
=
===================
*/
int IN_JoyButtons()
{
if(!Joystick) return 0;
SDL_JoystickUpdate();
int res = 0;
for(int i = 0; i < JoyNumButtons && i < 32; i++)
res |= SDL_JoystickGetButton(Joystick, i) << i;
return res;
}
boolean IN_JoyPresent()
{
return Joystick != NULL;
}
static void processEvent(SDL_Event *event)
{
switch (event->type)
{
// exit if the window is closed
case SDL_QUIT:
Quit(NULL);
// check for keypresses
case SDL_KEYDOWN:
{
if(event->key.keysym.sym==SDLK_SCROLLOCK || event->key.keysym.sym==SDLK_F12)
{
GrabInput = !GrabInput;
SDL_WM_GrabInput(GrabInput ? SDL_GRAB_ON : SDL_GRAB_OFF);
return;
}
LastScan = event->key.keysym.sym;
SDLMod mod = SDL_GetModState();
if(Keyboard[sc_Alt])
{
if(LastScan==SDLK_F4)
Quit(NULL);
}
if(LastScan == SDLK_KP_ENTER) LastScan = SDLK_RETURN;
else if(LastScan == SDLK_RSHIFT) LastScan = SDLK_LSHIFT;
else if(LastScan == SDLK_RALT) LastScan = SDLK_LALT;
else if(LastScan == SDLK_RCTRL) LastScan = SDLK_LCTRL;
else
{
if((mod & KMOD_NUM) == 0)
{
switch(LastScan)
{
case SDLK_KP2: LastScan = SDLK_DOWN; break;
case SDLK_KP4: LastScan = SDLK_LEFT; break;
case SDLK_KP6: LastScan = SDLK_RIGHT; break;
case SDLK_KP8: LastScan = SDLK_UP; break;
}
}
}
int sym = LastScan;
if(sym >= 'a' && sym <= 'z')
sym -= 32; // convert to uppercase
if(mod & (KMOD_SHIFT | KMOD_CAPS))
{
if(sym < lengthof(ShiftNames) && ShiftNames[sym])
LastASCII = ShiftNames[sym];
}
else
{
if(sym < lengthof(ASCIINames) && ASCIINames[sym])
LastASCII = ASCIINames[sym];
}
if(LastScan<SDLK_LAST)
Keyboard[LastScan] = 1;
if(LastScan == SDLK_PAUSE)
Paused = true;
break;
}
case SDL_KEYUP:
{
int key = event->key.keysym.sym;
if(key == SDLK_KP_ENTER) key = SDLK_RETURN;
else if(key == SDLK_RSHIFT) key = SDLK_LSHIFT;
else if(key == SDLK_RALT) key = SDLK_LALT;
else if(key == SDLK_RCTRL) key = SDLK_LCTRL;
else
{
if((SDL_GetModState() & KMOD_NUM) == 0)
{
switch(key)
{
case SDLK_KP2: key = SDLK_DOWN; break;
case SDLK_KP4: key = SDLK_LEFT; break;
case SDLK_KP6: key = SDLK_RIGHT; break;
case SDLK_KP8: key = SDLK_UP; break;
}
}
}
if(key<SDLK_LAST)
Keyboard[key] = 0;
break;
}
#if defined(GP2X)
case SDL_JOYBUTTONDOWN:
GP2X_ButtonDown(event->jbutton.button);
break;
case SDL_JOYBUTTONUP:
GP2X_ButtonUp(event->jbutton.button);
break;
#endif
}
}
void IN_WaitAndProcessEvents()
{
SDL_Event event;
if(!SDL_WaitEvent(&event)) return;
do
{
processEvent(&event);
}
while(SDL_PollEvent(&event));
}
void IN_ProcessEvents()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
processEvent(&event);
}
}
///////////////////////////////////////////////////////////////////////////
//
// IN_Startup() - Starts up the Input Mgr
//
///////////////////////////////////////////////////////////////////////////
void
IN_Startup(void)
{
if (IN_Started)
return;
IN_ClearKeysDown();
if(param_joystickindex >= 0 && param_joystickindex < SDL_NumJoysticks())
{
Joystick = SDL_JoystickOpen(param_joystickindex);
if(Joystick)
{
JoyNumButtons = SDL_JoystickNumButtons(Joystick);
if(JoyNumButtons > 32) JoyNumButtons = 32; // only up to 32 buttons are supported
JoyNumHats = SDL_JoystickNumHats(Joystick);
if(param_joystickhat < -1 || param_joystickhat >= JoyNumHats)
Quit("The joystickhat param must be between 0 and %i!", JoyNumHats - 1);
}
}
SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
if(fullscreen || forcegrabmouse)
{
GrabInput = true;
SDL_WM_GrabInput(SDL_GRAB_ON);
}
// I didn't find a way to ask libSDL whether a mouse is present, yet...
#if defined(GP2X)
MousePresent = false;
#elif defined(_arch_dreamcast)
MousePresent = DC_MousePresent();
#else
MousePresent = true;
#endif
IN_Started = true;
}
///////////////////////////////////////////////////////////////////////////
//
// IN_Shutdown() - Shuts down the Input Mgr
//
///////////////////////////////////////////////////////////////////////////
void
IN_Shutdown(void)
{
if (!IN_Started)
return;
if(Joystick)
SDL_JoystickClose(Joystick);
IN_Started = false;
}
///////////////////////////////////////////////////////////////////////////
//
// IN_ClearKeysDown() - Clears the keyboard array
//
///////////////////////////////////////////////////////////////////////////
void
IN_ClearKeysDown(void)
{
LastScan = sc_None;
LastASCII = key_None;
memset ((void *) Keyboard,0,sizeof(Keyboard));
}
///////////////////////////////////////////////////////////////////////////
//
// IN_ReadControl() - Reads the device associated with the specified
// player and fills in the control info struct
//
///////////////////////////////////////////////////////////////////////////
void
IN_ReadControl(int player,ControlInfo *info)
{
word buttons;
int dx,dy;
Motion mx,my;
dx = dy = 0;
mx = my = motion_None;
buttons = 0;
IN_ProcessEvents();
if (Keyboard[KbdDefs.upleft])
mx = motion_Left,my = motion_Up;
else if (Keyboard[KbdDefs.upright])
mx = motion_Right,my = motion_Up;
else if (Keyboard[KbdDefs.downleft])
mx = motion_Left,my = motion_Down;
else if (Keyboard[KbdDefs.downright])
mx = motion_Right,my = motion_Down;
if (Keyboard[KbdDefs.up])
my = motion_Up;
else if (Keyboard[KbdDefs.down])
my = motion_Down;
if (Keyboard[KbdDefs.left])
mx = motion_Left;
else if (Keyboard[KbdDefs.right])
mx = motion_Right;
if (Keyboard[KbdDefs.button0])
buttons += 1 << 0;
if (Keyboard[KbdDefs.button1])
buttons += 1 << 1;
dx = mx * 127;
dy = my * 127;
info->x = dx;
info->xaxis = mx;
info->y = dy;
info->yaxis = my;
info->button0 = (buttons & (1 << 0)) != 0;
info->button1 = (buttons & (1 << 1)) != 0;
info->button2 = (buttons & (1 << 2)) != 0;
info->button3 = (buttons & (1 << 3)) != 0;
info->dir = DirTable[((my + 1) * 3) + (mx + 1)];
}
///////////////////////////////////////////////////////////////////////////
//
// IN_WaitForKey() - Waits for a scan code, then clears LastScan and
// returns the scan code
//
///////////////////////////////////////////////////////////////////////////
ScanCode
IN_WaitForKey(void)
{
ScanCode result;
while ((result = LastScan)==0)
IN_WaitAndProcessEvents();
LastScan = 0;
return(result);
}
///////////////////////////////////////////////////////////////////////////
//
// IN_WaitForASCII() - Waits for an ASCII char, then clears LastASCII and
// returns the ASCII value
//
///////////////////////////////////////////////////////////////////////////
char
IN_WaitForASCII(void)
{
char result;
while ((result = LastASCII)==0)
IN_WaitAndProcessEvents();
LastASCII = '\0';
return(result);
}
///////////////////////////////////////////////////////////////////////////
//
// IN_Ack() - waits for a button or key press. If a button is down, upon
// calling, it must be released for it to be recognized
//
///////////////////////////////////////////////////////////////////////////
boolean btnstate[NUMBUTTONS];
void IN_StartAck(void)
{
IN_ProcessEvents();
//
// get initial state of everything
//
IN_ClearKeysDown();
memset(btnstate, 0, sizeof(btnstate));
int buttons = IN_JoyButtons() << 4;
if(MousePresent)
buttons |= IN_MouseButtons();
for(int i = 0; i < NUMBUTTONS; i++, buttons >>= 1)
if(buttons & 1)
btnstate[i] = true;
}
boolean IN_CheckAck (void)
{
IN_ProcessEvents();
//
// see if something has been pressed
//
if(LastScan)
return true;
int buttons = IN_JoyButtons() << 4;
if(MousePresent)
buttons |= IN_MouseButtons();
for(int i = 0; i < NUMBUTTONS; i++, buttons >>= 1)
{
if(buttons & 1)
{
if(!btnstate[i])
{
// Wait until button has been released
do
{
IN_WaitAndProcessEvents();
buttons = IN_JoyButtons() << 4;
if(MousePresent)
buttons |= IN_MouseButtons();
}
while(buttons & (1 << i));
return true;
}
}
else
btnstate[i] = false;
}
return false;
}
void IN_Ack (void)
{
IN_StartAck ();
do
{
IN_WaitAndProcessEvents();
}
while(!IN_CheckAck ());
}
///////////////////////////////////////////////////////////////////////////
//
// IN_UserInput() - Waits for the specified delay time (in ticks) or the
// user pressing a key or a mouse button. If the clear flag is set, it
// then either clears the key or waits for the user to let the mouse
// button up.
//
///////////////////////////////////////////////////////////////////////////
boolean IN_UserInput(longword delay)
{
longword lasttime;
lasttime = GetTimeCount();
IN_StartAck ();
do
{
IN_ProcessEvents();
if (IN_CheckAck())
return true;
DelayMS(5);
} while (GetTimeCount() - lasttime < delay);
return(false);
}
//===========================================================================
/*
===================
=
= IN_MouseButtons
=
===================
*/
int IN_MouseButtons (void)
{
if (MousePresent)
return INL_GetMouseButtons();
else
return 0;
}
bool IN_IsInputGrabbed()
{
return GrabInput;
}
void IN_CenterMouse()
{
SDL_WarpMouse(screenWidth / 2, screenHeight / 2);
}
#endif
| WarlockD/crispy-doom | stm32/wolf3d/id_in.cpp | C++ | gpl-2.0 | 17,126 |
<div class="mcl-login-form-login">
<h2><?php echo ($instance_id == "my_columbia_llm") ? "My Columbia LL.M." : "My Columbia Law and Admitted Student" ?></h2>
<h3>Security Question Update</h3>
<div <?php echo (isset($_SESSION['messages']['status'][0])) ? "class='status-msg'" : "" ?> >
<?php echo (isset($_SESSION['messages']['status'][0])) ? $_SESSION['messages']['status'][0] : "" ?>
</div>
<div <?php echo (isset($_SESSION['messages']['error'][0])) ? "class='error-msg'" : "" ?> >
<?php echo (isset($_SESSION['messages']['error'][0])) ? $_SESSION['messages']['error'][0] : "" ?>
</div>
<?php echo drupal_render($form); ?>
<p class="back-to-login">
<a id="back-to-login-link" href="<?php echo base_path() ?>admissions/jd/my-columbia-law">Back to Login Page</a>
</p>
</div>
<style type="text/css">
body div.messages {display: none;}
.menu-mlid-4476 a {color:#333333;}
div.mcl-login-form-login label {
font-weight: bold;
font-size: 13px;
color: #333333;
}
div.mcl-login-form-login div#edit-actions {
margin-bottom: 0 !important;
margin-top: 15px !important;
}
div.mcl-login-form-login label span.form-required {
display: none;
}
div.error-msg {
background-color: #FEF5F1;
color: #8C2E0B;
border: 1px solid #ED541D;
background-image: url("/misc/message-24-error.png");
background-position: 8px 8px;
background-repeat: no-repeat;
margin: 6px 0;
padding: 10px 10px 10px 50px;
font-size: 13px;
}
div.status-msg {
background-color: #F8FFF0;
color: #234600;
border: 1px solid #BBEE77;
background-image: url("/misc/message-24-ok.png");
background-position: 8px 8px;
background-repeat: no-repeat;
margin: 6px 0;
padding: 10px 10px 10px 50px;
font-size: 13px;
}
div.mcl-login-form-login input#edit-submit {
border-radius: 15px;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
background-color: #333333;
border: 2px solid #999999;
color: #FFFFFF;
font: 15px Verdana, Arial, sans-serif;
padding: 3px 15px 5px;
margin-bottom: 15px;
margin-top: 10px;
}
div.mcl-login-form-login input#edit-submit:active {
background-color: #186E9E;
color: #FFFFFF;
}
div.mcl-login-form-login select#edit-security-question-select {
width: 345px;
font: 12px/10px Verdana,Arial,Helvetica,sans-serif;
margin: 10px 0 15px;
}
div.mcl-login-form-login select#edit-security-question-select,
div.mcl-login-form-login input#edit-security-question-other,
div.mcl-login-form-login input#edit-security-answer {
background-color: #FFFFFF;
border: 2px solid #999999;
color: #666666;
display: block;
height: 25px;
padding: 1px 10px 3px;
}
div.mcl-login-form-login input#edit-security-question-other,
div.mcl-login-form-login input#edit-security-answer {
border-radius:15px;
-moz-border-radius:15px;
-webkit-border-radius:15px;
font: 21px/18px Verdana,Arial,Helvetica,sans-serif;
width: 321px;
margin: 10px 0;
}
div.mcl-login-form-login select#edit-security-question-select:focus,
div.mcl-login-form-login input#edit-security-question-other:focus,
div.mcl-login-form-login input#edit-security-answer {
border: #186E9E 2px solid;
}
p#mcl-security-answer {
font-size: 13px;
margin-top: 10px;
}
body div#cls-mcl-account-errors {
background-image: none;
margin: 0 0 20px;
}
body div#cls-mcl-account-errors label {
width: auto;
float: none;
color: #cc0000;
}
body div#cls-mcl-account-errors li {
margin: 0 0 5px 15px;
color: #cc0000;
}
div#cls-mcl-account-errors:after {
clear: both;
content: " ";
display: block;
font-size: 0;
height: 0;
line-height: 0;
visibility: hidden;
width: 0;
}
</style>
| nexttee/culaw | sites/default/modules/cls_mcl/templates/security_question_update.tpl.php | PHP | gpl-2.0 | 3,687 |
$Rev: 916 $
| boudewijnrempt/HyvesDesktop | 3rdparty/socorro/webapp-php/application/views/common/version.php | PHP | gpl-2.0 | 13 |
package utility;
public class IdConst extends Ident {
//Valeur de la constante
private int valeur;
//Initialisation d'une IdConst (nom, type et valeur)
public IdConst(String _name, int _type, int _valeur) {
super(_name, _type); //constructeur de Ident
this.valeur = _valeur;
}
public int getValeur() {return this.valeur;}
public void setValeur(int _v) {this.valeur = _v;}
//Verificateur de type
public boolean isConst() {return true;}
}
| william-insa/Projet_compilateur | Compilateur/src/utility/IdConst.java | Java | gpl-2.0 | 455 |
/**********************************************************************
Freeciv - Copyright (C) 1996 - A Kjeldberg, L Gregersen, P Unold
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
***********************************************************************/
#ifndef WC_COMMON_WORKLIST_H
#define WC_COMMON_WORKLIST_H
#include "shared.hh" /* MAX_LEN_NAME */
#define MAX_LEN_WORKLIST 16
#define MAX_NUM_WORKLISTS 16
/* worklist element flags */
enum worklist_elem_flag {
WEF_END, /* element is past end of list */
WEF_UNIT, /* element specifies a unit to be built */
WEF_IMPR, /* element specifies an improvement to be built */
WEF_LAST /* leave this last */
};
/* a worklist */
struct worklist {
bool is_valid;
char name[MAX_LEN_NAME];
enum worklist_elem_flag wlefs[MAX_LEN_WORKLIST];
int wlids[MAX_LEN_WORKLIST];
};
void init_worklist(struct worklist *pwl);
int worklist_length(const struct worklist *pwl);
bool worklist_is_empty(const struct worklist *pwl);
bool worklist_peek(const struct worklist *pwl, int *id, bool *is_unit);
bool worklist_peek_ith(const struct worklist *pwl, int *id, bool *is_unit,
int idx);
void worklist_advance(struct worklist *pwl);
void copy_worklist(struct worklist *dst, const struct worklist *src);
void worklist_remove(struct worklist *pwl, int idx);
bool worklist_append(struct worklist *pwl, int id, bool is_unit);
bool worklist_insert(struct worklist *pwl, int id, bool is_unit, int idx);
bool are_worklists_equal(const struct worklist *wlist1,
const struct worklist *wlist2);
#endif /* WC_COMMON_WORKLIST_H */
| seggil/warciv | common/worklist.hh | C++ | gpl-2.0 | 2,086 |
<?php
/* -----------------------------------------------------------------------------------------
$Id: xtc_get_uprid.inc.php 899 2005-04-29 02:40:57Z hhgag $
XT-Commerce - community made shopping
http://www.xt-commerce.com
Copyright (c) 2003 XT-Commerce
-----------------------------------------------------------------------------------------
based on:
(c) 2000-2001 The Exchange Project (earlier name of osCommerce)
(c) 2002-2003 osCommerce(general.php,v 1.225 2003/05/29); www.oscommerce.com
(c) 2003 nextcommerce (xtc_get_uprid.inc.php,v 1.3 2003/08/13); www.nextcommerce.org
Released under the GNU General Public License
---------------------------------------------------------------------------------------*/
// Return a product ID with attributes
function xtc_get_uprid($prid, $params) {
global $scModules;
if (is_numeric($prid)) {
$uprid = $prid;
if (is_array($params) && (sizeof($params) > 0)) {
$attributes_check = true;
$attributes_ids = '';
reset($params);
while (list($option, $value) = each($params)) {
//new module support
list($option, $value) = (class_exists('shoppingCartModules') ? $scModules->get_uprid(array($option, $value)) : array($option, $value));
if (is_numeric($option) && is_numeric($value)) {
$attributes_ids .= '{' . (int)$option . '}' . (int)$value;
} else {
$attributes_check = false;
break;
}
}
if ($attributes_check == true) {
$uprid .= $attributes_ids;
}
}
} else {
$uprid = xtc_get_prid($prid);
if (is_numeric($uprid)) {
if (strpos($prid, '{') !== false) {
$attributes_check = true;
$attributes_ids = '';
$attributes = explode('{', substr($prid, strpos($prid, '{')+1));
for ($i=0, $n=sizeof($attributes); $i<$n; $i++) {
$pair = explode('}', $attributes[$i]);
if (is_numeric($pair[0]) && is_numeric($pair[1])) {
$attributes_ids .= '{' . (int)$pair[0] . '}' . (int)$pair[1];
} else {
$attributes_check = false;
break;
}
}
if ($attributes_check == true) {
$uprid .= $attributes_ids;
}
}
} else {
return false;
}
}
return $uprid;
}
?> | dsiekiera/modified-bs4 | inc/xtc_get_uprid.inc.php | PHP | gpl-2.0 | 2,442 |
/*
* ZAL - The abstraction layer for Zimbra.
* Copyright (C) 2016 ZeXtras S.r.l.
*
* This file is part of ZAL.
*
* 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 2 of
* the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ZAL. If not, see <http://www.gnu.org/licenses/>.
*/
package org.openzal.zal;
import com.zimbra.cs.account.accesscontrol.generated.RightConsts;
public class RightConstants
{
public static String RT_sendAs = RightConsts.RT_sendAs;
public static String RT_domainAdminCosRights = RightConsts.RT_domainAdminCosRights;
public static String RT_loginAs = RightConsts.RT_loginAs;
public static String RT_domainAdminRights = RightConsts.RT_domainAdminRights;
public static String RT_adminLoginAs = RightConsts.RT_adminLoginAs;
public static String RT_domainAdminConsoleAccountsFeaturesTabRights =
RightConsts.RT_domainAdminConsoleAccountsFeaturesTabRights;
public static String RT_listZimlet = RightConsts.RT_listZimlet;
public static String RT_getZimlet = RightConsts.RT_getZimlet;
public static String RT_domainAdminZimletRights = RightConsts.RT_domainAdminZimletRights;
public static String RT_setAdminSavedSearch = RightConsts.RT_setAdminSavedSearch;
public static String RT_viewAdminSavedSearch = RightConsts.RT_viewAdminSavedSearch;
public static String RT_domainAdminConsoleDLSharesTabRights = RightConsts.RT_domainAdminConsoleDLSharesTabRights;
public static String RT_getAccountInfo = RightConsts.RT_getAccountInfo;
public static String RT_configureQuota = RightConsts.RT_configureQuota;
public static String RT_sendOnBehalfOf = RightConsts.RT_sendOnBehalfOf;
public static String RT_sendOnBehalfOfDistList = RightConsts.RT_sendOnBehalfOfDistList;
public static String RT_sendAsDistList = RightConsts.RT_sendAsDistList;
public static String RT_addGroupAlias = RightConsts.RT_addGroupAlias;
public static String RT_addGroupMember = RightConsts.RT_addGroupMember;
public static String RT_createGroup = RightConsts.RT_createGroup;
public static String RT_deleteGroup = RightConsts.RT_deleteGroup;
public static String RT_getGroup = RightConsts.RT_getGroup;
public static String RT_listGroup = RightConsts.RT_listGroup;
public static String RT_modifyGroup = RightConsts.RT_modifyGroup;
public static String RT_removeGroupAlias = RightConsts.RT_removeGroupAlias;
public static String RT_removeGroupMember = RightConsts.RT_removeGroupMember;
public static String RT_renameGroup = RightConsts.RT_renameGroup;
}
| ZeXtras/OpenZAL | src/java/org/openzal/zal/RightConstants.java | Java | gpl-2.0 | 2,924 |
<?php
/*
+---------------------------------------------------------------------------+
| OpenX v2.8 |
| ========== |
| |
| Copyright (c) 2003-2009 OpenX Limited |
| For contact details, see: http://www.openx.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 |
+---------------------------------------------------------------------------+
$Id: userlog-index.php 81439 2012-05-07 23:59:14Z chris.nutting $
*/
// Require the initialisation file
require_once '../../init.php';
// Required files
require_once MAX_PATH . '/lib/max/Admin_DA.php';
require_once MAX_PATH . '/lib/max/other/lib-userlog.inc.php';
require_once MAX_PATH . '/lib/OA/Dal.php';
require_once MAX_PATH . '/lib/OA/Admin/Template.php';
require_once MAX_PATH . '/www/admin/config.php';
require_once MAX_PATH . '/lib/OA/Dll/Audit.php';
require_once MAX_PATH . '/lib/OA/Admin/UI/Field/AuditDaySpanField.php';
require_once 'Pager/Pager.php';
require_once MAX_PATH . '/lib/OX/Translation.php';
// Security check
OA_Permission::enforceAccount(OA_ACCOUNT_ADMIN, OA_ACCOUNT_MANAGER, OA_ACCOUNT_ADVERTISER, OA_ACCOUNT_TRAFFICKER);
OA_Permission::enforceAccountPermission(OA_ACCOUNT_ADVERTISER, OA_PERM_USER_LOG_ACCESS);
OA_Permission::enforceAccountPermission(OA_ACCOUNT_TRAFFICKER, OA_PERM_USER_LOG_ACCESS);
// Register input variables
$advertiserId = MAX_getValue('advertiserId', 0);
$campaignId = MAX_getValue('campaignId', 0);
$publisherId = MAX_getValue('publisherId', 0);
$zoneId = MAX_getValue('zoneId', 0);
$startDate = MAX_getStoredValue('period_start', null);
$endDate = MAX_getStoredValue('period_end', null);
$periodPreset = MAX_getValue('period_preset', 'all_events');
if (!empty($advertiserId)) {
OA_Permission::enforceAccessToObject('clients', $advertiserId);
}
if (!empty($campaignId)) {
OA_Permission::enforceAccessToObject('campaigns', $campaignId);
}
if (!empty($publisherId)) {
OA_Permission::enforceAccessToObject('affiliates', $publisherId);
}
if (!empty($zoneId)) {
OA_Permission::enforceAccessToObject('zones', $zoneId);
}
/*-------------------------------------------------------*/
/* HTML framework */
/*-------------------------------------------------------*/
phpAds_PageHeader("5.4");
if (OA_Permission::isAccount(OA_ACCOUNT_ADMIN)) {
// Show all "My Account" sections
phpAds_ShowSections(array("5.1", "5.2", "5.3", "5.5", "5.6", "5.4"));
phpAds_UserlogSelection("index");
}
else if (OA_Permission::isAccount(OA_ACCOUNT_MANAGER)) {
// Show the "Preferences", "User Log" and "Channel Management" sections of the "My Account" sections
phpAds_ShowSections(array("5.1", "5.2", "5.4", "5.7"));
}
else if (OA_Permission::isAccount(OA_ACCOUNT_TRAFFICKER) || OA_Permission::isAccount(OA_ACCOUNT_ADVERTISER)) {
phpAds_ShowSections(array("5.1", "5.2", "5.4"));
}
// Paging related input variables
$listorder = htmlspecialchars(MAX_getStoredValue('listorder', 'updated'));
$oAudit = &OA_Dal::factoryDO('audit');
$aAuditColumns = $oAudit->table();
$aColumnNamesFound = array_keys($aAuditColumns, $listorder);
if (empty($aColumnNamesFound)) {
// Invalid column name to order by, set to default
$listorder = 'updated';
}
$orderdirection = htmlspecialchars(MAX_getStoredValue('orderdirection', 'up'));
if (!($orderdirection == 'up' || $orderdirection == 'down')) {
if (stristr($orderdirection, 'down')) {
$orderdirection = 'down';
} else {
$orderdirection = 'up';
}
}
$setPerPage = MAX_getStoredValue('setPerPage', 10);
$pageID = MAX_getStoredValue('pageID', 1);
// Setup date selector
$aPeriod = array(
'period_preset' => $periodPreset,
'period_start' => $startDate,
'period_end' => $endDate
);
$daySpan = new OA_Admin_UI_Audit_DaySpanField('period');
$daySpan->setValueFromArray($aPeriod);
$daySpan->enableAutoSubmit();
// Initialize parameters
$pageName = basename($_SERVER['SCRIPT_NAME']);
// Load template
$oTpl = new OA_Admin_Template('userlog-index.html');
// Get advertisers & publishers for filters
$showAdvertisers = OA_Permission::isAccount(OA_ACCOUNT_ADVERTISER, OA_ACCOUNT_MANAGER, OA_ACCOUNT_ADMIN);
$showPublishers = OA_Permission::isAccount(OA_ACCOUNT_TRAFFICKER, OA_ACCOUNT_MANAGER, OA_ACCOUNT_ADMIN);
$agencyId = OA_Permission::getAgencyId();
// Get advertisers if we show them
$aAdvertiser = $aPublisher = array();
if ($showAdvertisers) {
if (OA_Permission::isAccount(OA_ACCOUNT_ADVERTISER)) {
$tempAdvertiserId = OA_Permission::getEntityId();
$aAdvertiserList = Admin_DA::getAdvertisers(array('advertiser_id' => $tempAdvertiserId));
} else {
$aAdvertiserList = Admin_DA::getAdvertisers(array('agency_id' => $agencyId));
}
$aAdvertiser[0] = $GLOBALS['strSelectAdvertiser'];
foreach($aAdvertiserList as $key => $aValue) {
$aAdvertiser[$aValue['advertiser_id']] = $aValue['name'];
}
$aCampaign = array();
if (!empty($advertiserId)) {
$campaign = Admin_DA::getCampaigns(array('client_id' => $advertiserId));
$aCampaign[0] = $GLOBALS['strSelectPlacement'];
foreach($campaign as $key => $aValue) {
$aCampaign[$aValue['campaign_id']] = $aValue['campaignname'];
}
}
}
// Get publishers if we show them
if ($showPublishers) {
if (OA_Permission::isAccount(OA_ACCOUNT_TRAFFICKER)) {
$tempPublisherId = OA_Permission::getEntityId();
$aPublisherList = Admin_DA::getPublishers(array('publisher_id' => $tempPublisherId));
} else {
$aPublisherList = Admin_DA::getPublishers(array('agency_id' => $agencyId));
}
$aPublisher[0] = $GLOBALS['strSelectPublisher'];
foreach ($aPublisherList as $key => $aValue) {
$aPublisher[$aValue['publisher_id']] = $aValue['name'];
}
if (!empty($publisherId)) {
$zone = Admin_DA::getZones(array('publisher_id' => $publisherId));
$aZone[0] = $GLOBALS['strSelectZone'];
foreach ($zone as $key => $aValue) {
$aZone[$aValue['zone_id']] = $aValue['name'];
}
}
}
$oTrans = new OX_Translation();
$aParams = array(
'order' => $orderdirection,
'listorder' => $listorder,
'start_date' => $startDate,
'end_date' => $endDate,
'prevImg' => '<< ' . $oTrans->translate('Back'),
'nextImg' => $oTrans->translate('Next') . ' >>'
);
// Only pass advertiser or website props if we show related checkboxes
if ($showAdvertisers) {
$aParams['advertiser_id']= $advertiserId;
$aParams['campaign_id'] = $campaignId;
}
if ($showPublishers) {
$aParams['publisher_id'] = $publisherId;
$aParams['zone_id'] = $zoneId;
}
// Account security
if (OA_Permission::isAccount(OA_ACCOUNT_MANAGER)) {
$aParams['account_id'] = OA_Permission::getAccountId();
}
if (OA_Permission::isAccount(OA_ACCOUNT_ADVERTISER)) {
$aParams['advertiser_account_id'] = OA_Permission::getAccountId();
}
if (OA_Permission::isAccount(OA_ACCOUNT_TRAFFICKER)) {
$aParams['website_account_id'] = OA_Permission::getAccountId();
}
$oUserlog = new OA_Dll_Audit();
$aAuditData = $oUserlog->getAuditLog($aParams);
$aParams['totalItems'] = count($aAuditData);
if (!isset($pageID) || $pageID == 1) {
$aParams['startRecord'] = 0;
} else {
$aParams['startRecord'] = ($pageID * $setPerPage) - $setPerPage;
}
if ($aParams['startRecord'] > $aParams['totalItems']) {
$aParams['startRecord'] = 0;
}
$aParams['perPage'] = MAX_getStoredValue('setPerPage', 10);
// Retrieve audit details
$aAuditData = $oUserlog->getAuditLog($aParams);
$pager = & Pager::factory($aParams);
$per_page = $pager->_perPage;
$pager->history = $pager->getPageData();
$pager->pagerLinks = $pager->getLinks();
$pager->pagerLinks = $pager->pagerLinks['all'];
$pager->pagerSelect = preg_replace('/(<select.*?)(>)/i', '$1 onchange="submitForm()" id="setPerPage"$2', $pager->getPerPageSelectBox(10, 100, 10));
// Build column header link params
$aAllowdParams = array('advertiserId', 'campaignId', 'publisherId', 'zoneId');
foreach ($aAllowdParams as $key) {
if (!empty($$key)) {
$aUrlParam[$key] = "$key=".$$key;
}
}
$aUrlParam['listorder'] = "listorder=$listorder";
$aUrlParam['$orderdirection'] = ($orderdirection == 'down') ? "orderdirection=up" : "orderdirection=down";
$urlParam = implode('&', $aUrlParam);
// Replace context with translation
foreach ($aAuditData as $key => $aValue) {
$k = 'str'. str_replace(' ', '', $aValue['context']);
if (!empty($GLOBALS[$k])) {
$aAuditData[$key]['context'] = $GLOBALS[$k];
}
}
// Assign vars to template
$oTpl->assign('showAdvertisers', $showAdvertisers);
$oTpl->assign('showPublishers', $showPublishers);
if ($showAdvertisers) {
$oTpl->assign('aAdvertiser', $aAdvertiser);
$oTpl->assign('aCampaign', $aCampaign);
}
if ($showPublishers) {
$oTpl->assign('aPublisher', $aPublisher);
$oTpl->assign('aZone', $aZone);
}
$oTpl->assign('aAuditEnabled', OA::getConfigOption('audit', 'enabled', false));
$oTpl->assign('aAuditData', $aAuditData);
$oTpl->assign('aPeriodPreset', $aPeriodPreset);
$oTpl->assign('context', $context);
$oTpl->assign('advertiserId', $advertiserId);
$oTpl->assign('campaignId', $campaignId);
$oTpl->assign('publisherId', $publisherId);
$oTpl->assign('zoneId', $zoneId);
$oTpl->assign('urlParam', $urlParam);
$oTpl->assign('listorder', $listorder);
$oTpl->assign('orderdirection', $orderdirection);
$oTpl->assign('setPerPage', $setPerPage);
$oTpl->assign('pager', $pager);
$oTpl->assign('daySpan', $daySpan);
// Display page
$oTpl->display();
// display footer
phpAds_PageFooter();
// Store filter variables in session
$session['prefs'][$pageName]['advertiserId'] = $advertiserId;
$session['prefs'][$pageName]['campaignId'] = $campaignId;
$session['prefs'][$pageName]['publisherId'] = $publisherId;
$session['prefs'][$pageName]['zoneId'] = $zoneId;
$session['prefs'][$pageName]['period_preset'] = $periodPreset;
$seesion['prefs'][$pageName]['setPerPage'] = $setPerPage;
$session['prefs'][$pageName]['listorder'] = $listorder;
$session['prefs'][$pageName]['orderdirection'] = $orderdirection;
phpAds_SessionDataStore();
?>
| soeffing/openx_test | www/admin/userlog-index.php | PHP | gpl-2.0 | 11,731 |
package com.comphenix.xp.parser;
import static org.junit.Assert.*;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.MemoryConfiguration;
import org.junit.Test;
import com.comphenix.xp.expressions.RangeExpression;
import com.google.common.collect.Lists;
public class RangeParserTest {
@Test
public void test() {
RangeParser parser = new RangeParser();
String key = "range";
ConfigurationSection listValue = createWithKey(key, Lists.newArrayList(12));
ConfigurationSection textValue = createWithKey(key, "5 - 10");
ConfigurationSection doubleValue = createWithKey(key, 6.5);
try {
assertEquals(new RangeExpression(12), parser.parse(listValue, key));
assertEquals(new RangeExpression(5, 10), parser.parse(textValue, key));
assertEquals(new RangeExpression(6.5), parser.parse(doubleValue, key));
} catch (ParsingException e) {
// None of these should throw an exception
fail(e.toString());
}
}
private ConfigurationSection createWithKey(String key, Object value) {
MemoryConfiguration config = new MemoryConfiguration();
// Set the key-value pair
config.set(key, value);
return config;
}
}
| aadnk/ExperienceMod | ExperienceMod/src/test/java/com/comphenix/xp/parser/RangeParserTest.java | Java | gpl-2.0 | 1,231 |
<?php
declare(strict_types=1);
use TYPO3\CMS\Core\Authentication\AuthenticationService;
use TYPO3\CMS\Core\Controller\FileDumpController;
use TYPO3\CMS\Core\Controller\RequireJsController;
use TYPO3\CMS\Core\Hooks\BackendUserGroupIntegrityCheck;
use TYPO3\CMS\Core\Hooks\BackendUserPasswordCheck;
use TYPO3\CMS\Core\Hooks\CreateSiteConfiguration;
use TYPO3\CMS\Core\Hooks\DestroySessionHook;
use TYPO3\CMS\Core\Hooks\PagesTsConfigGuard;
use TYPO3\CMS\Core\MetaTag\EdgeMetaTagManager;
use TYPO3\CMS\Core\MetaTag\Html5MetaTagManager;
use TYPO3\CMS\Core\MetaTag\MetaTagManagerRegistry;
use TYPO3\CMS\Core\Resource\Index\ExtractorRegistry;
use TYPO3\CMS\Core\Resource\OnlineMedia\Metadata\Extractor;
use TYPO3\CMS\Core\Resource\Rendering\AudioTagRenderer;
use TYPO3\CMS\Core\Resource\Rendering\RendererRegistry;
use TYPO3\CMS\Core\Resource\Rendering\VideoTagRenderer;
use TYPO3\CMS\Core\Resource\Rendering\VimeoRenderer;
use TYPO3\CMS\Core\Resource\Rendering\YouTubeRenderer;
use TYPO3\CMS\Core\Resource\Security\FileMetadataPermissionsAspect;
use TYPO3\CMS\Core\Resource\Security\SvgHookHandler;
use TYPO3\CMS\Core\Resource\TextExtraction\PlainTextExtractor;
use TYPO3\CMS\Core\Resource\TextExtraction\TextExtractorRegistry;
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
defined('TYPO3') or die();
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][GeneralUtility::class]['moveUploadedFile'][] = SvgHookHandler::class . '->processMoveUploadedFile';
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][] = FileMetadataPermissionsAspect::class;
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][] = BackendUserGroupIntegrityCheck::class;
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][] = BackendUserPasswordCheck::class;
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/alt_doc.php']['makeEditForm_accessCheck'][] = FileMetadataPermissionsAspect::class . '->isAllowedToShowEditForm';
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['checkAccess'][] = FileMetadataPermissionsAspect::class . '->isAllowedToShowEditForm';
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'][] = FileMetadataPermissionsAspect::class;
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][] = DestroySessionHook::class;
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][] = PagesTsConfigGuard::class;
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][CreateSiteConfiguration::class] = CreateSiteConfiguration::class;
$GLOBALS['TYPO3_CONF_VARS']['FE']['eID_include']['dumpFile'] = FileDumpController::class . '::dumpAction';
$GLOBALS['TYPO3_CONF_VARS']['FE']['eID_include']['requirejs'] = RequireJsController::class . '::retrieveConfiguration';
$rendererRegistry = GeneralUtility::makeInstance(RendererRegistry::class);
$rendererRegistry->registerRendererClass(AudioTagRenderer::class);
$rendererRegistry->registerRendererClass(VideoTagRenderer::class);
$rendererRegistry->registerRendererClass(YouTubeRenderer::class);
$rendererRegistry->registerRendererClass(VimeoRenderer::class);
unset($rendererRegistry);
$textExtractorRegistry = GeneralUtility::makeInstance(TextExtractorRegistry::class);
$textExtractorRegistry->registerTextExtractor(PlainTextExtractor::class);
unset($textExtractorRegistry);
$extractorRegistry = GeneralUtility::makeInstance(ExtractorRegistry::class);
$extractorRegistry->registerExtractionService(Extractor::class);
unset($extractorRegistry);
// Register base authentication service
ExtensionManagementUtility::addService(
'core',
'auth',
AuthenticationService::class,
[
'title' => 'User authentication',
'description' => 'Authentication with username/password.',
'subtype' => 'getUserBE,getUserFE,authUserBE,authUserFE,processLoginDataBE,processLoginDataFE',
'available' => true,
'priority' => 50,
'quality' => 50,
'os' => '',
'exec' => '',
'className' => TYPO3\CMS\Core\Authentication\AuthenticationService::class,
]
);
$metaTagManagerRegistry = GeneralUtility::makeInstance(MetaTagManagerRegistry::class);
$metaTagManagerRegistry->registerManager(
'html5',
Html5MetaTagManager::class
);
$metaTagManagerRegistry->registerManager(
'edge',
EdgeMetaTagManager::class
);
unset($metaTagManagerRegistry);
// Add module configuration
ExtensionManagementUtility::addTypoScriptSetup(
'config.pageTitleProviders.record.provider = TYPO3\CMS\Core\PageTitle\RecordPageTitleProvider'
);
// Register preset for sys_news
if (empty($GLOBALS['TYPO3_CONF_VARS']['RTE']['Presets']['sys_news'])) {
$GLOBALS['TYPO3_CONF_VARS']['RTE']['Presets']['sys_news'] = 'EXT:core/Configuration/RTE/SysNews.yaml';
}
| TYPO3-CMS/core | ext_localconf.php | PHP | gpl-2.0 | 5,021 |
<?php
class Redux_Validation_url extends Redux_Options {
/* for PRO users! - *
* Field Constructor.
*
* Required - must call the parent constructor, then assign field and value to vars, and obviously call the render field function
*
* @since Redux_Options 1.0.0
*/
function __construct($field, $value, $current) {
parent::__construct();
$this->field = $field;
$this->field['msg'] = (isset($this->field['msg'])) ? $this->field['msg'] : __('You must provide a valid URL for this option.', Redux_TEXT_DOMAIN);
$this->value = $value;
$this->current = $current;
$this->validate();
}
/* for PRO users! - *
* Field Render Function.
*
* Takes the vars and validates them
*
* @since Redux_Options 1.0.0
*/
function validate() {
if (function_exists('filter_var') && filter_var($this->value, FILTER_VALIDATE_URL) == false) {
$this->value = (isset($this->current))?$this->current:'';
$this->error = $this->field;
} else {
$this->value = esc_url_raw($this->value);
}
}
}
| EmmaTope/SolidSteps | wp-content/themes/dante/includes/options/validation/url/validation_url.php | PHP | gpl-2.0 | 1,019 |
<?php
$this->currencies = array (
'adp' => 'Andorransk peseta',
'aed' => 'Förenade arabemiratens dirham',
'afa' => 'Afghani (1927-2002)',
'afn' => 'Afghani',
'all' => 'Albansk lek',
'amd' => 'Armenisk dram',
'ang' => 'Nederländsk antillisk gulden',
'aoa' => 'Angolansk kwanza',
'aok' => 'Angolansk kwanza (1977-1990)',
'aon' => 'Angolansk ny kwanza (1990-2000)',
'aor' => 'Angolansk kwanza – Reajustado (1995-1999)',
'ara' => 'Argentinsk austral',
'arp' => 'Argentinsk peso (1983-1985)',
'ars' => 'Argentinsk peso',
'ats' => 'Österrikisk schilling',
'aud' => 'Australisk dollar',
'awg' => 'Aruba-florin',
'azm' => 'Azerbajdzjansk manat',
'bad' => 'Bosnisk-hercegovinsk dinar',
'bam' => 'Konvertibel bosnisk-hercegovinsk mark',
'bbd' => 'Barbadisk dollar',
'bdt' => 'Bangladeshisk taka',
'bec' => 'Belgisk franc (konvertibel)',
'bef' => 'Belgisk franc',
'bel' => 'Belgisk franc (finansiell)',
'bgl' => 'Bulgarisk hård lev',
'bgn' => 'Bulgarisk ny lev',
'bhd' => 'Bahrainsk dinar',
'bif' => 'Burundisk franc',
'bmd' => 'Bermuda-dollar',
'bnd' => 'Bruneisk dollar',
'bob' => 'Boliviano',
'bop' => 'Boliviansk peso',
'bov' => 'Boliviansk mvdol',
'brb' => 'Brasiliansk cruzeiro novo (1967-1986)',
'brc' => 'Brasiliansk cruzado',
'bre' => 'Brasiliansk cruzeiro (1990-1993)',
'brl' => 'Brasiliansk real',
'brn' => 'Brasiliansk cruzado novo',
'brr' => 'Brasiliansk cruzeiro',
'bsd' => 'Bahamansk dollar',
'btn' => 'Bhutanesisk ngultrum',
'buk' => 'Burmesisk kyat',
'bwp' => 'Botswansk pula',
'byb' => 'Vitrysk ny rubel (1994-1999)',
'byr' => 'Vitrysk rubel',
'bzd' => 'Belizisk dollar',
'cad' => 'Kanadensisk dollar',
'cdf' => 'Kongolesisk franc congolais',
'che' => 'WIR Euro',
'chf' => 'Schweizisk franc',
'chw' => 'WIR Franc',
'clf' => 'Chilensk unidad de fomento',
'clp' => 'Chilensk peso',
'cny' => 'Kinesisk yuan renminbi',
'cop' => 'Colombiansk peso',
'cou' => 'Unidad de Valor Real',
'crc' => 'Costarikansk colón',
'csd' => 'Serbian Dinar',
'csk' => 'Tjeckisk hård koruna',
'cup' => 'Kubansk peso',
'cve' => 'Kapverdisk escudo',
'cyp' => 'Cypriotiskt pund',
'czk' => 'Tjeckisk koruna',
'ddm' => 'Östtysk mark',
'dem' => 'Tysk mark',
'djf' => 'Djiboutisk franc',
'dkk' => 'Dansk krona',
'dop' => 'Dominikansk peso',
'dzd' => 'Algerisk dinar',
'ecs' => 'Ecuadoriansk sucre',
'ecv' => 'Ecuadoriansk Unidad de Valor Constante (UVC)',
'eek' => 'Estnisk krona',
'egp' => 'Egyptiskt pund',
'eqe' => 'Ekwele',
'ern' => 'Eritreansk nakfa',
'esa' => 'Spanish Peseta (A account)',
'esb' => 'Spanish Peseta (convertible account)',
'esp' => 'Spansk peseta',
'etb' => 'Etiopisk birr',
'eur' => 'Euro',
'fim' => 'Finsk mark',
'fjd' => 'Fijiansk dollar',
'fkp' => 'Falklandsöarnas pund',
'frf' => 'Fransk franc',
'gbp' => 'Brittiskt pund sterling',
'gek' => 'Georgisk kupon larit',
'gel' => 'Georgisk lari',
'ghc' => 'Ghanansk cedi',
'gip' => 'Gibraltiskt pund',
'gmd' => 'Gambisk dalasi',
'gnf' => 'Guineansk franc',
'gns' => 'Guineansk syli',
'gqe' => 'Ekvatorialguineansk ekwele guineana',
'grd' => 'Grekisk drachma',
'gtq' => 'Guatemalansk quetzal',
'gwe' => 'Portugisiska Guinea-escudo',
'gwp' => 'Guinea-Bissau-peso',
'gyd' => 'Guyanansk dollar',
'hkd' => 'Hongkong-dollar',
'hnl' => 'Hoduransk lempira',
'hrd' => 'Kroatisk dinar',
'hrk' => 'Kroatisk kuna',
'htg' => 'Haitisk gourde',
'huf' => 'Ungersk forint',
'idr' => 'Indonesisk rupiah',
'iep' => 'Irländskt pund',
'ilp' => 'Israeliskt pund',
'ils' => 'Israelisk ny shekel',
'inr' => 'Indisk rupie',
'iqd' => 'Irakisk dinar',
'irr' => 'Iransk rial',
'isk' => 'Isländsk krona',
'itl' => 'Italiensk lira',
'jmd' => 'Jamaicansk dollar',
'jod' => 'Jordansk dinar',
'jpy' => 'Japansk yen',
'kes' => 'Kenyansk shilling',
'kgs' => 'Kirgizistansk som',
'khr' => 'Kambodjansk riel',
'kmf' => 'Komorisk franc',
'kpw' => 'Nordkoreansk won',
'krw' => 'Sydkoreansk won',
'kwd' => 'Kuwaitisk dinar',
'kyd' => 'Cayman-dollar',
'kzt' => 'Kazakisk tenge',
'lak' => 'Laotisk kip',
'lbp' => 'Libanesiskt pund',
'lkr' => 'Srilankesisk rupie',
'lrd' => 'Liberisk dollar',
'lsl' => 'Lesothisk loti',
'lsm' => 'Maloti',
'ltl' => 'Lettisk lita',
'ltt' => 'Lettisk talonas',
'luc' => 'Luxembourg Convertible Franc',
'luf' => 'Luxemburgsk franc',
'lul' => 'Luxembourg Financial Franc',
'lvl' => 'Lettisk lats',
'lvr' => 'Lettisk rubel',
'lyd' => 'Libysk dinar',
'mad' => 'Marockansk dirham',
'maf' => 'Marockansk franc',
'mdl' => 'Moldavisk leu',
'mga' => 'Madagaskisk ariary',
'mgf' => 'Madagaskisk franc',
'mkd' => 'Makedonisk denar',
'mlf' => 'Malisk franc',
'mmk' => 'Myanmarisk kyat',
'mnt' => 'Mongolisk tugrik',
'mop' => 'Macaoisk pataca',
'mro' => 'Mauretansk ouguiya',
'mtl' => 'Maltesisk lira',
'mtp' => 'Maltesiskt pund',
'mur' => 'Mauritisk rupie',
'mvr' => 'Maldivisk rufiyaa',
'mwk' => 'Malawisk kwacha',
'mxn' => 'Mexikansk peso',
'mxp' => 'Mexikansk silverpeso (1861-1992)',
'mxv' => 'Mexikansk Unidad de Inversion (UDI)',
'myr' => 'Malaysisk ringgit',
'mze' => 'Moçambikisk escudo',
'mzm' => 'Moçambikisk metical',
'nad' => 'Namibisk dollar',
'ngn' => 'Nigeriansk naira',
'nic' => 'Nicaraguansk córdoba',
'nio' => 'Nicaraguansk córdoba oro',
'nlg' => 'Nederländsk gulden',
'nok' => 'Norsk krona',
'npr' => 'Nepalesisk rupie',
'nzd' => 'Nyzeeländsk dollar',
'omr' => 'Omansk rial',
'pab' => 'Panamansk balboa',
'pei' => 'Peruansk inti',
'pen' => 'Peruansk sol nuevo',
'pes' => 'Peruansk sol',
'pgk' => 'Papuansk kina',
'php' => 'Filippinsk peso',
'pkr' => 'Pakistansk rupie',
'pln' => 'Polsk zloty',
'plz' => 'Polsk zloty (1950-1995)',
'pte' => 'Portugisisk escudo',
'pyg' => 'Paraguaysk guarani',
'qar' => 'Qatarisk rial',
'rhd' => 'Rhodesian Dollar',
'rol' => 'Rumänsk leu',
'ron' => 'Romanian Leu',
'rub' => 'Rysk rubel',
'rur' => 'Rysk rubel (1991-1998)',
'rwf' => 'Rwandisk franc',
'sar' => 'Saudisk riyal',
'sbd' => 'Salomon-dollar',
'scr' => 'Seychellisk rupie',
'sdd' => 'Sudanesisk dinar',
'sdp' => 'Sudanesiskt pund',
'sek' => 'Svensk krona',
'sgd' => 'Singaporiansk dollar',
'shp' => 'S:t Helena-pund',
'sit' => 'Slovensk tolar',
'skk' => 'Slovakisk koruna',
'sll' => 'Sierraleonsk leone',
'sos' => 'Somalisk shilling',
'srd' => 'Surinam Dollar',
'srg' => 'Surinamesisk gulden',
'std' => 'São Tomé och Príncipe-dobra',
'sur' => 'Sovjetisk rubel',
'svc' => 'Salvadoransk colón',
'syp' => 'Syriskt pund',
'szl' => 'Swaziländsk lilangeni',
'thb' => 'Thailändsk baht',
'tjr' => 'Tadzjikisk rubel',
'tjs' => 'Tadzjikisk somoni',
'tmm' => 'Turkmensk manat',
'tnd' => 'Tunisisk dinar',
'top' => 'Tongansk paʻanga',
'tpe' => 'Timoriansk escudo',
'trl' => 'Turkisk lira',
'try' => 'Ny turkisk lira',
'ttd' => 'Trinidadisk dollar',
'twd' => 'Taiwanesisk ny dollar',
'tzs' => 'Tanzanisk shilling',
'uah' => 'Ukrainsk hryvnia',
'uak' => 'Ukrainsk karbovanetz',
'ugs' => 'Ugandisk shilling (1966-1987)',
'ugx' => 'Ugandisk shilling',
'usd' => 'US-dollar',
'usn' => 'US-dollar (nästa dag)',
'uss' => 'US-dollar (samma dag)',
'uyp' => 'Uruguayansk peso (1975-1993)',
'uyu' => 'Uruguayansk peso uruguayo',
'uzs' => 'Uzbekisk sum',
'veb' => 'Venezuelansk bolivar',
'vnd' => 'Vietnamesisk dong',
'vuv' => 'Vanuatisk vatu',
'wst' => 'Västsamoansk tala',
'xaf' => 'CFA Franc BEAC',
'xag' => 'Silver',
'xau' => 'Gold',
'xba' => 'European Composite Unit',
'xbb' => 'European Monetary Unit',
'xbc' => 'European Unit of Account (XBC)',
'xbd' => 'European Unit of Account (XBD)',
'xcd' => 'Östkaribisk dollar',
'xdr' => 'Special Drawing Rights',
'xeu' => 'European Currency Unit',
'xfo' => 'Fransk guldfranc',
'xfu' => 'French UIC-Franc',
'xof' => 'CFA Franc BCEAO',
'xpd' => 'Palladium',
'xpf' => 'CFP-franc',
'xpt' => 'Platinum',
'xre' => 'RINET Funds',
'xts' => 'Testing Currency Code',
'xxx' => 'No Currency',
'ydd' => 'Jemenitisk dinar',
'yer' => 'Jemenitisk rial',
'yud' => 'Jugoslavisk hård dinar',
'yum' => 'Dinar (Serbien och Montenegro)',
'yun' => 'Jugoslavisk konvertibel dinar',
'zal' => 'Sydafrikansk rand (finansiell)',
'zar' => 'Sydafrikansk rand',
'zmk' => 'Zambisk kwacha',
'zrn' => 'Zairisk ny zaire',
'zrz' => 'Zairisk zaire',
'zwd' => 'Zimbabwisk dollar',
); | prdatur/soopfw | language/currencies/sv.php | PHP | gpl-2.0 | 8,556 |
<?php
/*
* Copyright 2014 Google Inc.
*
* 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.
*/
class Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1SubscriberEvent extends Google_Model
{
protected $customerEventType = 'Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1CustomerEvent';
protected $customerEventDataType = '';
protected $entitlementEventType = 'Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1EntitlementEvent';
protected $entitlementEventDataType = '';
/**
* @param Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1CustomerEvent
*/
public function setCustomerEvent(Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1CustomerEvent $customerEvent)
{
$this->customerEvent = $customerEvent;
}
/**
* @return Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1CustomerEvent
*/
public function getCustomerEvent()
{
return $this->customerEvent;
}
/**
* @param Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1EntitlementEvent
*/
public function setEntitlementEvent(Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1EntitlementEvent $entitlementEvent)
{
$this->entitlementEvent = $entitlementEvent;
}
/**
* @return Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1EntitlementEvent
*/
public function getEntitlementEvent()
{
return $this->entitlementEvent;
}
}
| palasthotel/grid-wordpress-box-social | vendor/google/apiclient-services/src/Google/Service/Cloudchannel/GoogleCloudChannelV1alpha1SubscriberEvent.php | PHP | gpl-2.0 | 1,892 |
<?php
/**
* content-gallery.php
*
* The default template for displaying posts with the Gallery post format.
* @package Theme_Material
* GPL3 Licensed
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<!-- Article header -->
<header class="entry-header"> <?php
// If single page, display the title
// Else, we display the title in a link
if ( is_single() ) : ?>
<h1><?php the_title(); ?></h1>
<?php else : ?>
<h1><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></h1>
<?php endif; ?>
<p class="entry-meta">
<?php
// Display the meta information
material_post_meta();
?>
</p>
</header> <!-- end entry-header -->
<!-- Article content -->
<div class="entry-content">
<?php
the_content( __( 'Continue reading →', 'material' ) );
wp_link_pages();
?>
</div> <!-- end entry-content -->
<!-- Article footer -->
<footer class="entry-footer">
<?php
// If we have a single page and the author bio exists, display it
if ( is_single() && get_the_author_meta( 'description' ) ) {
echo '<h2>' . __( 'Written by ', 'material' ) . get_the_author() . '</h2>';
echo '<p>' . the_author_meta( 'description' ) . '</p>';
}
?>
</footer> <!-- end entry-footer -->
</article> | puuga/wordpress | wp-content/themes/material/content-gallery.php | PHP | gpl-2.0 | 1,286 |
/*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
* Free SoftwareFoundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package javax.jms;
/**
* The exception
*/
public class InvalidSelectorException extends JMSException {
public InvalidSelectorException(String reason)
{
super(reason);
}
public InvalidSelectorException(String reason, String errorCode)
{
super(reason, errorCode);
}
}
| christianchristensen/resin | modules/jms/src/javax/jms/InvalidSelectorException.java | Java | gpl-2.0 | 1,322 |
# exercise from http://www.ling.gu.se/~lager/python_exercises.html
# solution from http://rosettacode.org/wiki/99_Bottles_of_Beer#Python
# "99 bottle of beer" is a traditional song in the US and Canada.
# it is popular to sing on long trips, as it has a very repetitive
# format which is easy to memorize, and can take a long time to sing.
# the song's simple lyrics are as follows:
# 99 bottles of beer on the wall, 99 bottles of beer.
# take one down, pass it around, 98 bottles of beer on the wall.
# the same verse is repeated, each time with one fewer bottle.
# the song is completed when the singers reach zero.
# Task now is to write a Python program
# capable of generating all the verses of the song.
print '------------------------------'
print '99 Bottles of Beer on the Wall'
print '------------------------------'
bottles = 99
song = '''
%d bottles of beer on the wall, %d bottles of beer.\n
Take one down, pass it around, %d bottles of beer.
'''
for bottles in range(99,0,-1):
print song %(bottles,bottles,bottles-1)
| SurAnand/pyuthon | 99beer.py | Python | gpl-2.0 | 1,042 |
/**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2017 UniPro <ugene@unipro.ru>
* http://ugene.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <U2Core/U2AssemblyUtils.h>
#include <U2Core/Log.h>
#include "BAMDbiPlugin.h"
#include "InvalidFormatException.h"
#include "SamReader.h"
#include "CigarValidator.h"
#include <SamtoolsAdapter.h>
namespace U2 {
namespace BAM {
const int SamReader::LOCAL_READ_BUFFER_SIZE = 100000;
Alignment SamReader::parseAlignmentString(QByteArray line) {
Alignment alignment;
if(line.isEmpty()) {
assert(0);
throw InvalidFormatException(BAMDbiPlugin::tr("Unexpected empty string"));
}
QByteArray recordTag;
QHash<QByteArray, QByteArray> fields;
QList<QByteArray> tokens = line.split('\t');
if (tokens.length() < 11) {
throw InvalidFormatException(BAMDbiPlugin::tr("Not enough fields in one of alignments"));
}
{
QByteArray &qname = tokens[0];
// workaround for malformed SAMs
if(!QRegExp("[ -~]{1,255}").exactMatch(qname)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid query template name: %1").arg(QString(qname)));
}
alignment.setName(qname);
}
{
bool ok = false;
int flagsValue = tokens[1].toInt(&ok);
if(!ok) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid FLAG value: %1").arg(QString(tokens[1])));
}
qint64 flags = 0;
if(flagsValue & 0x1) {
flags |= Fragmented;
}
if(flagsValue & 0x2) {
flags |= FragmentsAligned;
}
if(flagsValue & 0x4) {
flags |= Unmapped;
}
if(flagsValue & 0x8) {
flags |= NextUnmapped;
}
if(flagsValue & 0x10) {
flags |= Reverse;
}
if(flagsValue & 0x20) {
flags |= NextReverse;
}
if(flagsValue & 0x40) {
flags |= FirstInTemplate;
}
if(flagsValue & 0x80) {
flags |= LastInTemplate;
}
if(flagsValue & 0x100) {
flags |= SecondaryAlignment;
}
if(flagsValue & 0x200) {
flags |= FailsChecks;
}
if(flagsValue & 0x400) {
flags |= Duplicate;
}
alignment.setFlags(flags);
}
{
QByteArray &rname = tokens[2];
// workaround for malformed SAMs
if(!QRegExp("[*]|[!-()+-<>-~][ -~]*").exactMatch(rname)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid reference name: %1").arg(QString(rname)));
}
if ("*" == rname) {
alignment.setReferenceId(-1);
} else {
if (!referencesMap.contains(rname)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Undefined reference name: %1").arg(QString(rname)));
}
alignment.setReferenceId(referencesMap[rname]);
}
}
{
bool ok = false;
int position = tokens[3].toInt(&ok);
if(!ok) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid read position value: %1").arg(QString(tokens[3])));
}
if(position < 0) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid read position: %1").arg(position));
}
alignment.setPosition(position - 1); //to 0-based mapping
}
{
bool ok = false;
int mapQuality = tokens[4].toInt(&ok);
if(!ok) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mapping quality value: %1").arg(QString(tokens[4])));
}
if(mapQuality < 0 || mapQuality > 255) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mapping quality: %1").arg(mapQuality));
}
alignment.setMapQuality(mapQuality);
}
{
QByteArray &cigarString = tokens[5];
if(!QRegExp("[*]|([0-9]+[MIDNSHPX=])+").exactMatch(cigarString)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid cigar value: %1").arg(QString(cigarString)));
}
if ("*" != cigarString) {
QString err;
QList<U2CigarToken> res = U2AssemblyUtils::parseCigar(cigarString, err);
if (!err.isEmpty()) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid cigar value: %1").arg(QString(cigarString)));
}
QList<Alignment::CigarOperation> cigar;
for(int i = 0; i < res.length(); i++) {
Alignment::CigarOperation::Operation operation;
switch(res[i].op) {
case U2CigarOp_M:
operation = Alignment::CigarOperation::AlignmentMatch;
break;
case U2CigarOp_I:
operation = Alignment::CigarOperation::Insertion;
break;
case U2CigarOp_D:
operation = Alignment::CigarOperation::Deletion;
break;
case U2CigarOp_N:
operation = Alignment::CigarOperation::Skipped;
break;
case U2CigarOp_S:
operation = Alignment::CigarOperation::SoftClip;
break;
case U2CigarOp_H:
operation = Alignment::CigarOperation::HardClip;
break;
case U2CigarOp_P:
operation = Alignment::CigarOperation::Padding;
break;
case U2CigarOp_EQ:
operation = Alignment::CigarOperation::SequenceMatch;
break;
case U2CigarOp_X:
operation = Alignment::CigarOperation::SequenceMismatch;
break;
default:
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid cigar operation code: %1").arg(res[i].op));
}
int operatonLength = res[i].count;
cigar.append(Alignment::CigarOperation(operatonLength, operation));
}
alignment.setCigar(cigar);
}
}
{
QByteArray nextReference = tokens[6];
// workaround for malformed SAMs
if(!QRegExp("[*]|[=]|[!-()+-<>-~][ -~]*").exactMatch(nextReference)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mate reference name: %1").arg(QString(nextReference)));
}
if ("*" == nextReference) {
alignment.setNextReferenceId(-1);
} else if ("=" == nextReference) {
alignment.setNextReferenceId(alignment.getReferenceId());
} else {
if (!referencesMap.contains(nextReference)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Undefined mate reference name: %1").arg(QString(nextReference)));
}
alignment.setNextReferenceId(referencesMap[nextReference]);
}
alignment.setNextReferenceName(nextReference);
}
{
bool ok = false;
int nextPosition = tokens[7].toInt(&ok);
if(!ok) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mate position value: %1").arg(QString(tokens[7])));
}
if(nextPosition < 0) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mate position: %1").arg(nextPosition));
}
alignment.setNextPosition(nextPosition - 1); //to 0-based mapping
}
{
bool ok = false;
int templateLength = tokens[8].toInt(&ok);
if(!ok) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid template length value: %1").arg(QString(tokens[8])));
}
if(!(alignment.getFlags() & Fragmented)) {
if(0 != templateLength) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid template length of a single-fragment template: %1").arg(templateLength));
}
}
alignment.setTemplateLength(templateLength);
}
{
QByteArray sequence = tokens[9];
if(!QRegExp("[*]|[A-Za-z=.]+").exactMatch(sequence)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid sequence: %1").arg(QString(sequence)));
}
alignment.setSequence(sequence);
}
{
QByteArray quality = tokens[10];
if ("*" != quality) {
if(QRegExp("[!-~]+").exactMatch(quality)) {
alignment.setQuality(quality);
}
}
}
{
QByteArray samAuxString;
bool first = true;
QMap<QByteArray, QVariant> optionalFields;
for (int i = 11; i < tokens.length(); i++) {
if (!first) {
samAuxString += '\t';
}
samAuxString += tokens[i];
first = false;
}
alignment.setAuxData(SamtoolsAdapter::samString2aux(samAuxString));
}
{
// Validation of the CIGAR string.
int totalLength = 0;
int length = alignment.getSequence().length();
const QList<Alignment::CigarOperation> &cigar = alignment.getCigar();
CigarValidator validator(cigar);
validator.validate(&totalLength);
if(!cigar.isEmpty() && length != totalLength) {
const_cast<QList<Alignment::CigarOperation>&>(cigar).clear(); //Ignore invalid cigar
}
}
return alignment;
}
SamReader::SamReader(IOAdapter &ioAdapter):
Reader(ioAdapter),
readBuffer(LOCAL_READ_BUFFER_SIZE, '\0')
{
readHeader();
}
const Header &SamReader::getHeader()const {
return header;
}
Alignment SamReader::readAlignment(bool &eof) {
QByteArray alignmentString = readString(eof);
return parseAlignmentString(alignmentString);
}
bool SamReader::isEof()const {
return ioAdapter.isEof();
}
QByteArray SamReader::readString(bool &eof) {
char* buff = readBuffer.data();
bool lineOk = false;
int len = 0;
QByteArray result;
while((len = ioAdapter.readLine(buff, LOCAL_READ_BUFFER_SIZE, &lineOk)) == 0) {}
if (len == -1) {
eof = true;
} else {
result = QByteArray::fromRawData(buff, len);
}
return result;
}
void SamReader::readHeader() {
char* buff = readBuffer.data();
bool lineOk = false;
int len = 0;
qint64 bRead = ioAdapter.bytesRead();
QList<Header::Reference> references;
{
QList<Header::ReadGroup> readGroups;
QList<Header::Program> programs;
QList<QByteArray> previousProgramIds;
while ((len = ioAdapter.readLine(buff, LOCAL_READ_BUFFER_SIZE, &lineOk)) >= 0) {
if(isEof()){
break;
}
QByteArray line = QByteArray::fromRawData(buff, len);
if(line.isEmpty()) {
continue;
}
if(line.startsWith("@CO")) {
continue;
}
if(!line.startsWith('@')) {
ioAdapter.skip(bRead - ioAdapter.bytesRead());
break;
}
bRead = ioAdapter.bytesRead();
QByteArray recordTag;
QHash<QByteArray, QByteArray> fields;
{
QList<QByteArray> tokens = line.split('\t');
recordTag = tokens[0].mid(1);
if(!QRegExp("[A-Za-z][A-Za-z]").exactMatch(recordTag)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid header record tag: %1").arg(QString(recordTag)));
}
for(int index = 1;index < tokens.size();index++) {
QByteArray fieldTag;
QByteArray fieldValue;
{
int colonIndex = tokens[index].indexOf(':');
if(-1 != colonIndex) {
fieldTag = tokens[index].mid(0, colonIndex);
fieldValue = tokens[index].mid(colonIndex + 1);
} else if("PG" == recordTag) { // workaround for invalid headers produced by some programs
continue;
} else {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid header field: %1").arg(QString(tokens[index])));
}
}
if(!QRegExp("[A-Za-z][A-Za-z]").exactMatch(fieldTag) && "M5" != fieldTag) { //workaround for bug in the spec
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid header field tag: %1").arg(QString(fieldTag)));
}
// CL and PN tags of can contain any string
if(fieldTag!="CL" && fieldTag!="PN" && !QRegExp("[ -~]+").exactMatch(fieldValue)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid %1-%2 value: %3").arg(QString(recordTag)).arg(QString(fieldTag)).arg(QString(fieldValue)));
}
if(!fields.contains(fieldTag)) {
fields.insert(fieldTag, fieldValue);
} else {
throw InvalidFormatException(BAMDbiPlugin::tr("Duplicate header field: %1").arg(QString(fieldTag)));
}
}
}
if("HD" == recordTag) {
if(fields.contains("VN")) {
QByteArray value = fields["VN"];
if(!QRegExp("[0-9]+\\.[0-9]+").exactMatch(value)) {
//Do nothing to support malformed BAMs
//throw InvalidFormatException(BAMDbiPlugin::tr("Invalid HD-VN value: %1").arg(QString(value)));
}
header.setFormatVersion(Version::parseVersion(value));
} else {
throw InvalidFormatException(BAMDbiPlugin::tr("HD record without VN field"));
}
if(fields.contains("SO")) {
QByteArray value = fields["SO"];
if("unknown" == value) {
header.setSortingOrder(Header::Unknown);
} else if("unsorted" == value) {
header.setSortingOrder(Header::Unsorted);
} else if("queryname" == value) {
header.setSortingOrder(Header::QueryName);
} else if("coordinate" == value) {
header.setSortingOrder(Header::Coordinate);
} else if("sorted" == value) { // workaround for invalid headers produced by some programs
header.setSortingOrder(Header::Coordinate);
} else {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid HD-SO value: %1").arg(QString(value)));
}
} else {
header.setSortingOrder(Header::Unknown);
}
} else if("SQ" == recordTag) {
Header::Reference *reference = NULL;
QByteArray name;
if(fields.contains("SN")) {
name = fields["SN"];
} else {
throw InvalidFormatException(BAMDbiPlugin::tr("SQ record without SN field"));
}
if(fields.contains("LN")) {
QByteArray value = fields["LN"];
bool ok = false;
int length = value.toInt(&ok);
if(ok) {
Header::Reference newRef(name, length);
referencesMap.insert(name, references.size());
references.append(newRef);
reference = &(references.last());
} else {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid SQ-LN value: %1").arg(QString(value)));
}
} else {
throw InvalidFormatException(BAMDbiPlugin::tr("SQ record without LN field"));
}
assert(NULL != reference);
if(fields.contains("AS")) {
reference->setAssemblyId(fields["AS"]);
}
if(fields.contains("M5")) {
QByteArray value = fields["M5"];
//[a-f] is a workaround (not matching to SAM-1.3 spec) to open 1000 Genomes project BAMs
if(!QRegExp("[0-9A-Fa-f]+").exactMatch(value)) {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid SQ-M5 value: %1").arg(QString(value)));
}
reference->setMd5(fields["M5"]);
}
if(fields.contains("SP")) {
reference->setSpecies(fields["SP"]);
}
if(fields.contains("UR")) {
reference->setUri(fields["UR"]);
}
} else if("RG" == recordTag) {
Header::ReadGroup readGroup;
if(fields.contains("ID")) {
QByteArray value = fields["SN"];
readGroupsMap.insert(value, readGroups.size());
} else {
fields.insert("ID", "-1");
}
if(fields.contains("CN")) {
readGroup.setSequencingCenter(fields["CN"]);
}
if(fields.contains("DS")) {
readGroup.setDescription(fields["DS"]);
}
if(fields.contains("DT")) {
QByteArray value = fields["DT"];
QDateTime dateTime = QDateTime::fromString(value, Qt::ISODate);
if(dateTime.isValid()) {
readGroup.setDate(dateTime);
} else {
QDate date = QDate::fromString(value, Qt::ISODate);
if(date.isValid()) {
readGroup.setDate(date);
} else {
//Allow anything.
//throw InvalidFormatException(BAMDbiPlugin::tr("Invalid RG-DT field value: %1").arg(QString(value)));
}
}
}
if(fields.contains("LB")) {
readGroup.setLibrary(fields["LB"]);
}
if(fields.contains("PG")) {
readGroup.setPrograms(fields["PG"]);
}
if(fields.contains("PI")) {
QByteArray value = fields["PI"];
bool ok = false;
int predictedInsertSize = value.toInt(&ok);
if(ok) {
readGroup.setPredictedInsertSize(predictedInsertSize);
} else {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid RG-PI field value: %1").arg(QString(value)));
}
}
if(fields.contains("PL")) {
readGroup.setPlatform(fields["PL"]);
}
if(fields.contains("PU")) {
readGroup.setPlatformUnit(fields["PU"]);
}
if(fields.contains("SM")) {
readGroup.setSample(fields["SM"]);
}
readGroups.append(readGroup);
} else if("PG" == recordTag) {
Header::Program program;
if(!fields.contains("ID")) {
fields.insert("ID", QByteArray::number(programs.size()));
}
programsMap.insert(fields["ID"], programs.size());
if(fields.contains("PN")) {
program.setName(fields["PN"]);
}
if(fields.contains("CL")) {
program.setCommandLine(fields["CL"]);
}
if(fields.contains("PP")) {
previousProgramIds.append(fields["PP"]);
} else {
previousProgramIds.append(QByteArray());
}
if(fields.contains("VN")) {
program.setVersion(fields["VN"]);
}
programs.append(program);
}
}
for(int index = 0;index < programs.size();index++) {
const QByteArray &previousProgramId = previousProgramIds[index];
if(!previousProgramId.isEmpty()) {
if(programsMap.contains(previousProgramId)) {
programs[index].setPreviousId(programsMap[previousProgramId]);
} else {
throw InvalidFormatException(BAMDbiPlugin::tr("Invalid PG-PP field value: %1").arg(QString(previousProgramId)));
}
}
}
header.setReferences(references);
header.setReadGroups(readGroups);
header.setPrograms(programs);
}
}
} // namespace BAM
} // namespace U2
| mfursov/ugene | src/plugins/dbi_bam/src/SamReader.cpp | C++ | gpl-2.0 | 21,739 |
package com.code.taskmanager.bean;
import android.graphics.drawable.Drawable;
public class AppInfo {
public Drawable icon;
public String name;
public String packagename;
public boolean sysApp;
public long mem;
}
| silvernoo/KillTask | src/com/code/taskmanager/bean/AppInfo.java | Java | gpl-2.0 | 219 |
#####################################################################
# -*- coding: iso-8859-1 -*- #
# #
# Frets on Fire #
# Copyright (C) 2006 Sami Kyostila #
# 2008 Alarian #
# 2008 myfingershurt #
# 2008 Capo #
# 2008 Glorandwarf #
# 2008 QQStarS #
# 2008 Blazingamer #
# 2008 evilynux <evilynux@gmail.com> #
# #
# This program is free software; you can redistribute it and/or #
# modify it under the terms of the GNU General Public License #
# as published by the Free Software Foundation; either version 2 #
# of the License, or (at your option) any later version. #
# #
# 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. #
#####################################################################
from Song import Note, Tempo
from Mesh import Mesh
from Neck import Neck
import random
from copy import deepcopy
from Shader import shaders
from OpenGL.GL import *
import math
#myfingershurt: needed for multi-OS file fetching
import os
import Log
import Song #need the base song defines as well
from Instrument import *
class Guitar(Instrument):
def __init__(self, engine, playerObj, editorMode = False, player = 0, bass = False):
Instrument.__init__(self, engine, playerObj, player)
self.isDrum = False
self.isBassGuitar = bass
self.isVocal = False
self.debugMode = False
self.gameMode2p = self.engine.world.multiMode
self.matchingNotes = []
self.starSpinFrameIndex = 0
self.starSpinFrames = 16
self.logClassInits = self.engine.config.get("game", "log_class_inits")
if self.logClassInits == 1:
Log.debug("Guitar class init...")
#death_au: fixed neck size
#if self.engine.theme.twoDnote == False or self.engine.theme.twoDkeys == False:
#self.boardWidth = 3.6
#self.boardLength = 9.0
self.lastPlayedNotes = [] #MFH - for reverting when game discovers it implied incorrectly
self.missedNotes = []
self.missedNoteNums = []
self.editorMode = editorMode
#########For Animations
self.Animspeed = 30#Lower value = Faster animations
#For Animated Starnotes
self.indexCount = 0
#Alarian, For animated hitglow
self.HCountAni = False
#myfingershurt:
self.hopoStyle = self.engine.config.get("game", "hopo_system")
self.gh2sloppy = self.engine.config.get("game", "gh2_sloppy")
if self.gh2sloppy == 1:
self.hopoStyle = 4
self.sfxVolume = self.engine.config.get("audio", "SFX_volume")
#blazingamer
self.killfx = self.engine.config.get("performance", "killfx")
self.killCount = 0
self.bigMax = 1
#Get theme
themename = self.engine.data.themeLabel
#now theme determination logic is only in data.py:
self.theme = self.engine.data.theme
self.oFlash = None
#myfingershurt:
self.bassGrooveNeckMode = self.engine.config.get("game", "bass_groove_neck")
self.starspin = self.engine.config.get("performance", "starspin")
if self.twoDnote == True:
#Spinning starnotes or not?
#myfingershurt: allowing any non-Rock Band theme to have spinning starnotes if the SpinNotes.png is available in that theme's folder
if self.starspin == True and self.theme < 2:
#myfingershurt: check for SpinNotes, if not there then no animation
if self.gameMode2p == 6:
if engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"spinnotesbattle.png")):
self.starSpinFrames = 8
else:
self.starspin = False
if not engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notesbattle.png")):
engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notes.png"))
else:
if not engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"spinnotes.png")):
self.starspin = False
engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notes.png"))
else:
if self.gameMode2p == 6:
if not engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notesbattle.png")):
engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notes.png"))
else:
engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notes.png"))
#mfh - adding fallback for beta option
else:
#MFH - can't use IOError for fallback logic for a Mesh() call...
if self.engine.fileExists(os.path.join("themes", themename, "note.dae")):
engine.resource.load(self, "noteMesh", lambda: Mesh(engine.resource.fileName("themes", themename, "note.dae")))
else:
engine.resource.load(self, "noteMesh", lambda: Mesh(engine.resource.fileName("note.dae")))
for i in range(5):
if engine.loadImgDrawing(self, "notetex"+chr(97+i), os.path.join("themes", themename, "notetex_"+chr(97+i)+".png")):
self.notetex = True
else:
self.notetex = False
break
if self.engine.fileExists(os.path.join("themes", themename, "star.dae")):
engine.resource.load(self, "starMesh", lambda: Mesh(engine.resource.fileName("themes", themename, "star.dae")))
else:
self.starMesh = None
for i in range(5):
if engine.loadImgDrawing(self, "startex"+chr(97+i), os.path.join("themes", themename, "startex_"+chr(97+i)+".png")):
self.startex = True
else:
self.startex = False
break
for i in range(5):
if engine.loadImgDrawing(self, "staratex"+chr(97+i), os.path.join("themes", themename, "staratex_"+chr(97+i)+".png")):
self.staratex = True
else:
self.staratex = False
break
if self.gameMode2p == 6:
if not engine.loadImgDrawing(self, "battleFrets", os.path.join("themes", themename,"battle_frets.png")):
self.battleFrets = None
if self.twoDkeys == True:
engine.loadImgDrawing(self, "fretButtons", os.path.join("themes",themename,"fretbuttons.png"))
else:
defaultKey = False
#MFH - can't use IOError for fallback logic for a Mesh() call...
if self.engine.fileExists(os.path.join("themes", themename, "key.dae")):
engine.resource.load(self, "keyMesh", lambda: Mesh(engine.resource.fileName("themes", themename, "key.dae")))
else:
engine.resource.load(self, "keyMesh", lambda: Mesh(engine.resource.fileName("key.dae")))
defaultKey = True
if defaultKey:
self.keytex = False
else:
for i in range(5):
if engine.loadImgDrawing(self, "keytex"+chr(97+i), os.path.join("themes", themename, "keytex_"+chr(97+i)+".png")):
self.keytex = True
else:
self.keytex = False
break
#inkk: loading theme-dependant tail images
#myfingershurt: must ensure the new tails don't affect the Rock Band mod...
self.simpleTails = False
for i in range(0,7):
if not engine.loadImgDrawing(self, "tail"+str(i), os.path.join("themes",themename,"tails","tail"+str(i)+".png"), textureSize = (128, 128)):
self.simpleTails = True
break
if not engine.loadImgDrawing(self, "taile"+str(i), os.path.join("themes",themename,"tails","taile"+str(i)+".png"), textureSize = (128, 128)):
self.simpleTails = True
break
if not engine.loadImgDrawing(self, "btail"+str(i), os.path.join("themes",themename,"tails","btail"+str(i)+".png"), textureSize = (128, 128)):
self.simpleTails = True
break
if not engine.loadImgDrawing(self, "btaile"+str(i), os.path.join("themes",themename,"tails","btaile"+str(i)+".png"), textureSize = (128, 128)):
self.simpleTails = True
break
if self.simpleTails:
Log.debug("Simple tails used; complex tail loading error...")
if not engine.loadImgDrawing(self, "tail1", os.path.join("themes",themename,"tail1.png"), textureSize = (128, 128)):
engine.loadImgDrawing(self, "tail1", "tail1.png", textureSize = (128, 128))
if not engine.loadImgDrawing(self, "tail2", os.path.join("themes",themename,"tail2.png"), textureSize = (128, 128)):
engine.loadImgDrawing(self, "tail2", "tail2.png", textureSize = (128, 128))
if not engine.loadImgDrawing(self, "bigTail1", os.path.join("themes",themename,"bigtail1.png"), textureSize = (128, 128)):
engine.loadImgDrawing(self, "bigTail1", "bigtail1.png", textureSize = (128, 128))
if not engine.loadImgDrawing(self, "bigTail2", os.path.join("themes",themename,"bigtail2.png"), textureSize = (128, 128)):
engine.loadImgDrawing(self, "bigTail2", "bigtail2.png", textureSize = (128, 128))
if not engine.loadImgDrawing(self, "kill1", os.path.join("themes", themename, "kill1.png"), textureSize = (128, 128)):
engine.loadImgDrawing(self, "kill1", "kill1.png", textureSize = (128, 128))
if not engine.loadImgDrawing(self, "kill2", os.path.join("themes", themename, "kill2.png"), textureSize = (128, 128)):
engine.loadImgDrawing(self, "kill2", "kill2.png", textureSize = (128, 128))
#MFH - freestyle tails (for drum fills & BREs)
if not engine.loadImgDrawing(self, "freestyle1", os.path.join("themes", themename, "freestyletail1.png"), textureSize = (128, 128)):
engine.loadImgDrawing(self, "freestyle1", "freestyletail1.png", textureSize = (128, 128))
if not engine.loadImgDrawing(self, "freestyle2", os.path.join("themes", themename, "freestyletail2.png"), textureSize = (128, 128)):
engine.loadImgDrawing(self, "freestyle2", "freestyletail2.png", textureSize = (128, 128))
self.twoChordMax = False
self.rockLevel = 0.0
self.neck = Neck(self.engine, self, playerObj)
def selectPreviousString(self):
self.selectedString = (self.selectedString - 1) % self.strings
def selectString(self, string):
self.selectedString = string % self.strings
def selectNextString(self):
self.selectedString = (self.selectedString + 1) % self.strings
def noteBeingHeld(self):
noteHeld = False
for i in range(0,5):
if self.hit[i] == True:
noteHeld = True
return noteHeld
def isKillswitchPossible(self):
possible = False
for i in range(0,5):
if self.hit[i] == True:
possible = True
return possible
def renderTail(self, length, sustain, kill, color, flat = False, tailOnly = False, isTappable = False, big = False, fret = 0, spNote = False, freestyleTail = 0, pos = 0):
#volshebnyi - if freestyleTail == 0, act normally.
# if freestyleTail == 1, render an freestyle tail
# if freestyleTail == 2, render highlighted freestyle tail
if not self.simpleTails:#Tail Colors
tailcol = (1,1,1, color[3])
else:
if big == False and tailOnly == True:
tailcol = (.6, .6, .6, color[3])
else:
tailcol = (color)
#volshebnyi - tail color when sp is active
if self.starPowerActive and self.theme != 2 and not color == (0,0,0,1):#8bit
c = self.fretColors[5]
tailcol = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], color[3])
if flat:
tailscale = (1, .1, 1)
else:
tailscale = None
if sustain:
if not length == None:
size = (.08, length)
if size[1] > self.boardLength:
s = self.boardLength
else:
s = length
# if freestyleTail == 1, render freestyle tail
if freestyleTail == 0: #normal tail rendering
#myfingershurt: so any theme containing appropriate files can use new tails
if not self.simpleTails:
if big == True and tailOnly == True:
if kill and self.killfx == 0:
zsize = .25
tex1 = self.kill1
tex2 = self.kill2
#volshebnyi - killswitch tail width and color change
kEffect = ( math.sin( pos / 50 ) + 1 ) /2
size = (0.02+kEffect*0.15, s - zsize)
c = [self.killColor[0],self.killColor[1],self.killColor[2]]
if c != [0,0,0]:
for i in range(0,3):
c[i]=c[i]*kEffect+color[i]*(1-kEffect)
tailcol = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1)
else:
zsize = .25
size = (.17, s - zsize)
if self.starPowerActive and not color == (0,0,0,1):
tex1 = self.btail6
tex2 = self.btaile6
else:
if fret == 0:
tex1 = self.btail1
tex2 = self.btaile1
elif fret == 1:
tex1 = self.btail2
tex2 = self.btaile2
elif fret == 2:
tex1 = self.btail3
tex2 = self.btaile3
elif fret == 3:
tex1 = self.btail4
tex2 = self.btaile4
elif fret == 4:
tex1 = self.btail5
tex2 = self.btaile5
else:
zsize = .15
size = (.1, s - zsize)
if tailOnly:#Note let go
tex1 = self.tail0
tex2 = self.taile0
else:
if self.starPowerActive and not color == (0,0,0,1):
tex1 = self.tail6
tex2 = self.taile6
else:
if fret == 0:
tex1 = self.tail1
tex2 = self.taile1
elif fret == 1:
tex1 = self.tail2
tex2 = self.taile2
elif fret == 2:
tex1 = self.tail3
tex2 = self.taile3
elif fret == 3:
tex1 = self.tail4
tex2 = self.taile4
elif fret == 4:
tex1 = self.tail5
tex2 = self.taile5
else:
if big == True and tailOnly == True:
if kill:
zsize = .25
tex1 = self.kill1
tex2 = self.kill2
#volshebnyi - killswitch tail width and color change
kEffect = ( math.sin( pos / 50 ) + 1 ) /2
size = (0.02+kEffect*0.15, s - zsize)
c = [self.killColor[0],self.killColor[1],self.killColor[2]]
if c != [0,0,0]:
for i in range(0,3):
c[i]=c[i]*kEffect+color[i]*(1-kEffect)
tailcol = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1)
else:
zsize = .25
size = (.11, s - zsize)
tex1 = self.bigTail1
tex2 = self.bigTail2
else:
zsize = .15
size = (.08, s - zsize)
tex1 = self.tail1
tex2 = self.tail2
else: #freestyleTail > 0
# render an inactive freestyle tail (self.freestyle1 & self.freestyle2)
zsize = .25
if self.freestyleActive:
size = (.30, s - zsize) #was .15
else:
size = (.15, s - zsize)
tex1 = self.freestyle1
tex2 = self.freestyle2
if freestyleTail == 1:
#glColor4f(*color)
c1, c2, c3, c4 = color
tailGlow = 1 - (pos - self.freestyleLastFretHitTime[fret] ) / self.freestylePeriod
if tailGlow < 0:
tailGlow = 0
color = (c1 + c1*2.0*tailGlow, c2 + c2*2.0*tailGlow, c3 + c3*2.0*tailGlow, c4*0.6 + c4*0.4*tailGlow) #MFH - this fades inactive tails' color darker
tailcol = (color)
if self.theme == 2 and freestyleTail == 0 and big and tailOnly and shaders.enable("tail"):
color = (color[0]*1.5,color[1]*1.5,color[2]*1.5,1.0)
shaders.setVar("color",color)
if kill and self.killfx == 0:
h = shaders.getVar("height")
shaders.modVar("height",0.5,0.06/h-0.1)
shaders.setVar("offset",(5.0-size[1],0.0))
size=(size[0]*15,size[1])
self.engine.draw3Dtex(tex1, vertex = (-size[0], 0, size[0], size[1]), texcoord = (0.0, 0.0, 1.0, 1.0),
scale = tailscale, color = tailcol)
self.engine.draw3Dtex(tex2, vertex = (-size[0], size[1], size[0], size[1] + (zsize)),
scale = tailscale, texcoord = (0.0, 0.05, 1.0, 0.95), color = tailcol)
shaders.disable()
#MFH - this block of code renders the tail "beginning" - before the note, for freestyle "lanes" only
#volshebnyi
if freestyleTail > 0 and pos < self.freestyleStart + self.freestyleLength:
self.engine.draw3Dtex(tex2, vertex = (-size[0], 0-(zsize), size[0], 0 + (.05)),
scale = tailscale, texcoord = (0.0, 0.95, 1.0, 0.05), color = tailcol)
if tailOnly:
return
def renderNote(self, length, sustain, kill, color, flat = False, tailOnly = False, isTappable = False, big = False, fret = 0, spNote = False):
if flat:
glScalef(1, .1, 1)
if tailOnly:
return
if self.twoDnote == True:
#myfingershurt: this should be retrieved once at init, not repeatedly in-game whenever tails are rendered.
if self.notedisappear == True:#Notes keep on going when missed
notecol = (1,1,1)#capo
else:
if flat:#Notes disappear when missed
notecol = (.1,.1,.1)
else:
notecol = (1,1,1)
tailOnly == True
if self.theme < 2:
if self.starspin:
size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2)
texSize = (fret/5.0,fret/5.0+0.2)
if spNote == True:
if isTappable:
texY = (0.150+self.starSpinFrameIndex*0.05, 0.175+self.starSpinFrameIndex*0.05)
else:
texY = (0.125+self.starSpinFrameIndex*0.05, 0.150+self.starSpinFrameIndex*0.05)
else:
if isTappable:
texY = (0.025,0.05)
else:
texY = (0,0.025)
if self.starPowerActive:
texY = (0.10,0.125) #QQstarS
if isTappable:
texSize = (0.2,0.4)
else:
texSize = (0,0.2)
else:
size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2)
texSize = (fret/5.0,fret/5.0+0.2)
if spNote == True:
if isTappable:
texY = (0.6, 0.8)
else:
texY = (0.4,0.6)
else:
if isTappable:
texY = (0.2,0.4)
else:
texY = (0,0.2)
if self.starPowerActive:
texY = (0.8,1)
if isTappable:
texSize = (0.2,0.4)
else:
texSize = (0,0.2)
elif self.theme == 2:
size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2)
texSize = (fret/5.0,fret/5.0+0.2)
if spNote == True:
if isTappable:
texY = (3*0.166667, 4*0.166667)
else:
texY = (2*0.166667, 3*0.166667)
else:
if isTappable:
texY = (1*0.166667, 2*0.166667)
else:
texY = (0, 1*0.166667)
#myfingershurt: adding spNote==False conditional so that star notes can appear in overdrive
if self.starPowerActive and spNote == False:
if isTappable:
texY = (5*0.166667, 1)
else:
texY = (4*0.166667, 5*0.166667)
self.engine.draw3Dtex(self.noteButtons, vertex = (-size[0],size[1],size[0],-size[1]), texcoord = (texSize[0],texY[0],texSize[1],texY[1]),
scale = (1,1,0), rot = (30,1,0,0), multiples = True, color = color, vertscale = .27)
else:
shaders.setVar("Material",color,"notes")
#mesh = outer ring (black)
#mesh_001 = main note (key color)
#mesh_002 = top (spot or hopo if no mesh_003)
#mesh_003 = hopo bump (hopo color)
if spNote == True and self.starMesh is not None:
meshObj = self.starMesh
else:
meshObj = self.noteMesh
glPushMatrix()
glEnable(GL_DEPTH_TEST)
glDepthMask(1)
glShadeModel(GL_SMOOTH)
if self.noterotate:
glRotatef(90, 0, 1, 0)
glRotatef(-90, 1, 0, 0)
if spNote == True and self.threeDspin == True:
glRotate(90 + self.time/3, 0, 1, 0)
#death_au: fixed 3D note colours
#volshebnyi - note color when sp is active
glColor4f(*color)
if self.starPowerActive and self.theme != 2 and not color == (0,0,0,1):
c = self.fretColors[5]
glColor4f(.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1)
if fret == 0: # green note
glRotate(self.engine.theme.noterot[0], 0, 0, 1), glTranslatef(0, self.engine.theme.notepos[0], 0)
elif fret == 1: # red note
glRotate(self.engine.theme.noterot[1], 0, 0, 1), glTranslatef(0, self.engine.theme.notepos[1], 0)
elif fret == 2: # yellow
glRotate(self.engine.theme.noterot[2], 0, 0, 1), glTranslatef(0, self.engine.theme.notepos[2], 0)
elif fret == 3:# blue note
glRotate(self.engine.theme.noterot[3], 0, 0, 1), glTranslatef(0, self.engine.theme.notepos[3], 0)
elif fret == 4:# blue note
glRotate(self.engine.theme.noterot[4], 0, 0, 1), glTranslatef(0, self.engine.theme.notepos[4], 0)
if self.staratex == True and self.starPowerActive and spNote == False:
glColor3f(1,1,1)
glEnable(GL_TEXTURE_2D)
getattr(self,"staratex"+chr(97+fret)).texture.bind()
glMatrixMode(GL_TEXTURE)
glScalef(1, -1, 1)
glMatrixMode(GL_MODELVIEW)
glScalef(self.boardScaleX, self.boardScaleY, 1)
if isTappable:
mesh = "Mesh_001"
else:
mesh = "Mesh"
meshObj.render(mesh)
if shaders.enable("notes"):
shaders.setVar("isTextured",True)
meshObj.render(mesh)
shaders.disable()
glMatrixMode(GL_TEXTURE)
glLoadIdentity()
glMatrixMode(GL_MODELVIEW)
glDisable(GL_TEXTURE_2D)
elif self.notetex == True and spNote == False:
glColor3f(1,1,1)
glEnable(GL_TEXTURE_2D)
getattr(self,"notetex"+chr(97+fret)).texture.bind()
glMatrixMode(GL_TEXTURE)
glScalef(1, -1, 1)
glMatrixMode(GL_MODELVIEW)
glScalef(self.boardScaleX, self.boardScaleY, 1)
if isTappable:
mesh = "Mesh_001"
else:
mesh = "Mesh"
meshObj.render(mesh)
if shaders.enable("notes"):
shaders.setVar("isTextured",True)
meshObj.render(mesh)
shaders.disable()
glMatrixMode(GL_TEXTURE)
glLoadIdentity()
glMatrixMode(GL_MODELVIEW)
glDisable(GL_TEXTURE_2D)
elif self.startex == True and spNote == True:
glColor3f(1,1,1)
glEnable(GL_TEXTURE_2D)
getattr(self,"startex"+chr(97+fret)).texture.bind()
glMatrixMode(GL_TEXTURE)
glScalef(1, -1, 1)
glMatrixMode(GL_MODELVIEW)
glScalef(self.boardScaleX, self.boardScaleY, 1)
if isTappable:
mesh = "Mesh_001"
else:
mesh = "Mesh"
meshObj.render(mesh)
if shaders.enable("notes"):
shaders.setVar("isTextured",True)
meshObj.render(mesh)
shaders.disable()
glMatrixMode(GL_TEXTURE)
glLoadIdentity()
glMatrixMode(GL_MODELVIEW)
glDisable(GL_TEXTURE_2D)
else:
if shaders.enable("notes"):
shaders.setVar("isTextured",False)
meshObj.render("Mesh_001")
shaders.disable()
glColor3f(self.spotColor[0], self.spotColor[1], self.spotColor[2])
if isTappable:
if self.hopoColor[0] == -2:
glColor4f(*color)
else:
glColor3f(self.hopoColor[0], self.hopoColor[1], self.hopoColor[2])
if(meshObj.find("Mesh_003")) == True:
meshObj.render("Mesh_003")
glColor3f(self.spotColor[0], self.spotColor[1], self.spotColor[2])
meshObj.render("Mesh_002")
glColor3f(self.meshColor[0], self.meshColor[1], self.meshColor[2])
meshObj.render("Mesh")
glDepthMask(0)
glPopMatrix()
def renderFreestyleLanes(self, visibility, song, pos):
if not song:
return
if not song.readyToGo:
return
#boardWindowMin = pos - self.currentPeriod * 2
boardWindowMax = pos + self.currentPeriod * self.beatsPerBoard
track = song.midiEventTrack[self.player]
#MFH - render 5 freestyle tails when Song.freestyleMarkingNote comes up
if self.freestyleEnabled:
freestyleActive = False
#for time, event in track.getEvents(boardWindowMin, boardWindowMax):
for time, event in track.getEvents(pos - self.freestyleOffset , boardWindowMax + self.freestyleOffset):
if isinstance(event, Song.MarkerNote):
if event.number == Song.freestyleMarkingNote:
length = (event.length - 50) / self.currentPeriod / self.beatsPerUnit
w = self.boardWidth / self.strings
self.freestyleLength = event.length #volshebnyi
self.freestyleStart = time # volshebnyi
z = ((time - pos) / self.currentPeriod) / self.beatsPerUnit
z2 = ((time + event.length - pos) / self.currentPeriod) / self.beatsPerUnit
if z > self.boardLength * .8:
f = (self.boardLength - z) / (self.boardLength * .2)
elif z < 0:
f = min(1, max(0, 1 + z2))
else:
f = 1.0
#MFH - must extend the tail past the first fretboard section dynamically so we don't have to render the entire length at once
#volshebnyi - allow tail to move under frets
if time - self.freestyleOffset < pos:
freestyleActive = True
if z < -1.5:
length += z +1.5
z = -1.5
#MFH - render 5 freestyle tails
for theFret in range(0,5):
x = (self.strings / 2 - theFret) * w
c = self.fretColors[theFret]
color = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1 * visibility * f)
glPushMatrix()
glTranslatef(x, (1.0 - visibility) ** (theFret + 1), z)
freestyleTailMode = 1
self.renderTail(length, sustain = True, kill = False, color = color, flat = False, tailOnly = True, isTappable = False, big = True, fret = theFret, spNote = False, freestyleTail = freestyleTailMode, pos = pos)
glPopMatrix()
self.freestyleActive = freestyleActive
def renderNotes(self, visibility, song, pos, killswitch):
if not song:
return
if not song.readyToGo:
return
# Update dynamic period
self.currentPeriod = self.neckSpeed
#self.targetPeriod = self.neckSpeed
self.killPoints = False
w = self.boardWidth / self.strings
track = song.track[self.player]
num = 0
enable = True
starEventsInView = False
renderedNotes = reversed(self.getRequiredNotesForRender(song,pos))
for time, event in renderedNotes:
#for time, event in reversed(track.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)): #MFH - reverse order of note rendering
if isinstance(event, Tempo):
self.tempoBpm = event.bpm
if self.lastBpmChange > 0 and self.disableVBPM == True:
continue
if (pos - time > self.currentPeriod or self.lastBpmChange < 0) and time > self.lastBpmChange:
self.baseBeat += (time - self.lastBpmChange) / self.currentPeriod
self.targetBpm = event.bpm
self.lastBpmChange = time
self.neck.lastBpmChange = time
self.neck.baseBeat = self.baseBeat
# self.setBPM(self.targetBpm) # glorandwarf: was setDynamicBPM(self.targetBpm)
continue
if not isinstance(event, Note):
continue
if (event.noteBpm == 0.0):
event.noteBpm = self.tempoBpm
if self.coOpFailed:
if self.coOpRestart:
if time - self.coOpRescueTime < (self.currentPeriod * self.beatsPerBoard * 2):
continue
elif self.coOpRescueTime + (self.currentPeriod * self.beatsPerBoard * 2) < pos:
self.coOpFailed = False
self.coOpRestart = False
Log.debug("Turning off coOpFailed. Rescue successful.")
else:
continue #can't break. Tempo.
c = self.fretColors[event.number]
x = (self.strings / 2 - event.number) * w
z = ((time - pos) / self.currentPeriod) / self.beatsPerUnit
z2 = ((time + event.length - pos) / self.currentPeriod) / self.beatsPerUnit
if z > self.boardLength * .8:
f = (self.boardLength - z) / (self.boardLength * .2)
elif z < 0:
f = min(1, max(0, 1 + z2))
else:
f = 1.0
#volshebnyi - hide notes in BRE zone if BRE enabled
if self.freestyleEnabled and self.freestyleStart > 0:
if time >= self.freestyleStart-self.freestyleOffset and time < self.freestyleStart + self.freestyleLength+self.freestyleOffset:
z = -2.0
if self.twoDnote == True and not self.useFretColors:
color = (1,1,1, 1 * visibility * f)
else:
color = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1 * visibility * f)
if event.length > 120:
length = (event.length - 50) / self.currentPeriod / self.beatsPerUnit
else:
length = 0
flat = False
tailOnly = False
spNote = False
#myfingershurt: user setting for starpower refill / replenish notes
if self.starPowerActive:
if self.spRefillMode == 0: #mode 0 = no starpower / overdrive refill notes
self.spEnabled = False
elif self.spRefillMode == 1 and self.theme != 2: #mode 1 = overdrive refill notes in RB themes only
self.spEnabled = False
elif self.spRefillMode == 2 and song.midiStyle != 1: #mode 2 = refill based on MIDI type
self.spEnabled = False
if event.star:
#self.isStarPhrase = True
starEventsInView = True
if event.finalStar:
self.finalStarSeen = True
starEventsInView = True
if event.star and self.spEnabled:
spNote = True
if event.finalStar and self.spEnabled:
spNote = True
if event.played or event.hopod:
if event.flameCount < 1 and not self.starPowerGained:
Log.debug("star power added")
if self.gameMode2p == 6:
if self.battleSuddenDeath:
self.battleObjects = [1] + self.battleObjects[:2]
else:
self.battleObjects = [self.battleObjectsEnabled[random.randint(0,len(self.battleObjectsEnabled)-1)]] + self.battleObjects[:2]
self.battleGetTime = pos
self.battleObjectGained = True
Log.debug("Battle Object Gained, Objects %s" % str(self.battleObjects))
else:
if self.starPower < 100:
self.starPower += 25
if self.starPower > 100:
self.starPower = 100
self.neck.overdriveFlashCount = 0 #MFH - this triggers the oFlash strings & timer
self.starPowerGained = True
if event.tappable < 2:
isTappable = False
else:
isTappable = True
# Clip the played notes to the origin
#myfingershurt: this should be loaded once at init, not every render...
if self.notedisappear == True:#Notes keep on going when missed
###Capo###
if event.played or event.hopod:
tailOnly = True
length += z
z = 0
if length <= 0:
continue
if z < 0 and not (event.played or event.hopod):
color = (.6, .6, .6, .5 * visibility * f)
flat = True
###endCapo###
else:#Notes disappear when missed
if z < 0:
if event.played or event.hopod:
tailOnly = True
length += z
z = 0
if length <= 0:
continue
else:
color = (.6, .6, .6, .5 * visibility * f)
flat = True
big = False
self.bigMax = 0
for i in range(0,5):
if self.hit[i]:
big = True
self.bigMax += 1
#MFH - filter out this tail whitening when starpower notes have been disbled from a screwup
if self.spEnabled and killswitch:
if event.star or event.finalStar:
if big == True and tailOnly == True:
self.killPoints = True
color = (1,1,1,1)
if z + length < -1.0:
continue
if event.length <= 120:
length = None
sustain = False
if event.length > (1.4 * (60000.0 / event.noteBpm) / 4):
sustain = True
glPushMatrix()
glTranslatef(x, (1.0 - visibility) ** (event.number + 1), z)
if shaders.turnon:
shaders.setVar("note_position",(x, (1.0 - visibility) ** (event.number + 1), z),"notes")
if self.battleStatus[8]:
renderNote = random.randint(0,2)
else:
renderNote = 0
if renderNote == 0:
if big == True and num < self.bigMax:
num += 1
self.renderNote(length, sustain = sustain, kill = killswitch, color = color, flat = flat, tailOnly = tailOnly, isTappable = isTappable, big = True, fret = event.number, spNote = spNote)
else:
self.renderNote(length, sustain = sustain, kill = killswitch, color = color, flat = flat, tailOnly = tailOnly, isTappable = isTappable, fret = event.number, spNote = spNote)
glPopMatrix()
if (not starEventsInView and self.finalStarSeen):
self.spEnabled = True
self.finalStarSeen = False
self.isStarPhrase = False
def renderTails(self, visibility, song, pos, killswitch):
if not song:
return
if not song.readyToGo:
return
# Update dynamic period
self.currentPeriod = self.neckSpeed
#self.targetPeriod = self.neckSpeed
self.killPoints = False
w = self.boardWidth / self.strings
track = song.track[self.player]
num = 0
enable = True
renderedNotes = self.getRequiredNotesForRender(song,pos)
for time, event in renderedNotes:
#for time, event in track.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard):
if isinstance(event, Tempo):
self.tempoBpm = event.bpm
continue
if not isinstance(event, Note):
continue
if (event.noteBpm == 0.0):
event.noteBpm = self.tempoBpm
if self.coOpFailed:
if self.coOpRestart:
if time - self.coOpRescueTime < (self.currentPeriod * self.beatsPerBoard * 2):
continue
elif self.coOpRescueTime + (self.currentPeriod * self.beatsPerBoard * 2) < pos:
self.coOpFailed = False
self.coOpRestart = False
Log.debug("Turning off coOpFailed. Rescue successful.")
else:
continue
c = self.fretColors[event.number]
x = (self.strings / 2 - event.number) * w
z = ((time - pos) / self.currentPeriod) / self.beatsPerUnit
z2 = ((time + event.length - pos) / self.currentPeriod) / self.beatsPerUnit
if z > self.boardLength * .8:
f = (self.boardLength - z) / (self.boardLength * .2)
elif z < 0:
f = min(1, max(0, 1 + z2))
else:
f = 1.0
color = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1 * visibility * f)
if event.length > 120:
length = (event.length - 50) / self.currentPeriod / self.beatsPerUnit
else:
length = 0
flat = False
tailOnly = False
spNote = False
#myfingershurt: user setting for starpower refill / replenish notes
if event.star and self.spEnabled:
spNote = True
if event.finalStar and self.spEnabled:
spNote = True
if event.played or event.hopod:
if event.flameCount < 1 and not self.starPowerGained:
if self.gameMode2p == 6:
if self.battleSuddenDeath:
self.battleObjects = [1] + self.battleObjects[:2]
else:
self.battleObjects = [self.battleObjectsEnabled[random.randint(0,len(self.battleObjectsEnabled)-1)]] + self.battleObjects[:2]
self.battleGetTime = pos
self.battleObjectGained = True
Log.debug("Battle Object Gained, Objects %s" % str(self.battleObjects))
else:
if self.starPower < 100:
self.starPower += 25
if self.starPower > 100:
self.starPower = 100
self.neck.overdriveFlashCount = 0 #MFH - this triggers the oFlash strings & timer
self.starPowerGained = True
self.neck.ocount = 0
if event.tappable < 2:
isTappable = False
else:
isTappable = True
# Clip the played notes to the origin
#myfingershurt: this should be loaded once at init, not every render...
if self.notedisappear == True:#Notes keep on going when missed
###Capo###
if event.played or event.hopod:
tailOnly = True
length += z
z = 0
if length <= 0:
continue
if z < 0 and not (event.played or event.hopod):
color = (.6, .6, .6, .5 * visibility * f)
flat = True
###endCapo###
else:#Notes disappear when missed
if z < 0:
if event.played or event.hopod:
tailOnly = True
length += z
z = 0
if length <= 0:
continue
else:
color = (.6, .6, .6, .5 * visibility * f)
flat = True
big = False
self.bigMax = 0
for i in range(0,5):
if self.hit[i]:
big = True
self.bigMax += 1
if self.spEnabled and killswitch:
if event.star or event.finalStar:
if big == True and tailOnly == True:
self.killPoints = True
color = (1,1,1,1)
if z + length < -1.0:
continue
if event.length <= 120:
length = None
sustain = False
if event.length > (1.4 * (60000.0 / event.noteBpm) / 4):
sustain = True
glPushMatrix()
glTranslatef(x, (1.0 - visibility) ** (event.number + 1), z)
if self.battleStatus[8]:
renderNote = random.randint(0,2)
else:
renderNote = 0
if renderNote == 0:
if big == True and num < self.bigMax:
num += 1
self.renderTail(length, sustain = sustain, kill = killswitch, color = color, flat = flat, tailOnly = tailOnly, isTappable = isTappable, big = True, fret = event.number, spNote = spNote, pos = pos)
else:
self.renderTail(length, sustain = sustain, kill = killswitch, color = color, flat = flat, tailOnly = tailOnly, isTappable = isTappable, fret = event.number, spNote = spNote, pos = pos)
glPopMatrix()
if killswitch and self.killfx == 1:
glBlendFunc(GL_SRC_ALPHA, GL_ONE)
for time, event in self.playedNotes:
step = self.currentPeriod / 16
t = time + event.length
x = (self.strings / 2 - event.number) * w
c = self.fretColors[event.number]
s = t
proj = 1.0 / self.currentPeriod / self.beatsPerUnit
zStep = step * proj
def waveForm(t):
u = ((t - time) * -.1 + pos - time) / 64.0 + .0001
return (math.sin(event.number + self.time * -.01 + t * .03) + math.cos(event.number + self.time * .01 + t * .02)) * .1 + .1 + math.sin(u) / (5 * u)
glBegin(GL_TRIANGLE_STRIP)
f1 = 0
while t > time:
if ((t-pos)*proj) < self.boardLength:
z = (t - pos) * proj
else:
z = self.boardLength
if z < 0:
break
f2 = min((s - t) / (6 * step), 1.0)
a1 = waveForm(t) * f1
a2 = waveForm(t - step) * f2
if self.starPowerActive and self.theme != 2:#8bit
glColor4f(self.spColor[0],self.spColor[1],self.spColor[2],1) #(.3,.7,.9,1)
else:
glColor4f(c[0], c[1], c[2], .5)
glVertex3f(x - a1, 0, z)
glVertex3f(x - a2, 0, z - zStep)
glColor4f(1, 1, 1, .75)
glVertex3f(x, 0, z)
glVertex3f(x, 0, z - zStep)
if self.starPowerActive and self.theme != 2:#8bit
glColor4f(self.spColor[0],self.spColor[1],self.spColor[2],1) #(.3,.7,.9,1)
else:
glColor4f(c[0], c[1], c[2], .5)
glVertex3f(x + a1, 0, z)
glVertex3f(x + a2, 0, z - zStep)
glVertex3f(x + a2, 0, z - zStep)
glVertex3f(x - a2, 0, z - zStep)
t -= step
f1 = f2
glEnd()
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
def renderFrets(self, visibility, song, controls):
w = self.boardWidth / self.strings
size = (.22, .22)
v = 1.0 - visibility
glEnable(GL_DEPTH_TEST)
#Hitglow color option - myfingershurt sez this should be a Guitar class global, not retrieved ever fret render in-game...
for n in range(self.strings):
f = self.fretWeight[n]
c = self.fretColors[n]
if f and (controls.getState(self.actions[0]) or controls.getState(self.actions[1])):
f += 0.25
glColor4f(.1 + .8 * c[0] + f, .1 + .8 * c[1] + f, .1 + .8 * c[2] + f, visibility)
if self.fretPress:
y = v + f / 6
else:
y = v / 6
x = (self.strings / 2 - n) * w
if self.twoDkeys == True:
if self.battleStatus[4]:
fretWhamOffset = self.battleWhammyNow * .15
fretColor = (1,1,1,.5)
else:
fretWhamOffset = 0
fretColor = (1,1,1,1)
size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2.4)
if self.battleStatus[3] and self.battleFrets != None and self.battleBreakString == n:
texSize = (n/5.0+.042,n/5.0+0.158)
size = (.30, .40)
fretPos = 8 - round((self.battleBreakNow/self.battleBreakLimit) * 8)
texY = (fretPos/8.0,(fretPos + 1.0)/8)
self.engine.draw3Dtex(self.battleFrets, vertex = (size[0],size[1],-size[0],-size[1]), texcoord = (texSize[0], texY[0], texSize[1], texY[1]),
coord = (x,v + .08 + fretWhamOffset,0), multiples = True,color = fretColor, depth = True)
else:
texSize = (n/5.0,n/5.0+0.2)
texY = (0.0,1.0/3.0)
if controls.getState(self.keys[n]) or controls.getState(self.keys[n+5]):
texY = (1.0/3.0,2.0/3.0)
if self.hit[n] or (self.battleStatus[3] and self.battleBreakString == n):
texY = (2.0/3.0,1.0)
self.engine.draw3Dtex(self.fretButtons, vertex = (size[0],size[1],-size[0],-size[1]), texcoord = (texSize[0], texY[0], texSize[1], texY[1]),
coord = (x,v + fretWhamOffset,0), multiples = True,color = fretColor, depth = True)
else:
if self.keyMesh:
glPushMatrix()
glDepthMask(1)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glShadeModel(GL_SMOOTH)
glRotatef(90, 0, 1, 0)
glLightfv(GL_LIGHT0, GL_POSITION, (5.0, 10.0, -10.0, 0.0))
glLightfv(GL_LIGHT0, GL_AMBIENT, (.2, .2, .2, 0.0))
glLightfv(GL_LIGHT0, GL_DIFFUSE, (1.0, 1.0, 1.0, 0.0))
glRotatef(-90, 1, 0, 0)
glRotatef(-90, 0, 0, 1)
if n == 0: #green fret button
glRotate(self.engine.theme.keyrot[0], 0, 1, 0), glTranslatef(0, 0, self.engine.theme.keypos[0])
elif n == 1: #red fret button
glRotate(self.engine.theme.keyrot[1], 0, 1, 0), glTranslatef(0, 0, self.engine.theme.keypos[1])
elif n == 2: #yellow fret button
glRotate(self.engine.theme.keyrot[2], 0, 1, 0), glTranslatef(0, 0, self.engine.theme.keypos[2])
elif n == 3: #blue fret button
glRotate(self.engine.theme.keyrot[3], 0, 1, 0), glTranslatef(0, 0, self.engine.theme.keypos[3])
elif n == 4: #orange fret button
glRotate(self.engine.theme.keyrot[4], 0, 1, 0), glTranslatef(0, 0, self.engine.theme.keypos[4])
#Mesh - Main fret
#Key_001 - Top of fret (key_color)
#Key_002 - Bottom of fret (key2_color)
#Glow_001 - Only rendered when a note is hit along with the glow.svg
#if self.complexkey == True:
# glColor4f(.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], visibility)
# if self.battleStatus[4]:
# glTranslatef(x, y + self.battleWhammyNow * .15, 0)
# else:
# glTranslatef(x, y, 0)
if self.keytex == True:
glColor4f(1,1,1,visibility)
if self.battleStatus[4]:
glTranslatef(x, y + self.battleWhammyNow * .15, 0)
else:
glTranslatef(x, y, 0)
glEnable(GL_TEXTURE_2D)
getattr(self,"keytex"+chr(97+n)).texture.bind()
glMatrixMode(GL_TEXTURE)
glScalef(1, -1, 1)
glMatrixMode(GL_MODELVIEW)
glScalef(self.boardScaleX, self.boardScaleY, 1)
if f and not self.hit[n]:
self.keyMesh.render("Mesh_001")
elif self.hit[n]:
self.keyMesh.render("Mesh_002")
else:
self.keyMesh.render("Mesh")
glMatrixMode(GL_TEXTURE)
glLoadIdentity()
glMatrixMode(GL_MODELVIEW)
glDisable(GL_TEXTURE_2D)
else:
glColor4f(.1 + .8 * c[0] + f, .1 + .8 * c[1] + f, .1 + .8 * c[2] + f, visibility)
if self.battleStatus[4]:
glTranslatef(x, y + self.battleWhammyNow * .15 + v * 6, 0)
else:
glTranslatef(x, y + v * 6, 0)
key = self.keyMesh
if(key.find("Glow_001")) == True:
key.render("Mesh")
if(key.find("Key_001")) == True:
glColor3f(self.keyColor[0], self.keyColor[1], self.keyColor[2])
key.render("Key_001")
if(key.find("Key_002")) == True:
glColor3f(self.key2Color[0], self.key2Color[1], self.key2Color[2])
key.render("Key_002")
else:
key.render()
glDisable(GL_LIGHTING)
glDisable(GL_LIGHT0)
glDepthMask(0)
glPopMatrix()
######################
f = self.fretActivity[n]
if f and self.disableFretSFX != True:
if self.glowColor[0] == -1:
s = 1.0
else:
s = 0.0
while s < 1:
ms = s * (math.sin(self.time) * .25 + 1)
if self.glowColor[0] == -2:
glColor3f(c[0] * (1 - ms), c[1] * (1 - ms), c[2] * (1 - ms))
else:
glColor3f(self.glowColor[0] * (1 - ms), self.glowColor[1] * (1 - ms), self.glowColor[2] * (1 - ms))
glPushMatrix()
if self.battleStatus[4]:
glTranslatef(x, y + self.battleWhammyNow * .15, 0)
else:
glTranslatef(x, y, 0)
glScalef(.1 + .02 * ms * f, .1 + .02 * ms * f, .1 + .02 * ms * f)
glRotatef( 90, 0, 1, 0)
glRotatef(-90, 1, 0, 0)
glRotatef(-90, 0, 0, 1)
if self.twoDkeys == False and self.keytex == False:
if(self.keyMesh.find("Glow_001")) == True:
key.render("Glow_001")
else:
key.render()
glPopMatrix()
s += 0.2
#Hitglow color
if self.hitglow_color == 0:
glowcol = (c[0], c[1], c[2])#Same as fret
elif self.hitglow_color == 1:
glowcol = (1, 1, 1)#Actual color in .svg-file
f += 2
if self.battleStatus[4]:
self.engine.draw3Dtex(self.glowDrawing, coord = (x, y + self.battleWhammyNow * .15, 0.01), rot = (f * 90 + self.time, 0, 1, 0),
texcoord = (0.0, 0.0, 1.0, 1.0), vertex = (-size[0] * f, -size[1] * f, size[0] * f, size[1] * f),
multiples = True, alpha = True, color = glowcol)
else:
self.engine.draw3Dtex(self.glowDrawing, coord = (x, y, 0.01), rot = (f * 90 + self.time, 0, 1, 0),
texcoord = (0.0, 0.0, 1.0, 1.0), vertex = (-size[0] * f, -size[1] * f, size[0] * f, size[1] * f),
multiples = True, alpha = True, color = glowcol)
#self.hit[n] = False #MFH -- why? This prevents frets from being rendered under / before the notes...
glDisable(GL_DEPTH_TEST)
def renderFreestyleFlames(self, visibility, controls):
if self.flameColors[0][0][0] == -1:
return
w = self.boardWidth / self.strings
#track = song.track[self.player]
size = (.22, .22)
v = 1.0 - visibility
if self.disableFlameSFX != True:
flameLimit = 10.0
flameLimitHalf = round(flameLimit/2.0)
for fretNum in range(self.strings):
if controls.getState(self.keys[fretNum]) or controls.getState(self.keys[fretNum+5]):
if self.freestyleHitFlameCounts[fretNum] < flameLimit:
ms = math.sin(self.time) * .25 + 1
x = (self.strings / 2 - fretNum) * w
ff = 1 + 0.25
y = v + ff / 6
if self.theme == 2:
y -= 0.5
#flameSize = self.flameSizes[self.scoreMultiplier - 1][fretNum]
flameSize = self.flameSizes[self.cappedScoreMult - 1][fretNum]
if self.theme == 0 or self.theme == 1: #THIS SETS UP GH3 COLOR, ELSE ROCKBAND(which is DEFAULT in Theme.py)
flameColor = self.gh3flameColor
else: #MFH - fixing crash!
#try:
# flameColor = self.flameColors[self.scoreMultiplier - 1][fretNum]
#except IndexError:
flameColor = self.fretColors[fretNum]
if flameColor[0] == -2:
flameColor = self.fretColors[fretNum]
ff += 1.5 #ff first time is 2.75 after this
if self.freestyleHitFlameCounts[fretNum] < flameLimitHalf:
flamecol = tuple([flameColor[ifc] for ifc in range(3)])
rbStarColor = (.1, .1, .2, .3)
xOffset = (.0, - .005, .005, .0)
yOffset = (.20, .255, .255, .255)
scaleMod = .6 * ms * ff
scaleFix = (6.0, 5.5, 5.0, 4.7)
for step in range(4):
if self.starPowerActive and self.theme < 2:
flamecol = self.spColor
else: #Default starcolor (Rockband)
flamecol = (rbStarColor[step],)*3
hfCount = self.freestyleHitFlameCounts[fretNum]
if step == 0:
hfCount += 1
self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x+xOffset[step], y+yOffset[step], 0), rot = (90, 1, 0, 0),
scale = (.25 + .05 * step + scaleMod, hfCount/scaleFix[step] + scaleMod, hfCount/scaleFix[step] + scaleMod),
vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff),
texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol)
else:
flameColorMod = 0.1 * (flameLimit - self.freestyleHitFlameCounts[fretNum])
flamecol = tuple([flameColor[ifc]*flameColorMod for ifc in range(3)])
xOffset = (.0, - .005, .005, .005)
yOffset = (.35, .405, .355, .355)
scaleMod = .6 * ms * ff
scaleFix = (3.0, 2.5, 2.0, 1.7)
for step in range(4):
hfCount = self.freestyleHitFlameCounts[fretNum]
if step == 0:
hfCount += 1
else:
if self.starPowerActive and self.theme < 2:
flamecol = self.spColor
else: #Default starcolor (Rockband)
flamecol = (.4+.1*step,)*3
self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x+xOffset[step], y+yOffset[step], 0), rot = (90, 1, 0, 0),
scale = (.25 + .05 * step + scaleMod, hfCount/scaleFix[step] + scaleMod, hfCount/scaleFix[step] + scaleMod),
vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff),
texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol)
self.freestyleHitFlameCounts[fretNum] += 1
else: #MFH - flame count is done - reset it!
self.freestyleHitFlameCounts[fretNum] = 0 #MFH
def renderFlames(self, visibility, song, pos, controls):
if not song or self.flameColors[0][0][0] == -1:
return
w = self.boardWidth / self.strings
track = song.track[self.player]
size = (.22, .22)
v = 1.0 - visibility
if self.disableFlameSFX != True and (self.HCountAni == True and self.HCount2 > 12):
for n in range(self.strings):
f = self.fretWeight[n]
c = self.fretColors[n]
if f and (controls.getState(self.actions[0]) or controls.getState(self.actions[1])):
f += 0.25
y = v + f / 6
x = (self.strings / 2 - n) * w
f = self.fretActivity[n]
if f:
ms = math.sin(self.time) * .25 + 1
ff = f
ff += 1.2
#myfingershurt: need to cap flameSizes use of scoreMultiplier to 4x, the 5x and 6x bass groove mults cause crash:
self.cappedScoreMult = min(self.scoreMultiplier,4)
flameSize = self.flameSizes[self.cappedScoreMult - 1][n]
if self.theme == 0 or self.theme == 1: #THIS SETS UP GH3 COLOR, ELSE ROCKBAND(which is DEFAULT in Theme.py)
flameColor = self.gh3flameColor
else:
flameColor = self.flameColors[self.cappedScoreMult - 1][n]
flameColorMod = (1.19, 1.97, 10.59)
flamecol = tuple([flameColor[ifc]*flameColorMod[ifc] for ifc in range(3)])
if self.starPowerActive:
if self.theme == 0 or self.theme == 1: #GH3 starcolor
flamecol = self.spColor
else: #Default starcolor (Rockband)
flamecol = (.9,.9,.9)
if self.Hitanim != True:
self.engine.draw3Dtex(self.hitglowDrawing, coord = (x, y + .125, 0), rot = (90, 1, 0, 0),
scale = (0.5 + .6 * ms * ff, 1.5 + .6 * ms * ff, 1 + .6 * ms * ff),
vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff),
texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol)
#Alarian: Animated hitflames
else:
self.HCount = self.HCount + 1
if self.HCount > self.Animspeed-1:
self.HCount = 0
HIndex = (self.HCount * 16 - (self.HCount * 16) % self.Animspeed) / self.Animspeed
if HIndex > 15:
HIndex = 0
texX = (HIndex*(1/16.0), HIndex*(1/16.0)+(1/16.0))
self.engine.draw3Dtex(self.hitglowAnim, coord = (x, y + .225, 0), rot = (90, 1, 0, 0), scale = (2.4, 1, 3.3),
vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff),
texcoord = (texX[0],0.0,texX[1],1.0), multiples = True, alpha = True, color = (1,1,1))
ff += .3
flameColorMod = (1.19, 1.78, 12.22)
flamecol = tuple([flameColor[ifc]*flameColorMod[ifc] for ifc in range(3)])
if self.starPowerActive:
if self.theme == 0 or self.theme == 1: #GH3 starcolor
flamecol = self.spColor
else: #Default starcolor (Rockband)
flamecol = (.8,.8,.8)
if self.Hitanim != True:
self.engine.draw3Dtex(self.hitglow2Drawing, coord = (x, y + .25, .05), rot = (90, 1, 0, 0),
scale = (.40 + .6 * ms * ff, 1.5 + .6 * ms * ff, 1 + .6 * ms * ff),
vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff),
texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol)
if self.disableFlameSFX != True:
flameLimit = 10.0
flameLimitHalf = round(flameLimit/2.0)
renderedNotes = self.getRequiredNotesForRender(song,pos)
for time, event in renderedNotes:
if isinstance(event, Tempo):
continue
if not isinstance(event, Note):
continue
if (event.played or event.hopod) and event.flameCount < flameLimit:
ms = math.sin(self.time) * .25 + 1
x = (self.strings / 2 - event.number) * w
xlightning = (self.strings / 2 - event.number)*2.2*w
ff = 1 + 0.25
y = v + ff / 6
if self.theme == 2:
y -= 0.5
flameSize = self.flameSizes[self.cappedScoreMult - 1][event.number]
if self.theme == 0 or self.theme == 1: #THIS SETS UP GH3 COLOR, ELSE ROCKBAND(which is DEFAULT in Theme.py)
flameColor = self.gh3flameColor
else:
flameColor = self.flameColors[self.cappedScoreMult - 1][event.number]
if flameColor[0] == -2:
flameColor = self.fretColors[event.number]
ff += 1.5 #ff first time is 2.75 after this
if self.Hitanim2 == True:
self.HCount2 = self.HCount2 + 1
self.HCountAni = False
if self.HCount2 > 12:
if not event.length > (1.4 * (60000.0 / event.noteBpm) / 4):
self.HCount2 = 0
else:
self.HCountAni = True
if event.flameCount < flameLimitHalf:
HIndex = (self.HCount2 * 13 - (self.HCount2 * 13) % 13) / 13
if HIndex > 12 and self.HCountAni != True:
HIndex = 0
texX = (HIndex*(1/13.0), HIndex*(1/13.0)+(1/13.0))
self.engine.draw3Dtex(self.hitflamesAnim, coord = (x, y + .665, 0), rot = (90, 1, 0, 0), scale = (1.6, 1.6, 4.9),
vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff),
texcoord = (texX[0],0.0,texX[1],1.0), multiples = True, alpha = True, color = (1,1,1))
else:
flameColorMod = 0.1 * (flameLimit - event.flameCount)
flamecol = tuple([ifc*flameColorMod for ifc in flameColor])
scaleChange = (3.0,2.5,2.0,1.7)
yOffset = (.35, .405, .355, .355)
vtx = flameSize * ff
scaleMod = .6 * ms * ff
for step in range(4):
#draw lightning in GH themes on SP gain
if step == 0 and self.theme != 2 and event.finalStar and self.spEnabled:
self.engine.draw3Dtex(self.hitlightning, coord = (xlightning, y, 3.3), rot = (90, 1, 0, 0),
scale = (.15 + .5 * ms * ff, event.flameCount / 3.0 + .6 * ms * ff, 2), vertex = (.4,-2,-.4,2),
texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = (1,1,1))
continue
if step == 0:
yzscaleMod = event.flameCount/ scaleChange[step]
else:
yzscaleMod = (event.flameCount + 1)/ scaleChange[step]
if self.starPowerActive:
if self.theme == 0 or self.theme == 1:
spcolmod = .7+step*.1
flamecol = tuple([isp*spcolmod for isp in self.spColor])
else:
flamecol = (.4+step*.1,)*3#Default starcolor (Rockband)
if self.hitFlamesPresent == True:
self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x - .005, y + yOffset[step], 0), rot = (90, 1, 0, 0),
scale = (.25 + step*.05 + scaleMod, yzscaleMod + scaleMod, yzscaleMod + scaleMod),
vertex = (-vtx,-vtx,vtx,vtx), texcoord = (0.0,0.0,1.0,1.0),
multiples = True, alpha = True, color = flamecol)
elif self.hitFlamesPresent == True and self.Hitanim2 == False:
self.HCount2 = 13
self.HCountAni = True
if event.flameCount < flameLimitHalf:
flamecol = flameColor
if self.starPowerActive:
if self.theme == 0 or self.theme == 1: #GH3 starcolor
spcolmod = .3
flamecol = tuple([isp*spcolmod for isp in self.spColor])
else: #Default starcolor (Rockband)
flamecol = (.1,.1,.1)
self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x, y + .20, 0), rot = (90, 1, 0, 0),
scale = (.25 + .6 * ms * ff, event.flameCount/6.0 + .6 * ms * ff, event.flameCount / 6.0 + .6 * ms * ff),
vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0),
multiples = True, alpha = True, color = flamecol)
for i in range(3):
if self.starPowerActive:
if self.theme == 0 or self.theme == 1: #GH3 starcolor
spcolmod = 0.4+i*0.1
flamecol = tuple([isp*spcolmod for isp in self.spColor])
else: #Default starcolor (Rockband)
flamecol = (0.1+i*0.1,)*3
self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x-.005, y + .255, 0), rot = (90, 1, 0, 0),
scale = (.30 + i*0.05 + .6 * ms * ff, event.flameCount/(5.5 - i*0.4) + .6 * ms * ff, event.flameCount / (5.5 - i*0.4) + .6 * ms * ff),
vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0),
multiples = True, alpha = True, color = flamecol)
else:
flameColorMod = 0.1 * (flameLimit - event.flameCount)
flamecol = tuple([ifc*flameColorMod for ifc in flameColor])
scaleChange = (3.0,2.5,2.0,1.7)
yOffset = (.35, .405, .355, .355)
vtx = flameSize * ff
scaleMod = .6 * ms * ff
for step in range(4):
#draw lightning in GH themes on SP gain
if step == 0 and self.theme != 2 and event.finalStar and self.spEnabled:
self.engine.draw3Dtex(self.hitlightning, coord = (xlightning, y, 3.3), rot = (90, 1, 0, 0),
scale = (.15 + .5 * ms * ff, event.flameCount / 3.0 + .6 * ms * ff, 2), vertex = (.4,-2,-.4,2),
texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = (1,1,1))
continue
if step == 0:
yzscaleMod = event.flameCount/ scaleChange[step]
else:
yzscaleMod = (event.flameCount + 1)/ scaleChange[step]
if self.starPowerActive:
if self.theme == 0 or self.theme == 1:
spcolmod = .7+step*.1
flamecol = tuple([isp*spcolmod for isp in self.spColor])
else:
flamecol = (.4+step*.1,)*3#Default starcolor (Rockband)
self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x - .005, y + yOffset[step], 0), rot = (90, 1, 0, 0),
scale = (.25 + step*.05 + scaleMod, yzscaleMod + scaleMod, yzscaleMod + scaleMod),
vertex = (-vtx,-vtx,vtx,vtx), texcoord = (0.0,0.0,1.0,1.0),
multiples = True, alpha = True, color = flamecol)
event.flameCount += 1
def render(self, visibility, song, pos, controls, killswitch):
if shaders.turnon:
shaders.globals["dfActive"] = self.drumFillsActive
shaders.globals["breActive"] = self.freestyleActive
shaders.globals["rockLevel"] = self.rockLevel
if shaders.globals["killswitch"] != killswitch:
shaders.globals["killswitchPos"] = pos
shaders.globals["killswitch"] = killswitch
shaders.modVar("height",0.2,0.2,1.0,"tail")
if not self.starNotesSet == True:
self.totalNotes = 0
for time, event in song.track[self.player].getAllEvents():
if not isinstance(event, Note):
continue
self.totalNotes += 1
stars = []
maxStars = []
maxPhrase = self.totalNotes/120
for q in range(0,maxPhrase):
for n in range(0,10):
stars.append(self.totalNotes/maxPhrase*(q)+n+maxPhrase/4)
maxStars.append(self.totalNotes/maxPhrase*(q)+10+maxPhrase/4)
i = 0
for time, event in song.track[self.player].getAllEvents():
if not isinstance(event, Note):
continue
for a in stars:
if i == a:
self.starNotes.append(time)
event.star = True
for a in maxStars:
if i == a:
self.maxStars.append(time)
event.finalStar = True
i += 1
for time, event in song.track[self.player].getAllEvents():
if not isinstance(event, Note):
continue
for q in self.starNotes:
if time == q:
event.star = True
for q in self.maxStars:
#if time == q and not event.finalStar:
# event.star = True
if time == q: #MFH - no need to mark only the final SP phrase note as the finalStar as in drums, they will be hit simultaneously here.
event.finalStar = True
self.starNotesSet = True
if not (self.coOpFailed and not self.coOpRestart):
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_COLOR_MATERIAL)
if self.leftyMode:
if not self.battleStatus[6]:
glScalef(-1, 1, 1)
elif self.battleStatus[6]:
glScalef(-1, 1, 1)
if self.freestyleActive:
self.renderTails(visibility, song, pos, killswitch)
self.renderNotes(visibility, song, pos, killswitch)
self.renderFreestyleLanes(visibility, song, pos) #MFH - render the lanes on top of the notes.
self.renderFrets(visibility, song, controls)
if self.hitFlamesPresent: #MFH - only if present!
self.renderFreestyleFlames(visibility, controls) #MFH - freestyle hit flames
else:
self.renderTails(visibility, song, pos, killswitch)
if self.fretsUnderNotes: #MFH
if self.twoDnote == True:
self.renderFrets(visibility, song, controls)
self.renderNotes(visibility, song, pos, killswitch)
else:
self.renderNotes(visibility, song, pos, killswitch)
self.renderFrets(visibility, song, controls)
else:
self.renderNotes(visibility, song, pos, killswitch)
self.renderFrets(visibility, song, controls)
self.renderFreestyleLanes(visibility, song, pos) #MFH - render the lanes on top of the notes.
if self.hitFlamesPresent: #MFH - only if present!
self.renderFlames(visibility, song, pos, controls) #MFH - only when freestyle inactive!
if self.leftyMode:
if not self.battleStatus[6]:
glScalef(-1, 1, 1)
elif self.battleStatus[6]:
glScalef(-1, 1, 1)
#return notes
#MFH - corrected and optimized:
#def getRequiredNotesMFH(self, song, pos):
def getRequiredNotesMFH(self, song, pos, hopoTroubleCheck = False):
if self.battleStatus[2] and self.difficulty != 0:
if pos < self.battleStartTimes[2] + self.currentPeriod * self.beatsPerBoard or pos > self.battleStartTimes[2] - self.currentPeriod * self.beatsPerBoard + self.battleDiffUpLength:
song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue]
else:
song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue - 1]
track = song.track[self.player]
if hopoTroubleCheck:
notes = [(time, event) for time, event in track.getEvents(pos, pos + (self.earlyMargin*2)) if isinstance(event, Note)]
notes = [(time, event) for time, event in notes if not time==pos] #MFH - filter out the problem note that caused this check!
else:
notes = [(time, event) for time, event in track.getEvents(pos - self.lateMargin, pos + self.earlyMargin) if isinstance(event, Note)]
notes = [(time, event) for time, event in notes if not (event.hopod or event.played or event.skipped)]
notes = [(time, event) for time, event in notes if (time >= (pos - self.lateMargin)) and (time <= (pos + self.earlyMargin))]
sorted(notes, key=lambda x: x[0])
if self.battleStatus[7]:
notes = self.getDoubleNotes(notes)
return sorted(notes, key=lambda x: x[0]) #MFH - what the hell, this should be sorted by TIME not note number....
def getDoubleNotes(self, notes):
if self.battleStatus[7] and notes != []:
notes = sorted(notes, key=lambda x: x[0])
curTime = 0
tempnotes = []
tempnumbers = []
tempnote = None
curNumbers = []
noteCount = 0
for time, note in notes:
noteCount += 1
if not isinstance(note, Note):
if noteCount == len(notes) and len(curNumbers) < 3 and len(curNumbers) > 0:
maxNote = curNumbers[0]
minNote = curNumbers[0]
for i in range(0, len(curNumbers)):
if curNumbers[i] > maxNote:
maxNote = curNumbers[i]
if curNumbers[i] < minNote:
minNote = curNumbers[i]
curNumbers = []
if maxNote < 4:
tempnumbers.append(maxNote + 1)
elif minNote > 0:
tempnumbers.append(minNote - 1)
else:
tempnumbers.append(2)
elif noteCount == len(notes) and len(curNumbers) > 2:
tempnumbers.append(-1)
curNumbers = []
continue
if time != curTime:
if curTime != 0 and len(curNumbers) < 3:
maxNote = curNumbers[0]
minNote = curNumbers[0]
for i in range(0, len(curNumbers)):
if curNumbers[i] > maxNote:
maxNote = curNumbers[i]
if curNumbers[i] < minNote:
minNote = curNumbers[i]
curNumbers = []
if maxNote < 4:
tempnumbers.append(maxNote + 1)
elif minNote > 0:
tempnumbers.append(minNote - 1)
else:
tempnumbers.append(2)
elif (curTime != 0 or noteCount == len(notes)) and len(curNumbers) > 2:
tempnumbers.append(-1)
curNumbers = []
tempnotes.append((time,deepcopy(note)))
curTime = time
curNumbers.append(note.number)
if noteCount == len(notes) and len(curNumbers) < 3:
maxNote = curNumbers[0]
minNote = curNumbers[0]
for i in range(0, len(curNumbers)):
if curNumbers[i] > maxNote:
maxNote = curNumbers[i]
if curNumbers[i] < minNote:
minNote = curNumbers[i]
curNumbers = []
if maxNote < 4:
tempnumbers.append(maxNote + 1)
elif minNote > 0:
tempnumbers.append(minNote - 1)
else:
tempnumbers.append(2)
elif noteCount == len(notes) and len(curNumbers) > 2:
tempnumbers.append(-1)
curNumbers = []
else:
curNumbers.append(note.number)
if noteCount == len(notes) and len(curNumbers) < 3:
maxNote = curNumbers[0]
minNote = curNumbers[0]
for i in range(0, len(curNumbers)):
if curNumbers[i] > maxNote:
maxNote = curNumbers[i]
if curNumbers[i] < minNote:
minNote = curNumbers[i]
curNumbers = []
if maxNote < 4:
tempnumbers.append(maxNote + 1)
elif minNote > 0:
tempnumbers.append(minNote - 1)
else:
tempnumbers.append(2)
elif noteCount == len(notes) and len(curNumbers) > 2:
tempnumbers.append(-1)
curNumbers = []
noteCount = 0
for time, note in tempnotes:
if tempnumbers[noteCount] != -1:
note.number = tempnumbers[noteCount]
noteCount += 1
if time > self.battleStartTimes[7] + self.currentPeriod * self.beatsPerBoard and time < self.battleStartTimes[7] - self.currentPeriod * self.beatsPerBoard + self.battleDoubleLength:
notes.append((time,note))
else:
noteCount += 1
return sorted(notes, key=lambda x: x[0])
def getRequiredNotesForRender(self, song, pos):
if self.battleStatus[2] and self.difficulty != 0:
Log.debug(self.battleDiffUpValue)
song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue]
track0 = song.track[self.player]
notes0 = [(time, event) for time, event in track0.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)]
song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue - 1]
track1 = song.track[self.player]
notes1 = [(time, event) for time, event in track1.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)]
notes = []
for time,note in notes0:
if time < self.battleStartTimes[2] + self.currentPeriod * self.beatsPerBoard or time > self.battleStartTimes[2] - self.currentPeriod * self.beatsPerBoard + self.battleDiffUpLength:
notes.append((time,note))
for time,note in notes1:
if time > self.battleStartTimes[2] + self.currentPeriod * self.beatsPerBoard and time < self.battleStartTimes[2] - self.currentPeriod * self.beatsPerBoard + self.battleDiffUpLength:
notes.append((time,note))
notes0 = None
notes1 = None
track0 = None
track1 = None
notes = sorted(notes, key=lambda x: x[0])
#Log.debug(notes)
else:
track = song.track[self.player]
notes = [(time, event) for time, event in track.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)]
if self.battleStatus[7]:
notes = self.getDoubleNotes(notes)
return notes
#MFH - corrected and optimized:
def getRequiredNotesForJurgenOnTime(self, song, pos):
track = song.track[self.player]
notes = [(time, event) for time, event in track.getEvents(pos - self.lateMargin, pos + 30) if isinstance(event, Note)]
notes = [(time, event) for time, event in notes if not (event.hopod or event.played or event.skipped)]
if self.battleStatus[7]:
notes = self.getDoubleNotes(notes)
return sorted(notes, key=lambda x: x[0]) #MFH - what the hell, this should be sorted by TIME not note number....
def controlsMatchNotes(self, controls, notes):
# no notes?
if not notes:
return False
# check each valid chord
chords = {}
for time, note in notes:
if not time in chords:
chords[time] = []
chords[time].append((time, note))
#Make sure the notes are in the right time order
chordlist = chords.values()
chordlist.sort(lambda a, b: cmp(a[0][0], b[0][0]))
twochord = 0
for chord in chordlist:
# matching keys?
requiredKeys = [note.number for time, note in chord]
requiredKeys = self.uniqify(requiredKeys)
if len(requiredKeys) > 2 and self.twoChordMax == True:
twochord = 0
for k in self.keys:
if controls.getState(k):
twochord += 1
if twochord == 2:
skipped = len(requiredKeys) - 2
requiredKeys = [min(requiredKeys), max(requiredKeys)]
else:
twochord = 0
for n in range(self.strings):
if n in requiredKeys and not (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5])):
return False
if not n in requiredKeys and (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5])):
# The lower frets can be held down
if n > max(requiredKeys):
return False
if twochord != 0:
if twochord != 2:
for time, note in chord:
note.played = True
else:
self.twoChordApply = True
for time, note in chord:
note.skipped = True
chord[0][1].skipped = False
chord[-1][1].skipped = False
chord[0][1].played = True
chord[-1][1].played = True
if twochord == 2:
self.twoChord += skipped
return True
def controlsMatchNotes2(self, controls, notes, hopo = False):
# no notes?
if not notes:
return False
# check each valid chord
chords = {}
for time, note in notes:
if note.hopod == True and (controls.getState(self.keys[note.number]) or controls.getState(self.keys[note.number + 5])):
#if hopo == True and controls.getState(self.keys[note.number]):
self.playedNotes = []
return True
if not time in chords:
chords[time] = []
chords[time].append((time, note))
#Make sure the notes are in the right time order
chordlist = chords.values()
chordlist.sort(lambda a, b: cmp(a[0][0], b[0][0]))
twochord = 0
for chord in chordlist:
# matching keys?
requiredKeys = [note.number for time, note in chord]
requiredKeys = self.uniqify(requiredKeys)
if len(requiredKeys) > 2 and self.twoChordMax == True:
twochord = 0
for n, k in enumerate(self.keys):
if controls.getState(k):
twochord += 1
if twochord == 2:
skipped = len(requiredKeys) - 2
requiredKeys = [min(requiredKeys), max(requiredKeys)]
else:
twochord = 0
for n in range(self.strings):
if n in requiredKeys and not (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5])):
return False
if not n in requiredKeys and (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5])):
# The lower frets can be held down
if hopo == False and n >= min(requiredKeys):
return False
if twochord != 0:
if twochord != 2:
for time, note in chord:
note.played = True
else:
self.twoChordApply = True
for time, note in chord:
note.skipped = True
chord[0][1].skipped = False
chord[-1][1].skipped = False
chord[0][1].played = True
chord[-1][1].played = True
if twochord == 2:
self.twoChord += skipped
return True
def controlsMatchNotes3(self, controls, notes, hopo = False):
# no notes?
if not notes:
return False
# check each valid chord
chords = {}
for time, note in notes:
if note.hopod == True and (controls.getState(self.keys[note.number]) or controls.getState(self.keys[note.number + 5])):
#if hopo == True and controls.getState(self.keys[note.number]):
self.playedNotes = []
return True
if not time in chords:
chords[time] = []
chords[time].append((time, note))
#Make sure the notes are in the right time order
chordlist = chords.values()
#chordlist.sort(lambda a, b: cmp(a[0][0], b[0][0]))
chordlist.sort(key=lambda a: a[0][0])
self.missedNotes = []
self.missedNoteNums = []
twochord = 0
for chord in chordlist:
# matching keys?
requiredKeys = [note.number for time, note in chord]
requiredKeys = self.uniqify(requiredKeys)
if len(requiredKeys) > 2 and self.twoChordMax == True:
twochord = 0
for n, k in enumerate(self.keys):
if controls.getState(k):
twochord += 1
if twochord == 2:
skipped = len(requiredKeys) - 2
requiredKeys = [min(requiredKeys), max(requiredKeys)]
else:
twochord = 0
if (self.controlsMatchNote3(controls, chord, requiredKeys, hopo)):
if twochord != 2:
for time, note in chord:
note.played = True
else:
self.twoChordApply = True
for time, note in chord:
note.skipped = True
chord[0][1].skipped = False
chord[-1][1].skipped = False
chord[0][1].played = True
chord[-1][1].played = True
break
if hopo == True:
break
self.missedNotes.append(chord)
else:
self.missedNotes = []
self.missedNoteNums = []
for chord in self.missedNotes:
for time, note in chord:
if self.debugMode:
self.missedNoteNums.append(note.number)
note.skipped = True
note.played = False
if twochord == 2:
self.twoChord += skipped
return True
#MFH - special function for HOPO intentions checking
def controlsMatchNextChord(self, controls, notes):
# no notes?
if not notes:
return False
# check each valid chord
chords = {}
for time, note in notes:
if not time in chords:
chords[time] = []
chords[time].append((time, note))
#Make sure the notes are in the right time order
chordlist = chords.values()
chordlist.sort(key=lambda a: a[0][0])
twochord = 0
for chord in chordlist:
# matching keys?
self.requiredKeys = [note.number for time, note in chord]
self.requiredKeys = self.uniqify(self.requiredKeys)
if len(self.requiredKeys) > 2 and self.twoChordMax == True:
twochord = 0
self.twoChordApply = True
for n, k in enumerate(self.keys):
if controls.getState(k):
twochord += 1
if twochord == 2:
skipped = len(self.requiredKeys) - 2
self.requiredKeys = [min(self.requiredKeys), max(self.requiredKeys)]
else:
twochord = 0
if (self.controlsMatchNote3(controls, chord, self.requiredKeys, False)):
return True
else:
return False
def uniqify(self, seq, idfun=None):
# order preserving
if idfun is None:
def idfun(x): return x
seen = {}
result = []
for item in seq:
marker = idfun(item)
# in old Python versions:
# if seen.has_key(marker)
# but in new ones:
if marker in seen: continue
seen[marker] = 1
result.append(item)
return result
def controlsMatchNote3(self, controls, chordTuple, requiredKeys, hopo):
if len(chordTuple) > 1:
#Chords must match exactly
for n in range(self.strings):
if (n in requiredKeys and not (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5]))) or (n not in requiredKeys and (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5]))):
return False
else:
#Single Note must match that note
requiredKey = requiredKeys[0]
if not controls.getState(self.keys[requiredKey]) and not controls.getState(self.keys[requiredKey+5]):
return False
#myfingershurt: this is where to filter out higher frets held when HOPOing:
if hopo == False or self.hopoStyle == 2 or self.hopoStyle == 3:
#Check for higher numbered frets if not a HOPO or if GH2 strict mode
for n, k in enumerate(self.keys):
if (n > requiredKey and n < 5) or (n > 4 and n > requiredKey + 5):
#higher numbered frets cannot be held
if controls.getState(k):
return False
return True
def areNotesTappable(self, notes):
if not notes:
return
for time, note in notes:
if note.tappable > 1:
return True
return False
def startPick(self, song, pos, controls, hopo = False):
if hopo == True:
res = startPick2(song, pos, controls, hopo)
return res
if not song:
return False
if not song.readyToGo:
return False
self.playedNotes = []
self.matchingNotes = self.getRequiredNotes(song, pos)
if self.controlsMatchNotes(controls, self.matchingNotes):
self.pickStartPos = pos
for time, note in self.matchingNotes:
if note.skipped == True:
continue
self.pickStartPos = max(self.pickStartPos, time)
note.played = True
self.playedNotes.append([time, note])
if self.guitarSolo:
self.currentGuitarSoloHitNotes += 1
return True
return False
def startPick2(self, song, pos, controls, hopo = False):
if not song:
return False
if not song.readyToGo:
return False
self.playedNotes = []
self.matchingNotes = self.getRequiredNotes2(song, pos, hopo)
if self.controlsMatchNotes2(controls, self.matchingNotes, hopo):
self.pickStartPos = pos
for time, note in self.matchingNotes:
if note.skipped == True:
continue
self.pickStartPos = max(self.pickStartPos, time)
if hopo:
note.hopod = True
else:
note.played = True
if note.tappable == 1 or note.tappable == 2:
self.hopoActive = time
self.wasLastNoteHopod = True
elif note.tappable == 3:
self.hopoActive = -time
self.wasLastNoteHopod = True
else:
self.hopoActive = 0
self.wasLastNoteHopod = False
self.playedNotes.append([time, note])
if self.guitarSolo:
self.currentGuitarSoloHitNotes += 1
self.hopoLast = note.number
return True
return False
def startPick3(self, song, pos, controls, hopo = False):
if not song:
return False
if not song.readyToGo:
return False
self.lastPlayedNotes = self.playedNotes
self.playedNotes = []
self.matchingNotes = self.getRequiredNotesMFH(song, pos)
self.controlsMatchNotes3(controls, self.matchingNotes, hopo)
#myfingershurt
for time, note in self.matchingNotes:
if note.played != True:
continue
if shaders.turnon:
shaders.var["fret"][self.player][note.number]=shaders.time()
shaders.var["fretpos"][self.player][note.number]=pos
self.pickStartPos = pos
self.pickStartPos = max(self.pickStartPos, time)
if hopo:
note.hopod = True
else:
note.played = True
#self.wasLastNoteHopod = False
if note.tappable == 1 or note.tappable == 2:
self.hopoActive = time
self.wasLastNoteHopod = True
elif note.tappable == 3:
self.hopoActive = -time
self.wasLastNoteHopod = True
if hopo: #MFH - you just tapped a 3 - make a note of it. (har har)
self.hopoProblemNoteNum = note.number
self.sameNoteHopoString = True
else:
self.hopoActive = 0
self.wasLastNoteHopod = False
self.hopoLast = note.number
self.playedNotes.append([time, note])
if self.guitarSolo:
self.currentGuitarSoloHitNotes += 1
#myfingershurt: be sure to catch when a chord is played
if len(self.playedNotes) > 1:
lastPlayedNote = None
for time, note in self.playedNotes:
if isinstance(lastPlayedNote, Note):
if note.tappable == 1 and lastPlayedNote.tappable == 1:
self.LastStrumWasChord = True
#self.sameNoteHopoString = False
else:
self.LastStrumWasChord = False
lastPlayedNote = note
elif len(self.playedNotes) > 0: #ensure at least that a note was played here
self.LastStrumWasChord = False
if len(self.playedNotes) != 0:
return True
return False
def soloFreestylePick(self, song, pos, controls):
numHits = 0
for theFret in range(5):
self.freestyleHit[theFret] = controls.getState(self.keys[theFret+5])
if self.freestyleHit[theFret]:
if shaders.turnon:
shaders.var["fret"][self.player][theFret]=shaders.time()
shaders.var["fretpos"][self.player][theFret]=pos
numHits += 1
return numHits
#MFH - TODO - handle freestyle picks here
def freestylePick(self, song, pos, controls):
numHits = 0
#if not song:
# return numHits
if not controls.getState(self.actions[0]) and not controls.getState(self.actions[1]):
return 0
for theFret in range(5):
self.freestyleHit[theFret] = controls.getState(self.keys[theFret])
if self.freestyleHit[theFret]:
if shaders.turnon:
shaders.var["fret"][self.player][theFret]=shaders.time()
shaders.var["fretpos"][self.player][theFret]=pos
numHits += 1
return numHits
def endPick(self, pos):
for time, note in self.playedNotes:
if time + note.length > pos + self.noteReleaseMargin:
self.playedNotes = []
return False
self.playedNotes = []
return True
def getPickLength(self, pos):
if not self.playedNotes:
return 0.0
# The pick length is limited by the played notes
pickLength = pos - self.pickStartPos
for time, note in self.playedNotes:
pickLength = min(pickLength, note.length)
return pickLength
def coOpRescue(self, pos):
self.coOpRestart = True #initializes Restart Timer
self.coOpRescueTime = pos
self.starPower = 0
Log.debug("Rescued at " + str(pos))
def run(self, ticks, pos, controls):
if not self.paused:
self.time += ticks
#MFH - Determine which frame to display for starpower notes
if self.starspin:
self.indexCount = self.indexCount + 1
if self.indexCount > self.Animspeed-1:
self.indexCount = 0
self.starSpinFrameIndex = (self.indexCount * self.starSpinFrames - (self.indexCount * self.starSpinFrames) % self.Animspeed) / self.Animspeed
if self.starSpinFrameIndex > self.starSpinFrames - 1:
self.starSpinFrameIndex = 0
#myfingershurt: must not decrease SP if paused.
if self.starPowerActive == True and self.paused == False:
self.starPower -= ticks/self.starPowerDecreaseDivisor
if self.starPower <= 0:
self.starPower = 0
self.starPowerActive = False
#MFH - call to play star power deactivation sound, if it exists (if not play nothing)
if self.engine.data.starDeActivateSoundFound:
#self.engine.data.starDeActivateSound.setVolume(self.sfxVolume)
self.engine.data.starDeActivateSound.play()
# update frets
if self.editorMode:
if (controls.getState(self.actions[0]) or controls.getState(self.actions[1])):
for i in range(self.strings):
if controls.getState(self.keys[i]) or controls.getState(self.keys[i+5]):
activeFrets.append(i)
activeFrets = activeFrets or [self.selectedString]
else:
activeFrets = []
else:
activeFrets = [note.number for time, note in self.playedNotes]
for n in range(self.strings):
if controls.getState(self.keys[n]) or controls.getState(self.keys[n+5]) or (self.editorMode and self.selectedString == n):
self.fretWeight[n] = 0.5
else:
self.fretWeight[n] = max(self.fretWeight[n] - ticks / 64.0, 0.0)
if n in activeFrets:
self.fretActivity[n] = min(self.fretActivity[n] + ticks / 32.0, 1.0)
else:
self.fretActivity[n] = max(self.fretActivity[n] - ticks / 64.0, 0.0)
#MFH - THIS is where note sustains should be determined... NOT in renderNotes / renderFrets / renderFlames -.-
if self.fretActivity[n]:
self.hit[n] = True
else:
self.hit[n] = False
if self.vbpmLogicType == 0: #MFH - VBPM (old)
if self.currentBpm != self.targetBpm:
diff = self.targetBpm - self.currentBpm
if (round((diff * .03), 4) != 0):
self.currentBpm = round(self.currentBpm + (diff * .03), 4)
else:
self.currentBpm = self.targetBpm
self.setBPM(self.currentBpm) # glorandwarf: was setDynamicBPM(self.currentBpm)
for time, note in self.playedNotes:
if pos > time + note.length:
return False
return True
| cherbib/fofix | src/Guitar.py | Python | gpl-2.0 | 95,964 |
#include "string\string.h"
#include "..\testcommon.h"
#include <gtest/gtest.h>
const struct test_isnumeric
{
std::wstring given;
bool is;
bool allowDecimals;
friend std::ostream& operator <<(std::ostream& os, const test_isnumeric& obj)
{
return os
<< "Given : " << myodd::strings::WString2String(obj.given)
<< " Expected : " << (obj.is ? "true" : "false")
<< " Allow decimals : " << (obj.allowDecimals ? "true" : "false");
}
};
struct MyOddStringIsNumeric : testing::Test, testing::WithParamInterface<test_isnumeric>
{
};
struct MyOddStringIsNumericWithAllowDecimals : testing::Test, testing::WithParamInterface<test_isnumeric>
{
};
TEST_P(MyOddStringIsNumeric, IsNumericDefaultParams)
{
auto param = GetParam();
auto given = GetParam().given;
auto is = GetParam().is;
ASSERT_EQ(is, myodd::strings::IsNumeric(given));
}
TEST_P(MyOddStringIsNumericWithAllowDecimals, UseAllowDecimalsFlag)
{
auto param = GetParam();
auto given = GetParam().given;
auto is = GetParam().is;
auto allowDecimals = GetParam().allowDecimals;
ASSERT_EQ(is, myodd::strings::IsNumeric(given, allowDecimals));
}
INSTANTIATE_TEST_CASE_P(NegativeStrings, MyOddStringIsNumeric,
testing::Values(
test_isnumeric{ L"-1", true },
test_isnumeric{ L"-0", true },
test_isnumeric{ L"-.1", true },
test_isnumeric{ L"-0.1", true },
test_isnumeric{ L"-1.1", true },
test_isnumeric{ L"-999", true },
test_isnumeric{ L"-999.a", false },
test_isnumeric{ L"-1.1.1", false }
));
INSTANTIATE_TEST_CASE_P(NegativeStringsDecimalsAllowed, MyOddStringIsNumericWithAllowDecimals,
testing::Values(
test_isnumeric{ L"-1", true, true },
test_isnumeric{ L"-0", true, true },
test_isnumeric{ L"-.1", true, true },
test_isnumeric{ L"-0.1", true, true },
test_isnumeric{ L"-1.1", true, true },
test_isnumeric{ L"-999", true, true },
test_isnumeric{ L"-999.a", false, true },
test_isnumeric{ L"-1.1.1", false, true }
));
INSTANTIATE_TEST_CASE_P(NegativeStringsDecimalsNotAllowed, MyOddStringIsNumericWithAllowDecimals,
testing::Values(
test_isnumeric{ L"-1", true, false },
test_isnumeric{ L"-0", true, false },
test_isnumeric{ L"-1.", true, false }, // 1. is not a decimal
test_isnumeric{ L"-.1", false, false },
test_isnumeric{ L"-0.1", false, false },
test_isnumeric{ L"-1.1", false, false },
test_isnumeric{ L"-999", true, false },
test_isnumeric{ L"-999.a", false, false },
test_isnumeric{ L"-1.1.1", false, false }
));
INSTANTIATE_TEST_CASE_P(PositiveStrings, MyOddStringIsNumeric,
testing::Values(
test_isnumeric{ L"1", true },
test_isnumeric{ L"+0", true },
test_isnumeric{ L".1", true },
test_isnumeric{ L"0.1", true },
test_isnumeric{ L"+0.1", true },
test_isnumeric{ L"+.1", true },
test_isnumeric{ L"1.1", true },
test_isnumeric{ L"-999", true },
test_isnumeric{ L"-999.a", false },
test_isnumeric{ L"-1.1.1", false },
test_isnumeric{ L"1.", true },
test_isnumeric{ L" 1. ", true },
test_isnumeric{ L" 10 ", true },
test_isnumeric{ L" 10.4 ", true },
test_isnumeric{ L" 10 . 4 ", false }
));
INSTANTIATE_TEST_CASE_P(PositiveStringsDecimalsNotAllowed, MyOddStringIsNumericWithAllowDecimals,
testing::Values(
test_isnumeric{ L"1", true, false },
test_isnumeric{ L"+0", true, false },
test_isnumeric{ L".1", false, false },
test_isnumeric{ L"0.1", false, false },
test_isnumeric{ L"+0.1", false, false },
test_isnumeric{ L"+.1", false, false },
test_isnumeric{ L"1.1", false, false },
test_isnumeric{ L"-999", true, false },
test_isnumeric{ L"-999.a", false, false },
test_isnumeric{ L"-1.1.1", false, false },
test_isnumeric{ L"1.", true, false },
test_isnumeric{ L" 1. ", true, false },
test_isnumeric{ L" 10 ", true, false },
test_isnumeric{ L" 10.4 ", false, false },
test_isnumeric{ L" 10 . 4 ", false, false }
));
INSTANTIATE_TEST_CASE_P(MiscStrings, MyOddStringIsNumeric,
testing::Values(
test_isnumeric{ L"-", false },
test_isnumeric{ L".", false },
test_isnumeric{ L"+", false },
test_isnumeric{ L"A1,1", false },
test_isnumeric{ L"1,1", false },
test_isnumeric{ L"+A11", false },
test_isnumeric{ L"A11", false },
test_isnumeric{ L"11A", false },
test_isnumeric{ L"11A", false },
test_isnumeric{ L" 1 2 ", false },
test_isnumeric{ L"-999.1 2", false },
test_isnumeric{ L"999.1 2", false },
test_isnumeric{ L"", false }, // empty
test_isnumeric{ L" ", false } // empty
));
INSTANTIATE_TEST_CASE_P(MiscStringsWithDecimalFlag, MyOddStringIsNumericWithAllowDecimals,
testing::Values(
test_isnumeric{ L"-", false, false },
test_isnumeric{ L".", false, false },
test_isnumeric{ L"+", false, false },
test_isnumeric{ L"A1,1", false, false },
test_isnumeric{ L"1,1", false, false },
test_isnumeric{ L"+A11", false, false },
test_isnumeric{ L"A11", false, false },
test_isnumeric{ L"11A", false, false },
test_isnumeric{ L"11A", false, false },
test_isnumeric{ L" 1 2 ", false, false },
test_isnumeric{ L"-999.1 2", false, false },
test_isnumeric{ L"999.1 2", false, false },
test_isnumeric{ L"", false, false }, // empty
test_isnumeric{ L" ", false, false }, // empty
test_isnumeric{ L"-", false, true },
test_isnumeric{ L".", false, true },
test_isnumeric{ L"+", false, true },
test_isnumeric{ L"A1,1", false, true },
test_isnumeric{ L"1,1", false, true },
test_isnumeric{ L"+A11", false, true },
test_isnumeric{ L"A11", false, true },
test_isnumeric{ L"11A", false, true },
test_isnumeric{ L"11A", false, true },
test_isnumeric{ L" 1 2 ", false, true },
test_isnumeric{ L"-999.1 2", false, true },
test_isnumeric{ L"999.1 2", false, true },
test_isnumeric{ L"", false, true }, // empty
test_isnumeric{ L" ", false, true } // empty
));
| FFMG/myoddweb.piger | myoddtest/string/teststring_isnumeric.cpp | C++ | gpl-2.0 | 6,066 |
# Copyright 1999 by Jeffrey Chang. All rights reserved.
# Copyright 2000 by Jeffrey Chang. All rights reserved.
# Revisions Copyright 2007 by Peter Cock. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Module for working with Prosite files from ExPASy (DEPRECATED).
Most of the functionality in this module has moved to Bio.ExPASy.Prosite;
please see
Bio.ExPASy.Prosite.read To read a Prosite file containing one entry.
Bio.ExPASy.Prosite.parse Iterates over entries in a Prosite file.
Bio.ExPASy.Prosite.Record Holds Prosite data.
For
scan_sequence_expasy Scan a sequence for occurrences of Prosite patterns.
_extract_pattern_hits Extract Prosite patterns from a web page.
PatternHit Holds data from a hit against a Prosite pattern.
please see the new module Bio.ExPASy.ScanProsite.
The other functions and classes in Bio.Prosite (including
Bio.Prosite.index_file and Bio.Prosite.Dictionary) are considered deprecated,
and were not moved to Bio.ExPASy.Prosite. If you use this functionality,
please contact the Biopython developers at biopython-dev@biopython.org to
avoid permanent removal of this module from Biopython.
This module provides code to work with the prosite dat file from
Prosite.
http://www.expasy.ch/prosite/
Tested with:
Release 15.0, July 1998
Release 16.0, July 1999
Release 17.0, Dec 2001
Release 19.0, Mar 2006
Functions:
parse Iterates over entries in a Prosite file.
scan_sequence_expasy Scan a sequence for occurrences of Prosite patterns.
index_file Index a Prosite file for a Dictionary.
_extract_record Extract Prosite data from a web page.
_extract_pattern_hits Extract Prosite patterns from a web page.
Classes:
Record Holds Prosite data.
PatternHit Holds data from a hit against a Prosite pattern.
Dictionary Accesses a Prosite file using a dictionary interface.
RecordParser Parses a Prosite record into a Record object.
_Scanner Scans Prosite-formatted data.
_RecordConsumer Consumes Prosite data to a Record object.
"""
import warnings
import Bio
warnings.warn("Bio.Prosite is deprecated, and will be removed in a"\
" future release of Biopython. Most of the functionality "
" is now provided by Bio.ExPASy.Prosite. If you want to "
" continue to use Bio.Prosite, please get in contact "
" via the mailing lists to avoid its permanent removal from"\
" Biopython.", Bio.BiopythonDeprecationWarning)
from types import *
import re
import sgmllib
from Bio import File
from Bio import Index
from Bio.ParserSupport import *
# There is probably a cleaner way to write the read/parse functions
# if we don't use the "parser = RecordParser(); parser.parse(handle)"
# approach. Leaving that for the next revision of Bio.Prosite.
def parse(handle):
import cStringIO
parser = RecordParser()
text = ""
for line in handle:
text += line
if line[:2]=='//':
handle = cStringIO.StringIO(text)
record = parser.parse(handle)
text = ""
if not record: # Then this was the copyright notice
continue
yield record
def read(handle):
parser = RecordParser()
try:
record = parser.parse(handle)
except ValueError, error:
if error.message=="There doesn't appear to be a record":
raise ValueError("No Prosite record found")
else:
raise error
# We should have reached the end of the record by now
remainder = handle.read()
if remainder:
raise ValueError("More than one Prosite record found")
return record
class Record:
"""Holds information from a Prosite record.
Members:
name ID of the record. e.g. ADH_ZINC
type Type of entry. e.g. PATTERN, MATRIX, or RULE
accession e.g. PS00387
created Date the entry was created. (MMM-YYYY)
data_update Date the 'primary' data was last updated.
info_update Date data other than 'primary' data was last updated.
pdoc ID of the PROSITE DOCumentation.
description Free-format description.
pattern The PROSITE pattern. See docs.
matrix List of strings that describes a matrix entry.
rules List of rule definitions (from RU lines). (strings)
prorules List of prorules (from PR lines). (strings)
NUMERICAL RESULTS
nr_sp_release SwissProt release.
nr_sp_seqs Number of seqs in that release of Swiss-Prot. (int)
nr_total Number of hits in Swiss-Prot. tuple of (hits, seqs)
nr_positive True positives. tuple of (hits, seqs)
nr_unknown Could be positives. tuple of (hits, seqs)
nr_false_pos False positives. tuple of (hits, seqs)
nr_false_neg False negatives. (int)
nr_partial False negatives, because they are fragments. (int)
COMMENTS
cc_taxo_range Taxonomic range. See docs for format
cc_max_repeat Maximum number of repetitions in a protein
cc_site Interesting site. list of tuples (pattern pos, desc.)
cc_skip_flag Can this entry be ignored?
cc_matrix_type
cc_scaling_db
cc_author
cc_ft_key
cc_ft_desc
cc_version version number (introduced in release 19.0)
DATA BANK REFERENCES - The following are all
lists of tuples (swiss-prot accession,
swiss-prot name)
dr_positive
dr_false_neg
dr_false_pos
dr_potential Potential hits, but fingerprint region not yet available.
dr_unknown Could possibly belong
pdb_structs List of PDB entries.
"""
def __init__(self):
self.name = ''
self.type = ''
self.accession = ''
self.created = ''
self.data_update = ''
self.info_update = ''
self.pdoc = ''
self.description = ''
self.pattern = ''
self.matrix = []
self.rules = []
self.prorules = []
self.postprocessing = []
self.nr_sp_release = ''
self.nr_sp_seqs = ''
self.nr_total = (None, None)
self.nr_positive = (None, None)
self.nr_unknown = (None, None)
self.nr_false_pos = (None, None)
self.nr_false_neg = None
self.nr_partial = None
self.cc_taxo_range = ''
self.cc_max_repeat = ''
self.cc_site = []
self.cc_skip_flag = ''
self.dr_positive = []
self.dr_false_neg = []
self.dr_false_pos = []
self.dr_potential = []
self.dr_unknown = []
self.pdb_structs = []
class PatternHit:
"""Holds information from a hit against a Prosite pattern.
Members:
name ID of the record. e.g. ADH_ZINC
accession e.g. PS00387
pdoc ID of the PROSITE DOCumentation.
description Free-format description.
matches List of tuples (start, end, sequence) where
start and end are indexes of the match, and sequence is
the sequence matched.
"""
def __init__(self):
self.name = None
self.accession = None
self.pdoc = None
self.description = None
self.matches = []
def __str__(self):
lines = []
lines.append("%s %s %s" % (self.accession, self.pdoc, self.name))
lines.append(self.description)
lines.append('')
if len(self.matches) > 1:
lines.append("Number of matches: %s" % len(self.matches))
for i in range(len(self.matches)):
start, end, seq = self.matches[i]
range_str = "%d-%d" % (start, end)
if len(self.matches) > 1:
lines.append("%7d %10s %s" % (i+1, range_str, seq))
else:
lines.append("%7s %10s %s" % (' ', range_str, seq))
return "\n".join(lines)
class Dictionary:
"""Accesses a Prosite file using a dictionary interface.
"""
__filename_key = '__filename'
def __init__(self, indexname, parser=None):
"""__init__(self, indexname, parser=None)
Open a Prosite Dictionary. indexname is the name of the
index for the dictionary. The index should have been created
using the index_file function. parser is an optional Parser
object to change the results into another form. If set to None,
then the raw contents of the file will be returned.
"""
self._index = Index.Index(indexname)
self._handle = open(self._index[Dictionary.__filename_key])
self._parser = parser
def __len__(self):
return len(self._index)
def __getitem__(self, key):
start, len = self._index[key]
self._handle.seek(start)
data = self._handle.read(len)
if self._parser is not None:
return self._parser.parse(File.StringHandle(data))
return data
def __getattr__(self, name):
return getattr(self._index, name)
class RecordParser(AbstractParser):
"""Parses Prosite data into a Record object.
"""
def __init__(self):
self._scanner = _Scanner()
self._consumer = _RecordConsumer()
def parse(self, handle):
self._scanner.feed(handle, self._consumer)
return self._consumer.data
class _Scanner:
"""Scans Prosite-formatted data.
Tested with:
Release 15.0, July 1998
"""
def feed(self, handle, consumer):
"""feed(self, handle, consumer)
Feed in Prosite data for scanning. handle is a file-like
object that contains prosite data. consumer is a
Consumer object that will receive events as the report is scanned.
"""
if isinstance(handle, File.UndoHandle):
uhandle = handle
else:
uhandle = File.UndoHandle(handle)
consumer.finished = False
while not consumer.finished:
line = uhandle.peekline()
if not line:
break
elif is_blank_line(line):
# Skip blank lines between records
uhandle.readline()
continue
elif line[:2] == 'ID':
self._scan_record(uhandle, consumer)
elif line[:2] == 'CC':
self._scan_copyrights(uhandle, consumer)
else:
raise ValueError("There doesn't appear to be a record")
def _scan_copyrights(self, uhandle, consumer):
consumer.start_copyrights()
self._scan_line('CC', uhandle, consumer.copyright, any_number=1)
self._scan_terminator(uhandle, consumer)
consumer.end_copyrights()
def _scan_record(self, uhandle, consumer):
consumer.start_record()
for fn in self._scan_fns:
fn(self, uhandle, consumer)
# In Release 15.0, C_TYPE_LECTIN_1 has the DO line before
# the 3D lines, instead of the other way around.
# Thus, I'll give the 3D lines another chance after the DO lines
# are finished.
if fn is self._scan_do.im_func:
self._scan_3d(uhandle, consumer)
consumer.end_record()
def _scan_line(self, line_type, uhandle, event_fn,
exactly_one=None, one_or_more=None, any_number=None,
up_to_one=None):
# Callers must set exactly one of exactly_one, one_or_more, or
# any_number to a true value. I do not explicitly check to
# make sure this function is called correctly.
# This does not guarantee any parameter safety, but I
# like the readability. The other strategy I tried was have
# parameters min_lines, max_lines.
if exactly_one or one_or_more:
read_and_call(uhandle, event_fn, start=line_type)
if one_or_more or any_number:
while 1:
if not attempt_read_and_call(uhandle, event_fn,
start=line_type):
break
if up_to_one:
attempt_read_and_call(uhandle, event_fn, start=line_type)
def _scan_id(self, uhandle, consumer):
self._scan_line('ID', uhandle, consumer.identification, exactly_one=1)
def _scan_ac(self, uhandle, consumer):
self._scan_line('AC', uhandle, consumer.accession, exactly_one=1)
def _scan_dt(self, uhandle, consumer):
self._scan_line('DT', uhandle, consumer.date, exactly_one=1)
def _scan_de(self, uhandle, consumer):
self._scan_line('DE', uhandle, consumer.description, exactly_one=1)
def _scan_pa(self, uhandle, consumer):
self._scan_line('PA', uhandle, consumer.pattern, any_number=1)
def _scan_ma(self, uhandle, consumer):
self._scan_line('MA', uhandle, consumer.matrix, any_number=1)
## # ZN2_CY6_FUNGAL_2, DNAJ_2 in Release 15
## # contain a CC line buried within an 'MA' line. Need to check
## # for that.
## while 1:
## if not attempt_read_and_call(uhandle, consumer.matrix, start='MA'):
## line1 = uhandle.readline()
## line2 = uhandle.readline()
## uhandle.saveline(line2)
## uhandle.saveline(line1)
## if line1[:2] == 'CC' and line2[:2] == 'MA':
## read_and_call(uhandle, consumer.comment, start='CC')
## else:
## break
def _scan_pp(self, uhandle, consumer):
#New PP line, PostProcessing, just after the MA line
self._scan_line('PP', uhandle, consumer.postprocessing, any_number=1)
def _scan_ru(self, uhandle, consumer):
self._scan_line('RU', uhandle, consumer.rule, any_number=1)
def _scan_nr(self, uhandle, consumer):
self._scan_line('NR', uhandle, consumer.numerical_results,
any_number=1)
def _scan_cc(self, uhandle, consumer):
self._scan_line('CC', uhandle, consumer.comment, any_number=1)
def _scan_dr(self, uhandle, consumer):
self._scan_line('DR', uhandle, consumer.database_reference,
any_number=1)
def _scan_3d(self, uhandle, consumer):
self._scan_line('3D', uhandle, consumer.pdb_reference,
any_number=1)
def _scan_pr(self, uhandle, consumer):
#New PR line, ProRule, between 3D and DO lines
self._scan_line('PR', uhandle, consumer.prorule, any_number=1)
def _scan_do(self, uhandle, consumer):
self._scan_line('DO', uhandle, consumer.documentation, exactly_one=1)
def _scan_terminator(self, uhandle, consumer):
self._scan_line('//', uhandle, consumer.terminator, exactly_one=1)
#This is a list of scan functions in the order expected in the file file.
#The function definitions define how many times each line type is exected
#(or if optional):
_scan_fns = [
_scan_id,
_scan_ac,
_scan_dt,
_scan_de,
_scan_pa,
_scan_ma,
_scan_pp,
_scan_ru,
_scan_nr,
_scan_cc,
# This is a really dirty hack, and should be fixed properly at
# some point. ZN2_CY6_FUNGAL_2, DNAJ_2 in Rel 15 and PS50309
# in Rel 17 have lines out of order. Thus, I have to rescan
# these, which decreases performance.
_scan_ma,
_scan_nr,
_scan_cc,
_scan_dr,
_scan_3d,
_scan_pr,
_scan_do,
_scan_terminator
]
class _RecordConsumer(AbstractConsumer):
"""Consumer that converts a Prosite record to a Record object.
Members:
data Record with Prosite data.
"""
def __init__(self):
self.data = None
def start_record(self):
self.data = Record()
def end_record(self):
self._clean_record(self.data)
def identification(self, line):
cols = line.split()
if len(cols) != 3:
raise ValueError("I don't understand identification line\n%s" \
% line)
self.data.name = self._chomp(cols[1]) # don't want ';'
self.data.type = self._chomp(cols[2]) # don't want '.'
def accession(self, line):
cols = line.split()
if len(cols) != 2:
raise ValueError("I don't understand accession line\n%s" % line)
self.data.accession = self._chomp(cols[1])
def date(self, line):
uprline = line.upper()
cols = uprline.split()
# Release 15.0 contains both 'INFO UPDATE' and 'INF UPDATE'
if cols[2] != '(CREATED);' or \
cols[4] != '(DATA' or cols[5] != 'UPDATE);' or \
cols[7][:4] != '(INF' or cols[8] != 'UPDATE).':
raise ValueError("I don't understand date line\n%s" % line)
self.data.created = cols[1]
self.data.data_update = cols[3]
self.data.info_update = cols[6]
def description(self, line):
self.data.description = self._clean(line)
def pattern(self, line):
self.data.pattern = self.data.pattern + self._clean(line)
def matrix(self, line):
self.data.matrix.append(self._clean(line))
def postprocessing(self, line):
postprocessing = self._clean(line).split(";")
self.data.postprocessing.extend(postprocessing)
def rule(self, line):
self.data.rules.append(self._clean(line))
def numerical_results(self, line):
cols = self._clean(line).split(";")
for col in cols:
if not col:
continue
qual, data = [word.lstrip() for word in col.split("=")]
if qual == '/RELEASE':
release, seqs = data.split(",")
self.data.nr_sp_release = release
self.data.nr_sp_seqs = int(seqs)
elif qual == '/FALSE_NEG':
self.data.nr_false_neg = int(data)
elif qual == '/PARTIAL':
self.data.nr_partial = int(data)
elif qual in ['/TOTAL', '/POSITIVE', '/UNKNOWN', '/FALSE_POS']:
m = re.match(r'(\d+)\((\d+)\)', data)
if not m:
raise Exception("Broken data %s in comment line\n%s" \
% (repr(data), line))
hits = tuple(map(int, m.groups()))
if(qual == "/TOTAL"):
self.data.nr_total = hits
elif(qual == "/POSITIVE"):
self.data.nr_positive = hits
elif(qual == "/UNKNOWN"):
self.data.nr_unknown = hits
elif(qual == "/FALSE_POS"):
self.data.nr_false_pos = hits
else:
raise ValueError("Unknown qual %s in comment line\n%s" \
% (repr(qual), line))
def comment(self, line):
#Expect CC lines like this:
#CC /TAXO-RANGE=??EPV; /MAX-REPEAT=2;
#Can (normally) split on ";" and then on "="
cols = self._clean(line).split(";")
for col in cols:
if not col or col[:17] == 'Automatic scaling':
# DNAJ_2 in Release 15 has a non-standard comment line:
# CC Automatic scaling using reversed database
# Throw it away. (Should I keep it?)
continue
if col.count("=") == 0:
#Missing qualifier! Can we recover gracefully?
#For example, from Bug 2403, in PS50293 have:
#CC /AUTHOR=K_Hofmann; N_Hulo
continue
qual, data = [word.lstrip() for word in col.split("=")]
if qual == '/TAXO-RANGE':
self.data.cc_taxo_range = data
elif qual == '/MAX-REPEAT':
self.data.cc_max_repeat = data
elif qual == '/SITE':
pos, desc = data.split(",")
self.data.cc_site.append((int(pos), desc))
elif qual == '/SKIP-FLAG':
self.data.cc_skip_flag = data
elif qual == '/MATRIX_TYPE':
self.data.cc_matrix_type = data
elif qual == '/SCALING_DB':
self.data.cc_scaling_db = data
elif qual == '/AUTHOR':
self.data.cc_author = data
elif qual == '/FT_KEY':
self.data.cc_ft_key = data
elif qual == '/FT_DESC':
self.data.cc_ft_desc = data
elif qual == '/VERSION':
self.data.cc_version = data
else:
raise ValueError("Unknown qual %s in comment line\n%s" \
% (repr(qual), line))
def database_reference(self, line):
refs = self._clean(line).split(";")
for ref in refs:
if not ref:
continue
acc, name, type = [word.strip() for word in ref.split(",")]
if type == 'T':
self.data.dr_positive.append((acc, name))
elif type == 'F':
self.data.dr_false_pos.append((acc, name))
elif type == 'N':
self.data.dr_false_neg.append((acc, name))
elif type == 'P':
self.data.dr_potential.append((acc, name))
elif type == '?':
self.data.dr_unknown.append((acc, name))
else:
raise ValueError("I don't understand type flag %s" % type)
def pdb_reference(self, line):
cols = line.split()
for id in cols[1:]: # get all but the '3D' col
self.data.pdb_structs.append(self._chomp(id))
def prorule(self, line):
#Assume that each PR line can contain multiple ";" separated rules
rules = self._clean(line).split(";")
self.data.prorules.extend(rules)
def documentation(self, line):
self.data.pdoc = self._chomp(self._clean(line))
def terminator(self, line):
self.finished = True
def _chomp(self, word, to_chomp='.,;'):
# Remove the punctuation at the end of a word.
if word[-1] in to_chomp:
return word[:-1]
return word
def _clean(self, line, rstrip=1):
# Clean up a line.
if rstrip:
return line[5:].rstrip()
return line[5:]
def scan_sequence_expasy(seq=None, id=None, exclude_frequent=None):
"""scan_sequence_expasy(seq=None, id=None, exclude_frequent=None) ->
list of PatternHit's
Search a sequence for occurrences of Prosite patterns. You can
specify either a sequence in seq or a SwissProt/trEMBL ID or accession
in id. Only one of those should be given. If exclude_frequent
is true, then the patterns with the high probability of occurring
will be excluded.
"""
from Bio import ExPASy
if (seq and id) or not (seq or id):
raise ValueError("Please specify either a sequence or an id")
handle = ExPASy.scanprosite1(seq, id, exclude_frequent)
return _extract_pattern_hits(handle)
def _extract_pattern_hits(handle):
"""_extract_pattern_hits(handle) -> list of PatternHit's
Extract hits from a web page. Raises a ValueError if there
was an error in the query.
"""
class parser(sgmllib.SGMLParser):
def __init__(self):
sgmllib.SGMLParser.__init__(self)
self.hits = []
self.broken_message = 'Some error occurred'
self._in_pre = 0
self._current_hit = None
self._last_found = None # Save state of parsing
def handle_data(self, data):
if data.find('try again') >= 0:
self.broken_message = data
return
elif data == 'illegal':
self.broken_message = 'Sequence contains illegal characters'
return
if not self._in_pre:
return
elif not data.strip():
return
if self._last_found is None and data[:4] == 'PDOC':
self._current_hit.pdoc = data
self._last_found = 'pdoc'
elif self._last_found == 'pdoc':
if data[:2] != 'PS':
raise ValueError("Expected accession but got:\n%s" % data)
self._current_hit.accession = data
self._last_found = 'accession'
elif self._last_found == 'accession':
self._current_hit.name = data
self._last_found = 'name'
elif self._last_found == 'name':
self._current_hit.description = data
self._last_found = 'description'
elif self._last_found == 'description':
m = re.findall(r'(\d+)-(\d+) (\w+)', data)
for start, end, seq in m:
self._current_hit.matches.append(
(int(start), int(end), seq))
def do_hr(self, attrs):
# <HR> inside a <PRE> section means a new hit.
if self._in_pre:
self._current_hit = PatternHit()
self.hits.append(self._current_hit)
self._last_found = None
def start_pre(self, attrs):
self._in_pre = 1
self.broken_message = None # Probably not broken
def end_pre(self):
self._in_pre = 0
p = parser()
p.feed(handle.read())
if p.broken_message:
raise ValueError(p.broken_message)
return p.hits
def index_file(filename, indexname, rec2key=None):
"""index_file(filename, indexname, rec2key=None)
Index a Prosite file. filename is the name of the file.
indexname is the name of the dictionary. rec2key is an
optional callback that takes a Record and generates a unique key
(e.g. the accession number) for the record. If not specified,
the id name will be used.
"""
import os
if not os.path.exists(filename):
raise ValueError("%s does not exist" % filename)
index = Index.Index(indexname, truncate=1)
index[Dictionary._Dictionary__filename_key] = filename
handle = open(filename)
records = parse(handle)
end = 0L
for record in records:
start = end
end = handle.tell()
length = end - start
if rec2key is not None:
key = rec2key(record)
else:
key = record.name
if not key:
raise KeyError("empty key was produced")
elif key in index:
raise KeyError("duplicate key %s found" % key)
index[key] = start, length
| BlogomaticProject/Blogomatic | opt/blog-o-matic/usr/lib/python/Bio/Prosite/__init__.py | Python | gpl-2.0 | 27,006 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.orionline.entidade;
/**
*
* @author ronald
*/
public class BarrasRelacionadas extends ProdutoAUX{
}
| ronaldsantos63/ConversorOrionline | src/br/com/orionline/entidade/BarrasRelacionadas.java | Java | gpl-2.0 | 323 |
// taikaDlg.cpp : implementation file
//
#include "stdafx.h"
#include "taika.h"
#include "taikaDlg.h"
#include "Props.h"
#include "DlgVarmuuskopioi.h"
#include "DlgSiivoaTietokanta.h"
#include "DlgAsetukset.h"
#include "DlgLuoUusiTietokanta.h"
#include "DlgAbout.h"
#include "StringHelper_luokka.h"
#include <afxpriv.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CTaikaDlg dialog
CTaikaDlg::CTaikaDlg(CWnd* pParent /*=NULL*/)
: CDialog(CTaikaDlg::IDD, pParent), m_pMenu(NULL)
{
//{{AFX_DATA_INIT(CTaikaDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CTaikaDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CTaikaDlg)
DDX_Control(pDX, IDC_TABMAIN, m_tabMain);
DDX_Control(pDX, IDC_SHEET_PLACEHOLDER, m_picPlaceHolder);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CTaikaDlg, CDialog)
//{{AFX_MSG_MAP(CTaikaDlg)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_CLOSE()
ON_WM_DESTROY()
ON_COMMAND(IDM_AVAA_RAPORTTI, OnAvaaRaportti)
ON_COMMAND(IDM_TALLETA_RAPORTTI, OnTalletaRaportti)
ON_COMMAND(IDM_VARMUUSKOPIOI_TIETOKANTA, OnVarmuuskopioiTietokanta)
ON_COMMAND(IDM_VAIHDA_TIETOKANTA, OnVaihdaTietokanta)
ON_COMMAND(IDM_TALLETA_LISTAT, OnTalletaListat)
ON_COMMAND(IDM_AVAA_LISTAT, OnAvaaListat)
ON_COMMAND(IDM_AVAA_RAPORTTI_TM, OnAvaaRaporttiTm)
ON_COMMAND(IDM_TALLETA_RAPORTTI_TM, OnTalletaRaporttiTm)
ON_COMMAND(IDM_SIIVOA_TIETOKANTA, OnSiivoaTietokanta)
ON_COMMAND(IDM_EMAIL, OnEmail)
ON_COMMAND(IDK_VALITSEKAIKKI, OnValitsekaikki)
ON_COMMAND(IDK_AVAA, OnAvaa)
ON_COMMAND(IDK_TALLETA, OnTalleta)
ON_COMMAND(IDK_ETSI, OnEtsi)
ON_COMMAND(IDK_ETSI_F3, OnEtsiF3)
ON_COMMAND(IDK_UUSI, OnUusi)
ON_NOTIFY(TCN_SELCHANGE, IDC_TABMAIN, OnSelchangeTabmain)
ON_WM_SIZE()
ON_WM_SIZING()
ON_COMMAND(IDM_ASETUKSET, OnAsetukset)
ON_COMMAND(IDM_LUO_UUSI_TIETOKANTA, OnLuoUusiTietokanta)
ON_COMMAND(IDK_IMPORT, OnImport)
ON_COMMAND(IDM_TUO_LASKUTUSOHJELMASTA, OnTuoLaskutusohjelmasta)
ON_COMMAND(IDK_POISTA_X, OnPoista)
ON_COMMAND(IDK_PAIVITA_V5, OnPaivitaV5)
ON_COMMAND(IDK_EMAIL, OnEmail)
ON_COMMAND(IDM_ABOUT, OnAbout)
//}}AFX_MSG_MAP
ON_WM_INITMENUPOPUP()
ON_MESSAGE(WM_USER_NEW_REPORT, OnMsgUusiRaportti)
ON_MESSAGE(WM_IDLEUPDATECMDUI, OnIdleUpdateCmdUI)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTaikaDlg message handlers
LRESULT CTaikaDlg::OnIdleUpdateCmdUI(WPARAM wParam, LPARAM lparam)
{
return 0L;
}
BOOL CTaikaDlg::OnInitDialog()
{
int ret;
RECT trect, crect;
TCITEM tci;
CString cs;
DbSqlite db;
Parse parse;
CRect rcSheet;
string use_db;
CDialog::OnInitDialog();
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// Päällimmäisin dialogi - aluksi raportit
m_mainShowMode = SHOW_RAPORTIT;
// Kansiot - luo kansiot, jos niitä ei löydy
luoKansiot(Props::e().m_app_path);
// Asetukset - luo perusasetukset, jos ei löydy
if(Props::i().get(OPTIONS_AIKAJARJESTYS_R) == "")
{
use_db = Props::e().m_app_path + DEFAULT_DB_NAME;
Props::i().set(OPTIONS_DB_PATH, use_db);
Props::i().set(OPTIONS_DB_NAME, DEFAULT_DB_NAME);
Props::i().set(OPTIONS_AUTOPARSE, "TRUE");
Props::i().set(OPTIONS_LASKUTUSOHJELMA, LAS_NONE);
Props::i().set(OPTIONS_LASKUTUSOHJELMA_POLKU, "c:\\");
Props::i().set(OPTIONS_LASKUTUSOHJELMA_KOKO_POLKU, "");
Props::i().set(OPTIONS_KAYNTIKERTAVELOITUS, C_TRUE);
Props::i().set(OPTIONS_HINNAT, HINNAT_LASKOHJ);
Props::i().set(OPTIONS_LASKUTUSTILA, LTILA_LASKUTTAMATTOMAT);
Props::i().set(OPTIONS_LASKUNMAKSUAIKA, "30");
Props::i().set(OPTIONS_YHDISTATAPAHTUMAT, C_TRUE);
Props::i().set(OPTIONS_OPENPATH, (LPCSTR)Props::e().m_app_path);
Props::i().set(OPTIONS_SAVEPATH, (LPCSTR)Props::e().m_app_path);
Props::i().set(OPTIONS_AJAT, StringHelper::itoa(TIME_MINUTES, 10));
Props::i().set(OPTIONS_ALKAEN_R, DATE_VANHIN_TYO);
Props::i().set(OPTIONS_PAATTYEN_R, DATE_UUSIN_TYO);
Props::i().set(OPTIONS_ALKAEN_VIIMEISIN_R, "1.1.2008");
Props::i().set(OPTIONS_PAATTYEN_VIIMEISIN_R, "1.1.2008");
Props::i().set(OPTIONS_ALKAEN_T, DATE_VANHIN_TYO);
Props::i().set(OPTIONS_PAATTYEN_T, DATE_UUSIN_TYO);
Props::i().set(OPTIONS_ALKAEN_VIIMEISIN_T, "1.1.2008");
Props::i().set(OPTIONS_PAATTYEN_VIIMEISIN_T, "1.1.2008");
Props::i().set(OPTIONS_AIKAJARJESTYS_R, DESCENT_S);
Props::i().set(OPTIONS_AIKAJARJESTYS_T, DESCENT_S);
Props::i().set(OPTIONS_KMKERROIN, "0.43");
use_db = Props::e().m_app_path + "varmuuskopiot\\";
Props::i().set(OPTIONS_DB_BACKUP_PATH, use_db);
Props::i().set(OPTIONS_EM_RECIPIENTS, "");
Props::i().set(OPTIONS_EM_FROM, "");
Props::i().set(OPTIONS_EM_SMTP_SERVER, "");
Props::i().set(OPTIONS_EM_SMTP_PORT, "25");
Props::i().set(OPTIONS_PRNT_ASNIMI, PRNT_ASNIMINRO);
Props::i().set(OPTIONS_PRNT_ASALOITUSPVM, PRNT_PVM_AIKA);
Props::i().set(OPTIONS_PRNT_ASLOPETUSPVM, PRNT_PVM_AIKA);
Props::i().set(OPTIONS_PRNT_ASTYOAIKA, PRNT_TYOAIKA_MIN);
Props::i().set(OPTIONS_PRNT_ASTYOTYYPIT, PRNT_TYOTYYPIT);
Props::i().set(OPTIONS_PRNT_TTALOITUSPVM, PRNT_PVM_AIKA);
Props::i().set(OPTIONS_PRNT_TTLOPETUSPVM, PRNT_PVM_AIKA);
Props::i().set(OPTIONS_PRNT_TTTYOAIKA, PRNT_TYOAIKA_MIN);
Props::i().set(OPTIONS_PRNT_TTTYOTYYPIT, PRNT_TYOTYYPIT);
Props::i().set(OPTIONS_PRNT_TMPAIVAYKSET, PRNT_PVM_AIKA_MOLEMMAT);
Props::i().set(OPTIONS_PRNT_TMMATKA, PRNT_MATKAT_TARKOITUS);
Props::i().set(OPTIONS_PRNT_TMLUKEMAT, PRNT_LUKEMAT);
Props::i().set(OPTIONS_PRNT_TMYKSAJOA, PRNT_YKSAJOA);
Props::i().set(OPTIONS_PRNT_TMTYOAJOA, PRNT_TYOAJOA);
Props::i().set(OPTIONS_PRNT_SIVUTUS, C_TRUE);
Props::i().set(OPTIONS_PRNT_YLATUNNISTE_TEXT, "");
Props::i().set(OPTIONS_PRNT_ALATUNNISTE_TEXT, "");
Props::i().set(OPTIONS_PRNT_YLATUNNISTE, C_TRUE);
Props::i().set(OPTIONS_PRNT_ALATUNNISTE, C_TRUE);
Props::i().set(OPTIONS_PRNT_YLAPAIVAYS, C_TRUE);
Props::i().set(OPTIONS_PRNT_FONTINKOKO, FONTSIZE_8);
Props::i().set(OPTIONS_PRNT_FONTINNIMI, "Arial");
Props::i().set(OPTIONS_PRNT_YHTEENVETO, C_TRUE);
Props::i().set(OPTIONS_PRNT_KMKORVAUS, C_TRUE);
Props::i().set(OPTIONS_PRNT_YHDISTATAPAHTUMAT, C_TRUE);
Props::i().set(OPTIONS_EM_SMTP_USE_AUTH, C_FALSE);
Props::i().set(OPTIONS_EM_SMTP_RMBR_UN, C_FALSE);
Props::i().set(OPTIONS_EM_SMTP_USERNAME, "");
Props::i().set(OPTIONS_LSTHEADER_RATA, "");
Props::i().set(OPTIONS_LSTHEADER_RAMY, "");
Props::i().set(OPTIONS_LSTHEADER_LIAR, "");
Props::i().set(OPTIONS_LSTHEADER_LIAS, "");
Props::i().set(OPTIONS_LSTHEADER_LILA, "");
Props::i().set(OPTIONS_LSTHEADER_LITT, "");
Props::i().set(OPTIONS_LSTHEADER_LITR, "");
Props::i().set(OPTIONS_LSTHEADER_LITU, "");
Props::i().set(OPTIONS_LSTHEADER_TYTY, "");
}
// Otetaan tietokannan polku asetuksista, Tarkistetaan tietokanta (luodaan, jos ei ole olemassa)
Props::e().m_db_path = Props::i().get(OPTIONS_DB_PATH).c_str();
if((ret = db.check()) != RETURN_OK)
Props::e().m_db_path = ""; // Virheen sattuessa, ei tietokantaa!!! //EndDialog(IDCANCEL);
// Tarkistetaan onko saapuneet kansiossa uusia raportteja
if(ret == RETURN_OK) parse.parseSaapuneet(PARSE_SAAPUNEET);
// Dialogin otsikko resurssista ja tietokannan nimi asetuksista
usedDB();
// Menu paikoilleen (aluksi IDR_RAPORTIT_MENU, asetetaan eri dilogeissa vastaamaan paremmin niiden toimintoja)
m_pMenu = pageRaportit.createMenu();
this->SetMenu(m_pMenu);
AfxGetMainWnd()->DrawMenuBar();
// Koko ruutu
ShowWindow(SW_MAXIMIZE);
// Alustetaan tab-kontolli
GetClientRect(&crect);
m_tabMain.SetWindowPos(NULL, 0, 0, crect.right, crect.bottom, SWP_NOMOVE|SWP_NOZORDER);
tci.mask = TCIF_IMAGE|TCIF_TEXT; tci.iImage = 0; tci.pszText = (LPSTR)(LPCSTR)Props::i().lang("TAIKADLG_1");
m_tabMain.InsertItem(0, &tci);
tci.mask = TCIF_IMAGE|TCIF_TEXT; tci.iImage = 0; tci.pszText = (LPSTR)(LPCSTR)Props::i().lang("TAIKADLG_2");
m_tabMain.InsertItem(1, &tci);
tci.mask = TCIF_IMAGE|TCIF_TEXT; tci.iImage = 0; tci.pszText = (LPSTR)(LPCSTR)Props::i().lang("TAIKADLG_3");
m_tabMain.InsertItem(2, &tci);
// Placeholder ylänurkkaan
m_tabMain.GetItemRect(0, &trect); // tabin headerin koko
m_tabMain.GetClientRect(&crect); // tabin koko
m_picPlaceHolder.SetWindowPos(NULL, PAGE_LEFT, PAGE_TOP + trect.bottom, crect.right - PAGE_LEFT - PAGE_RIGHT, crect.bottom - trect.bottom - PAGE_TOP - PAGE_BOTTOM, SWP_NOZORDER);
// Luo dialogit
pageRaportit.CRHCreateGenericChildDialog(this, IDC_SHEET_PLACEHOLDER, 0, NULL);
pageListat.CRHCreateGenericChildDialog(this, IDC_SHEET_PLACEHOLDER, 0, NULL);
pageTyomatkat.CRHCreateGenericChildDialog(this, IDC_SHEET_PLACEHOLDER, 0, NULL);
// Ja uudestaan menu - dialogien luonti voi sotkea näytettävän menun
if(m_pMenu) m_pMenu->DestroyMenu();
m_pMenu = pageRaportit.createMenu();
this->SetMenu(m_pMenu);
AfxGetMainWnd()->DrawMenuBar();
return TRUE; // return TRUE unless you set the focus to a control
}
void CTaikaDlg::OnClose()
{
CDialog::OnClose();
}
void CTaikaDlg::OnDestroy()
{
CDialog::OnDestroy();
if(m_pMenu)
m_pMenu->DestroyMenu(); // Tuhoa menu
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CTaikaDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
HCURSOR CTaikaDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
BOOL CTaikaDlg::PreTranslateMessage(MSG* pMsg)
{
if(pMsg->message == WM_KEYDOWN) // Estetään RETURNIN painaminen dialogissa (dialogi ei sulkeudu vahingossa)
{
if(pMsg->wParam == VK_RETURN) return TRUE;
}
SendMessageToDescendants(WM_KICKIDLE, 0, 0, FALSE, FALSE);
return CDialog::PreTranslateMessage(pMsg);
}
void CTaikaDlg::OnOK()
{}
void CTaikaDlg::OnCancel()
{
CDialog::OnCancel();
}
void CTaikaDlg::OnSize(UINT nType, int cx, int cy)
{
BOOL resize = FALSE;
RECT crect, trect;
int page_width, page_height;
// Varmista, että ikkunat on luotu
if(this->GetSafeHwnd() == 0) return;
if(m_tabMain.GetSafeHwnd() == 0) return;
if(m_picPlaceHolder.GetSafeHwnd() == 0) return;
CDialog::OnSize(nType, cx, cy);
// tab-control ruudun kokoiseksi
GetClientRect(&crect);
m_tabMain.SetWindowPos(NULL, 0, 0, crect.right, crect.bottom, SWP_NOMOVE|SWP_NOZORDER);
// placeholder tabin kokoiseksi
m_tabMain.GetItemRect(0, &trect); // tabin headerin koko
m_tabMain.GetClientRect(&crect); // tabin koko
page_width = crect.right - PAGE_LEFT - PAGE_RIGHT; // sivun koko: w = tabin w - marginaalit, h = tabin h - tabin h - marginaalit
page_height = crect.bottom - trect.bottom - PAGE_TOP - PAGE_BOTTOM;
m_picPlaceHolder.SetWindowPos(NULL, 0, 0, page_width, page_height, SWP_NOMOVE|SWP_NOZORDER);
// Muuta lapsidialogien koot
if(pageRaportit.GetSafeHwnd() != NULL)
pageRaportit.windowSize();
if(pageListat.GetSafeHwnd() != NULL)
pageListat.windowSize();
if(pageTyomatkat.GetSafeHwnd() != NULL)
pageTyomatkat.windowSize();
}
void CTaikaDlg::OnSizing(UINT nSide, LPRECT lpRect)
{
if(lpRect->right - lpRect->left < 890) lpRect->right = lpRect->left + 890;
if(lpRect->bottom - lpRect->top < 500) lpRect->bottom = lpRect->top + 500;
}
// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // //
// Komentojen käsittelijät
// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // //
void CTaikaDlg::OnSelchangeTabmain(NMHDR* pNMHDR, LRESULT* pResult)
{
int sel = m_tabMain.GetCurSel();
if(sel == 0 && m_mainShowMode != SHOW_RAPORTIT)
{
m_mainShowMode = SHOW_RAPORTIT;
pageRaportit.ShowWindow(SW_SHOW);
pageListat.ShowWindow(SW_HIDE);
pageTyomatkat.ShowWindow(SW_HIDE);
pageRaportit.OnSetActive();
}
else if(sel == 1)
{
m_mainShowMode = SHOW_LISTAT;
pageRaportit.ShowWindow(SW_HIDE);
pageListat.ShowWindow(SW_SHOW);
pageTyomatkat.ShowWindow(SW_HIDE);
pageListat.OnSetActive();
}
else if(sel == 2)
{
m_mainShowMode = SHOW_TYOMATKAT;
pageRaportit.ShowWindow(SW_HIDE);
pageListat.ShowWindow(SW_HIDE);
pageTyomatkat.ShowWindow(SW_SHOW);
pageTyomatkat.OnSetActive();
}
*pResult = 0;
}
LRESULT CTaikaDlg::OnMsgUusiRaportti(WPARAM wparam, LPARAM lparam)
{
//int s;
Parse parse;
this->BringWindowToTop();
parse.parseSaapuneet(PARSE_ADD_FILE); // Parsitaan saapuneet lista ja päivitetään näytöt
if(wparam == PARAM_TTI || wparam == PARAM_TTA)
paivitaNaytot(TRUE, TRUE, FALSE, SYNC_ALL);
return 0;
}
void CTaikaDlg::luoKansiot(CString app_path)
{ // Luo kansiot jos niitä ei löydy
WIN32_FIND_DATA fd;
HANDLE hfile = NULL;
CString dirpath, cs;
dirpath = app_path + "saapuneet\\";
if((hfile = FindFirstFile(dirpath, &fd)) != INVALID_HANDLE_VALUE) FindClose(hfile);
else { if(GetLastError() == ERROR_PATH_NOT_FOUND) CreateDirectory(dirpath, NULL); }
dirpath = app_path + "raportit\\";
if((hfile = FindFirstFile(dirpath, &fd)) != INVALID_HANDLE_VALUE) FindClose(hfile);
else { if(GetLastError() == ERROR_PATH_NOT_FOUND) CreateDirectory(dirpath, NULL); }
dirpath = app_path + "varmuuskopiot\\";
if((hfile = FindFirstFile(dirpath, &fd)) != INVALID_HANDLE_VALUE) FindClose(hfile);
else { if(GetLastError() == ERROR_PATH_NOT_FOUND) CreateDirectory(dirpath, NULL); }
}
/////////////////////////////////////////////////////////////////////////////
// Menun itemien disablointi/enablointi logiikka
void CTaikaDlg::OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu)
{
if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible())
setRaporttiMenu(nIndex);
if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible())
setListatMenu(nIndex);
}
void CTaikaDlg::setRaporttiMenu(UINT nIndex)
{
int flags;
CMenu *pMenu = this->GetMenu();
if(nIndex == 0) // Tiedosto-menu
{
// IDM_TALLETA_RAPORTTI
if(pageRaportit.m_lstAsiakkaat.GetSelCount() > 0 || pageRaportit.m_plstRaportit->GetItemCount() > 0) flags = MF_ENABLED;
else flags = MF_DISABLED|MF_GRAYED;
pMenu->EnableMenuItem(IDM_TALLETA_RAPORTTI, flags);
}
}
void CTaikaDlg::setListatMenu(UINT nIndex)
{}
/////////////////////////////////////////////////////////////////////////////
// IDM_RAPORTIT_MENU - Menu itemien viestit
void CTaikaDlg::OnAvaaRaportti()
{
//int s;
Parse parse;
if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) // Avaa .tti-tiedosto
{ if(!parse.avaaTTI(this->GetSafeHwnd())) return; }
paivitaNaytot(TRUE, TRUE, FALSE, SYNC_ALL);
}
void CTaikaDlg::OnTalletaRaportti()
{
Parse parse;
if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) // Talleta valitut ID_WORKUNIT/ID_SALESUNIT-tiedostoon (.tta)
{ parse.talletaTTI(this->GetSafeHwnd(), pageRaportit.getMode()); }
}
void CTaikaDlg::OnEmail()
{
Parse parse;
//if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) pageRaportit.email();
if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) pageListat.email();
}
void CTaikaDlg::OnAbout()
{
CDlgAbout dlga;
dlga.DoModal();
}
/////////////////////////////////////////////////////////////////////////////
// IDM_LISTAT_MENU - Menu itemien viestit
void CTaikaDlg::OnAvaaListat()
{
Parse parse;
if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) // Avaa .tta-tiedosto
{ if(!parse.avaaTTA(this->GetSafeHwnd())) return; }
paivitaNaytot(FALSE, FALSE, FALSE, SYNC_ALL);
}
void CTaikaDlg::OnTalletaListat()
{
Parse parse;
if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) // Talleta listat
{ parse.talletaTTA(this->GetSafeHwnd(), "", 0, 0, 0, 0, MODE_SAVE); }
}
void CTaikaDlg::OnTuoLaskutusohjelmasta()
{
OnImport();
}
/////////////////////////////////////////////////////////////////////////////
// IDM_TYOMATKAT_MENU - Menu itemien viestit
void CTaikaDlg::OnAvaaRaporttiTm()
{
//int s;
Parse parse;
if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible()) // Avaa .tti-tiedosto
{ if(!parse.avaaTTI(this->GetSafeHwnd())) return; }
paivitaNaytot(TRUE, TRUE, FALSE, SYNC_ALL);
}
void CTaikaDlg::OnTalletaRaporttiTm()
{
Parse parse;
vector <ItemData_travel*> id_vect;
// Haetaan GetSaveFileName()-funktiossa valitun tilan mukaan vektoriin talletettavat tiedot
if(m_mainShowMode != SHOW_TYOMATKAT || !pageTyomatkat.IsWindowVisible()) return;
pageTyomatkat.haeItemDataList(&id_vect, MODE_TYONTEKIJANTIEDOT);
if(id_vect.size() > 0)
{
parse.talletaTTI_tyomatkat(this->GetSafeHwnd(), id_vect); // Talletetaan
pageTyomatkat.vapautaItemDataList(&id_vect, MODE_TYONTEKIJANTIEDOT); // Vapautetaan muisti
}
}
/////////////////////////////////////////////////////////////////////////////
// IDM_RAPORTIT_MENU, IDM_LISTAT_MENU, IDM_ASETUKSET - Menu itemien yhteiset viestit
void CTaikaDlg::OnVarmuuskopioiTietokanta()
{
DlgVarmuuskopioi dlg;
if(dlg.DoModal() == IDOK)
paivitaNaytot(TRUE, TRUE, FALSE, SYNC_ALL);
}
void CTaikaDlg::OnVaihdaTietokanta()
{
DWORD e;
CString file;
char buf[128] = {0};
OPENFILENAME ofn;
DlgParseInfo dlg;
char *lpstrFile = NULL, strFileTitle[MAX_PATH];
try
{
file = Props::i().get(OPTIONS_DB_PATH).c_str();
if(!(lpstrFile = new char[MAX_PATH * 100])) throw(0); // Tarpeeksi tilaa useammalle tiedostonimelle
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = this->GetSafeHwnd();
ofn.lpstrFilter = Props::i().langs("TAIKADLG_4", buf, 128);
ofn.lpstrTitle = Props::i().lang("TAIKADLG_5");
ofn.lpstrInitialDir = file;
ofn.lpstrCustomFilter = NULL; ofn.nFilterIndex = 1;
*lpstrFile = NULL; ofn.lpstrFile = lpstrFile; ofn.nMaxFile = MAX_PATH * 100;
ofn.lpstrFileTitle = strFileTitle; ofn.nMaxFileTitle = MAX_PATH;
ofn.Flags = OFN_EXPLORER|OFN_HIDEREADONLY|OFN_LONGNAMES|OFN_PATHMUSTEXIST;
ofn.lpstrDefExt = NULL; ofn.lCustData = NULL;
if(!GetOpenFileName(&ofn)) throw(0);
Props::i().set(OPTIONS_DB_PATH, ofn.lpstrFile); // talleta, mahdollisesti uusi, polku asetuksiin
Props::i().set(OPTIONS_DB_NAME, (char*)(ofn.lpstrFile + ofn.nFileOffset));
Props::e().m_db_path = ofn.lpstrFile;
paivitaNaytot(TRUE, TRUE, TRUE, SYNC_ALL);
}
catch(...)
{
if((e = CommDlgExtendedError()) != ERROR_SUCCESS)
{
file.Format(Props::i().lang("TAIKADLG_6"), e);
MessageBox(file, Props::e().m_app_title, MB_ICONEXCLAMATION|MB_TASKMODAL|MB_TOPMOST|MB_OK);
}
}
if(lpstrFile) delete [] lpstrFile;
}
void CTaikaDlg::OnAsetukset()
{
CDlgAsetukset dlg;
dlg.DoModal();
}
void CTaikaDlg::OnLuoUusiTietokanta()
{
CDlgLuoUusiTietokanta dlg;
if(dlg.DoModal() == IDOK)
paivitaNaytot(TRUE, TRUE, TRUE, SYNC_ALL);
}
void CTaikaDlg::OnSiivoaTietokanta()
{
DlgSiivoaTietokanta dlg;
if(dlg.DoModal() == IDOK)
paivitaNaytot(TRUE, TRUE, FALSE, SYNC_ALL);
}
// Accelerator-näppäimet (kaasutusnäppäimet)
void CTaikaDlg::OnValitsekaikki()
{
if(GetForegroundWindow() != this)
GetForegroundWindow()->PostMessage(WM_USER_SELECTALL);
else
{
if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) pageRaportit.valitseKaikki();
if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) pageListat.valitseKaikki();
if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible()) pageTyomatkat.valitseKaikki();
}
}
void CTaikaDlg::OnAvaa()
{
if(GetForegroundWindow() == this)
{
if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) OnAvaaRaportti();
if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) OnAvaaListat();
if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible()) OnAvaaRaporttiTm();
}
}
void CTaikaDlg::OnTalleta()
{
if(GetForegroundWindow() == this)
{
if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) OnTalletaRaportti();
if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) OnTalletaListat();
if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible()) OnTalletaRaporttiTm();
}
}
void CTaikaDlg::OnEtsi()
{
if(GetForegroundWindow() == this)
{
if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) pageRaportit.etsi(KEY_CTRLF);
if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) pageListat.etsi(KEY_CTRLF);
}
}
void CTaikaDlg::OnEtsiF3()
{
if(GetForegroundWindow() == this)
{
if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) pageRaportit.etsi(KEY_F3);
if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) pageListat.etsi(KEY_F3);
}
}
void CTaikaDlg::OnPoista()
{ poista(); }
BOOL CTaikaDlg::poista()
{
if(GetForegroundWindow() == this)
{
if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) pageRaportit.poistaItems();
if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) pageListat.poista();
if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible()) pageTyomatkat.poistaValitut();
return TRUE;
}
return FALSE;
}
void CTaikaDlg::OnUusi()
{
if(GetForegroundWindow() == this)
{
if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) pageRaportit.lisaaTapahtuma(0);
if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) pageListat.lisaa();
if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible()) pageTyomatkat.lisaaUusi(0);
}
}
void CTaikaDlg::OnImport()
{
if(GetForegroundWindow() == this)
{
if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible())
{ if(pageListat.importListat() == IDOK) paivitaNaytot(TRUE, FALSE, FALSE, SYNC_ALL); }
}
}
void CTaikaDlg::OnPaivitaV5()
{
if(GetForegroundWindow() == this)
paivitaNaytot(TRUE, TRUE, TRUE, SYNC_ALL);
}
// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // //
// Yhteiset funktiot
// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // //
void CTaikaDlg::paivitaNaytot(BOOL date, BOOL select, BOOL database, int type)
{ // Keskitetty näyttöjen päivitys
if(m_mainShowMode == SHOW_RAPORTIT)
{
pageRaportit.paivitaAARListat("", NULL, FALSE);
pageRaportit.paivitaTyontekijat("", NULL, FALSE);
pageRaportit.paivitaTyotyyppi("", NULL, FALSE);
pageRaportit.paivitaPaivays(0, "", NULL, FALSE);
if(date) pageRaportit.paivitaPaivays(0, "", NULL, FALSE);
if(select) pageRaportit.uusiHaku(NULL);
syncListat(SYNC_FROM_RAPORTIT, type);
}
if(m_mainShowMode == SHOW_LISTAT)
{
pageListat.paivitaAsiakasryhmat("", TRUE);
pageListat.paivitaAsiakkaat("");
pageListat.paivitaTila();
syncListat(SYNC_FROM_LISTAT, type);
}
if(m_mainShowMode == SHOW_TYOMATKAT)
{
pageTyomatkat.paivitaTyontekijat("", NULL, FALSE);
pageTyomatkat.paivitaPaivays(0, "", NULL, FALSE);
if(date) pageTyomatkat.paivitaPaivays(0, "", NULL, FALSE);
if(select) pageTyomatkat.uusiHaku(NULL);
syncListat(SYNC_FROM_TYOMATKAT, type);
}
if(database) usedDB();
}
void CTaikaDlg::syncListat(int from, int type)
{ // Listojen muutokset heijastuu kaikkien eri näyttöjen listoihin -> välitä tieto päivityksestä näytöille
if(from != SYNC_FROM_RAPORTIT)
Props::e().m_sync_raportit |= type;
if(from != SYNC_FROM_LISTAT)
Props::e().m_sync_listat |= type;
if(from != SYNC_FROM_TYOMATKAT)
Props::e().m_sync_tyomatkat |= type;
// Etsi-toiminnon vanhat osumat poistetaan, jos asiakkaat muuttuneet
if((type&SYNC_ASIAKKAAT) || (type&SYNC_ASIAKASRYHMAT))
Props::e().m_dlgEtsi.clear();
}
void CTaikaDlg::usedDB()
{
CString cs;
cs = Props::i().lang("APPNAME") + CString(" - ") + Props::i().get(OPTIONS_DB_NAME).c_str();
this->SetWindowText(cs);
} | ptesavol/t-time | VS2005App/taikaDlg.cpp | C++ | gpl-2.0 | 25,345 |
// Generated by CoffeeScript 1.8.0
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
(function(jQuery) {
var $, $event, AwesomeGallery, CustomAdapter, FooBoxAdapter, GalleryFilters, JetpackAdapter, LightboxAdapter, MagnificPopupAdapter, Modernizr, PrettyPhotoAdapter, SwipeboxAdapter, capitalize, classes, dispatchMethod, document, getStyleProperty, iLightboxAdapter, prefixes, resizeTimeout, result, setIsoTransform, testName, tests, transformFnNotations, transformProp, transitionDurProp, transitionEndEvent, transitionProp;
if (!jQuery) {
return alert('Message from UberGrid: jQuery not found!');
} else {
if (parseInt(jQuery().jquery.replace(/\./g, '')) < 172) {
return alert('Message from Awesome Gallery: You have jQuery < 1.7.2. Please upgrade your jQuery or enable "Force new jQuery version" option at Awesome Gallery settings page.');
} else {
$ = jQuery;
document = window.document;
Modernizr = window.Modernizr;
transitionEndEvent = null;
capitalize = function(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
};
prefixes = "Moz Webkit O Ms".split(" ");
getStyleProperty = function(propName) {
var i, len, prefixed, style;
style = document.documentElement.style;
prefixed = void 0;
if (typeof style[propName] === "string") {
return propName;
}
propName = capitalize(propName);
i = 0;
len = prefixes.length;
while (i < len) {
prefixed = prefixes[i] + propName;
if (typeof style[prefixed] === "string") {
return prefixed;
}
i++;
}
};
transformProp = getStyleProperty("transform");
transitionProp = getStyleProperty("transitionProperty");
tests = {
csstransforms: function() {
return !!transformProp;
},
csstransforms3d: function() {
var $div, $style, mediaQuery, test, vendorCSSPrefixes;
test = !!getStyleProperty("perspective");
if (test) {
vendorCSSPrefixes = " -o- -moz- -ms- -webkit- -khtml- ".split(" ");
mediaQuery = "@media (" + vendorCSSPrefixes.join("transform-3d),(") + "modernizr)";
$style = $("<style>" + mediaQuery + "{#modernizr{height:3px}}" + "</style>").appendTo("head");
$div = $("<div id=\"modernizr\" />").appendTo("html");
test = $div.height() === 3;
$div.remove();
$style.remove();
}
return test;
},
csstransitions: function() {
return !!transitionProp;
}
};
testName = void 0;
if (Modernizr) {
for (testName in tests) {
if (!Modernizr.hasOwnProperty(testName)) {
Modernizr.addTest(testName, tests[testName]);
}
}
} else {
Modernizr = window.Modernizr = {
_version: "1.6ish: miniModernizr for Isotope"
};
classes = " ";
result = void 0;
for (testName in tests) {
result = tests[testName]();
Modernizr[testName] = result;
classes += " " + (result ? "" : "no-") + testName;
}
$("html").addClass(classes);
}
/*
provides hooks for .css({ scale: value, translate: [x, y] })
Progressively enhanced CSS transforms
Uses hardware accelerated 3D transforms for Safari
or falls back to 2D transforms.
*/
if (Modernizr.csstransforms) {
transformFnNotations = (Modernizr.csstransforms3d ? {
translate: function(position) {
return "translate3d(" + position[0] + "px, " + position[1] + "px, 0) ";
},
scale: function(scale) {
return "scale3d(" + scale + ", " + scale + ", 1) ";
}
} : {
translate: function(position) {
return "translate(" + position[0] + "px, " + position[1] + "px) ";
},
scale: function(scale) {
return "scale(" + scale + ") ";
}
});
setIsoTransform = function(elem, name, value) {
var data, fnName, newData, scaleFn, transformObj, transformValue, translateFn, valueFns;
data = $.data(elem, "isoTransform") || {};
newData = {};
fnName = void 0;
transformObj = {};
transformValue = void 0;
newData[name] = value;
$.extend(data, newData);
for (fnName in data) {
transformValue = data[fnName];
transformObj[fnName] = transformFnNotations[fnName](transformValue);
}
translateFn = transformObj.translate || "";
scaleFn = transformObj.scale || "";
valueFns = translateFn + scaleFn;
$.data(elem, "isoTransform", data);
elem.style[transformProp] = valueFns;
};
$.cssNumber.scale = true;
$.cssHooks.scale = {
set: function(elem, value) {
setIsoTransform(elem, "scale", value);
},
get: function(elem, computed) {
var transform;
transform = $.data(elem, "isoTransform");
if (transform && transform.scale) {
return transform.scale;
} else {
return 1;
}
}
};
$.fx.step.scale = function(fx) {
$.cssHooks.scale.set(fx.elem, fx.now + fx.unit);
};
$.cssNumber.translate = true;
$.cssHooks.translate = {
set: function(elem, value) {
setIsoTransform(elem, "translate", value);
},
get: function(elem, computed) {
var transform;
transform = $.data(elem, "isoTransform");
if (transform && transform.translate) {
return transform.translate;
} else {
return [0, 0];
}
}
};
}
transitionEndEvent = void 0;
transitionDurProp = void 0;
if (Modernizr.csstransitions) {
transitionEndEvent = {
WebkitTransitionProperty: "webkitTransitionEnd",
MozTransitionProperty: "transitionend",
OTransitionProperty: "oTransitionEnd otransitionend",
transitionProperty: "transitionend"
};
[
{
transitionProp: transitionProp
}
];
transitionDurProp = getStyleProperty("transitionDuration");
}
$event = $.event;
dispatchMethod = ($.event.handle ? "handle" : "dispatch");
resizeTimeout = void 0;
$event.special.smartresize = {
setup: function() {
$(this).bind("resize", $event.special.smartresize.handler);
},
teardown: function() {
$(this).unbind("resize", $event.special.smartresize.handler);
},
handler: function(event, execAsap) {
var args, context;
context = this;
args = arguments;
event.type = "smartresize";
if (resizeTimeout) {
clearTimeout(resizeTimeout);
}
resizeTimeout = setTimeout(function() {
$event[dispatchMethod].apply(context, args);
}, (execAsap === "execAsap" ? 0 : 100));
}
};
$.fn.smartresize = function(fn) {
if (fn) {
return this.bind("smartresize", fn);
} else {
return this.trigger("smartresize", ["execAsap"]);
}
};
LightboxAdapter = (function() {
LightboxAdapter.create = function($images, config) {
switch (config.name) {
case 'magnific-popup':
return new MagnificPopupAdapter($images, config);
case 'swipebox':
return new SwipeboxAdapter($images, config);
case 'prettyphoto':
return new PrettyPhotoAdapter($images, config);
case 'ilightbox':
return new iLightboxAdapter($images, config);
case 'jetpack':
return new JetpackAdapter($images, config);
case 'foobox':
return new FooBoxAdapter($images, config);
default:
return null;
}
};
function LightboxAdapter($el, config) {
this.onPrevSlide = __bind(this.onPrevSlide, this);
this.onNextSlide = __bind(this.onNextSlide, this);
this.onAfterClose = __bind(this.onAfterClose, this);
this.onKeyUp = __bind(this.onKeyUp, this);
this.setHash = __bind(this.setHash, this);
this.getInstanceIndex = __bind(this.getInstanceIndex, this);
this.onImageClicked = __bind(this.onImageClicked, this);
this.getLightboxCaption2 = __bind(this.getLightboxCaption2, this);
this.getLightboxCaption1 = __bind(this.getLightboxCaption1, this);
this.getSlug = __bind(this.getSlug, this);
this.getId = __bind(this.getId, this);
this.getAllLightboxLinks = __bind(this.getAllLightboxLinks, this);
this.getLightboxLinks = __bind(this.getLightboxLinks, this);
this.getDeeplinkImage = __bind(this.getDeeplinkImage, this);
this.clickImage = __bind(this.clickImage, this);
this.loadDeepLink = __bind(this.loadDeepLink, this);
this.checkForDeeplink = __bind(this.checkForDeeplink, this);
this.addImages = __bind(this.addImages, this);
this.reset = __bind(this.reset, this);
this.$el = $el;
this.config = config;
this.getAllLightboxLinks().off('click').removeClass('prettyphoto').removeClass('thickbox');
setTimeout(this.reset, 1);
this.reset();
this.checkForDeeplink();
}
LightboxAdapter.prototype.reset = function() {
this.getAllLightboxLinks().off('click', this.onImageClicked);
return this.getLightboxLinks().on('click', this.onImageClicked);
};
LightboxAdapter.prototype.addImages = function(images) {
return this.reset();
};
LightboxAdapter.prototype.checkForDeeplink = function() {
var gridId, image;
if (location.hash.match(/^#\d+\-/)) {
gridId = location.hash.replace(/^\#/, '').replace(/\-.*/, '');
if (gridId !== this.getId()) {
return false;
}
image = location.hash.replace(/^.*\//, '');
this.loadDeepLink(image);
return true;
}
};
LightboxAdapter.prototype.loadDeepLink = function(image) {
var linkedImage;
linkedImage = this.getDeeplinkImage(image);
if (linkedImage.length > 0) {
return this.clickImage(linkedImage);
} else {
return this.config.loadMoreCallback();
}
};
LightboxAdapter.prototype.clickImage = function(image) {
return $(image).find('a.asg-lightbox').click();
};
LightboxAdapter.prototype.getDeeplinkImage = function(id) {
return jQuery.grep(this.getLightboxLinks().closest('.asg-image'), (function(_this) {
return function(cell) {
return $(cell).data('slug').toString() === id;
};
})(this));
};
LightboxAdapter.prototype.linkSelector = '.asg-image:not(.asg-hidden) .asg-image-wrapper.asg-lightbox';
LightboxAdapter.prototype.allLinkSelector = '.asg-image .asg-image-wrapper.asg-lightbox';
LightboxAdapter.prototype.getLightboxLinks = function() {
return this.$el.find(this.linkSelector);
};
LightboxAdapter.prototype.getAllLightboxLinks = function() {
return this.$el.find(this.allLinkSelector);
};
LightboxAdapter.prototype.getId = function() {
return this.$el.parent().attr('id').replace(/\-\d+$/, '').replace(/^.*\-/, '');
};
LightboxAdapter.prototype.getSlug = function() {
return this.$el.parent().attr('data-slug');
};
LightboxAdapter.prototype.getLightboxCaption1 = function(el) {
var caption_1;
if (caption_1 = el.find('.asg-lightbox-caption1').html()) {
caption_1 = $('<h3 />').html(caption_1)[0].outerHTML;
} else {
caption_1 = '';
}
return caption_1;
};
LightboxAdapter.prototype.getLightboxCaption2 = function(el) {
var caption_2;
if (caption_2 = el.find('.asg-lightbox-caption2').html()) {
caption_2 = $('<div />').html(caption_2)[0].outerHTML;
} else {
caption_2 = '';
}
return caption_2;
};
LightboxAdapter.prototype.onImageClicked = function(event) {
var cell;
cell = jQuery(event.target).closest('.asg-image');
this.scrollTop = jQuery(document).scrollTop();
return this.setHash(cell);
};
LightboxAdapter.prototype.getID = function() {
return this.$el.parent().attr('id').replace(/\-\d+$/, '').replace(/.+\-/, '');
};
LightboxAdapter.prototype.getInstanceIndex = function() {
return this.$el.parent().attr('id').replace(/.*\-/, '');
};
LightboxAdapter.prototype.setHash = function(cell) {
var cellSlug, id;
id = this.getID();
cellSlug = cell.data('slug');
this.prevHash = location.hash;
return location.hash = "" + id + "-" + (this.getSlug()) + "/" + cellSlug;
};
LightboxAdapter.prototype.resetHash = function() {
if (this.prevHash) {
location.hash = this.prevHash;
delete this.prevHash;
} else {
location.hash = '#';
}
if (this.scrollTop && this.scrollTop > 0) {
return jQuery(document).scrollTop(this.scrollTop);
}
};
LightboxAdapter.prototype.onKeyUp = function(event) {
if (event.keyCode === 37) {
return this.onPrevSlide();
} else if (event.keyCode === 39) {
return this.onNextSlide();
} else if (event.keyCode === 27) {
return this.onAfterClose();
}
};
LightboxAdapter.prototype.onAfterClose = function() {
$(window).off('keyup', this.onKeyup);
return this.resetHash();
};
LightboxAdapter.prototype.onNextSlide = function() {
var lightboxLinks;
this.currentIndex += 1;
lightboxLinks = this.getLightboxLinks();
if (this.currentIndex === lightboxLinks.length) {
this.currentIndex = lightboxLinks.length - 1;
}
return this.setHash(this.getLightboxLinks().eq(this.currentIndex).closest('.asg-image'));
};
LightboxAdapter.prototype.onPrevSlide = function() {
this.currentIndex -= 1;
if (this.currentIndex < 0) {
this.currentIndex = 0;
}
return this.setHash(this.getLightboxLinks().eq(this.currentIndex).closest('.asg-image'));
};
return LightboxAdapter;
})();
CustomAdapter = (function(_super) {
__extends(CustomAdapter, _super);
function CustomAdapter() {
return CustomAdapter.__super__.constructor.apply(this, arguments);
}
return CustomAdapter;
})(LightboxAdapter);
FooBoxAdapter = (function(_super) {
__extends(FooBoxAdapter, _super);
function FooBoxAdapter() {
this.addImages = __bind(this.addImages, this);
this.initFoobox = __bind(this.initFoobox, this);
this.fooboxPresent = __bind(this.fooboxPresent, this);
this.reset = __bind(this.reset, this);
return FooBoxAdapter.__super__.constructor.apply(this, arguments);
}
FooBoxAdapter.prototype.reset = function() {
FooBoxAdapter.__super__.reset.call(this);
if (this.fooboxPresent()) {
return this.initFoobox();
} else {
return $((function(_this) {
return function() {
if (_this.fooboxPresent()) {
return _this.initFoobox();
}
};
})(this));
}
};
FooBoxAdapter.prototype.fooboxPresent = function() {
return window.FOOBOX && window.FOOBOX.o;
};
FooBoxAdapter.prototype.initFoobox = function() {
var fooboxOptions;
fooboxOptions = jQuery.extend({}, window.FOOBOX.o, {
deeplinking: false,
affiliate: false,
slideshow: {
enabled: true
},
selector: this.linkSelector
});
return this.$el.foobox(fooboxOptions).on('foobox.afterLoad', (function(_this) {
return function(event) {
return _this.setHash(_this.getLightboxLinks().eq(event.fb.item.index).closest('.asg-image'));
};
})(this)).on('foobox.close', (function(_this) {
return function() {
return _this.resetHash();
};
})(this));
};
FooBoxAdapter.prototype.addImages = function(images) {
var image, _i, _len;
for (_i = 0, _len = images.length; _i < _len; _i++) {
image = images[_i];
image = $(image).closest('.asg-image');
image.attr('title', this.getLightboxCaption1(image));
image.find('img').attr('alt', this.getLightboxCaption2(image));
}
return FooBoxAdapter.__super__.addImages.call(this, images);
};
return FooBoxAdapter;
})(LightboxAdapter);
JetpackAdapter = (function(_super) {
__extends(JetpackAdapter, _super);
function JetpackAdapter($el, config) {
this.onPrevSlide = __bind(this.onPrevSlide, this);
this.onNextSlide = __bind(this.onNextSlide, this);
this.setHashFromCurrentIndex = __bind(this.setHashFromCurrentIndex, this);
this.onAfterClose = __bind(this.onAfterClose, this);
this.startCarousel = __bind(this.startCarousel, this);
this.onImageClicked = __bind(this.onImageClicked, this);
this.addImages = __bind(this.addImages, this);
JetpackAdapter.__super__.constructor.call(this, $el, config);
this.$el.data('carousel-extra', {
blog_id: 1,
permalink: 'http://awesome-gallery.dev'
});
}
JetpackAdapter.prototype.addImages = function(images) {
var image, url, wrapper, _i, _len;
images.addClass('tiled-gallery-item');
for (_i = 0, _len = images.length; _i < _len; _i++) {
image = images[_i];
image = $(image);
wrapper = image.closest('.asg-image');
url = image.find('.asg-image-wrapper').attr('href');
image.find('img').data({
'orig-file': url,
'orig-size': "" + (wrapper.data('width')) + "," + (wrapper.data('height')),
'large-file': url,
'medium-file': url,
'small-file': url,
'image-title': this.getLightboxCaption1(wrapper),
'image-description': this.getLightboxCaption2(wrapper),
'image-meta': wrapper.data('meta'),
'attachment-id': wrapper.data('attachment-id') ? wrapper.data('attachment-id') : 'asg-hack',
'comments-opened': wrapper.data('attachment-id') ? 1 : null
});
}
return images.on('click', this.onImageClicked);
};
JetpackAdapter.prototype.onImageClicked = function(event) {
event.preventDefault();
if ($.fn.jp_carousel) {
return this.startCarousel(event);
} else {
return $(document).ready(setTimeout(((function(_this) {
return function() {
return _this.startCarousel(event);
};
})(this)), 500));
}
};
JetpackAdapter.prototype.startCarousel = function(event) {
this.currentIndex = this.$el.find(this.linkSelector).index($(event.target).closest('.asg-image-wrapper'));
if (this.$el.jp_carousel) {
this.$el.jp_carousel({
start_index: this.currentIndex,
'items_selector': ".asg-image:not(.asg-hidden) .asg-image-wrapper img"
});
return setTimeout(this.setHashFromCurrentIndex, 500);
} else {
return $(document).ready((function(_this) {
return function() {
return setTimeout(function() {
_this.$el.jp_carousel({
start_index: _this.currentIndex,
'items_selector': ".asg-image:not(.asg-hidden) .asg-image-wrapper img"
});
return setTimeout(_this.setHashFromCurrentIndex, 500);
}, 600);
};
})(this));
}
};
JetpackAdapter.prototype.onAfterClose = function() {
JetpackAdapter.__super__.onAfterClose.apply(this, arguments);
jQuery(document).off('keyup', this.onKeyUp);
$('.jp-carousel-next-button').off('click', this.onNextSlide);
return $('.jp-carousel-previous-button').off('click', this.onPrevSlide);
};
JetpackAdapter.prototype.setHashFromCurrentIndex = function() {
this.setHash(this.getLightboxLinks().eq(this.currentIndex).closest('.asg-image'));
$('.jp-carousel-next-button').click(this.onNextSlide);
$('.jp-carousel-previous-button').click(this.onPrevSlide);
$(document).on('keyup', this.onKeyUp);
return $(document).on('click', '.jp-carousel-close-hint', this.onAfterClose);
};
JetpackAdapter.prototype.onNextSlide = function() {
var lightboxLinks;
this.currentIndex += 1;
lightboxLinks = this.getLightboxLinks();
if (this.currentIndex === lightboxLinks.length) {
this.currentIndex = 0;
}
return setTimeout(this.setHashFromCurrentIndex, 400);
};
JetpackAdapter.prototype.onPrevSlide = function() {
this.currentIndex -= 1;
if (this.currentIndex < 0) {
this.currentIndex = this.getLightboxLinks().size() - 1;
}
return setTimeout(this.setHashFromCurrentIndex, 400);
};
return JetpackAdapter;
})(LightboxAdapter);
MagnificPopupAdapter = (function(_super) {
__extends(MagnificPopupAdapter, _super);
function MagnificPopupAdapter($el, config) {
var _this;
_this = this;
$el.magnificPopup({
type: 'image',
delegate: this.linkSelector,
gallery: {
enabled: true
},
mainClass: 'mfp-asg',
image: {
titleSrc: function() {
var caption_1, caption_2, el;
el = this.currItem.el.parent();
if (caption_1 = el.find('.asg-lightbox-caption1').html()) {
caption_1 = $('<h3 />').html(caption_1)[0].outerHTML;
} else {
caption_1 = '';
}
if (caption_2 = el.find('.asg-lightbox-caption2').html()) {
caption_2 = $('<div />').html(caption_2)[0].outerHTML;
} else {
caption_2 = '';
}
if (caption_1 + caption_2) {
return caption_1 + caption_2;
}
return null;
},
markup: '<div class="mfp-figure">' + '<div class="mfp-close"></div>' + '<figure>' + '<div class="mfp-img"></div>' + '<div class="mfp-asg-border"></div>' + '<figcaption>' + '<div class="mfp-bottom-bar">' + '<div class="mfp-title"></div>' + '<div class="mfp-counter"></div>' + '</div>' + '</figcaption>' + '</figure>' + '</div>'
},
callbacks: {
open: (function() {
jQuery('.mfp-wrap').addClass('mfp-asg');
return this._lastFocusedEl = null;
}),
markupParse: (function(template) {
return template.find('.mfp-counter').remove();
}),
afterClose: (function(_this) {
return function() {
return _this.resetHash();
};
})(this),
afterChange: function() {
return _this.setHash(this.currItem.el.closest('.asg-image'));
}
}
});
MagnificPopupAdapter.__super__.constructor.call(this, $el, config);
}
return MagnificPopupAdapter;
})(LightboxAdapter);
SwipeboxAdapter = (function(_super) {
__extends(SwipeboxAdapter, _super);
function SwipeboxAdapter() {
this.onImageClicked = __bind(this.onImageClicked, this);
return SwipeboxAdapter.__super__.constructor.apply(this, arguments);
}
SwipeboxAdapter.prototype.onImageClicked = function(event) {
var elements, lightboxImages;
SwipeboxAdapter.__super__.onImageClicked.call(this, event);
event.preventDefault();
elements = this.$el.find(this.linkSelector);
lightboxImages = $.map(elements, (function(_this) {
return function(image) {
image = $(image);
return {
href: image.attr('href'),
title: function() {
var caption1, caption2, html;
image = image.closest('.asg-image');
html = $('<div/>');
if (caption2 = _this.getLightboxCaption2(image)) {
html.append($('<small class="asg-small"/>').html(caption2));
}
if (caption1 = _this.getLightboxCaption1(image)) {
html.append($('<div />').html(caption1));
}
return html.html();
}
};
};
})(this));
this.currentIndex = elements.index($(event.target).closest('a.asg-image-wrapper'));
$.swipebox(lightboxImages, {
initialIndexOnArray: this.currentIndex
});
jQuery('#swipebox-next').click(this.onNextSlide);
jQuery('#swipebox-prev').click(this.onPrevSlide);
return jQuery(window).on('keyup', this.onKeyUp);
};
return SwipeboxAdapter;
})(LightboxAdapter);
PrettyPhotoAdapter = (function(_super) {
__extends(PrettyPhotoAdapter, _super);
function PrettyPhotoAdapter() {
this.onPrevSlide = __bind(this.onPrevSlide, this);
this.onNextSlide = __bind(this.onNextSlide, this);
this.onKeyUp = __bind(this.onKeyUp, this);
this.onImageClicked = __bind(this.onImageClicked, this);
return PrettyPhotoAdapter.__super__.constructor.apply(this, arguments);
}
PrettyPhotoAdapter.prototype.onImageClicked = function(event) {
var descriptions, elements, titles, urls;
event.preventDefault();
event.stopPropagation();
elements = this.$el.find(this.linkSelector);
urls = elements.map((function(_this) {
return function(index, image) {
return $(image).closest('a.asg-image-wrapper').attr('href');
};
})(this));
titles = elements.map((function(_this) {
return function(index, image) {
return _this.getLightboxCaption1($(image).closest('.asg-image'));
};
})(this));
descriptions = elements.map((function(_this) {
return function(index, image) {
return _this.getLightboxCaption2($(image).closest('.asg-image'));
};
})(this));
$.fn.prettyPhoto(this.config.settings);
$.prettyPhoto.open(urls, titles, descriptions, this.currentIndex = elements.index($(event.target).closest('.asg-image-wrapper')));
this.setHash($(event.target).closest('.asg-image'));
$(document).on('keydown.prettyphoto', this.onKeyUp);
$('.pp_previous').on('click.asg', this.onPrevSlide);
return $('.pp_next').on('click.asg', this.onNextSlide);
};
PrettyPhotoAdapter.prototype.onKeyUp = function(event) {
if (event.keyCode === 37) {
return this.onPrevSlide();
} else if (event.keyCode === 39) {
return this.onNextSlide();
} else if (event.keyCode === 27) {
return this.resetHash();
}
};
PrettyPhotoAdapter.prototype.onNextSlide = function() {
var lightboxLinks;
this.currentIndex += 1;
lightboxLinks = this.getLightboxLinks();
if (this.currentIndex === lightboxLinks.length) {
this.currentIndex = lightboxLinks.length - 1;
}
return this.setHash(this.getLightboxLinks().eq(this.currentIndex).closest('.asg-image'));
};
PrettyPhotoAdapter.prototype.onPrevSlide = function() {
this.currentIndex -= 1;
if (this.currentIndex < 0) {
this.currentIndex = 0;
}
return this.setHash(this.getLightboxLinks().eq(this.currentIndex).closest('.asg-image'));
};
return PrettyPhotoAdapter;
})(LightboxAdapter);
iLightboxAdapter = (function(_super) {
__extends(iLightboxAdapter, _super);
function iLightboxAdapter($el, config) {
this.onImageClicked = __bind(this.onImageClicked, this);
if (!$.iLightBox) {
alert('iLightbox not detected. Please install end enable iLightbox plugin.');
}
iLightboxAdapter.__super__.constructor.call(this, $el, config);
}
iLightboxAdapter.prototype.onImageClicked = function(event) {
var elements, index, lightboxImages, options;
iLightboxAdapter.__super__.onImageClicked.call(this, event);
event.preventDefault();
elements = this.$el.find(this.linkSelector);
lightboxImages = $.map(elements, (function(_this) {
return function(el) {
var data;
data = $(el);
return {
title: _this.getLightboxCaption1(data),
url: data.attr('href'),
caption: _this.getLightboxCaption2(data),
thumbnail: $(el).find('.asg-image-wrapper img').attr('src')
};
};
})(this));
this.currentIndex = index = elements.index($(event.target).closest('.asg-image-wrapper'));
options = $.extend(this.config.settings, ILIGHTBOX.options && eval("(" + rawurldecode(ILIGHTBOX.options) + ")") || {});
return $.iLightBox(lightboxImages, $.extend({
startFrom: index,
callback: {
onAfterChange: (function(_this) {
return function(instance) {
_this.currentIndex = instance.currentItem;
return _this.setHash(elements.eq(_this.currentIndex).closest('.asg-image'));
};
})(this),
onHide: (function(_this) {
return function() {
return _this.resetHash();
};
})(this)
}
}, options));
};
return iLightboxAdapter;
})(LightboxAdapter);
GalleryFilters = (function() {
function GalleryFilters($el, filterCallback) {
this.onFilterClick = __bind(this.onFilterClick, this);
this.createFilter = __bind(this.createFilter, this);
this.createSortedFilters = __bind(this.createSortedFilters, this);
this.createAll = __bind(this.createAll, this);
this.add = __bind(this.add, this);
var list;
this.$el = $el;
this.tags = [];
this.filterCallback = filterCallback;
this.current = null;
this.$el.on('click', '.asg-filter', this.onFilterClick);
this.$el.hide();
this.suspendCreation = false;
if ((list = this.$el.data('list')) && list !== '') {
this.add(list.split(/,\s*/));
this.suspendCreation = true;
}
}
GalleryFilters.prototype.add = function(tags) {
var tag, _i, _len;
if (this.suspendCreation) {
return;
}
for (_i = 0, _len = tags.length; _i < _len; _i++) {
tag = tags[_i];
if (tag === '') {
continue;
}
if (!this.tags.hasOwnProperty(tag)) {
this.tags[tag] = true;
if (!this.$el.data('sort')) {
this.createFilter(tag);
this.$el.show();
}
}
}
if (this.$el.data('sort')) {
this.$el.empty();
return this.createSortedFilters();
} else {
if (this.tags.length !== 0) {
return this.createAll();
}
}
};
GalleryFilters.prototype.createAll = function() {
var all;
this.$el.prepend(all = $("<div class='asg-filter' />").append($("<a data-tag='' href='#' />").text(this.$el.data('all'))));
if (this.current === '' || this.current === null) {
return all.addClass('asg-active');
}
};
GalleryFilters.prototype.createSortedFilters = function() {
var tag, tags, _i, _len;
this.createAll();
tags = [];
for (tag in this.tags) {
if (this.tags.hasOwnProperty(tag)) {
tags.push(tag);
}
}
tags.sort();
for (_i = 0, _len = tags.length; _i < _len; _i++) {
tag = tags[_i];
this.createFilter(tag);
}
if (tags.length > 0) {
return this.$el.show();
}
};
GalleryFilters.prototype.createFilter = function(tag) {
var a, filter;
filter = $('<div class="asg-filter" />').append(a = $("<a href='#' />").text(tag).attr('data-tag', tag)).appendTo(this.$el);
if (tag === this.current) {
return filter.addClass('asg-active');
}
};
GalleryFilters.prototype.onFilterClick = function(event) {
var filter;
event.preventDefault();
filter = $(event.target);
this.$el.find('> div').removeClass('asg-active');
$(filter).parent().addClass('asg-active');
this.current = $(filter).attr('data-tag');
return this.filterCallback(this.current);
};
return GalleryFilters;
})();
AwesomeGallery = (function() {
var AnimationQueue, GalleryImage, GridLayoutStrategy, HorizontalFlowLayoutStrategy, ImageCaption, ImageOverlay, LayoutStrategy, SlidingElement, VerticalFlowLayoutStrategy;
function AwesomeGallery(id, config) {
this.dispose = __bind(this.dispose, this);
this.applyFiltering = __bind(this.applyFiltering, this);
this.getFilteredImages = __bind(this.getFilteredImages, this);
this.add = __bind(this.add, this);
this.loadMore = __bind(this.loadMore, this);
this.initLoadMore = __bind(this.initLoadMore, this);
this.loadMoreActive = __bind(this.loadMoreActive, this);
this.deepLinkLoadMoreCallback = __bind(this.deepLinkLoadMoreCallback, this);
this.showDeeplinkLoadOverlay = __bind(this.showDeeplinkLoadOverlay, this);
this.showWhenVisible = __bind(this.showWhenVisible, this);
var lightboxConfig;
this.$window = $(window);
this.id = id;
this.config = config;
this.page = 1;
this.$el = $("#awesome-gallery-" + id);
this.$el.data('awesome-gallery', this);
this.$images = this.$el.find('.asg-images');
this.recursive = 0;
this.animationQueue = new AnimationQueue();
if ((this.$filters = this.$el.find('.asg-filters')).size() > 0) {
this.filters = new GalleryFilters(this.$filters, this.applyFiltering);
}
this.images = [];
this.layout = LayoutStrategy.create(this.$images, this.config.layout, this.animationQueue);
this.loading = false;
this.loadMoreCount = 0;
lightboxConfig = this.config.lightbox;
if (this.loadMoreActive()) {
lightboxConfig = $.extend({
loadMoreCallback: this.deepLinkLoadMoreCallback
}, lightboxConfig);
this.initLoadMore();
}
this.lightboxAdapter = LightboxAdapter.create(this.$images, lightboxConfig);
this.add(this.$el.find('.asg-image'));
this.showWhenVisible();
}
AwesomeGallery.prototype.showWhenVisible = function() {
if (!this.$el.is(':visible') || this.$el.width() < 50) {
return setTimeout(this.showWhenVisible, 250);
} else {
return this.layout.reLayout();
}
};
AwesomeGallery.prototype.showDeeplinkLoadOverlay = function() {
return this.$images.append('<div class="asg-deeplink-overlay"><div class="asg-deeplink-loader"></div></div>');
};
AwesomeGallery.prototype.deepLinkLoadMoreCallback = function() {
this.loadMoreCount += 1;
this.showDeeplinkLoadOverlay();
if (this.loadMoreCount < 3) {
return this.loadMore((function(_this) {
return function() {
if (_this.lightboxAdapter.checkForDeeplink()) {
return _this.$images.find('.asg-deeplink-overlay').remove();
}
};
})(this));
} else {
return this.$images.find('.asg-deeplink-overlay').remove();
}
};
AwesomeGallery.prototype.loadMoreActive = function() {
return this.$el.find('.asg-bottom').size() > 0;
};
AwesomeGallery.prototype.initLoadMore = function() {
if ((this.$loadMore = this.$el.find('.asg-bottom .asg-load-more')).size() > 0) {
return this.$loadMore.click((function(_this) {
return function() {
_this.recursive = 0;
return _this.loadMore();
};
})(this));
} else {
return this.$window.on('scroll.asg', (function(_this) {
return function() {
if (!(_this.loading || _this.allLoaded)) {
if (_this.$images.height() + _this.$images.offset().top - 400 < _this.$window.scrollTop() + _this.$window.height()) {
return _this.loadMore();
}
}
};
})(this));
}
};
AwesomeGallery.prototype.loadMore = function(callback) {
if (this.loading || this.allLoaded) {
return;
}
this.loading = true;
if (this.$loadMore && this.$loadMore.size() > 0) {
this.$loadMore.hide();
}
this.$loading = this.$el.find('.asg-bottom .asg-loading').addClass('asg-visible');
return setTimeout((function(_this) {
return function() {
return $.post("" + _this.config.ajaxurl + "&page=" + (_this.page + 1) + "&id=" + _this.id, function(response) {
var tmp;
_this.loading = false;
_this.page += 1;
_this.$loading.removeClass('asg-visible');
if (response.have_more) {
_this.$loadMore.show();
} else {
_this.$el.find('.asg-bottom .asg-all-loaded').show();
_this.allLoaded = true;
}
tmp = $('<div/>').html(response.images);
_this.add(tmp.find('.asg-image').appendTo(_this.$images));
if (callback) {
return callback();
}
});
};
})(this), 50);
};
AwesomeGallery.prototype.add = function(images) {
var image, newFilteredImages, newImage, newImages, _i, _len;
newImages = [];
for (_i = 0, _len = images.length; _i < _len; _i++) {
image = images[_i];
newImage = new GalleryImage($(image), this.animationQueue, this.config);
this.images.push(newImage);
newImages.push(newImage);
if (this.filters) {
this.filters.add(newImage.getTags());
}
}
if (this.lightboxAdapter) {
this.lightboxAdapter.addImages(images);
}
newFilteredImages = this.getFilteredImages(newImages);
this.layout.add(newImages);
this.layout.layout(newFilteredImages);
if (newFilteredImages.length > 0) {
} else {
if (!this.loading && this.recursive < 2) {
this.recursive += 1;
return this.loadMore();
}
}
};
AwesomeGallery.prototype.getFilteredImages = function(images) {
return images = $.grep(images, (function(_this) {
return function(item) {
var matches;
matches = !_this.currentFilter || (jQuery.inArray(_this.currentFilter, item.getTags()) !== -1);
if (matches) {
item.show();
} else {
item.hide();
}
return matches;
};
})(this));
};
AwesomeGallery.prototype.applyFiltering = function(filter) {
this.currentFilter = filter;
this.layout.reLayout(this.getFilteredImages(this.images));
if (this.lightboxAdapter) {
this.lightboxAdapter.reset();
}
return this.recursive = 0;
};
AwesomeGallery.prototype.dispose = function() {
this.$window.off('scroll', this.windowScrolled);
if (this.$loadMore) {
return this.$loadMore.off('click', this.loadNextPage);
}
};
SlidingElement = (function() {
function SlidingElement($el, $wrapper, animationQueue) {
this.slideOut = __bind(this.slideOut, this);
this.cleanupClass = __bind(this.cleanupClass, this);
this.slideIn = __bind(this.slideIn, this);
this.getTransitionClass = __bind(this.getTransitionClass, this);
this.$el = $el;
this.$wrapper = $wrapper;
this.animationQueue = animationQueue;
if (transitionEndEvent) {
this.$el.on(transitionEndEvent[transitionProp], this.cleanupClass);
} else {
setTimeout(((function(_this) {
return function() {
return _this.cleanupClass();
};
})(this)), 200);
}
if (!($el.hasClass('asg-position-bottom') && $el.hasClass('asg-effect-slide') && $el.hasClass('asg-on-hover'))) {
if (!this.$el.hasClass('asg-off-hover')) {
this.$wrapper.on('mouseout', this.cleanupClass);
}
if (this.$el.hasClass('asg-on-hover') && this.$el.hasClass('asg-effect-slide')) {
this.$wrapper.hover(((function(_this) {
return function(event) {
return _this.slideIn(event);
};
})(this)), (function(_this) {
return function(event) {
return _this.slideOut(event);
};
})(this));
}
}
if (this.$el.hasClass('asg-off-hover') && this.$el.hasClass('asg-effect-slide')) {
this.$wrapper.hover(((function(_this) {
return function(event) {
return _this.slideOut(event);
};
})(this)), (function(_this) {
return function(event) {
return _this.slideIn(event);
};
})(this));
}
}
SlidingElement.prototype.getTransitionClass = function(event) {
var klass, x, y;
x = event.offsetX - this.$wrapper.width() / 2;
y = event.offsetY - this.$wrapper.height() / 2;
if (x > 0) {
if (Math.abs(x) > Math.abs(y)) {
klass = 'asg-slide-right';
} else {
if (y < 0) {
klass = 'asg-slide-top';
} else {
klass = 'asg-slide-bottom';
}
}
} else {
if (Math.abs(x) > Math.abs(y)) {
klass = 'asg-slide-left';
} else {
if (y < 0) {
klass = 'asg-slide-top';
} else {
klass = 'asg-slide-bottom';
}
}
}
return klass;
};
SlidingElement.prototype.slideIn = function(event) {
this.$el.addClass('asg-no-transition');
this.cleanupClass();
this.$el.addClass(this.getTransitionClass(event));
this.$el.height();
this.$el.removeClass('asg-no-transition');
return this.cleanupClass();
};
SlidingElement.prototype.cleanupClass = function() {
var klass, _i, _len, _ref, _results;
_ref = ['asg-slide-left', 'asg-slide-right', 'asg-slide-top', 'asg-slide-bottom'];
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
klass = _ref[_i];
_results.push(this.$el.removeClass(klass));
}
return _results;
};
SlidingElement.prototype.slideOut = function(event) {
var klass;
klass = this.getTransitionClass(event);
return this.$el.addClass(klass);
};
return SlidingElement;
})();
ImageOverlay = (function(_super) {
__extends(ImageOverlay, _super);
function ImageOverlay($el, $wrapper, animationQueue) {
ImageOverlay.__super__.constructor.call(this, $el, $wrapper, animationQueue);
}
return ImageOverlay;
})(SlidingElement);
ImageCaption = (function(_super) {
__extends(ImageCaption, _super);
function ImageCaption($el, $wrapper, animationQueue) {
this.layout = __bind(this.layout, this);
var h, img;
ImageCaption.__super__.constructor.call(this, $el, $wrapper, animationQueue);
this.centered = $el.hasClass('asg-position-center');
if (this.centered) {
$wrapper.hover(((function(_this) {
return function() {
return $el.css({
'margin-top': -$el.outerHeight() / 2
});
};
})(this)), null);
$el.on('resize', (function(_this) {
return function() {
return _this.layout();
};
})(this));
}
img = $el.parent().find('img');
h = $el.height();
if ($el.hasClass('asg-position-bottom') && $el.hasClass('asg-effect-slide') && $el.hasClass('asg-on-hover')) {
this.$wrapper.hover(((function(_this) {
return function() {
h = $el.outerHeight();
img.animate({
'top': "-" + (h / 2) + "px"
}, {
'queue': false,
duration: 400
});
return $el.css({
bottom: "-" + h + "px"
}).animate({
bottom: 0
}, {
queue: false,
duration: 350
});
};
})(this)), ((function(_this) {
return function() {
img.animate({
top: 0
}, {
queue: false,
duration: 400
});
return $el.animate({
bottom: "-" + h + "px"
}, {
queue: false,
duration: 350
});
};
})(this)));
}
}
ImageCaption.prototype.layout = function() {
if (this.centered) {
if (this.$el.hasClass('asg-mode-on') || this.$el.hasClass('asg-mode-on-hover')) {
this.$el.css({
opacity: 0
});
}
return setTimeout((function(_this) {
return function() {
var style;
style = {
'margin-top': -_this.$el.outerHeight() / 2
};
if (_this.$el.hasClass('asg-mode-on') || _this.$el.hasClass('asg-mode-on-hover')) {
_this.$el.css('opacity', '');
}
return _this.$el.css(style);
};
})(this), Math.random(500) + 600);
}
};
return ImageCaption;
})(SlidingElement);
AnimationQueue = (function() {
function AnimationQueue() {
this.flush = __bind(this.flush, this);
this.clear = __bind(this.clear, this);
this.enqueue = __bind(this.enqueue, this);
}
AnimationQueue.prototype.queue = [];
AnimationQueue.prototype.queues = [];
AnimationQueue.prototype.flushInterval = null;
AnimationQueue.prototype.flushTimespan = 10;
AnimationQueue.prototype.enqueue = function($el, style) {
this.queue.push([$el, style]);
if (!this.flushInterval) {
return this.flushInterval = setTimeout(this.flush, this.flushTimespan);
}
};
AnimationQueue.prototype.clear = function() {
this.queue = [];
clearTimeout(this.flushInterval);
return this.flushInterval = null;
};
AnimationQueue.prototype.flush = function() {
var i, item;
i = 50;
while (i > 0 && this.queue.length > 0) {
item = this.queue.shift();
item[0].css(item[1]);
i -= 1;
}
if (this.queue.length > 0) {
this.flushInterval = setTimeout(this.flush, this.flushTimespan);
return this.flushInterval = null;
}
};
return AnimationQueue;
})();
GalleryImage = (function() {
function GalleryImage($el, animationQueue, config) {
this.slideIn = __bind(this.slideIn, this);
this.layout = __bind(this.layout, this);
this.getTags = __bind(this.getTags, this);
this.show = __bind(this.show, this);
this.hide = __bind(this.hide, this);
var $caption, $overlay;
this.$el = $el;
this.animationQueue = animationQueue;
this.$image = this.$el.find('.asg-image-wrapper img');
if (window.devicePixelRatio) {
this.$image.attr('src', this.$image.attr('src') + ("&zoom=" + window.devicePixelRatio));
}
if (this.$image[0].complete || this.$image[0].naturalWidth > 0) {
this.$el.addClass('asg-loaded');
} else {
this.$image.on('load', (function(_this) {
return function() {
return _this.$el.addClass('asg-loaded');
};
})(this));
}
this.naturalWidth = this.$el.data('width');
this.naturalHeight = this.$el.data('height');
this.$el.data('asg-image', this);
this.config = config;
if (($overlay = this.$el.find('.asg-image-overlay')).size() > 0) {
this.overlay = new ImageOverlay($overlay, this.$el, this.animationQueue);
}
if (($caption = this.$el.find('.asg-image-caption-wrapper')).size() > 0) {
this.caption = new ImageCaption($caption, this.$el, this.animationQueue);
}
this.laidOut = false;
this.$el.on('transitionend', (function(_this) {
return function() {
return setTimeout(function() {
_this.$el.addClass('asg-laid-out');
return _this.laidOut = true;
}, Math.random() * 1000 + 100);
};
})(this));
}
GalleryImage.prototype.hide = function() {
return this.$el.addClass('asg-hidden');
};
GalleryImage.prototype.show = function() {
return this.$el.removeClass('asg-hidden');
};
GalleryImage.prototype.getTags = function() {
if (this.tags) {
return this.tags;
}
return this.tags = this.$el.data('tags').split(', ');
};
GalleryImage.prototype.layout = function(x, y, width, height) {
var css;
if (!this.laidOut) {
setTimeout((function(_this) {
return function() {
_this.$el.addClass('asg-laid-out');
return _this.laidOut = true;
};
})(this), Math.random() * 1000 + 100);
}
if (Modernizr.csstransforms && Modernizr.csstransitions) {
css = {
translate: [x, y]
};
} else {
css = {
left: x,
top: y
};
}
if (width && height) {
this.animationQueue.enqueue(this.$el, $.extend(css, {
width: width,
height: height
}));
} else {
this.animationQueue.enqueue(this.$el, css);
}
if (this.caption) {
return this.caption.layout();
}
};
GalleryImage.prototype.slideIn = function(event, element, zero) {
var css, x, y;
x = event.offsetX - this.wrapper.width() / 2;
y = event.offsetY - this.wrapper.height() / 2;
if (Math.abs(x) > Math.abs(y)) {
if (x > 0) {
css = {
'left': "" + (this.wrapper.width()) + "px",
top: 0
};
} else {
css = {
'left': "-" + (this.wrapper.width()) + "px",
top: 0
};
}
} else {
if (y < 0) {
css = {
'top': "-" + (this.wrapper.height()) + "px",
left: 0
};
} else {
css = {
'top': "" + (this.wrapper.height()) + "px",
left: 0
};
}
}
return element.css(css).animate(zero, 'fast');
};
GalleryImage.prototype.slideOut = function(event, element) {
var css, x, y;
x = event.offsetX - this.wrapper.width() / 2;
y = event.offsetY - this.wrapper.height() / 2;
if (x > 0) {
if (Math.abs(x) > Math.abs(y)) {
css = {
'left': "" + (this.wrapper.width()) + "px"
};
} else {
if (y < 0) {
css = {
'top': "-" + (this.wrapper.height()) + "px"
};
} else {
css = {
'top': "" + (this.wrapper.height()) + "px"
};
}
}
} else {
if (Math.abs(x) > Math.abs(y)) {
css = {
'left': "-" + (this.wrapper.width()) + "px"
};
} else {
if (y < 0) {
css = {
'top': "-" + (this.wrapper.height()) + "px"
};
} else {
css = {
'top': "" + (this.wrapper.height()) + "px"
};
}
}
}
return element.animate(css, 'fast');
};
return GalleryImage;
})();
LayoutStrategy = (function() {
LayoutStrategy.create = function(wrapper, config, animationQueue) {
if (config.mode === "usual") {
return new GridLayoutStrategy(wrapper, config, animationQueue);
} else if (config.mode === "vertical-flow") {
return new VerticalFlowLayoutStrategy(wrapper, config, animationQueue);
} else if (config.mode === 'horizontal-flow') {
return new HorizontalFlowLayoutStrategy(wrapper, config, animationQueue);
}
};
function LayoutStrategy($el, options, animationQueue) {
this.getColumnWidth = __bind(this.getColumnWidth, this);
this.getColumns = __bind(this.getColumns, this);
this.reLayoutRequired = __bind(this.reLayoutRequired, this);
this.layout = __bind(this.layout, this);
this.add = __bind(this.add, this);
this.reset = __bind(this.reset, this);
this.reLayout = __bind(this.reLayout, this);
this.onResized = __bind(this.onResized, this);
this.$el = $el;
this.images = [];
this.animationQueue = animationQueue;
$(window).smartresize(this.onResized);
this.checkLayoutInterval = setInterval(this.onResized, 500);
this.options = options;
this.reset();
}
LayoutStrategy.prototype.onResized = function() {
if (this.reLayoutRequired()) {
return this.reLayout();
}
};
LayoutStrategy.prototype.reLayout = function(images) {
if (images == null) {
images = null;
}
if (images) {
this.images = images;
}
this.reset();
return this.layout();
};
LayoutStrategy.prototype.reset = function() {
this.index = 0;
this.width = this.$el.parent().width();
this.columns = this.getColumns();
return this.columnWidth = this.getColumnWidth();
};
LayoutStrategy.prototype.add = function(images) {
return this.images = this.images.concat(images);
};
LayoutStrategy.prototype.layout = function(images) {
var size;
if (images == null) {
images = null;
}
images = images || this.images;
this.animationQueue.clear();
this.placeItems(images);
size = this.getContainerSize();
return this.$el.css({
width: size.width + "px",
height: size.height + "px"
});
};
LayoutStrategy.prototype.reLayoutRequired = function() {
return this.$el.parent().width() !== this.width;
};
LayoutStrategy.prototype.getColumns = function() {
var columns, fullWidth, width;
width = this.width;
columns = Math.floor((width + this.options.gap) / (this.options.width + this.options.gap + this.options.border * 2));
fullWidth = columns * (this.options.width + this.options.border * 2) + (columns - 1) * this.options.gap;
if (width > fullWidth) {
columns = columns + 1;
}
if (columns === 0) {
columns = 1;
}
return columns;
};
LayoutStrategy.prototype.getColumnWidth = function() {
var columns;
columns = this.columns;
if (columns > 1) {
return Math.floor((this.width + this.options.gap) / columns - this.options.gap);
}
return this.width;
};
return LayoutStrategy;
})();
GridLayoutStrategy = (function(_super) {
__extends(GridLayoutStrategy, _super);
function GridLayoutStrategy() {
this.getContainerSize = __bind(this.getContainerSize, this);
this.placeItems = __bind(this.placeItems, this);
this.reset = __bind(this.reset, this);
return GridLayoutStrategy.__super__.constructor.apply(this, arguments);
}
GridLayoutStrategy.prototype.reset = function() {
GridLayoutStrategy.__super__.reset.apply(this, arguments);
return this.rowHeight = Math.floor(this.options.height * this.columnWidth / this.options.width);
};
GridLayoutStrategy.prototype.placeItems = function(images) {
var border, col, image, row, x, y, _i, _len, _results;
if (this.index === 0 && images.length < this.columns) {
this.columns = images.length;
this.columnWidth = this.options.width;
this.rowHeight = this.options.height;
}
border = this.options.border * 2;
_results = [];
for (_i = 0, _len = images.length; _i < _len; _i++) {
image = images[_i];
col = this.index % this.columns;
row = Math.floor(this.index / this.columns);
x = col * (this.columnWidth + this.options.gap);
y = row * (this.rowHeight + this.options.gap);
image.layout(x, y, this.columnWidth - border, Math.floor(this.rowHeight - border));
_results.push(this.index += 1);
}
return _results;
};
GridLayoutStrategy.prototype.getContainerSize = function() {
var size;
size = {};
size.height = Math.ceil(1.0 * this.index / this.columns) * (this.rowHeight + this.options.gap + this.options.border);
if (this.options.hanging === 'hide' && this.index % this.columns !== 0) {
size.height -= this.rowHeight + this.options.gap + this.options.border;
}
if (this.index <= this.columns) {
size.width = this.columnWidth * this.index + this.options.gap * this.index - 1;
} else {
size.width = this.width;
}
return size;
};
return GridLayoutStrategy;
})(LayoutStrategy);
VerticalFlowLayoutStrategy = (function(_super) {
__extends(VerticalFlowLayoutStrategy, _super);
function VerticalFlowLayoutStrategy() {
this.placeItems = __bind(this.placeItems, this);
this.reset = __bind(this.reset, this);
return VerticalFlowLayoutStrategy.__super__.constructor.apply(this, arguments);
}
VerticalFlowLayoutStrategy.prototype.reset = function() {
var col, _i, _ref, _results;
VerticalFlowLayoutStrategy.__super__.reset.apply(this, arguments);
this.columnHeights = [];
this.columnImages = [];
_results = [];
for (col = _i = 0, _ref = this.columns - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; col = 0 <= _ref ? ++_i : --_i) {
this.columnImages[col] = [];
_results.push(this.columnHeights[col] = 0);
}
return _results;
};
VerticalFlowLayoutStrategy.prototype.placeItems = function(images) {
var columnIndex, columnWidth, columns, highestColumn, highestHeight, image, imageHeight, imageWidth, lastInHighestColumn, lastInHighestColumnHeight, lowestColumn, lowestHeight, newLowestHeight, _i, _len;
if (this.index === 0 && images.length < this.columns) {
this.columns = images.length;
this.columnWidth = this.options.width;
}
columns = this.columns;
columnWidth = this.columnWidth;
imageWidth = columnWidth - this.options.border * 2;
for (_i = 0, _len = images.length; _i < _len; _i++) {
image = images[_i];
imageHeight = image.naturalHeight * imageWidth * 1.0 / image.naturalWidth;
columnIndex = this.index % columns;
this.columnImages[columnIndex].push(image);
image.layout(columnIndex * columnWidth + this.options.gap * columnIndex, this.columnHeights[columnIndex] + this.options.gap, imageWidth, imageHeight);
this.columnHeights[columnIndex] += imageHeight + this.options.gap + this.options.border * 2;
this.index += 1;
}
while (true) {
lowestColumn = $.inArray(Math.min.apply(null, this.columnHeights), this.columnHeights);
highestColumn = $.inArray(Math.max.apply(null, this.columnHeights), this.columnHeights);
if (lowestColumn === highestColumn) {
return;
}
lastInHighestColumn = this.columnImages[highestColumn].pop();
if (!lastInHighestColumn) {
return;
}
lastInHighestColumnHeight = lastInHighestColumn.naturalHeight * imageWidth / lastInHighestColumn.naturalWidth + this.options.gap + this.options.border * 2;
lowestHeight = this.columnHeights[lowestColumn];
highestHeight = this.columnHeights[highestColumn];
newLowestHeight = lowestHeight + lastInHighestColumnHeight;
if (newLowestHeight >= highestHeight) {
return;
}
this.columnImages[lowestColumn].push(lastInHighestColumn);
lastInHighestColumn.layout(lowestColumn * (this.columnWidth + this.options.gap), this.columnHeights[lowestColumn] + this.options.gap);
this.columnHeights[highestColumn] -= lastInHighestColumnHeight;
this.columnHeights[lowestColumn] += lastInHighestColumnHeight;
}
};
VerticalFlowLayoutStrategy.prototype.getContainerSize = function() {
var height, i, size, _i, _ref;
height = 0;
size = {};
for (i = _i = 0, _ref = this.columns - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) {
if (this.columnHeights[i] > height) {
height = this.columnHeights[i];
}
}
if (this.index < this.columns) {
size.width = this.columnWidth * this.index;
} else {
size.width = this.width;
}
size.height = height + this.options.gap;
return size;
};
return VerticalFlowLayoutStrategy;
})(LayoutStrategy);
HorizontalFlowLayoutStrategy = (function(_super) {
__extends(HorizontalFlowLayoutStrategy, _super);
function HorizontalFlowLayoutStrategy() {
this.getContainerSize = __bind(this.getContainerSize, this);
this.placeItems = __bind(this.placeItems, this);
this.startNewRow = __bind(this.startNewRow, this);
this.shrinkCurrentRow = __bind(this.shrinkCurrentRow, this);
this.reset = __bind(this.reset, this);
return HorizontalFlowLayoutStrategy.__super__.constructor.apply(this, arguments);
}
HorizontalFlowLayoutStrategy.prototype.reset = function() {
HorizontalFlowLayoutStrategy.__super__.reset.apply(this, arguments);
this.currentRow = [];
this.sizes = [];
this.currentRowWidth = 0;
this.rows = [this.currentRow];
this.elementSizes = [this.sizes];
this.height = 0;
return this.prevWidth = 0;
};
HorizontalFlowLayoutStrategy.prototype.shrinkCurrentRow = function(newHeight) {
var shrinkFactor, x;
x = 0;
shrinkFactor = this.options.height / newHeight;
return $.each(this.currentRow, (function(_this) {
return function(rowIndex, image) {
var imageWidth;
if (rowIndex !== _this.currentRow.length - 1 || _this.currentRowWidth < _this.prevWidth) {
imageWidth = Math.floor(_this.sizes[rowIndex] / shrinkFactor);
image.layout(x, _this.height, imageWidth, newHeight);
return x += imageWidth + _this.options.gap + _this.options.border * 2;
} else {
return image.layout(x, _this.height, _this.width - x - _this.options.border * 2, newHeight);
}
};
})(this));
};
HorizontalFlowLayoutStrategy.prototype.startNewRow = function() {
this.rows.push(this.currentRow = []);
this.elementSizes.push(this.sizes = []);
return this.currentRowWidth = 0;
};
HorizontalFlowLayoutStrategy.prototype.placeItems = function(images) {
var elementWidth, height, image, index, shrinkFactor, width, x, _i, _len;
width = this.width;
index = 0;
for (_i = 0, _len = images.length; _i < _len; _i++) {
image = images[_i];
this.currentRow.push(image);
this.sizes.push(elementWidth = image.naturalWidth / image.naturalHeight * this.options.height);
this.currentRowWidth += elementWidth + this.options.gap + this.options.border * 2;
if (this.currentRowWidth >= width + this.options.gap) {
this.currentRowWidth -= this.options.gap;
shrinkFactor = (this.currentRowWidth - (this.currentRow.length - 1) * this.options.gap - this.currentRow.length * this.options.border * 2) / (width - (this.currentRow.length - 1) * this.options.gap - this.currentRow.length * this.options.border * 2);
height = Math.floor(this.options.height / shrinkFactor);
this.shrinkCurrentRow(height);
this.height += height + this.options.gap + this.options.border * 2;
this.startNewRow();
}
index += 1;
}
if (this.currentRowWidth < this.width) {
x = 0;
return $.each(this.currentRow, (function(_this) {
return function(rowIndex, image) {
var imageWidth;
imageWidth = Math.floor(_this.sizes[rowIndex]);
image.layout(x, _this.height, imageWidth, _this.options.height);
return x += imageWidth + _this.options.gap + _this.options.border * 2;
};
})(this));
}
};
HorizontalFlowLayoutStrategy.prototype.getContainerSize = function() {
var size;
size = {};
if (this.rows.length > 1) {
size.height = this.height;
if (this.options.allowHanging && this.currentRowWidth < this.width && this.currentRowWidth > 0) {
size.height += this.options.height + this.options.gap + this.options.border * 2;
}
} else {
if (this.currentRow.length > 0) {
size.height = this.options.height + this.options.gap + this.options.border * 2;
} else {
size.height = 0;
}
}
if (this.rows.length < 2 && this.currentRowWidth > 0) {
size.width = this.currentRowWidth;
} else {
size.width = this.width;
}
return size;
};
return HorizontalFlowLayoutStrategy;
})(LayoutStrategy);
return AwesomeGallery;
})();
return window.AwesomeGallery = AwesomeGallery;
}
}
})(window.asgjQuery || window.jQuery || window.$ || jQuery || $);
}).call(this);
| jcwproductions/jcwproductions-blog | wp-content/plugins/awesome-gallery/assets/js/awesome-gallery.js | JavaScript | gpl-2.0 | 76,673 |
import pathlib
import h5py
import numpy as np
import pytest
from scipy.ndimage.filters import gaussian_filter
import dclab
from dclab.rtdc_dataset.feat_anc_plugin.plugin_feature import (
PlugInFeature, import_plugin_feature_script,
remove_plugin_feature, remove_all_plugin_features,
PluginImportError)
from dclab.rtdc_dataset.feat_anc_core.ancillary_feature import (
BadFeatureSizeWarning)
from helper_methods import retrieve_data
data_dir = pathlib.Path(__file__).parent / "data"
@pytest.fixture(autouse=True)
def cleanup_plugin_features():
"""Fixture used to cleanup plugin feature tests"""
# code run before the test
pass
# then the test is run
yield
# code run after the test
# remove our test plugin examples
remove_all_plugin_features()
def compute_single_plugin_feature(rtdc_ds):
"""Basic plugin method"""
circ_per_area = rtdc_ds["circ"] / rtdc_ds["area_um"]
return circ_per_area
def compute_multiple_plugin_features(rtdc_ds):
"""Basic plugin method with dictionary returned"""
circ_per_area = rtdc_ds["circ"] / rtdc_ds["area_um"]
circ_times_area = rtdc_ds["circ"] * rtdc_ds["area_um"]
return {"circ_per_area": circ_per_area, "circ_times_area": circ_times_area}
def compute_non_scalar_plugin_feature(rtdc_ds):
"""Basic non-scalar plugin method"""
image_gauss_filter = gaussian_filter(rtdc_ds["image"], sigma=(0, 1, 1))
return {"image_gauss_filter": image_gauss_filter}
def example_plugin_info_single_feature():
"""plugin info for a single feature"""
info = {
"method": compute_single_plugin_feature,
"description": "This plugin will compute a feature",
"long description": "Even longer description that "
"can span multiple lines",
"feature names": ["circ_per_area"],
"feature labels": ["Circularity per Area"],
"features required": ["circ", "area_um"],
"config required": [],
"method check required": lambda x: True,
"scalar feature": [True],
"version": "0.1.0",
}
return info
def example_plugin_info_multiple_feature():
"""plugin info for multiple features"""
info = {
"method": compute_multiple_plugin_features,
"description": "This plugin will compute some features",
"long description": "Even longer description that "
"can span multiple lines",
"feature names": ["circ_per_area", "circ_times_area"],
"feature labels": ["Circularity per Area", "Circularity times Area"],
"features required": ["circ", "area_um"],
"config required": [],
"method check required": lambda x: True,
"scalar feature": [True, True],
"version": "0.1.0",
}
return info
def example_plugin_info_non_scalar_feature():
"""plugin info for non-scalar feature"""
info = {
"method": compute_non_scalar_plugin_feature,
"description": "This plugin will compute a non-scalar feature",
"long description": "This non-scalar feature is a Gaussian filter of "
"the image",
"feature names": ["image_gauss_filter"],
"feature labels": ["Gaussian Filtered Image"],
"features required": ["image"],
"config required": [],
"method check required": lambda x: True,
"scalar feature": [False],
"version": "0.1.0",
}
return info
def compute_with_user_section(rtdc_ds):
"""setup a plugin method that uses user config section
The "user:n_constrictions" metadata must be set
"""
nc = rtdc_ds.config["user"]["n_constrictions"]
assert isinstance(nc, int), (
'"n_constrictions" should be an integer value.')
area_of_region = rtdc_ds["area_um"] * nc
return {"area_of_region": area_of_region}
def test_pf_attribute_ancill_info():
"""Check the plugin feature attribute input to AncillaryFeature"""
info = example_plugin_info_single_feature()
pf = PlugInFeature("circ_per_area", info)
assert pf.plugin_feature_info["feature name"] == "circ_per_area"
assert pf.plugin_feature_info["method"] is compute_single_plugin_feature
assert pf.plugin_feature_info["config required"] == []
assert pf.plugin_feature_info["features required"] == ["circ", "area_um"]
def test_pf_attribute_plugin_feature_info():
"""Check the plugin feature info attribute"""
info = example_plugin_info_single_feature()
# comparing lambda functions fails due to differing memory locations
info.pop("method check required")
pf = PlugInFeature("circ_per_area", info)
pf.plugin_feature_info.pop("method check required")
plugin_feature_info = {
"method": compute_single_plugin_feature,
"description": "This plugin will compute a feature",
"long description": "Even longer description that "
"can span multiple lines",
"feature name": "circ_per_area",
"feature label": "Circularity per Area",
"feature shape": (1,),
"features required": ["circ", "area_um"],
"config required": [],
"scalar feature": True,
"version": "0.1.0",
"plugin path": None,
"identifier": "3a3e72c4cb015424ebbe6d4af63f2170",
}
assert pf.plugin_feature_info == plugin_feature_info
def test_pf_attributes():
"""Check the plugin feature attributes"""
plugin_path = data_dir / "feat_anc_plugin_creative.py"
plugin_list = dclab.load_plugin_feature(plugin_path)
pf1, pf2 = plugin_list
plugin_file_info = import_plugin_feature_script(plugin_path)
assert pf1.feature_name == pf1.feature_name == \
plugin_file_info["feature names"][0]
assert pf2.feature_name == pf2.feature_name == \
plugin_file_info["feature names"][1]
assert plugin_path.samefile(pf1.plugin_path)
assert plugin_path.samefile(pf1.plugin_feature_info["plugin path"])
assert plugin_path.samefile(pf2.plugin_path)
assert plugin_path.samefile(pf2.plugin_feature_info["plugin path"])
assert pf1._original_info == plugin_file_info
assert pf2._original_info == plugin_file_info
def test_pf_attributes_af_inherited():
"""Check the plugin feature attributes inherited from AncillaryFeature"""
plugin_path = data_dir / "feat_anc_plugin_creative.py"
plugin_list = dclab.load_plugin_feature(plugin_path)
pf, _ = plugin_list
plugin_file_info = import_plugin_feature_script(plugin_path)
assert pf.feature_name == plugin_file_info["feature names"][0]
assert pf.method == plugin_file_info["method"]
assert pf.req_config == plugin_file_info["config required"]
assert pf.req_features == plugin_file_info["features required"]
assert pf.req_func == plugin_file_info["method check required"]
assert pf.priority == 0
def test_pf_bad_plugin_feature_name_list():
"""Basic test of a bad feature name for PlugInFeature"""
info = example_plugin_info_single_feature()
info["feature names"] = "Peter-Pan's Best Friend!"
with pytest.raises(ValueError, match="must be a list, got"):
PlugInFeature("Peter-Pan's Best Friend!", info)
def test_pf_bad_plugin_feature_name():
"""Basic test of a bad feature name for PlugInFeature"""
info = example_plugin_info_single_feature()
info["feature names"] = ["Peter-Pan's Best Friend!"]
with pytest.raises(ValueError, match="only contain lower-case characters"):
PlugInFeature("Peter-Pan's Best Friend!", info)
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_exists_in_hierarchy():
"""Test that RTDCHierarchy works with PlugInFeature"""
info = example_plugin_info_single_feature()
pf = PlugInFeature("circ_per_area", info)
h5path = retrieve_data("fmt-hdf5_fl_2018.zip")
with dclab.new_dataset(h5path) as ds:
assert pf.feature_name in ds
assert dclab.dfn.feature_exists(pf.feature_name)
child = dclab.new_dataset(ds)
assert pf.feature_name in child
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_export_and_load():
"""Check that exported and loaded hdf5 file will keep a plugin feature"""
h5path = retrieve_data("fmt-hdf5_fl_2018.zip")
# initialize PlugInFeature instance
info = example_plugin_info_single_feature()
pf = PlugInFeature("circ_per_area", info)
with dclab.new_dataset(h5path) as ds:
# extract the feature information from the dataset
assert pf in PlugInFeature.features
circ_per_area = ds[pf.feature_name]
# export the data to a new file
expath = h5path.with_name("exported.rtdc")
ds.export.hdf5(expath, features=ds.features_innate + [pf.feature_name])
# make sure that worked
with h5py.File(expath, "r") as h5:
assert pf.feature_name in h5["events"]
assert np.allclose(h5["events"][pf.feature_name], circ_per_area)
# now check again with dclab
with dclab.new_dataset(expath) as ds2:
assert pf in PlugInFeature.features
assert pf.feature_name in ds2
assert pf.feature_name in ds2.features_innate
assert np.allclose(ds2[pf.feature_name], circ_per_area)
# and a control check
remove_plugin_feature(pf)
assert pf.feature_name not in ds2
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_export_non_scalar():
h5path = retrieve_data("fmt-hdf5_image-bg_2020.zip")
# initialize PlugInFeature instance
info = example_plugin_info_non_scalar_feature()
pf = PlugInFeature("image_gauss_filter", info)
with dclab.new_dataset(h5path) as ds:
# extract the feature information from the dataset
assert pf in PlugInFeature.features
image_gauss_filter = ds[pf.feature_name]
# export the data to a new file
expath = h5path.with_name("exported.rtdc")
with pytest.warns(UserWarning, match="out on a limb"):
ds.export.hdf5(expath,
features=[pf.feature_name])
# make sure that worked
with h5py.File(expath, "r") as h5:
assert pf.feature_name in h5["events"]
assert np.allclose(h5["events"][pf.feature_name], image_gauss_filter)
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_export_non_scalar_single_event():
h5path = retrieve_data("fmt-hdf5_image-bg_2020.zip")
# initialize PlugInFeature instance
info = example_plugin_info_non_scalar_feature()
info["feature shapes"] = [(80, 250)]
pf = PlugInFeature("image_gauss_filter", info)
with dclab.new_dataset(h5path) as ds:
# extract the feature information from the dataset
assert pf in PlugInFeature.features
image_gauss_filter = ds[pf.feature_name]
# export the data to a new file
expath = h5path.with_name("exported.rtdc")
ds.export.hdf5(expath, features=["image", pf.feature_name])
# write another single event
with dclab.RTDCWriter(expath) as hw:
hw.store_feature(pf.feature_name, ds["image"][0])
hw.store_feature("image", ds["image"][0])
# make sure that worked
with h5py.File(expath, "r") as h5:
assert pf.feature_name in h5["events"]
assert np.allclose(h5["events"][pf.feature_name][:-1],
image_gauss_filter)
assert np.allclose(h5["events"][pf.feature_name][-1],
h5["events/image"][0])
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_export_non_scalar_no_warning():
h5path = retrieve_data("fmt-hdf5_image-bg_2020.zip")
# initialize PlugInFeature instance
info = example_plugin_info_non_scalar_feature()
info["feature shapes"] = [(80, 250)]
pf = PlugInFeature("image_gauss_filter", info)
with dclab.new_dataset(h5path) as ds:
# extract the feature information from the dataset
assert pf in PlugInFeature.features
image_gauss_filter = ds[pf.feature_name]
# export the data to a new file
expath = h5path.with_name("exported.rtdc")
ds.export.hdf5(expath, features=[pf.feature_name])
# make sure that worked
with h5py.File(expath, "r") as h5:
assert pf.feature_name in h5["events"]
assert np.allclose(h5["events"][pf.feature_name], image_gauss_filter)
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_export_non_scalar_bad_shape():
h5path = retrieve_data("fmt-hdf5_image-bg_2020.zip")
# initialize PlugInFeature instance
info = example_plugin_info_non_scalar_feature()
info["feature shapes"] = [(42, 27)]
pf = PlugInFeature("image_gauss_filter", info)
with dclab.new_dataset(h5path) as ds:
# extract the feature information from the dataset
assert pf in PlugInFeature.features
# export the data to a new file
expath = h5path.with_name("exported.rtdc")
with pytest.raises(ValueError, match="Bad shape"):
ds.export.hdf5(expath, features=[pf.feature_name])
def test_pf_feature_exists():
"""Basic check that the plugin feature name exists in definitions"""
plugin_path = data_dir / "feat_anc_plugin_creative.py"
plugin_list = dclab.load_plugin_feature(plugin_path)
assert dclab.dfn.feature_exists(plugin_list[0].feature_name)
assert dclab.dfn.feature_exists(plugin_list[1].feature_name)
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_filtering_with_plugin_feature():
"""Filtering with plugin feature"""
h5path = retrieve_data("fmt-hdf5_fl_2018.zip")
with dclab.new_dataset(h5path) as ds:
info = example_plugin_info_single_feature()
pf = PlugInFeature("circ_per_area", info)
ds.config["filtering"][f"{pf.feature_name} min"] = 0.030
ds.config["filtering"][f"{pf.feature_name} max"] = 0.031
ds.apply_filter()
assert np.sum(ds.filter.all) == 1
assert ds.filter.all[4]
def test_pf_import_plugin_info():
"""Check the plugin test example info is a dict"""
plugin_path = data_dir / "feat_anc_plugin_creative.py"
info = import_plugin_feature_script(plugin_path)
assert isinstance(info, dict)
def test_pf_import_plugin_info_bad_path():
"""Raise error when a bad pathname is given"""
bad_plugin_path = "not/a/real/path/plugin.py"
with pytest.raises(PluginImportError, match="could be not be found"):
import_plugin_feature_script(bad_plugin_path)
def test_pf_incorrect_input_info():
"""Raise error when info is not a dictionary"""
info = ["this", "is", "not", "a", "dict"]
with pytest.raises(ValueError, match="must be a dict"):
PlugInFeature("feature_1", info)
def test_pf_incorrect_input_feature_name():
"""Raise error when the feature_name doesn't match info feature name"""
info = example_plugin_info_single_feature()
# `feature_name` is "circ_per_area" in info
with pytest.raises(ValueError, match="is not defined"):
PlugInFeature("not_the_correct_name", info)
def test_pf_incorrect_input_method():
"""Raise error when method is not callable"""
info = example_plugin_info_single_feature()
# set `info["method"]` to something that isn't callable
info["method"] = "this_is_a_string"
with pytest.raises(ValueError, match="is not callable"):
PlugInFeature("circ_per_area", info)
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_initialize_plugin_after_loading():
"""plugin feature loads correctly after feature added to hdf5 file"""
h5path = retrieve_data("fmt-hdf5_fl_2018.zip")
with dclab.new_dataset(h5path) as ds:
circ_per_area = compute_single_plugin_feature(ds)
with h5py.File(h5path, "a") as h5:
h5["events"]["circ_per_area"] = circ_per_area
with dclab.new_dataset(h5path) as ds:
assert "circ_per_area" not in ds
info = example_plugin_info_single_feature()
PlugInFeature("circ_per_area", info)
assert "circ_per_area" in ds
assert "circ_per_area" in ds.features_innate
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_initialize_plugin_feature_single():
"""Check that single plugin feature exists independant of loaded dataset"""
ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip"))
info = example_plugin_info_single_feature()
PlugInFeature("circ_per_area", info)
assert "circ_per_area" in ds
circ_per_area = ds["circ_per_area"]
assert np.allclose(circ_per_area, ds["circ"] / ds["area_um"])
# check that PlugInFeature exists independent of loaded ds
ds2 = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip"))
assert "circ_per_area" in ds2
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_initialize_plugin_feature_non_scalar():
"""Check that the non-scalar plugin feature works"""
ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip"))
info = example_plugin_info_non_scalar_feature()
PlugInFeature("image_gauss_filter", info)
assert "image_gauss_filter" in ds
image_gauss_filter = ds["image_gauss_filter"]
assert np.allclose(image_gauss_filter,
gaussian_filter(ds["image"], sigma=(0, 1, 1)))
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_initialize_plugin_features_multiple():
"""Check multiple plugin features exist independant of loaded dataset"""
ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip"))
assert "circ_per_area" not in ds.features_innate
assert "circ_times_area" not in ds.features_innate
info = example_plugin_info_multiple_feature()
PlugInFeature("circ_per_area", info)
PlugInFeature("circ_times_area", info)
assert "circ_per_area" in ds
assert "circ_times_area" in ds
assert dclab.dfn.feature_exists("circ_per_area")
assert dclab.dfn.feature_exists("circ_times_area")
circ_per_area = ds["circ_per_area"]
circ_times_area = ds["circ_times_area"]
assert np.allclose(circ_per_area, ds["circ"] / ds["area_um"])
assert np.allclose(circ_times_area, ds["circ"] * ds["area_um"])
def test_pf_input_no_feature_labels():
"""Check that feature labels are populated even if not given"""
info = example_plugin_info_single_feature()
info.pop("feature labels")
feature_name = "circ_per_area"
pf = PlugInFeature(feature_name, info)
assert dclab.dfn.feature_exists(feature_name)
label = dclab.dfn.get_feature_label(feature_name)
assert label == "Plugin feature {}".format(feature_name)
assert label == pf.plugin_feature_info["feature label"]
def test_pf_input_no_scalar_feature():
"""Check that scalar feature bools are populated even if not given"""
info = example_plugin_info_single_feature()
info.pop("scalar feature")
pf = PlugInFeature("circ_per_area", info)
assert pf.plugin_feature_info["scalar feature"]
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_load_plugin():
"""Basic check for loading a plugin feature via a script"""
ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip"))
assert "circ_per_area" not in ds.features_innate
assert "circ_times_area" not in ds.features_innate
plugin_path = data_dir / "feat_anc_plugin_creative.py"
plugin_list = dclab.load_plugin_feature(plugin_path)
assert isinstance(plugin_list[0], PlugInFeature)
assert isinstance(plugin_list[1], PlugInFeature)
assert "circ_per_area" in ds
assert "circ_times_area" in ds
circ_per_area = ds["circ_per_area"]
circ_times_area = ds["circ_times_area"]
assert np.allclose(circ_per_area, ds["circ"] / ds["area_um"])
assert np.allclose(circ_times_area, ds["circ"] * ds["area_um"])
def test_pf_minimum_info_input():
"""Only method and feature names are required to create PlugInFeature"""
info = {"method": compute_single_plugin_feature,
"feature names": ["circ_per_area"]}
pf = PlugInFeature("circ_per_area", info)
# check that all other plugin_feature_info is populated
assert "method" in pf.plugin_feature_info
assert callable(pf.plugin_feature_info["method"])
assert "description" in pf.plugin_feature_info
assert "long description" in pf.plugin_feature_info
assert "feature name" in pf.plugin_feature_info
assert "feature label" in pf.plugin_feature_info
assert "features required" in pf.plugin_feature_info
assert "config required" in pf.plugin_feature_info
assert "method check required" in pf.plugin_feature_info
assert "scalar feature" in pf.plugin_feature_info
assert "version" in pf.plugin_feature_info
assert "plugin path" in pf.plugin_feature_info
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_remove_all_plugin_features():
"""Remove all plugin features at once"""
ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip"))
assert "circ_per_area" not in ds.features_innate
assert "circ_times_area" not in ds.features_innate
plugin_path = data_dir / "feat_anc_plugin_creative.py"
dclab.load_plugin_feature(plugin_path)
assert "circ_per_area" in ds
assert "circ_times_area" in ds
assert dclab.dfn.feature_exists("circ_per_area")
assert dclab.dfn.feature_exists("circ_times_area")
remove_all_plugin_features()
assert "circ_per_area" not in ds
assert "circ_times_area" not in ds
assert not dclab.dfn.feature_exists("circ_per_area")
assert not dclab.dfn.feature_exists("circ_times_area")
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_remove_plugin_feature():
"""Remove individual plugin features"""
ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip"))
assert "circ_per_area" not in ds
assert "circ_times_area" not in ds
plugin_path = data_dir / "feat_anc_plugin_creative.py"
plugin_list = dclab.load_plugin_feature(plugin_path)
assert len(plugin_list) == 2
assert "circ_per_area" in ds
assert "circ_per_area" not in ds.features_innate
assert "circ_times_area" in ds
assert "circ_times_area" not in ds.features_innate
assert dclab.dfn.feature_exists("circ_per_area")
assert dclab.dfn.feature_exists("circ_times_area")
remove_plugin_feature(plugin_list[0])
remove_plugin_feature(plugin_list[1])
assert "circ_per_area" not in ds
assert "circ_times_area" not in ds
assert not dclab.dfn.feature_exists("circ_per_area")
assert not dclab.dfn.feature_exists("circ_times_area")
with pytest.raises(TypeError,
match="hould be an instance of PlugInFeature"):
not_a_plugin_instance = [4, 6, 5]
remove_plugin_feature(not_a_plugin_instance)
def test_pf_try_existing_feature_fails():
"""An existing feature name is not allowed"""
info = example_plugin_info_single_feature()
info["feature names"] = ["deform"]
with pytest.raises(ValueError, match="Feature 'deform' already exists"):
PlugInFeature("deform", info)
def test_pf_with_empty_feature_label_string():
"""An empty string is replaced with a real feature label
Show that an empty `feature_label` will still give a descriptive
feature label. See `dclab.dfn._add_feature_to_definitions` for details.
"""
info = example_plugin_info_single_feature()
info["feature labels"] = [""]
feature_name = "circ_per_area"
PlugInFeature(feature_name, info)
assert dclab.dfn.feature_exists("circ_per_area")
label = dclab.dfn.get_feature_label("circ_per_area")
assert label != ""
assert label == "Plugin feature {}".format(feature_name)
def test_pf_with_feature_label():
"""Check that a plugin feature label is added to definitions"""
info = example_plugin_info_single_feature()
info["feature labels"] = ["Circ / Area [1/µm²]"]
feature_name = "circ_per_area"
PlugInFeature(feature_name, info)
assert dclab.dfn.feature_exists("circ_per_area")
label = dclab.dfn.get_feature_label("circ_per_area")
assert label == "Circ / Area [1/µm²]"
def test_pf_with_no_feature_label():
"""A feature label of None is replaced with a real feature label
Show that `feature_label=None` will still give a descriptive
feature label. See `dclab.dfn._add_feature_to_definitions` for details.
"""
info = example_plugin_info_single_feature()
info["feature labels"] = [None]
feature_name = "circ_per_area"
PlugInFeature(feature_name, info)
assert dclab.dfn.feature_exists("circ_per_area")
label = dclab.dfn.get_feature_label("circ_per_area")
assert label is not None
assert label == "Plugin feature {}".format(feature_name)
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_with_user_config_section():
"""Use a plugin feature with the user defined config section"""
info = {"method": compute_with_user_section,
"feature names": ["area_of_region"],
"config required": [["user", ["n_constrictions"]]]}
PlugInFeature("area_of_region", info)
ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip"))
assert "area_of_region" not in ds, "not available b/c missing metadata"
# add some metadata to the user config section
metadata = {"channel": True,
"n_constrictions": 3}
ds.config["user"].update(metadata)
assert ds.config["user"] == metadata
assert "area_of_region" in ds, "available b/c metadata is set"
area_of_region1 = ds["area_of_region"]
area_of_region1_calc = (ds["area_um"] *
ds.config["user"]["n_constrictions"])
assert np.allclose(area_of_region1, area_of_region1_calc)
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_with_user_config_section_fails():
"""Use a plugin feature with the user defined config section"""
info = {"method": compute_with_user_section,
"feature names": ["area_of_region"],
"config required": [["user", ["n_constrictions"]]]}
PlugInFeature("area_of_region", info)
ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip"))
# show that the plugin feature is not available before setting the
# user metadata
ds.config["user"].clear()
with pytest.raises(KeyError,
match=r"Feature \'area_of_region\' does not exist"):
ds["area_of_region"]
# show that the plugin fails when the user metadata type is wrong
ds.config["user"]["n_constrictions"] = 4.99
with pytest.raises(AssertionError, match="should be an integer value"):
ds["area_of_region"]
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_wrong_data_shape_1():
h5path = retrieve_data("fmt-hdf5_fl_2018.zip")
with dclab.new_dataset(h5path) as ds:
info = example_plugin_info_single_feature()
info["scalar feature"] = [False]
pf = PlugInFeature("circ_per_area", info)
with pytest.raises(ValueError, match="is not a scalar feature"):
ds[pf.feature_name]
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_wrong_data_shape_2():
h5path = retrieve_data("fmt-hdf5_fl_2018.zip")
with dclab.new_dataset(h5path) as ds:
info = example_plugin_info_single_feature()
info["scalar feature"] = [True]
info["method"] = lambda x: np.arange(len(ds) * 2).reshape(-1, 2)
pf = PlugInFeature("circ_per_area", info)
with pytest.raises(ValueError, match="is a scalar feature"):
ds[pf.feature_name]
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_wrong_length_1():
"""plugin feature should have same length"""
h5path = retrieve_data("fmt-hdf5_fl_2018.zip")
with dclab.new_dataset(h5path) as ds:
info = example_plugin_info_single_feature()
info["method"] = lambda x: np.arange(len(ds) // 2)
pf = PlugInFeature("circ_per_area", info)
with pytest.warns(BadFeatureSizeWarning,
match="to match event number"):
ds[pf.feature_name]
@pytest.mark.filterwarnings(
"ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning")
def test_pf_wrong_length_2():
"""plugin feature should have same length"""
h5path = retrieve_data("fmt-hdf5_fl_2018.zip")
with dclab.new_dataset(h5path) as ds:
info = example_plugin_info_single_feature()
info["method"] = lambda x: np.arange(len(ds) * 2)
pf = PlugInFeature("circ_per_area", info)
with pytest.warns(BadFeatureSizeWarning,
match="to match event number"):
ds[pf.feature_name]
if __name__ == "__main__":
# Run all tests
loc = locals()
for key in list(loc.keys()):
if key.startswith("test_") and hasattr(loc[key], "__call__"):
loc[key]()
remove_all_plugin_features()
| ZellMechanik-Dresden/dclab | tests/test_rtdc_feat_anc_plugin.py | Python | gpl-2.0 | 29,760 |
package net.idtoki.instelec.controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import org.apache.torque.TorqueException;
import org.apache.torque.util.Criteria;
import net.idtoki.instelec.manager.TareasManager;
import net.idtoki.instelec.group.TareasGroupBean;
import net.idtoki.instelec.helper.TareasHelper;
import net.idtoki.instelec.model.TareasPeer;
import net.idtoki.instelec.model.Tareas;
import net.idtoki.instelec.manager.OrdenestrabajoManager;
import net.idtoki.instelec.group.OrdenestrabajoGroupBean;
import net.idtoki.instelec.model.OrdenestrabajoPeer;
import net.idtoki.instelec.helper.OrdenestrabajoHelper;
import net.idtoki.instelec.manager.TipotareasManager;
import net.idtoki.instelec.group.TipotareasGroupBean;
import net.idtoki.instelec.model.TipotareasPeer;
import net.idtoki.instelec.helper.TipotareasHelper;
import net.idtoki.instelec.manager.CategoriasManager;
import net.idtoki.instelec.group.CategoriasGroupBean;
import net.idtoki.instelec.model.CategoriasPeer;
import net.idtoki.instelec.helper.CategoriasHelper;
import net.idtoki.instelec.helper.MaterialesHelper;
import net.zylk.tools.ajax.AjaxUtils;
import net.zylk.tools.ajax.AjaxUtils.DinamicGridBean;
import net.zylk.tools.format.FormatUtils;
import net.zylk.tools.pdf.PdfUtils;
import net.zylk.tools.xml.XmlUtils;
import net.zylk.torque.TorqueUtils;
import net.zylk.web.WebUtils;
/**
* The skeleton for this class was autogenerated by Torque on:
*
* [Thu Aug 10 13:35:35 CEST 2006]
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*/
public class TareasController
extends net.idtoki.instelec.controller.BaseTareasController
{
private static final Logger logger = Logger.getLogger("net.idtoki.instelec.controller.TareasController");
private TransformerFactory tFactory = TransformerFactory.newInstance();
private Transformer tareas_transformer = null;
private Transformer tareass_transformer = null;
public void init(ServletConfig config)
{
super.init();
ResourceBundle resource = ResourceBundle.getBundle("net/idtoki/instelec/app/config/app-config");
File tareas = new File(resource.getString("app.xsl.templates.dir")+"/PdfTareas.xslt");
Source xslSource = new StreamSource(tareas);
File tareass = new File(resource.getString("app.xsl.templates.dir")+"/PdfListaTareas.xslt");
Source xslSourceT = new StreamSource(tareass);
try{
tareas_transformer = tFactory.newTransformer(xslSource);
tareass_transformer = tFactory.newTransformer(xslSourceT);
}catch (Exception e){
e.printStackTrace();
}
}
//Función para la inserción/actualización de registros
public void serviceAddTareas(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
//Con esto se consigue transformar el request a UTF
//para temas de acentos y otros caracteres
utf8RequestService(request);
//recojo los parametros del formulario y doy de alta un nuevo elmento
try
{
Tareas elTareas = TareasHelper.createObj(request);
TareasGroupBean gbTareas = new TareasGroupBean();
elTareas.setFechainicio(FormatUtils.ddmmaaaa2aaaammdd(elTareas.getFechainicio(),"-",""));
gbTareas.setElemento(elTareas);
gbTareas.save();
}
catch(TorqueException te)
{
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
//Función para la eliminación de un registro
//este método invoca al método public void deleteTareas(int idBorrar)
//definido en el TareasManager
public void serviceDeleteTareas(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
int idBorrar=-1;
idBorrar=WebUtils.getintParam(request, "borrarId");
if (idBorrar!=-1)
if (TareasManager.borraTareas(idBorrar))
WebUtils.writeXmlResponse(response,XmlUtils.buildXmlOKResponse("ISO-8859-1"));
else
WebUtils.writeXmlResponse(response,XmlUtils.buildXmlNotOKResponse("ISO-8859-1"));
}
// Funciones para las ordenaciones y filtrados de información
private Criteria ordenacion(Criteria c,String CampoOrdenacion,String OrdenOrdenacion)
{
if((OrdenOrdenacion != null )&& (OrdenOrdenacion.compareTo("ASC")==0))
if ((CampoOrdenacion != null))
{
c.addAscendingOrderByColumn(CampoOrdenacion.toString());
}
if ((OrdenOrdenacion != null) && (OrdenOrdenacion.compareTo("DESC")==0))
if ((CampoOrdenacion != null))
{
c.addDescendingOrderByColumn(CampoOrdenacion.toString());
}
return c;
}
private Criteria filtro(Criteria c,int filtro)
{
String cadena = null;
switch (filtro)
{
case 1:
//Caso uno de Filtrado
//c.add(Campo,valor);
break;
case 2:
//Caso dos de Filtrado
//c.add(Campo,valor);
break;
default:
//caso por defecto
break;
}
return c;
}
public StringBuffer replaceStringBuffer (StringBuffer strBA, String strOrigen, String strDestino)
{
return new StringBuffer(strBA.toString().replaceAll(strOrigen,strDestino));
}
private Criteria criteriaTareasTableContent(HttpServletRequest request,Criteria c) throws IOException, ServletException
{
String param = "";
param = WebUtils.getStringParam(request, new OrdenestrabajoHelper().getIdordenName());
if(param != null)
TorqueUtils.addEqualCriteria(c,TareasPeer.IDORDEN,param);
param = WebUtils.getStringParam(request, new TipotareasHelper().getIdtipotareaName());
if(param != null)
TorqueUtils.addEqualCriteria(c,TareasPeer.IDTIPOTAREA,param);
param = WebUtils.getStringParam(request, new CategoriasHelper().getIdcategoriaName());
if(param != null)
TorqueUtils.addEqualCriteria(c,TareasPeer.IDCATEGORIA,param);
String paramSortCol = WebUtils.getStringParam(request, "sort_col");
String paramSortDir = WebUtils.getStringParam(request, "sort_dir");
int paramFiltro = WebUtils.getintParam(request, "filtro");
c = ordenacion(c,paramSortCol,paramSortDir);
c = filtro(c,paramFiltro);
return c;
}
public String getPathElementTareas(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, TorqueException
{
Criteria c= new Criteria();
String strPath = "";
int claveId=-1;
int claveFkId=-1;
claveId=WebUtils.getintParam(request, "tareas.IDTAREA");
if (claveId!=-1)
{
c.add(TareasPeer.IDTAREA, claveId);
TareasGroupBean trgb = TareasManager.getTareass(c);
strPath = trgb.getTareas(0).getPathTareasParsed(request.getQueryString());
}
return "<path>" + strPath + "</path>";
}
public String getPathTableContentTareas(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, TorqueException
{
Criteria c= new Criteria();
String strPath = "";
int claveId=-1;
claveId=WebUtils.getintParam(request, "ordenestrabajo.IDORDEN");
if(claveId != -1){
strPath = OrdenestrabajoManager.getOrdenestrabajo(claveId).getPathOrdenestrabajoParsed(request.getQueryString());
}
claveId=WebUtils.getintParam(request, "tipotareas.IDTIPOTAREA");
if(claveId != -1){
strPath = TipotareasManager.getTipotareas(claveId).getPathTipotareasParsed(request.getQueryString());
}
claveId=WebUtils.getintParam(request, "categorias.IDCATEGORIA");
if(claveId != -1){
strPath = CategoriasManager.getCategorias(claveId).getPathCategoriasParsed(request.getQueryString());
}
return "<path>" + strPath + "</path>";
}
public void serviceTareasTableContent(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, TorqueException
{
utf8RequestService(request);
int numElemPedidosBD = 40;
int gap = 0;//gap = viewedRows - numElemVisiblesUltPag
DinamicGridBean dgb = WebUtils.getDinamicGridBeanParam(request,numElemPedidosBD,gap);
Criteria c =TareasManager.buildSearchCriteria(dgb);
c =criteriaTareasTableContent(request,c);
TareasGroupBean cgb = TareasManager.getTareass(c);
dgb.setTotalSize(cgb.getTotalSize());
String[] methodos= new String[] {
TareasHelper.FECHAINICIO_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.HORAS_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.IDORDEN_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.IDTIPOTAREA_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.IDCATEGORIA_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.OBSERVACIONES_GET_METHOD_NAME+"TareasParsed"
,"getHijosMaterialesTareas"
,"getEditTareas"
,"getDeleteTareas"
};
StringBuffer cadena=null;
cadena = AjaxUtils.buildXmlAjaxResponseTableContentFromListObj(cgb.getAlmacen(),methodos,TareasHelper.IDTAREA_GET_METHOD_NAME, dgb,"ISO-8859-1");
cadena.insert(cadena.indexOf("</ajax-response>"),"<response type='object' id='divPath'>" + getPathTableContentTareas(request,response) + "</response>");
xmlResponseService(response,cadena);
}
public void serviceTareasUlContent(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
utf8RequestService(request);
String[] methodos= new String[] {
"getULContentTareasParsed"
};
String param = WebUtils.getStringParam(request, "value");
if(param==null || param.length() <= 0)
param = WebUtils.getStringParam(request, new MaterialesHelper().getIdtareaName());
TareasGroupBean mgb = TareasManager.getTareass(TareasManager.buildSearchCriteria(param));
simpleResponseService(response, AjaxUtils.buildAjaxULContentFromListObj(mgb.getAlmacen(),methodos, TareasHelper.COMPLEX_ID_GET_METHOD,"Tareas"));
}
public void serviceTareasElement(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, TorqueException
{
StringBuffer cadena=null;
Criteria c= new Criteria();
int claveId=-1;
claveId=WebUtils.getintParam(request, "tareas.IDTAREA");
if (claveId!=-1)
{
c.add(TareasPeer.IDTAREA, claveId);
}
c.addAscendingOrderByColumn(TareasPeer.IDTAREA);
TareasGroupBean trgb = TareasManager.getTareass(c);
if (trgb.getTotalSize()!=0)
{
String [] parametros={
TareasHelper.IDTAREA_GET_METHOD_NAME
,TareasHelper.FECHAINICIO_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.HORAS_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.IDORDEN_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.IDTIPOTAREA_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.IDCATEGORIA_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.OBSERVACIONES_GET_METHOD_NAME+"TareasParsed"
,"getImporteCalculadoTareasParsed"
,"getManoObraCalculadoTareasParsed"
};
cadena=trgb.buildXml(parametros,null,"ISO-8859-1");
cadena.insert(cadena.indexOf("</result>"),getPathElementTareas(request,response));
}
xmlResponseService(response, cadena);
}
protected StringBuffer updateIdtareaResponseCallBack(String s)
{
ArrayList a = AjaxUtils.splitIdFields(s);
return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getIdtareaTareasParsed());
}
protected StringBuffer updateFechainicioResponseCallBack(String s)
{
ArrayList a = AjaxUtils.splitIdFields(s);
return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getFechainicioTareasParsed());
}
protected StringBuffer updateHorasResponseCallBack(String s)
{
ArrayList a = AjaxUtils.splitIdFields(s);
return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getHorasTareasParsed());
}
protected StringBuffer updateIdordenResponseCallBack(String s)
{
ArrayList a = AjaxUtils.splitIdFields(s);
return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getIdordenTareasParsed());
}
protected StringBuffer updateIdtipotareaResponseCallBack(String s)
{
ArrayList a = AjaxUtils.splitIdFields(s);
return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getIdtipotareaTareasParsed());
}
protected StringBuffer updateIdcategoriaResponseCallBack(String s)
{
ArrayList a = AjaxUtils.splitIdFields(s);
return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getIdcategoriaTareasParsed());
}
protected StringBuffer updateObservacionesResponseCallBack(String s)
{
ArrayList a = AjaxUtils.splitIdFields(s);
return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getObservacionesTareasParsed());
}
public void serviceTareasOrdenestrabajo(HttpServletRequest request, HttpServletResponse response) throws IOException, TorqueException, ServletException
{
String cadena=null;
Criteria c= new Criteria();
int claveId=-1;
claveId=WebUtils.getintParam(request, "ordenestrabajo.IDORDEN");
if (claveId!=-1)
{
c.add(OrdenestrabajoPeer.IDORDEN, claveId);
}
c.addAscendingOrderByColumn(OrdenestrabajoPeer.IDORDEN);
OrdenestrabajoGroupBean trgb = OrdenestrabajoManager.getOrdenestrabajos(c);
if (trgb.getTotalSize()!=0)
{
cadena = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>";
cadena = cadena + "<result><tareas.IDORDEN>" + trgb.getOrdenestrabajo(0).getULContentOrdenestrabajoParsed() + "</tareas.IDORDEN></result>";
}
xmlResponseService(response, new StringBuffer(cadena));
}
public void serviceTareasTipotareas(HttpServletRequest request, HttpServletResponse response) throws IOException, TorqueException, ServletException
{
String cadena=null;
Criteria c= new Criteria();
int claveId=-1;
claveId=WebUtils.getintParam(request, "tipotareas.IDTIPOTAREA");
if (claveId!=-1)
{
c.add(TipotareasPeer.IDTIPOTAREA, claveId);
}
c.addAscendingOrderByColumn(TipotareasPeer.IDTIPOTAREA);
TipotareasGroupBean trgb = TipotareasManager.getTipotareass(c);
if (trgb.getTotalSize()!=0)
{
cadena = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>";
cadena = cadena + "<result><tareas.IDTIPOTAREA>" + trgb.getTipotareas(0).getULContentTipotareasParsed() + "</tareas.IDTIPOTAREA></result>";
}
xmlResponseService(response, new StringBuffer(cadena));
}
public void serviceTareasCategorias(HttpServletRequest request, HttpServletResponse response) throws IOException, TorqueException, ServletException
{
String cadena=null;
Criteria c= new Criteria();
int claveId=-1;
claveId=WebUtils.getintParam(request, "categorias.IDCATEGORIA");
if (claveId!=-1)
{
c.add(CategoriasPeer.IDCATEGORIA, claveId);
}
c.addAscendingOrderByColumn(CategoriasPeer.IDCATEGORIA);
CategoriasGroupBean trgb = CategoriasManager.getCategoriass(c);
if (trgb.getTotalSize()!=0)
{
cadena = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>";
cadena = cadena + "<result><tareas.IDCATEGORIA>" + trgb.getCategorias(0).getULContentCategoriasParsed() + "</tareas.IDCATEGORIA></result>";
}
xmlResponseService(response, new StringBuffer(cadena));
}
public void serviceGetTareasDetallePdf(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
utf8RequestService(request);
String[] getMethodos= new String[] {
TareasHelper.IDTAREA_GET_METHOD_NAME
,TareasHelper.FECHAINICIO_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.HORAS_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.IDORDEN_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.IDTIPOTAREA_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.IDCATEGORIA_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.OBSERVACIONES_GET_METHOD_NAME+"TareasParsed"
};
TareasGroupBean tgb = new TareasGroupBean();
try
{
tgb.setElemento(TareasHelper.getTareas(request));
} catch (TorqueException e)
{
logger.severe(e.getMessage());
}
byte[] content = PdfUtils.getBytes(replaceStringBuffer(tgb.buildXml(getMethodos, null,"ISO-8859-1"),"n/a"," "), tareas_transformer,"ISO-8859-1");
response.addHeader("content-disposition","attachment;filename=Tareas.pdf");
response.setContentType("application/pdf");
response.setHeader("Cache-Control", "");//para que funcione en IE
response.setContentLength(content.length);
response.getOutputStream().write(content);
response.getOutputStream().flush();
response.getOutputStream().close();
}
public void serviceTareasTableContentPdf(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
utf8RequestService(request);
Criteria c= new Criteria();
String paramQuery = WebUtils.getStringParam(request, "query");
if ((paramQuery != null)&& (paramQuery.compareTo("")!=0) )
c = TareasManager.buildSearchCriteria(paramQuery);
c =criteriaTareasTableContent(request,c);
TareasGroupBean tgb = TareasManager.getTareass(c);
String[] methodos= new String[] {
TareasHelper.FECHAINICIO_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.HORAS_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.IDORDEN_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.IDTIPOTAREA_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.IDCATEGORIA_GET_METHOD_NAME+"TareasParsed"
,TareasHelper.OBSERVACIONES_GET_METHOD_NAME+"TareasParsed"
};
byte[] content = PdfUtils.getBytes(replaceStringBuffer(tgb.buildXml(methodos, null,"ISO-8859-1"),"n/a"," "), tareass_transformer,"ISO-8859-1");
response.addHeader("content-disposition","attachment;filename=ListaTareas.pdf");
response.setContentType("application/pdf");
response.setHeader("Cache-Control", "");//para que funcione en IE
response.setContentLength(content.length);
response.getOutputStream().write(content);
response.getOutputStream().flush();
response.getOutputStream().close();
}
public void serviceCosteCategoriasTareas(HttpServletRequest request, HttpServletResponse response) throws IOException, TorqueException, ServletException
{
String cadena=null;
Criteria c= new Criteria();
String claveId="";
claveId=WebUtils.getStringParam(request, "tareas.IDCATEGORIA");
if (claveId!="")
{
int iId = Integer.parseInt(claveId.split("-")[0]);
c.add(CategoriasPeer.IDCATEGORIA, iId);
}
CategoriasGroupBean trgb = CategoriasManager.getCategoriass(c);
if (trgb.getTotalSize()!=0)
{
cadena = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>";
cadena = cadena + "<result><tareas.COSTECATEGORIA>" + trgb.getCategorias(0).getCoste() + "</tareas.COSTECATEGORIA></result>";
}
xmlResponseService(response, new StringBuffer(cadena));
}
}
| Esleelkartea/instelec-app | instelecapp_v1.0.0_src/src/net/idtoki/instelec/controller/TareasController.java | Java | gpl-2.0 | 18,850 |
// SPDX-License-Identifier: GPL-2.0
#include <errno.h>
#include <QtBluetooth/QBluetoothAddress>
#include <QLowEnergyController>
#include <QLowEnergyService>
#include <QCoreApplication>
#include <QElapsedTimer>
#include <QEventLoop>
#include <QThread>
#include <QTimer>
#include <QDebug>
#include <QLoggingCategory>
#include <libdivecomputer/version.h>
#include "libdivecomputer.h"
#include "core/qt-ble.h"
#include "core/btdiscovery.h"
#if defined(SSRF_CUSTOM_IO)
#include <libdivecomputer/custom_io.h>
#define BLE_TIMEOUT 12000 // 12 seconds seems like a very long time to wait
#define DEBUG_THRESHOLD 20
static int debugCounter;
#define IS_HW(_d) same_string((_d)->vendor, "Heinrichs Weikamp")
#define IS_SHEARWATER(_d) same_string((_d)->vendor, "Shearwater")
#define MAXIMAL_HW_CREDIT 255
#define MINIMAL_HW_CREDIT 32
extern "C" {
void waitFor(int ms) {
Q_ASSERT(QCoreApplication::instance());
Q_ASSERT(QThread::currentThread());
QElapsedTimer timer;
timer.start();
do {
QCoreApplication::processEvents(QEventLoop::AllEvents, ms);
QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
QThread::msleep(10);
} while (timer.elapsed() < ms);
}
void BLEObject::serviceStateChanged(QLowEnergyService::ServiceState s)
{
Q_UNUSED(s)
QList<QLowEnergyCharacteristic> list;
auto service = qobject_cast<QLowEnergyService*>(sender());
if (service)
list = service->characteristics();
Q_FOREACH(QLowEnergyCharacteristic c, list) {
qDebug() << " " << c.uuid().toString();
}
}
void BLEObject::characteristcStateChanged(const QLowEnergyCharacteristic &c, const QByteArray &value)
{
if (IS_HW(device)) {
if (c.uuid() == hwAllCharacteristics[HW_OSTC_BLE_DATA_TX]) {
hw_credit--;
receivedPackets.append(value);
if (hw_credit == MINIMAL_HW_CREDIT)
setHwCredit(MAXIMAL_HW_CREDIT - MINIMAL_HW_CREDIT);
} else {
qDebug() << "ignore packet from" << c.uuid() << value.toHex();
}
} else {
receivedPackets.append(value);
}
}
void BLEObject::characteristicWritten(const QLowEnergyCharacteristic &c, const QByteArray &value)
{
if (IS_HW(device)) {
if (c.uuid() == hwAllCharacteristics[HW_OSTC_BLE_CREDITS_RX]) {
bool ok;
hw_credit += value.toHex().toInt(&ok, 16);
isCharacteristicWritten = true;
}
} else {
if (debugCounter < DEBUG_THRESHOLD)
qDebug() << "BLEObject::characteristicWritten";
}
}
void BLEObject::writeCompleted(const QLowEnergyDescriptor &d, const QByteArray &value)
{
Q_UNUSED(value)
Q_UNUSED(d)
qDebug() << "BLE write completed";
}
void BLEObject::addService(const QBluetoothUuid &newService)
{
qDebug() << "Found service" << newService;
bool isStandardUuid = false;
newService.toUInt16(&isStandardUuid);
if (IS_HW(device)) {
/* The HW BT/BLE piece or hardware uses, what we
* call here, "a Standard UUID. It is standard because the Telit/Stollmann
* manufacturer applied for an own UUID for its product, and this was granted
* by the Bluetooth SIG.
*/
if (newService != QUuid("{0000fefb-0000-1000-8000-00805f9b34fb}"))
return; // skip all services except the right one
} else if (isStandardUuid) {
qDebug () << " .. ignoring standard service";
return;
}
auto service = controller->createServiceObject(newService, this);
qDebug() << " .. created service object" << service;
if (service) {
services.append(service);
connect(service, &QLowEnergyService::stateChanged, this, &BLEObject::serviceStateChanged);
connect(service, &QLowEnergyService::characteristicChanged, this, &BLEObject::characteristcStateChanged);
connect(service, &QLowEnergyService::characteristicWritten, this, &BLEObject::characteristicWritten);
connect(service, &QLowEnergyService::descriptorWritten, this, &BLEObject::writeCompleted);
service->discoverDetails();
}
}
BLEObject::BLEObject(QLowEnergyController *c, dc_user_device_t *d)
{
controller = c;
device = d;
debugCounter = 0;
}
BLEObject::~BLEObject()
{
qDebug() << "Deleting BLE object";
}
dc_status_t BLEObject::write(const void *data, size_t size, size_t *actual)
{
Q_UNUSED(actual) // that seems like it might cause problems
if (!receivedPackets.isEmpty()) {
qDebug() << ".. write HIT with still incoming packets in queue";
}
QList<QLowEnergyCharacteristic> list = preferredService()->characteristics();
if (list.isEmpty())
return DC_STATUS_IO;
QByteArray bytes((const char *)data, (int) size);
const QLowEnergyCharacteristic &c = list.constFirst();
QLowEnergyService::WriteMode mode;
mode = (c.properties() & QLowEnergyCharacteristic::WriteNoResponse) ?
QLowEnergyService::WriteWithoutResponse :
QLowEnergyService::WriteWithResponse;
if (IS_SHEARWATER(device))
bytes.prepend("\1\0", 2);
preferredService()->writeCharacteristic(c, bytes, mode);
return DC_STATUS_SUCCESS;
}
dc_status_t BLEObject::read(void *data, size_t size, size_t *actual)
{
if (actual)
*actual = 0;
if (receivedPackets.isEmpty()) {
QList<QLowEnergyCharacteristic> list = preferredService()->characteristics();
if (list.isEmpty())
return DC_STATUS_IO;
int msec = BLE_TIMEOUT;
while (msec > 0 && receivedPackets.isEmpty()) {
waitFor(100);
msec -= 100;
};
}
// Still no packet?
if (receivedPackets.isEmpty())
return DC_STATUS_IO;
QByteArray packet = receivedPackets.takeFirst();
if (IS_SHEARWATER(device))
packet.remove(0,2);
if ((size_t)packet.size() > size)
return DC_STATUS_NOMEMORY;
memcpy((char *)data, packet.data(), packet.size());
if (actual)
*actual += packet.size();
return DC_STATUS_SUCCESS;
}
dc_status_t BLEObject::setHwCredit(unsigned int c)
{
/* The Terminal I/O client transmits initial UART credits to the server (see 6.5).
*
* Notice that we have to write to the characteristic here, and not to its
* descriptor as for the enabeling of notifications or indications.
*
* Futher notice that this function has the implicit effect of processing the
* event loop (due to waiting for the confirmation of the credit request).
* So, as characteristcStateChanged will be triggered, while receiving
* data from the OSTC, these are processed too.
*/
QList<QLowEnergyCharacteristic> list = preferredService()->characteristics();
isCharacteristicWritten = false;
preferredService()->writeCharacteristic(list[HW_OSTC_BLE_CREDITS_RX],
QByteArray(1, c),
QLowEnergyService::WriteWithResponse);
/* And wait for the answer*/
int msec = BLE_TIMEOUT;
while (msec > 0 && !isCharacteristicWritten) {
waitFor(100);
msec -= 100;
};
if (!isCharacteristicWritten)
return DC_STATUS_TIMEOUT;
return DC_STATUS_SUCCESS;
}
dc_status_t BLEObject::setupHwTerminalIo(QList<QLowEnergyCharacteristic> allC)
{ /* This initalizes the Terminal I/O client as described in
* http://www.telit.com/fileadmin/user_upload/products/Downloads/sr-rf/BlueMod/TIO_Implementation_Guide_r04.pdf
* Referenced section numbers below are from that document.
*
* This is for all HW computers, that use referenced BT/BLE hardware module from Telit
* (formerly Stollmann). The 16 bit UUID 0xFEFB (or a derived 128 bit UUID starting with
* 0x0000FEFB is a clear indication that the OSTC is equipped with this BT/BLE hardware.
*/
if (allC.length() != 4) {
qDebug() << "This should not happen. HW/OSTC BT/BLE device without 4 Characteristics";
return DC_STATUS_IO;
}
/* The Terminal I/O client subscribes to indications of the UART credits TX
* characteristic (see 6.4).
*
* Notice that indications are subscribed to by writing 0x0200 to its descriptor. This
* can be understood by looking for Client Characteristic Configuration, Assigned
* Number: 0x2902. Enabling/Disabeling is setting the proper bit, and they
* differ for indications and notifications.
*/
QLowEnergyDescriptor d = allC[HW_OSTC_BLE_CREDITS_TX].descriptors().first();
preferredService()->writeDescriptor(d, QByteArray::fromHex("0200"));
/* The Terminal I/O client subscribes to notifications of the UART data TX
* characteristic (see 6.2).
*/
d = allC[HW_OSTC_BLE_DATA_TX].descriptors().first();
preferredService()->writeDescriptor(d, QByteArray::fromHex("0100"));
/* The Terminal I/O client transmits initial UART credits to the server (see 6.5). */
return setHwCredit(MAXIMAL_HW_CREDIT);
}
dc_status_t qt_ble_open(dc_custom_io_t *io, dc_context_t *context, const char *devaddr)
{
Q_UNUSED(context)
debugCounter = 0;
QLoggingCategory::setFilterRules(QStringLiteral("qt.bluetooth* = true"));
/*
* LE-only devices get the "LE:" prepended by the scanning
* code, so that the rfcomm code can see they only do LE.
*
* We just skip that prefix (and it doesn't always exist,
* since the device may support both legacy BT and LE).
*/
if (!strncmp(devaddr, "LE:", 3))
devaddr += 3;
// HACK ALERT! Qt 5.9 needs this for proper Bluez operation
qputenv("QT_DEFAULT_CENTRAL_SERVICES", "1");
#if defined(Q_OS_MACOS) || defined(Q_OS_IOS)
QBluetoothDeviceInfo remoteDevice = getBtDeviceInfo(devaddr);
QLowEnergyController *controller = QLowEnergyController::createCentral(remoteDevice);
#else
// this is deprecated but given that we don't use Qt to scan for
// devices on Android, we don't have QBluetoothDeviceInfo for the
// paired devices and therefore cannot use the newer interfaces
// that are preferred starting with Qt 5.7
QBluetoothAddress remoteDeviceAddress(devaddr);
QLowEnergyController *controller = new QLowEnergyController(remoteDeviceAddress);
#endif
qDebug() << "qt_ble_open(" << devaddr << ")";
if (IS_SHEARWATER(io->user_device))
controller->setRemoteAddressType(QLowEnergyController::RandomAddress);
// Try to connect to the device
controller->connectToDevice();
// Create a timer. If the connection doesn't succeed after five seconds or no error occurs then stop the opening step
int msec = BLE_TIMEOUT;
while (msec > 0 && controller->state() == QLowEnergyController::ConnectingState) {
waitFor(100);
msec -= 100;
};
switch (controller->state()) {
case QLowEnergyController::ConnectedState:
qDebug() << "connected to the controller for device" << devaddr;
break;
default:
qDebug() << "failed to connect to the controller " << devaddr << "with error" << controller->errorString();
report_error("Failed to connect to %s: '%s'", devaddr, controller->errorString().toUtf8().data());
controller->disconnectFromDevice();
delete controller;
return DC_STATUS_IO;
}
/* We need to discover services etc here! */
BLEObject *ble = new BLEObject(controller, io->user_device);
ble->connect(controller, SIGNAL(serviceDiscovered(QBluetoothUuid)), SLOT(addService(QBluetoothUuid)));
qDebug() << " .. discovering services";
controller->discoverServices();
msec = BLE_TIMEOUT;
while (msec > 0 && controller->state() == QLowEnergyController::DiscoveringState) {
waitFor(100);
msec -= 100;
};
qDebug() << " .. done discovering services";
if (ble->preferredService() == nullptr) {
qDebug() << "failed to find suitable service on" << devaddr;
report_error("Failed to find suitable service on '%s'", devaddr);
controller->disconnectFromDevice();
delete controller;
return DC_STATUS_IO;
}
qDebug() << " .. discovering details";
msec = BLE_TIMEOUT;
while (msec > 0 && ble->preferredService()->state() == QLowEnergyService::DiscoveringServices) {
waitFor(100);
msec -= 100;
};
if (ble->preferredService()->state() != QLowEnergyService::ServiceDiscovered) {
qDebug() << "failed to find suitable service on" << devaddr;
report_error("Failed to find suitable service on '%s'", devaddr);
controller->disconnectFromDevice();
delete controller;
return DC_STATUS_IO;
}
qDebug() << " .. enabling notifications";
/* Enable notifications */
QList<QLowEnergyCharacteristic> list = ble->preferredService()->characteristics();
if (!list.isEmpty()) {
const QLowEnergyCharacteristic &c = list.constLast();
if (IS_HW(io->user_device)) {
dc_status_t r = ble->setupHwTerminalIo(list);
if (r != DC_STATUS_SUCCESS)
return r;
} else {
QList<QLowEnergyDescriptor> l = c.descriptors();
qDebug() << "Descriptor list with" << l.length() << "elements";
QLowEnergyDescriptor d;
foreach(d, l)
qDebug() << "Descriptor:" << d.name() << "uuid:" << d.uuid().toString();
if (!l.isEmpty()) {
bool foundCCC = false;
foreach (d, l) {
if (d.type() == QBluetoothUuid::ClientCharacteristicConfiguration) {
// pick the correct characteristic
foundCCC = true;
break;
}
}
if (!foundCCC)
// if we didn't find a ClientCharacteristicConfiguration, try the first one
d = l.first();
qDebug() << "now writing \"0x0100\" to the descriptor" << d.uuid().toString();
ble->preferredService()->writeDescriptor(d, QByteArray::fromHex("0100"));
}
}
}
// Fill in info
io->userdata = (void *)ble;
return DC_STATUS_SUCCESS;
}
dc_status_t qt_ble_close(dc_custom_io_t *io)
{
BLEObject *ble = (BLEObject *) io->userdata;
io->userdata = NULL;
delete ble;
return DC_STATUS_SUCCESS;
}
static void checkThreshold()
{
if (++debugCounter == DEBUG_THRESHOLD) {
QLoggingCategory::setFilterRules(QStringLiteral("qt.bluetooth* = false"));
qDebug() << "turning off further BT debug output";
}
}
dc_status_t qt_ble_read(dc_custom_io_t *io, void* data, size_t size, size_t *actual)
{
checkThreshold();
BLEObject *ble = (BLEObject *) io->userdata;
return ble->read(data, size, actual);
}
dc_status_t qt_ble_write(dc_custom_io_t *io, const void* data, size_t size, size_t *actual)
{
checkThreshold();
BLEObject *ble = (BLEObject *) io->userdata;
return ble->write(data, size, actual);
}
} /* extern "C" */
#endif
| neolit123/subsurface | core/qt-ble.cpp | C++ | gpl-2.0 | 13,635 |
package com.uvic.textshare.service.rest;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.io.UnsupportedEncodingException;
import java.lang.String;
import com.uvic.textshare.service.matching.MatchingFunction;
import com.uvic.textshare.service.model.*;
import com.google.appengine.api.users.*;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gson.Gson;
@SuppressWarnings("unused")
@Path("/")
public class TextbookResource {
private static int numberOf_offered_books;
private static int numberOf_requested_books;
private static int numberOf_matches;
MatchingFunction matchingFunction = new MatchingFunction();
String matchDate;
/*
*
* Start of REST Methods
*
*/
@POST
@Path("/retrieve")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String getTextbook(String input) {
try {
//Create a filter for retrieving all the books associated with that user
JSONObject obj = new JSONObject(input);
String user_id = obj.getString("uid");
Filter userFilter = new FilterPredicate("uid", FilterOperator.EQUAL, user_id);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query q = new Query("User").setFilter(userFilter);
Entity user = datastore.prepare(q).asSingleEntity();
if(user == null && !user_id.equals("")) {
createUser(obj);
return "[]";
}
else
{
Query q2 = new Query("Textbook").setFilter(userFilter);
PreparedQuery pd2 = datastore.prepare(q2);
List<Entity> textbooks = pd2.asList(FetchOptions.Builder.withDefaults());
String json = new Gson().toJson(textbooks);
return json;
}
} catch(NullPointerException e)
{
e.printStackTrace();
return "[]"; //something went wrong
}
}
@POST
@Path("/add")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String addTextbook(String input) throws ParseException {
try {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
JSONObject text = new JSONObject(input);
Date addDate = new Date();
matchDate = "emtpy";
String response = matchingFunction.checkForMatch(
text.getString("isbn"),
text.getString("uid"),
text.getString("type"),
text.getString("title"),
text.getDouble("condition"),
text.getString("edition"));
String[] parts = response.split("-");
String matched = parts[0];
if(matched.equals("yes")) {
matchDate = parts[1];
numberOf_matches++;
}
double radius = text.getDouble("radius");
radius = radius / 1000.0;
if(radius > 30 || radius < 5) {
radius = 15.0;
}
Entity textbook = new Entity("Textbook");
textbook.setProperty("uid", text.getString("uid"));
textbook.setProperty("type", text.getString("type"));
textbook.setUnindexedProperty("title", text.getString("title"));
textbook.setUnindexedProperty("author", text.getString("author"));
textbook.setProperty("isbn", text.getString("isbn"));
textbook.setProperty("edition", text.getString("edition"));
textbook.setProperty("condition", text.getDouble("condition"));
textbook.setProperty("date", addDate);
textbook.setProperty("matchDate", matchDate);
textbook.setProperty("matched", matched);
textbook.setUnindexedProperty("image", text.getString("image"));
textbook.setUnindexedProperty("lat", text.getDouble("lat"));
textbook.setUnindexedProperty("lon", text.getDouble("lon"));
textbook.setUnindexedProperty("radius", radius);
datastore.put(textbook);
String bookOwner = text.getString("uid");
String typeOfEntry = text.getString("type");
updateUserKarma(bookOwner, typeOfEntry, 5);
if(typeOfEntry.equals("offer"))
TextbookResource.numberOf_offered_books++;
else
TextbookResource.numberOf_requested_books++;
String json = new Gson().toJson(textbook);
return json;
} catch(NullPointerException e) {
e.printStackTrace();
return "{}"; //something went wrong!
}
}
@POST
@Path("/delete")
@Consumes(MediaType.APPLICATION_JSON)
public void deleteTextbook(String input) throws JSONException {
try {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
JSONObject obj = new JSONObject(input);
Long id = (long) obj.getDouble("id");
Key textbookKey = KeyFactory.createKey("Textbook", id);
datastore.delete(textbookKey);
} catch(NullPointerException e) {
e.printStackTrace();
}
}
@POST
@Path("/updateUserRadius")
@Consumes(MediaType.APPLICATION_JSON)
public void updateUserRadius(String input) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
try {
JSONObject obj = new JSONObject(input);
String uid = obj.getString("uid");
double radius = obj.getDouble("radius");
radius = radius / 1000.0;
if(radius > 30 || radius < 5) {
radius = 15.0;
}
Filter userFilter = new FilterPredicate("uid", FilterOperator.EQUAL, uid);
Query q = new Query("User").setFilter(userFilter);
Entity user = datastore.prepare(q).asSingleEntity();
user.setUnindexedProperty("radius", radius);
datastore.put(user);
q = new Query("Textbook").setFilter(userFilter);
List<Entity> textbooks = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
if(!textbooks.isEmpty()) {
for(int i = 0; i < textbooks.size(); i++) {
Delay.oneSecondDelay();
Entity textbook = textbooks.get(i);
textbook.setUnindexedProperty("radius", radius);
datastore.put(textbook);
}
}
} catch(NullPointerException e) {
e.printStackTrace();
}
}
@POST
@Path("/updateUserLocation")
@Consumes(MediaType.APPLICATION_JSON)
public void updateUserLocation(String input) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
try {
JSONObject obj = new JSONObject(input);
String uid = obj.getString("uid");
double lat = obj.getDouble("lat");
double lon = obj.getDouble("lon");
Filter userFilter = new FilterPredicate("uid", FilterOperator.EQUAL, uid);
Query q = new Query("User").setFilter(userFilter);
Entity user = datastore.prepare(q).asSingleEntity();
user.setUnindexedProperty("lat", lat);
user.setUnindexedProperty("lon", lon);
datastore.put(user);
q = new Query("Textbook").setFilter(userFilter);
List<Entity> textbooks = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
if(!textbooks.isEmpty()) {
for(int i = 0; i < textbooks.size(); i++) {
Delay.oneSecondDelay();
Entity textbook = textbooks.get(i);
textbook.setUnindexedProperty("lat", lat);
textbook.setUnindexedProperty("lon", lon);
datastore.put(textbook);
}
}
} catch(NullPointerException e) {
e.printStackTrace();
}
}
@POST
@Path("/unmatchTextbook")
@Consumes(MediaType.APPLICATION_JSON)
public void unmatchTextbook(String input) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
try {
JSONObject obj = new JSONObject(input);
Long id = (long) obj.getDouble("id");
String title = obj.getString("title");
String isbn = obj.getString("isbn");
String type = obj.getString("type");
String uid = obj.getString("uid");
String matchDate = obj.getString("matchDate");
double condition = obj.getDouble("condition");
String edition = obj.getString("edition");
String uidTwo;
String typeTwo;
if(type.equals("offer"))
typeTwo = "request";
else
typeTwo = "offer";
//Delete the match entry and retrieve other user's UID.
Filter matchFilter = new FilterPredicate("matchDate", FilterOperator.EQUAL, matchDate);
Query q = new Query("Match").setFilter(matchFilter);
Entity match = datastore.prepare(q).asSingleEntity();
if(!uid.equals((String) match.getProperty("userOneId")))
uidTwo = (String) match.getProperty("userOneId");
else
uidTwo = (String) match.getProperty("userTwoId");
Key matchKey = match.getKey();
datastore.delete(matchKey);
Delay.oneSecondDelay();
//Check for a new match. Omit matching each other again.
String matchedOne = matchingFunction.checkForMatch(isbn, uid, type, title, condition, edition);
Delay.oneSecondDelay();
String matchedTwo = matchingFunction.checkForMatch(isbn, uidTwo, typeTwo, title, condition, edition);
//Update database based on the result of new searches for matches.
if(matchedOne.equals("no")) {
Key textbookKey = KeyFactory.createKey("Textbook", id);
Query q2 = new Query(textbookKey);
Entity textbook = datastore.prepare(q2).asSingleEntity();
textbook.setProperty("matched", "no");
textbook.setProperty("matchDate", null);
datastore.put(textbook);
}
else
{
String[] parts = matchedOne.split("-");
String matchDateOne = parts[1];
Key textbookKey = KeyFactory.createKey("Textbook", id);
Query q2 = new Query(textbookKey);
Entity textbook = datastore.prepare(q2).asSingleEntity();
textbook.setProperty("matched", "yes");
textbook.setProperty("matchDate", matchDateOne);
datastore.put(textbook);
}
Filter isbnFilter = new FilterPredicate("isbn", FilterOperator.EQUAL,isbn);
Filter uidFilter = new FilterPredicate("uid", FilterOperator.EQUAL, uidTwo);
Filter searchFilter = CompositeFilterOperator.and(isbnFilter, uidFilter);
Delay.oneSecondDelay();
if(matchedTwo.equals("no")) {
q = new Query("Textbook").setFilter(searchFilter);
Entity textbookTwo = datastore.prepare(q).asSingleEntity();
textbookTwo.setProperty("matched", "no");
textbookTwo.setProperty("matchDate", null);
datastore.put(textbookTwo);
}
else
{
String[] parts = matchedTwo.split("-");
String matchDateTwo = parts[1];
q = new Query("Textbook").setFilter(searchFilter);
Entity textbookTwo = datastore.prepare(q).asSingleEntity();
textbookTwo.setProperty("matched", "yes");
textbookTwo.setProperty("matchDate", matchDateTwo);
datastore.put(textbookTwo);
}
} catch(NullPointerException e) {
e.printStackTrace();
}
}
@POST
@Path("/completeMatch")
@Consumes(MediaType.APPLICATION_JSON)
public void completeMatch(String input) {
try {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
JSONObject obj = new JSONObject(input);
Long idOfInitiator = (long) obj.getDouble("id");
String uidOfInitiator = obj.getString("uid");
String matchDate = obj.getString("matchDate");
String type = obj.getString("type");
String uidofMatch;
//Delete the match entry
Filter matchFilter = new FilterPredicate("matchDate", FilterOperator.EQUAL, matchDate);
Query q = new Query("Match").setFilter(matchFilter);
Entity match = datastore.prepare(q).asSingleEntity();
if(!uidOfInitiator.equals((String) match.getProperty("userOneId")))
uidofMatch = (String) match.getProperty("userOneId");
else
uidofMatch = (String) match.getProperty("userTwoId");
Key matchKey = match.getKey();
datastore.delete(matchKey);
//Delete Books
Key textbookKey = KeyFactory.createKey("Textbook", idOfInitiator);
datastore.delete(textbookKey);
Filter uidFilter = new FilterPredicate("uid", FilterOperator.EQUAL, uidofMatch);
Filter searchFilter = CompositeFilterOperator.and(uidFilter, matchFilter);
q = new Query("Textbook").setFilter(searchFilter);
Entity textbook = datastore.prepare(q).asSingleEntity();
matchKey = textbook.getKey();
datastore.delete(matchKey);
} catch(NullPointerException e) {
e.printStackTrace();
}
}
@POST
@Path("/getUser")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String getUser(String input) {
try {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
JSONObject obj = new JSONObject(input);
String uid = obj.getString("uid");
Filter userFilter = new FilterPredicate("uid", FilterOperator.EQUAL, uid);
Query q = new Query("User").setFilter(userFilter);
Entity user = datastore.prepare(q).asSingleEntity();
if(user == null)
return "{}";
String json = new Gson().toJson(user);
return json;
} catch(NullPointerException e) {
e.printStackTrace();
return "{}";
}
}
@GET
@Path("/getLastFiveBooks")
@Produces(MediaType.APPLICATION_JSON)
public String getLastFiveBooks() {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query query = new Query("Textbook").addSort("date", Query.SortDirection.DESCENDING);
List<Entity> textbooks = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5));
String json = new Gson().toJson(textbooks);
return json;
}
@GET
@Path("/getStatistics")
@Produces(MediaType.APPLICATION_JSON)
public String getStatistics() {
Statistics stats = new Statistics(numberOf_offered_books, numberOf_requested_books, numberOf_matches);
String json = new Gson().toJson(stats);
return json;
}
/*
*
* End of REST Methods
*
*/
/*
*
* Start of Support Methods
*
*/
private void createUser(JSONObject obj) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Entity user = new Entity("User");
user.setUnindexedProperty("name", obj.getString("name"));
user.setProperty("uid", obj.getString("uid"));
user.setUnindexedProperty("email", obj.getString("email"));
user.setUnindexedProperty("lat", obj.getDouble("lat"));
user.setUnindexedProperty("lon", obj.getDouble("lon"));
user.setUnindexedProperty("request_karma", 0);
user.setUnindexedProperty("offer_karma", 0);
user.setUnindexedProperty("radius", 15.0); //default value for radius.
datastore.put(user);
}
private void updateUserKarma(String uid, String type, int points) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Filter userFilter = new FilterPredicate("uid", FilterOperator.EQUAL, uid);
Query q = new Query("User").setFilter(userFilter);
Entity user = datastore.prepare(q).asSingleEntity();
int updatedKarma;
if(type.equals("offer"))
{
updatedKarma = Integer.parseInt(user.getProperty("offer_karma").toString());
updatedKarma += 5;
user.setUnindexedProperty("offer_karma", updatedKarma);
}
else
{
updatedKarma = Integer.parseInt(user.getProperty("request_karma").toString());
updatedKarma += 5;
user.setUnindexedProperty("request_karma", updatedKarma);
}
datastore.put(user);
}
/*
*
* End of Support Methods
*
*/
}
| Brkk/flybrary | src/main/java/com/uvic/textshare/service/rest/TextbookResource.java | Java | gpl-2.0 | 16,036 |
/* Copyright (c) 2000, 2015, Oracle and/or its affiliates. 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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU 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 St, Fifth Floor, Boston, MA 02110-1301 USA */
/**
@file
@brief
Implementation of name resolution stage
@defgroup Query_Resolver Query Resolver
@{
*/
#include "sql_select.h"
#include "sql_resolver.h"
#include "sql_optimizer.h"
#include "opt_trace.h"
#include "sql_base.h"
#include "auth_common.h"
#include "opt_explain_format.h"
#include "sql_test.h" // print_where
#include "aggregate_check.h"
static void propagate_nullability(List<TABLE_LIST> *tables, bool nullable);
static const Item::enum_walk walk_subquery=
Item::enum_walk(Item::WALK_POSTFIX | Item::WALK_SUBQUERY);
uint build_bitmap_for_nested_joins(List<TABLE_LIST> *join_list,
uint first_unused);
/**
Prepare query block for optimization.
Resolve table and column information.
Resolve all expressions (item trees), ie WHERE clause, join conditions,
GROUP BY clause, HAVING clause, ORDER BY clause, LIMIT clause.
Prepare all subqueries recursively as part of resolving the expressions.
Apply permanent transformations to the abstract syntax tree, such as
semi-join transformation, derived table transformation, elimination of
constant values and redundant clauses (e.g ORDER BY, GROUP BY).
@param thd thread handler
@returns false if success, true if error
@note on privilege checking for SELECT query that possibly contains view
or derived table references:
- When this function is called, it is assumed that the precheck() function
has been called. precheck() ensures that the user has some SELECT
privileges to the tables involved in the query. When resolving views
it has also been established that the user has some privileges for them.
To prepare a view for privilege checking, it is also needed to call
check_view_privileges() after views have been merged into the query.
This is not necessary for unnamed derived tables since it has already
been established that we have SELECT privileges for the underlying tables
by the precheck functions. (precheck() checks a query without resolved
views, ie. before tables are opened, so underlying tables of views
are not yet available).
- When a query block is resolved, always ensure that the user has SELECT
privileges to the columns referenced in the WHERE clause, the join
conditions, the GROUP BY clause, the HAVING clause and the ORDER BY clause.
- When resolving the outer-most query block, ensure that the user also has
SELECT privileges to the columns in the selected expressions.
- When setting up a derived table or view for materialization, ensure that
the user has SELECT privileges to the columns in the selected expressions
- Column privileges are normally checked by Item_field::fix_fields().
Exceptions are select list of derived tables/views which are checked
in TABLE_LIST::setup_materialized_derived(), and natural/using join
conditions that are checked in mark_common_columns().
- As far as INSERT, UPDATE and DELETE statements have the same expressions
as a SELECT statement, this note applies to those statements as well.
*/
bool SELECT_LEX::prepare(THD *thd)
{
DBUG_ENTER("SELECT_LEX::prepare");
// We may do subquery transformation, or Item substitution:
Prepare_error_tracker tracker(thd);
DBUG_ASSERT(this == thd->lex->current_select());
DBUG_ASSERT(join == NULL);
SELECT_LEX_UNIT *const unit= master_unit();
if (top_join_list.elements > 0)
propagate_nullability(&top_join_list, false);
is_item_list_lookup= true;
Opt_trace_context * const trace= &thd->opt_trace;
Opt_trace_object trace_wrapper(trace);
Opt_trace_object trace_prepare(trace, "join_preparation");
trace_prepare.add_select_number(select_number);
Opt_trace_array trace_steps(trace, "steps");
// Initially, "all_fields" is the select list
all_fields= fields_list;
/* Check that all tables, fields, conds and order are ok */
if (!(active_options() & OPTION_SETUP_TABLES_DONE))
{
if (setup_tables(thd, get_table_list(), false))
DBUG_RETURN(true);
if (derived_table_count && resolve_derived(thd, true))
DBUG_RETURN(true);
// Wait with privilege checking until all derived tables are resolved.
if (!thd->derived_tables_processing &&
check_view_privileges(thd, SELECT_ACL, SELECT_ACL))
DBUG_RETURN(true);
}
// Precompute and store the row types of NATURAL/USING joins.
if (setup_natural_join_row_types(thd, join_list, &context))
DBUG_RETURN(true);
Mem_root_array<Item_exists_subselect *, true>
sj_candidates_local(thd->mem_root);
sj_candidates= &sj_candidates_local;
/*
Item and Item_field CTORs will both increment some counters
in current_select(), based on the current parsing context.
We are not parsing anymore: any new Items created now are due to
query rewriting, so stop incrementing counters.
*/
DBUG_ASSERT(parsing_place == CTX_NONE);
parsing_place= CTX_NONE;
resolve_place= RESOLVE_SELECT_LIST;
/*
Setup the expressions in the SELECT list. Wait with privilege checking
until all derived tables are resolved, except do privilege checking for
subqueries inside a derived table.
*/
const bool check_privs= !thd->derived_tables_processing ||
master_unit()->item != NULL;
thd->mark_used_columns= check_privs ? MARK_COLUMNS_READ : MARK_COLUMNS_NONE;
ulonglong want_privilege_saved= thd->want_privilege;
thd->want_privilege= check_privs ? SELECT_ACL : 0;
if (with_wild && setup_wild(thd))
DBUG_RETURN(true);
if (setup_ref_array(thd))
DBUG_RETURN(true); /* purecov: inspected */
if (setup_fields(thd, ref_ptrs, fields_list, thd->want_privilege,
&all_fields, true))
DBUG_RETURN(true);
resolve_place= RESOLVE_NONE;
const nesting_map save_allow_sum_func= thd->lex->allow_sum_func;
// Do not allow local set functions for join conditions, WHERE and GROUP BY
thd->lex->allow_sum_func&= ~((nesting_map)1 << nest_level);
thd->mark_used_columns= MARK_COLUMNS_READ;
thd->want_privilege= SELECT_ACL;
// Set up join conditions and WHERE clause
if (setup_conds(thd))
DBUG_RETURN(true);
// Set up the GROUP BY clause
int all_fields_count= all_fields.elements;
if (group_list.elements && setup_group(thd))
DBUG_RETURN(true);
hidden_group_field_count= all_fields.elements - all_fields_count;
// Allow local set functions in HAVING and ORDER BY
thd->lex->allow_sum_func|= (nesting_map)1 << nest_level;
// Setup the HAVING clause
if (m_having_cond)
{
thd->where="having clause";
having_fix_field= true;
resolve_place= RESOLVE_HAVING;
if (!m_having_cond->fixed &&
(m_having_cond->fix_fields(thd, &m_having_cond) ||
m_having_cond->check_cols(1)))
DBUG_RETURN(true);
having_fix_field= false;
resolve_place= RESOLVE_NONE;
}
// Set up the ORDER BY clause
all_fields_count= all_fields.elements;
int hidden_order_field_count= 0;
if (order_list.elements)
{
if (setup_order(thd, ref_ptrs, get_table_list(), fields_list, all_fields,
order_list.first))
DBUG_RETURN(true);
hidden_order_field_count= all_fields.elements - all_fields_count;
}
// Query block is completely resolved, restore set function allowance
thd->lex->allow_sum_func= save_allow_sum_func;
thd->want_privilege= want_privilege_saved;
/*
Permanently remove redundant parts from the query if
1) This is a subquery
2) This is the first time this query is prepared (since the
transformation is permanent)
3) Not normalizing a view. Removal should take place when a
query involving a view is optimized, not when the view
is created
*/
if (unit->item && // 1)
first_execution && // 2)
!(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW)) // 3)
{
remove_redundant_subquery_clauses(thd, hidden_group_field_count,
hidden_order_field_count);
}
if (order_list.elements && setup_order_final(thd, hidden_order_field_count))
DBUG_RETURN(true); /* purecov: inspected */
if (is_distinct() &&
is_grouped() &&
hidden_group_field_count == 0 &&
olap == UNSPECIFIED_OLAP_TYPE)
{
/*
All GROUP expressions are in SELECT list, so resulting rows are distinct.
ROLLUP is not specified, so adds no row. So all rows in the result set
are distinct, DISTINCT is useless.
@todo could remove DISTINCT if ROLLUP were specified and all GROUP
expressions were non-nullable, because ROLLUP adds only NULL values.
Currently, ROLLUP+DISTINCT is rejected because executor cannot handle
it in all cases.
*/
remove_base_options(SELECT_DISTINCT);
}
/*
Printing the expanded query should happen here and not elsewhere, because
when a view is merged (when the view is opened in open_tables()), the
parent query's select_lex does not yet contain a correct WHERE clause (it
misses the view's merged WHERE clause). This is corrected only just above,
in TABLE_LIST::prep_where(), called by
setup_without_group()->setup_conds().
We also have to wait for fix_fields() on HAVING, above.
At this stage, we also have properly set up Item_ref-s.
*/
{
Opt_trace_object trace_wrapper(trace);
opt_trace_print_expanded_query(thd, this, &trace_wrapper);
}
/*
When normalizing a view (like when writing a view's body to the FRM),
subquery transformations don't apply (if they did, IN->EXISTS could not be
undone in favour of materialization, when optimizing a later statement
using the view)
*/
if (unit->item && // This is a subquery
this != unit->fake_select_lex && // A real query block
// Not normalizing a view
!(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW))
{
// Query block represents a subquery within an IN/ANY/ALL/EXISTS predicate
if (resolve_subquery(thd))
DBUG_RETURN(true);
}
if (m_having_cond && m_having_cond->with_sum_func)
m_having_cond->split_sum_func2(thd, ref_ptrs, all_fields, &m_having_cond,
true);
if (inner_sum_func_list)
{
Item_sum *end=inner_sum_func_list;
Item_sum *item_sum= end;
do
{
item_sum= item_sum->next;
item_sum->split_sum_func2(thd, ref_ptrs,
all_fields, item_sum->ref_by, false);
} while (item_sum != end);
}
if (inner_refs_list.elements && fix_inner_refs(thd))
DBUG_RETURN(true); /* purecov: inspected */
if (group_list.elements)
{
/*
Because HEAP tables can't index BIT fields we need to use an
additional hidden field for grouping because later it will be
converted to a LONG field. Original field will remain of the
BIT type and will be returned to a client.
*/
for (ORDER *ord= (ORDER *)group_list.first; ord; ord= ord->next)
{
if ((*ord->item)->type() == Item::FIELD_ITEM &&
(*ord->item)->field_type() == MYSQL_TYPE_BIT)
{
Item_field *field= new Item_field(thd, *(Item_field**)ord->item);
int el= all_fields.elements;
ref_ptrs[el]= field;
all_fields.push_front(field);
ord->item= &ref_ptrs[el];
}
}
}
if (setup_ftfuncs(this)) /* should be after having->fix_fields */
DBUG_RETURN(true);
if (query_result() && query_result()->prepare(fields_list, unit))
DBUG_RETURN(true);
if (olap == ROLLUP_TYPE && resolve_rollup(thd))
DBUG_RETURN(true); /* purecov: inspected */
if (flatten_subqueries())
DBUG_RETURN(true);
sj_candidates= NULL;
if (!outer_select())
{
/*
This code is invoked in the following cases:
- if this is an outer-most query block of a SELECT or multi-table
UPDATE/DELETE statement. Notice that for a UNION, this applies to
all query blocks. It also applies to a fake_select_lex object.
- if this is one of highest-level subqueries, if the statement is
something else; like subq-i in:
UPDATE t1 SET col1=(subq-1), col2=(subq-2);
Local transforms are applied after query block merging.
This means that we avoid unnecessary invocations, as local transforms
would otherwise have been performed first before query block merging and
then another time after query block merging.
Thus, apply_local_transforms() may run only after the top query
is finished with query block merging. That's why
apply_local_transforms() is initiated only by the top query, and then
recurses into subqueries.
*/
if (apply_local_transforms(thd, true))
DBUG_RETURN(true);
}
DBUG_ASSERT(!thd->is_error());
DBUG_RETURN(false);
}
/**
Apply local transformations, such as query block merging.
Also perform partition pruning, which is most effective after transformations
have been done.
@param thd thread handler
@param prune if true, then prune partitions based on const conditions
@returns false if success, true if error
Since this is called after flattening of query blocks, call this function
while traversing the query block hierarchy top-down.
*/
bool SELECT_LEX::apply_local_transforms(THD *thd, bool prune)
{
DBUG_ENTER("SELECT_LEX::apply_local_transforms");
/*
If query block contains one or more merged derived tables/views,
walk through lists of columns in select lists and remove unused columns.
*/
if (derived_table_count &&
first_execution &&
!(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW))
delete_unused_merged_columns(&top_join_list);
for (SELECT_LEX_UNIT *unit= first_inner_unit();
unit;
unit= unit->next_unit())
{
for (SELECT_LEX *sl= unit->first_select();
sl;
sl= sl->next_select())
{
// Prune all subqueries, regardless of passed argument
if (sl->apply_local_transforms(thd, true))
DBUG_RETURN(true);
}
if (unit->fake_select_lex &&
unit->fake_select_lex->apply_local_transforms(thd, false))
DBUG_RETURN(true);
}
if (first_execution &&
!(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW))
{
/*
The following code will allocate the new items in a permanent
MEMROOT for prepared statements and stored procedures.
*/
Prepared_stmt_arena_holder ps_arena_holder(thd);
// Convert all outer joins to inner joins if possible
if (simplify_joins(thd, &top_join_list, true, false, &m_where_cond))
DBUG_RETURN(true);
if (record_join_nest_info(&top_join_list))
DBUG_RETURN(true);
build_bitmap_for_nested_joins(&top_join_list, 0);
/*
Here are reasons why we do the following check here (i.e. late).
* setup_fields () may have done split_sum_func () on aggregate items of
the SELECT list, so for reliable comparison of the ORDER BY list with
the SELECT list, we need to wait until split_sum_func() has been done on
the ORDER BY list.
* we get "most of the time" fixed items, which is always a good
thing. Some outer references may not be fixed, though.
* we need nested_join::used_tables, and this member is set in
simplify_joins()
* simplify_joins() does outer-join-to-inner conversion, which increases
opportunities for functional dependencies (weak-to-strong, which is
unusable, becomes strong-to-strong).
* check_only_full_group_by() is dependent on processing done by
simplify_joins() (for example it uses the value of
SELECT_LEX::outer_join).
The drawback is that the checks are after resolve_subquery(), so can
meet strange "internally added" items.
Note that when we are creating a view, simplify_joins() doesn't run so
check_only_full_group_by() cannot run, any error will be raised only
when the view is later used (SELECTed...)
*/
if ((thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY) &&
(is_distinct() || is_grouped()) &&
check_only_full_group_by(thd))
DBUG_RETURN(true);
}
fix_prepare_information(thd);
/*
Prune partitions for all query blocks after query block merging, if
pruning is wanted.
*/
if (partitioned_table_count && prune)
{
for (TABLE_LIST *tbl= leaf_tables; tbl; tbl= tbl->next_leaf)
{
/*
This will only prune constant conditions, which will be used for
lock pruning.
*/
if (prune_partitions(thd, tbl->table,
tbl->join_cond() ? tbl->join_cond() :
m_where_cond))
DBUG_RETURN(true); /* purecov: inspected */
}
}
DBUG_RETURN(false);
}
/**
Check if the subquery predicate can be executed via materialization.
@param predicate IN subquery predicate
@param thd THD
@param select_lex SELECT_LEX of the subquery
@param outer Parent SELECT_LEX (outer to subquery)
@return TRUE if subquery allows materialization, FALSE otherwise.
*/
bool subquery_allows_materialization(Item_in_subselect *predicate,
THD *thd,
SELECT_LEX *select_lex,
const SELECT_LEX *outer)
{
const uint elements= predicate->unit->first_select()->item_list.elements;
DBUG_ENTER("subquery_allows_materialization");
DBUG_ASSERT(elements >= 1);
DBUG_ASSERT(predicate->left_expr->cols() == elements);
OPT_TRACE_TRANSFORM(&thd->opt_trace, trace_wrapper, trace_mat,
select_lex->select_number,
"IN (SELECT)", "materialization");
const char *cause= NULL;
if (predicate->substype() != Item_subselect::IN_SUBS)
{
// Subq-mat cannot handle 'outer_expr > {ANY|ALL}(subq)'...
cause= "not an IN predicate";
}
else if (select_lex->is_part_of_union())
{
// Subquery must be a single query specification clause (not a UNION)
cause= "in UNION";
}
else if (!select_lex->master_unit()->first_select()->leaf_tables)
{
// Subquery has no tables, hence no point in materializing.
cause= "no inner tables";
}
else if (!outer->join)
{
/*
Maybe this is a subquery of a single table UPDATE/DELETE (TODO:
handle this by switching to multi-table UPDATE/DELETE).
*/
cause= "parent query has no JOIN";
}
else if (!outer->leaf_tables)
{
// The upper query is SELECT ... FROM DUAL. No gain in materializing.
cause= "no tables in outer query";
}
else if (predicate->dependent_before_in2exists())
{
/*
Subquery should not be correlated; the correlation due to predicates
injected by IN->EXISTS does not count as we will remove them if we
choose materialization.
TODO:
This is an overly restrictive condition. It can be extended to:
(Subquery is non-correlated ||
Subquery is correlated to any query outer to IN predicate ||
(Subquery is correlated to the immediate outer query &&
Subquery !contains {GROUP BY, ORDER BY [LIMIT],
aggregate functions}) && subquery predicate is not under "NOT IN"))
*/
cause= "correlated";
}
else
{
/*
Check that involved expression types allow materialization.
This is a temporary fix for BUG#36752; see bug report for
description of restrictions we need to put on the compared expressions.
*/
DBUG_ASSERT(predicate->left_expr->fixed);
// @see comment in Item_subselect::element_index()
bool has_nullables= predicate->left_expr->maybe_null;
List_iterator<Item> it(predicate->unit->first_select()->item_list);
for (uint i= 0; i < elements; i++)
{
Item * const inner= it++;
Item * const outer= predicate->left_expr->element_index(i);
if (!types_allow_materialization(outer, inner))
{
cause= "type mismatch";
break;
}
if (inner->is_blob_field()) // 6
{
cause= "inner blob";
break;
}
has_nullables|= inner->maybe_null;
}
if (!cause)
{
trace_mat.add("has_nullable_expressions", has_nullables);
/*
Subquery materialization cannot handle NULLs partial matching
properly, yet. If the outer or inner values are NULL, the
subselect_hash_sj_engine may reply FALSE when it should reply UNKNOWN.
So, we must limit it to those three cases:
- when FALSE and UNKNOWN are equivalent answers. I.e. this is a a
top-level predicate (this implies it is not negated).
- when outer and inner values cannot be NULL.
- when there is a single inner column (because for this we have a
limited implementation of NULLs partial matching).
*/
const bool is_top_level= predicate->is_top_level_item();
trace_mat.add("treat_UNKNOWN_as_FALSE", is_top_level);
if (!is_top_level && has_nullables && (elements > 1))
cause= "cannot_handle_partial_matches";
else
{
trace_mat.add("possible", true);
DBUG_RETURN(TRUE);
}
}
}
DBUG_ASSERT(cause != NULL);
trace_mat.add("possible", false).add_alnum("cause", cause);
DBUG_RETURN(false);
}
/**
Make list of leaf tables of join table tree
@param list pointer to pointer on list first element
@param tables table list
@returns pointer on pointer to next_leaf of last element
*/
static TABLE_LIST **make_leaf_tables(TABLE_LIST **list, TABLE_LIST *tables)
{
for (TABLE_LIST *table= tables; table; table= table->next_local)
{
// A mergable view is not allowed to have a table pointer.
DBUG_ASSERT(!(table->is_view() && table->is_merged() && table->table));
if (table->merge_underlying_list)
{
DBUG_ASSERT(table->is_merged());
list= make_leaf_tables(list, table->merge_underlying_list);
}
else
{
*list= table;
list= &table->next_leaf;
}
}
return list;
}
/**
Check privileges for the view tables merged into a query block.
@param thd Thread context.
@param want_privilege_first Privileges requested for the first leaf.
@param want_privilege_next Privileges requested for the remaining leaves.
@note Beware that it can't properly check privileges in cases when
table being changed is not the first table in the list of leaf
tables (for example, for multi-UPDATE).
@note The inner loop is slightly inefficient. A view will have its privileges
checked once for every base table that it refers to.
@returns false if success, true if error.
*/
bool st_select_lex::check_view_privileges(THD *thd,
ulong want_privilege_first,
ulong want_privilege_next)
{
ulong want_privilege= want_privilege_first;
Internal_error_handler_holder<View_error_handler, TABLE_LIST>
view_handler(thd, true, leaf_tables);
for (TABLE_LIST *tl= leaf_tables; tl; tl= tl->next_leaf)
{
for (TABLE_LIST *ref= tl; ref->referencing_view; ref= ref->referencing_view)
{
if (check_single_table_access(thd, want_privilege, ref, false))
return true;
}
want_privilege= want_privilege_next;
}
return false;
}
/**
Set up table leaves in the query block based on list of tables.
@param thd Thread handler
@param tables List of tables to handle
@param select_insert It is SELECT ... INSERT command
@note
Check also that the 'used keys' and 'ignored keys' exists and set up the
table structure accordingly.
Create a list of leaf tables.
This function has to be called for all tables that are used by items,
as otherwise table->map is not set and all Item_field will be regarded
as const items.
@returns False on success, true on error
*/
bool st_select_lex::setup_tables(THD *thd, TABLE_LIST *tables,
bool select_insert)
{
DBUG_ENTER("st_select_lex::setup_tables");
DBUG_ASSERT ((select_insert && !tables->next_name_resolution_table) ||
!tables ||
(context.table_list && context.first_name_resolution_table));
make_leaf_tables(&leaf_tables, tables);
TABLE_LIST *first_select_table= NULL;
if (select_insert)
{
// "insert_table" is needed for remap_tables().
thd->lex->insert_table= leaf_tables->top_table();
// Get first table in SELECT part
first_select_table= thd->lex->insert_table->next_local;
// Then, find the first leaf table
if (first_select_table)
first_select_table= first_select_table->first_leaf_table();
}
uint tableno= 0;
leaf_table_count= 0;
partitioned_table_count= 0;
Opt_hints_qb *qb_hints= context.select_lex->opt_hints_qb;
for (TABLE_LIST *tr= leaf_tables; tr; tr= tr->next_leaf, tableno++)
{
TABLE *const table= tr->table;
if (tr == first_select_table)
{
/*
For INSERT ... SELECT command, restart numbering from zero for first
leaf table from SELECT part of query.
*/
first_select_table= 0;
tableno= 0;
}
if (tableno >= MAX_TABLES)
{
my_error(ER_TOO_MANY_TABLES,MYF(0), static_cast<int>(MAX_TABLES));
DBUG_RETURN(true);
}
tr->set_tableno(tableno);
leaf_table_count++; // Count the input tables of the query
if (table == NULL)
continue;
table->pos_in_table_list= tr;
tr->reset();
if (qb_hints && // QB hints initialized
!tr->opt_hints_table) // Table hints are not adjusted yet
{
tr->opt_hints_table= qb_hints->adjust_table_hints(table, tr->alias);
}
if (tr->process_index_hints(table))
DBUG_RETURN(true);
if (table->part_info) // Count number of partitioned tables
partitioned_table_count++;
}
if (qb_hints)
qb_hints->check_unresolved(thd);
DBUG_RETURN(false);
}
/**
Re-map table numbers for all tables in a query block.
@param thd Thread handler
@note
This function needs to be called after setup_tables() has been called,
and after a query block for a subquery has been merged into a parent
quary block.
*/
void st_select_lex::remap_tables(THD *thd)
{
LEX *const lex= thd->lex;
TABLE_LIST *first_select_table= NULL;
if (lex->insert_table &&
lex->insert_table == leaf_tables->top_table())
{
/*
For INSERT ... SELECT command, restart numbering from zero for first
leaf table from SELECT part of query.
*/
// Get first table in SELECT part
first_select_table= lex->insert_table->next_local;
// Then, recurse down to get first leaf table
if (first_select_table)
first_select_table= first_select_table->first_leaf_table();
}
uint tableno= 0;
for (TABLE_LIST *tl= leaf_tables; tl; tl= tl->next_leaf)
{
// Reset table number after having reached first table after insert table
if (first_select_table == tl)
tableno= 0;
tl->set_tableno(tableno++);
}
}
/**
@brief Resolve derived table and view references in query block
@param thd Pointer to THD.
@param apply_semijoin if true, apply semi-join transform when possible
@return false if success, true if error
*/
bool st_select_lex::resolve_derived(THD *thd, bool apply_semijoin)
{
DBUG_ENTER("st_select_lex::resolve_derived");
DBUG_ASSERT(derived_table_count);
materialized_derived_table_count= 0;
// Prepare derived tables and views that belong to this query block.
for (TABLE_LIST *tl= get_table_list(); tl; tl= tl->next_local)
{
if (!tl->is_view_or_derived() || tl->is_merged())
continue;
if (tl->resolve_derived(thd, apply_semijoin))
DBUG_RETURN(true);
}
/*
Merge the derived tables that do not require materialization into
the current query block, if possible.
Merging is only done once and must not be repeated for prepared execs.
*/
if (!(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW) &&
first_execution)
{
for (TABLE_LIST *tl= get_table_list(); tl; tl= tl->next_local)
{
if (!tl->is_view_or_derived() ||
tl->is_merged() ||
!tl->is_mergeable())
continue;
if (merge_derived(thd, tl))
DBUG_RETURN(true); /* purecov: inspected */
}
}
// Prepare remaining derived tables for materialization
for (TABLE_LIST *tl= get_table_list(); tl; tl= tl->next_local)
{
// Ensure that any derived table is merged or materialized after prepare:
DBUG_ASSERT(first_execution || !tl->is_view_or_derived() ||
tl->is_merged() || tl->uses_materialization());
if (!tl->is_view_or_derived() || tl->is_merged())
continue;
if (tl->setup_materialized_derived(thd))
DBUG_RETURN(true);
materialized_derived_table_count++;
}
/*
The loops above will not reach derived tables that are contained within
other derived tables that have been merged into the enclosing query block.
To reach them, traverse the list of leaf tables and resolve and
setup for materialization those derived tables that have no TABLE
object (they have not been set up yet).
*/
if (!first_execution)
{
for (TABLE_LIST *tl= leaf_tables; tl; tl= tl->next_leaf)
{
if (!tl->is_view_or_derived() || tl->table != NULL)
continue;
DBUG_ASSERT(!tl->is_merged());
if (tl->resolve_derived(thd, apply_semijoin))
DBUG_RETURN(true); /* purecov: inspected */
if (tl->setup_materialized_derived(thd))
DBUG_RETURN(true); /* purecov: inspected */
materialized_derived_table_count++;
}
}
DBUG_RETURN(false);
}
/**
@brief Resolve predicate involving subquery
@param thd Pointer to THD.
@retval FALSE Success.
@retval TRUE Error.
@details
Perform early unconditional subquery transformations:
- Convert subquery predicate into semi-join, or
- Mark the subquery for execution using materialization, or
- Perform IN->EXISTS transformation, or
- Perform more/less ALL/ANY -> MIN/MAX rewrite
- Substitute trivial scalar-context subquery with its value
@todo for PS, make the whole block execute only on the first execution
*/
bool SELECT_LEX::resolve_subquery(THD *thd)
{
DBUG_ENTER("resolve_subquery");
bool chose_semijoin= false;
SELECT_LEX *const outer= outer_select();
/*
@todo for PS, make the whole block execute only on the first execution.
resolve_subquery() is only invoked in the first execution for subqueries
that are transformed to semijoin, but for other subqueries, this function
is called for every execution. One solution is perhaps to define
exec_method in class Item_subselect and exit immediately if unequal to
EXEC_UNSPECIFIED.
*/
Item_subselect *subq_predicate= master_unit()->item;
DBUG_ASSERT(subq_predicate);
/**
@note
In this case: IN (SELECT ... UNION SELECT ...), SELECT_LEX::prepare() is
called for each of the two UNION members, and in those two calls,
subq_predicate is the same, not sure this is desired (double work?).
*/
Item_in_subselect * const in_predicate=
(subq_predicate->substype() == Item_subselect::IN_SUBS) ?
static_cast<Item_in_subselect *>(subq_predicate) : NULL;
if (in_predicate)
{
thd->lex->set_current_select(outer);
char const *save_where= thd->where;
thd->where= "IN/ALL/ANY subquery";
Disable_semijoin_flattening DSF(outer, true);
bool result= !in_predicate->left_expr->fixed &&
in_predicate->left_expr->fix_fields(thd,
&in_predicate->left_expr);
thd->lex->set_current_select(this);
thd->where= save_where;
if (result)
DBUG_RETURN(true);
/*
Check if the left and right expressions have the same # of
columns, i.e. we don't have a case like
(oe1, oe2) IN (SELECT ie1, ie2, ie3 ...)
TODO why do we have this duplicated in IN->EXISTS transformers?
psergey-todo: fix these: grep for duplicated_subselect_card_check
*/
if (item_list.elements != in_predicate->left_expr->cols())
{
my_error(ER_OPERAND_COLUMNS, MYF(0), in_predicate->left_expr->cols());
DBUG_RETURN(true);
}
}
DBUG_PRINT("info", ("Checking if subq can be converted to semi-join"));
/*
Check if we're in subquery that is a candidate for flattening into a
semi-join (which is done in flatten_subqueries()). The requirements are:
1. Subquery predicate is an IN/=ANY subquery predicate
2. Subquery is a single SELECT (not a UNION)
3. Subquery does not have GROUP BY
4. Subquery does not use aggregate functions or HAVING
5. Subquery predicate is (a) in an ON/WHERE clause, and (b) at
the AND-top-level of that clause.
6. Parent query block accepts semijoins (i.e we are not in a subquery of
a single table UPDATE/DELETE (TODO: We should handle this at some
point by switching to multi-table UPDATE/DELETE)
7. We're not in a confluent table-less subquery, like "SELECT 1".
8. No execution method was already chosen (by a prepared statement)
9. Parent select is not a confluent table-less select
10. Neither parent nor child select have STRAIGHT_JOIN option.
*/
if (thd->optimizer_switch_flag(OPTIMIZER_SWITCH_SEMIJOIN) &&
in_predicate && // 1
!is_part_of_union() && // 2
!group_list.elements && // 3
!m_having_cond && !with_sum_func && // 4
(outer->resolve_place == st_select_lex::RESOLVE_CONDITION || // 5a
outer->resolve_place == st_select_lex::RESOLVE_JOIN_NEST) && // 5a
!outer->semijoin_disallowed && // 5b
outer->sj_candidates && // 6
leaf_table_count && // 7
in_predicate->exec_method ==
Item_exists_subselect::EXEC_UNSPECIFIED && // 8
outer->leaf_table_count && // 9
!((active_options() | outer->active_options()) &
SELECT_STRAIGHT_JOIN)) //10
{
DBUG_PRINT("info", ("Subquery is semi-join conversion candidate"));
/* Notify in the subquery predicate where it belongs in the query graph */
in_predicate->embedding_join_nest= outer->resolve_nest;
/* Register the subquery for further processing in flatten_subqueries() */
outer->sj_candidates->push_back(in_predicate);
chose_semijoin= true;
}
if (in_predicate)
{
Opt_trace_context * const trace= &thd->opt_trace;
OPT_TRACE_TRANSFORM(trace, oto0, oto1,
select_number, "IN (SELECT)", "semijoin");
oto1.add("chosen", chose_semijoin);
}
if (!chose_semijoin &&
subq_predicate->select_transformer(this) ==
Item_subselect::RES_ERROR)
DBUG_RETURN(true);
DBUG_RETURN(false);
}
/**
Expand all '*' in list of expressions with the matching column references
Function should not be called with no wild cards in select list
@param thd thread handler
@returns false if OK, true if error
*/
bool SELECT_LEX::setup_wild(THD *thd)
{
DBUG_ENTER("SELECT_LEX::setup_wild");
DBUG_ASSERT(with_wild);
// PS/SP uses arena so that changes are made permanently.
Prepared_stmt_arena_holder ps_arena_holder(thd);
Item *item;
List_iterator<Item> it(fields_list);
while (with_wild && (item= it++))
{
Item_field *item_field;
if (item->type() == Item::FIELD_ITEM &&
(item_field= (Item_field *) item) &&
item_field->field_name &&
item_field->field_name[0] == '*' &&
!item_field->field)
{
const uint elem= fields_list.elements;
const bool any_privileges= item_field->any_privileges;
Item_subselect *subsel= master_unit()->item;
if (subsel && subsel->substype() == Item_subselect::EXISTS_SUBS)
{
/*
It is EXISTS(SELECT * ...) and we can replace * by any constant.
Item_int do not need fix_fields() because it is basic constant.
*/
it.replace(new Item_int(NAME_STRING("Not_used"), (longlong) 1,
MY_INT64_NUM_DECIMAL_DIGITS));
}
else
{
if (insert_fields(thd, item_field->context,
item_field->db_name, item_field->table_name,
&it, any_privileges))
DBUG_RETURN(true);
}
/*
all_fields is a list that has the fields list as a tail.
Because of this we have to update the element count also for this
list after expanding the '*' entry.
*/
all_fields.elements+= fields_list.elements - elem;
with_wild--;
}
}
DBUG_RETURN(false);
}
/**
Resolve WHERE condition and join conditions
@param thd thread handler
@returns false if success, true if error
*/
bool SELECT_LEX::setup_conds(THD *thd)
{
DBUG_ENTER("SELECT_LEX::setup_conds");
/*
it_is_update set to TRUE when tables of primary SELECT_LEX (SELECT_LEX
which belong to LEX, i.e. most up SELECT) will be updated by
INSERT/UPDATE/LOAD
NOTE: using this condition helps to prevent call of prepare_check_option()
from subquery of VIEW, because tables of subquery belongs to VIEW
(see condition before prepare_check_option() call)
*/
const bool it_is_update= (this == thd->lex->select_lex) &&
thd->lex->which_check_option_applicable();
const bool save_is_item_list_lookup= is_item_list_lookup;
is_item_list_lookup= false;
DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns));
if (m_where_cond)
{
resolve_place= st_select_lex::RESOLVE_CONDITION;
thd->where="where clause";
if ((!m_where_cond->fixed &&
m_where_cond->fix_fields(thd, &m_where_cond)) ||
m_where_cond->check_cols(1))
DBUG_RETURN(true);
resolve_place= st_select_lex::RESOLVE_NONE;
}
/*
Apply fix_fields() to all ON clauses at all levels of nesting,
including the ones inside view definitions.
*/
for (TABLE_LIST *table= leaf_tables; table; table= table->next_leaf)
{
TABLE_LIST *embedded; /* The table at the current level of nesting. */
TABLE_LIST *embedding= table; /* The parent nested table reference. */
do
{
embedded= embedding;
if (embedded->join_cond())
{
resolve_place= st_select_lex::RESOLVE_JOIN_NEST;
resolve_nest= embedded;
thd->where="on clause";
if ((!embedded->join_cond()->fixed &&
embedded->join_cond()->fix_fields(thd, embedded->join_cond_ref())) ||
embedded->join_cond()->check_cols(1))
DBUG_RETURN(true);
cond_count++;
resolve_place= st_select_lex::RESOLVE_NONE;
resolve_nest= NULL;
}
embedding= embedded->embedding;
}
while (embedding &&
embedding->nested_join->join_list.head() == embedded);
/* process CHECK OPTION */
if (it_is_update)
{
TABLE_LIST *view= table->top_table();
if (view->effective_with_check)
{
if (view->prepare_check_option(thd))
DBUG_RETURN(true); /* purecov: inspected */
thd->change_item_tree(&table->check_option, view->check_option);
}
}
}
is_item_list_lookup= save_is_item_list_lookup;
DBUG_ASSERT(thd->lex->current_select() == this);
DBUG_ASSERT(!thd->is_error());
DBUG_RETURN(false);
}
/**
Set NESTED_JOIN::counter=0 in all nested joins in passed list.
@param join_list Pass NULL. Non-NULL is reserved for recursive inner calls,
then it is a list of nested joins to process, and may also contain base
tables which will be ignored.
*/
void SELECT_LEX::reset_nj_counters(List<TABLE_LIST> *join_list)
{
if (join_list == NULL)
join_list= &top_join_list;
List_iterator<TABLE_LIST> li(*join_list);
TABLE_LIST *table;
DBUG_ENTER("reset_nj_counters");
while ((table= li++))
{
NESTED_JOIN *nested_join;
if ((nested_join= table->nested_join))
{
nested_join->nj_counter= 0;
reset_nj_counters(&nested_join->join_list);
}
}
DBUG_VOID_RETURN;
}
/**
Simplify joins replacing outer joins by inner joins whenever it's
possible.
The function, during a retrieval of join_list, eliminates those
outer joins that can be converted into inner join, possibly nested.
It also moves the join conditions for the converted outer joins
and from inner joins to conds.
The function also calculates some attributes for nested joins:
- used_tables
- not_null_tables
- dep_tables.
- on_expr_dep_tables
The first two attributes are used to test whether an outer join can
be substituted for an inner join. The third attribute represents the
relation 'to be dependent on' for tables. If table t2 is dependent
on table t1, then in any evaluated execution plan table access to
table t2 must precede access to table t2. This relation is used also
to check whether the query contains invalid cross-references.
The forth attribute is an auxiliary one and is used to calculate
dep_tables.
As the attribute dep_tables qualifies possibles orders of tables in the
execution plan, the dependencies required by the straight join
modifiers are reflected in this attribute as well.
The function also removes all braces that can be removed from the join
expression without changing its meaning.
@note
An outer join can be replaced by an inner join if the where condition
or the join condition for an embedding nested join contains a conjunctive
predicate rejecting null values for some attribute of the inner tables.
E.g. in the query:
@code
SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a WHERE t2.b < 5
@endcode
the predicate t2.b < 5 rejects nulls.
The query is converted first to:
@code
SELECT * FROM t1 INNER JOIN t2 ON t2.a=t1.a WHERE t2.b < 5
@endcode
then to the equivalent form:
@code
SELECT * FROM t1, t2 ON t2.a=t1.a WHERE t2.b < 5 AND t2.a=t1.a
@endcode
Similarly the following query:
@code
SELECT * from t1 LEFT JOIN (t2, t3) ON t2.a=t1.a t3.b=t1.b
WHERE t2.c < 5
@endcode
is converted to:
@code
SELECT * FROM t1, (t2, t3) WHERE t2.c < 5 AND t2.a=t1.a t3.b=t1.b
@endcode
One conversion might trigger another:
@code
SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a
LEFT JOIN t3 ON t3.b=t2.b
WHERE t3 IS NOT NULL =>
SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a, t3
WHERE t3 IS NOT NULL AND t3.b=t2.b =>
SELECT * FROM t1, t2, t3
WHERE t3 IS NOT NULL AND t3.b=t2.b AND t2.a=t1.a
@endcode
The function removes all unnecessary braces from the expression
produced by the conversions.
E.g.
@code
SELECT * FROM t1, (t2, t3) WHERE t2.c < 5 AND t2.a=t1.a AND t3.b=t1.b
@endcode
finally is converted to:
@code
SELECT * FROM t1, t2, t3 WHERE t2.c < 5 AND t2.a=t1.a AND t3.b=t1.b
@endcode
It also will remove braces from the following queries:
@code
SELECT * from (t1 LEFT JOIN t2 ON t2.a=t1.a) LEFT JOIN t3 ON t3.b=t2.b
SELECT * from (t1, (t2,t3)) WHERE t1.a=t2.a AND t2.b=t3.b.
@endcode
The benefit of this simplification procedure is that it might return
a query for which the optimizer can evaluate execution plan with more
join orders. With a left join operation the optimizer does not
consider any plan where one of the inner tables is before some of outer
tables.
IMPLEMENTATION
The function is implemented by a recursive procedure. On the recursive
ascent all attributes are calculated, all outer joins that can be
converted are replaced and then all unnecessary braces are removed.
As join list contains join tables in the reverse order sequential
elimination of outer joins does not require extra recursive calls.
SEMI-JOIN NOTES
Remove all semi-joins that have are within another semi-join (i.e. have
an "ancestor" semi-join nest)
EXAMPLES
Here is an example of a join query with invalid cross references:
@code
SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t3.a LEFT JOIN t3 ON t3.b=t1.b
@endcode
@param thd thread handler
@param join_list list representation of the join to be converted
@param top true <=> cond is the where condition
@param in_sj TRUE <=> processing semi-join nest's children
@param[in,out] cond In: condition to which the join condition for converted
outer joins is to be added;
Out: new condition
@param changelog Don't specify this parameter, it is reserved for
recursive calls inside this function
@returns true for error, false for success
*/
bool
SELECT_LEX::simplify_joins(THD *thd,
List<TABLE_LIST> *join_list, bool top,
bool in_sj, Item **cond, uint *changelog)
{
/*
Each type of change done by this function, or its recursive calls, is
tracked in a bitmap:
*/
enum change
{
NONE= 0,
OUTER_JOIN_TO_INNER= 1 << 0,
JOIN_COND_TO_WHERE= 1 << 1,
PAREN_REMOVAL= 1 << 2,
SEMIJOIN= 1 << 3
};
uint changes= 0; // To keep track of changes.
if (changelog == NULL) // This is the top call.
changelog= &changes;
TABLE_LIST *table;
NESTED_JOIN *nested_join;
TABLE_LIST *prev_table= 0;
List_iterator<TABLE_LIST> li(*join_list);
const bool straight_join= active_options() & SELECT_STRAIGHT_JOIN;
DBUG_ENTER("simplify_joins");
/*
Try to simplify join operations from join_list.
The most outer join operation is checked for conversion first.
*/
while ((table= li++))
{
table_map used_tables;
table_map not_null_tables= (table_map) 0;
if ((nested_join= table->nested_join))
{
/*
If the element of join_list is a nested join apply
the procedure to its nested join list first.
*/
if (table->join_cond())
{
Item *join_cond= table->join_cond();
/*
If a join condition JC is attached to the table,
check all null rejected predicates in this condition.
If such a predicate over an attribute belonging to
an inner table of an embedded outer join is found,
the outer join is converted to an inner join and
the corresponding join condition is added to JC.
*/
if (simplify_joins(thd, &nested_join->join_list,
false, in_sj || table->sj_cond(),
&join_cond, changelog))
DBUG_RETURN(true);
if (join_cond != table->join_cond())
{
DBUG_ASSERT(join_cond);
table->set_join_cond(join_cond);
}
}
nested_join->used_tables= (table_map) 0;
nested_join->not_null_tables=(table_map) 0;
if (simplify_joins(thd, &nested_join->join_list, top,
in_sj || table->sj_cond(), cond, changelog))
DBUG_RETURN(true);
used_tables= nested_join->used_tables;
not_null_tables= nested_join->not_null_tables;
}
else
{
used_tables= table->map();
if (*cond)
not_null_tables= (*cond)->not_null_tables();
}
if (table->embedding)
{
table->embedding->nested_join->used_tables|= used_tables;
table->embedding->nested_join->not_null_tables|= not_null_tables;
}
if (!table->outer_join || (used_tables & not_null_tables))
{
/*
For some of the inner tables there are conjunctive predicates
that reject nulls => the outer join can be replaced by an inner join.
*/
if (table->outer_join)
{
*changelog|= OUTER_JOIN_TO_INNER;
table->outer_join= 0;
}
if (table->join_cond())
{
*changelog|= JOIN_COND_TO_WHERE;
/* Add join condition to the WHERE or upper-level join condition. */
if (*cond)
{
Item_cond_and *new_cond=
static_cast<Item_cond_and*>(and_conds(*cond, table->join_cond()));
if (!new_cond)
DBUG_RETURN(true);
new_cond->top_level_item();
/*
It is always a new item as both the upper-level condition and a
join condition existed
*/
DBUG_ASSERT(!new_cond->fixed);
if (new_cond->fix_fields(thd, NULL))
DBUG_RETURN(true);
/* If join condition has a pending rollback in THD::change_list */
List_iterator<Item> lit(*new_cond->argument_list());
Item *arg;
while ((arg= lit++))
{
/*
The join condition isn't necessarily the second argument anymore,
since fix_fields may have merged it into an existing AND expr.
*/
if (arg == table->join_cond())
thd->change_item_tree_place(table->join_cond_ref(), lit.ref());
else if (arg == *cond)
thd->change_item_tree_place(cond, lit.ref());
}
*cond= new_cond;
}
else
{
*cond= table->join_cond();
/* If join condition has a pending rollback in THD::change_list */
thd->change_item_tree_place(table->join_cond_ref(), cond);
}
table->set_join_cond(NULL);
}
}
if (!top)
continue;
/*
Only inner tables of non-convertible outer joins remain with
the join condition.
*/
if (table->join_cond())
{
table->dep_tables|= table->join_cond()->used_tables();
// At this point the joined tables always have an embedding join nest:
DBUG_ASSERT(table->embedding);
table->dep_tables&= ~table->embedding->nested_join->used_tables;
// Embedding table depends on tables used in embedded join conditions.
table->embedding->on_expr_dep_tables|= table->join_cond()->used_tables();
}
if (prev_table)
{
/* The order of tables is reverse: prev_table follows table */
if (prev_table->straight || straight_join)
prev_table->dep_tables|= used_tables;
if (prev_table->join_cond())
{
prev_table->dep_tables|= table->on_expr_dep_tables;
table_map prev_used_tables= prev_table->nested_join ?
prev_table->nested_join->used_tables :
prev_table->map();
/*
If join condition contains only references to inner tables
we still make the inner tables dependent on the outer tables.
It would be enough to set dependency only on one outer table
for them. Yet this is really a rare case.
Note:
PSEUDO_TABLE_BITS mask should not be counted as it
prevents update of inner table dependencies.
For example it might happen if RAND()/COUNT(*) function
is used in JOIN ON clause.
*/
if (!((prev_table->join_cond()->used_tables() & ~PSEUDO_TABLE_BITS) &
~prev_used_tables))
prev_table->dep_tables|= used_tables;
}
}
prev_table= table;
}
/*
Flatten nested joins that can be flattened.
no join condition and not a semi-join => can be flattened.
*/
li.rewind();
while ((table= li++))
{
nested_join= table->nested_join;
if (table->sj_cond() && !in_sj)
{
/*
If this is a semi-join that is not contained within another semi-join,
leave it intact (otherwise it is flattened)
*/
*changelog|= SEMIJOIN;
}
else if (nested_join && !table->join_cond())
{
*changelog|= PAREN_REMOVAL;
TABLE_LIST *tbl;
List_iterator<TABLE_LIST> it(nested_join->join_list);
while ((tbl= it++))
{
tbl->embedding= table->embedding;
tbl->join_list= table->join_list;
tbl->dep_tables|= table->dep_tables;
}
li.replace(nested_join->join_list);
}
}
if (changes)
{
Opt_trace_context * trace= &thd->opt_trace;
if (unlikely(trace->is_started()))
{
Opt_trace_object trace_wrapper(trace);
Opt_trace_object trace_object(trace, "transformations_to_nested_joins");
{
Opt_trace_array trace_changes(trace, "transformations");
if (changes & SEMIJOIN)
trace_changes.add_alnum("semijoin");
if (changes & OUTER_JOIN_TO_INNER)
trace_changes.add_alnum("outer_join_to_inner_join");
if (changes & JOIN_COND_TO_WHERE)
trace_changes.add_alnum("JOIN_condition_to_WHERE");
if (changes & PAREN_REMOVAL)
trace_changes.add_alnum("parenthesis_removal");
}
// the newly transformed query is worth printing
opt_trace_print_expanded_query(thd, this, &trace_object);
}
}
DBUG_RETURN(false);
}
/**
Record join nest info in the select block.
After simplification of inner join, outer join and semi-join structures:
- record the remaining semi-join structures in the enclosing query block.
- record transformed join conditions in TABLE_LIST objects.
This function is called recursively for each join nest and/or table
in the query block.
@param select The query block
@param tables List of tables and join nests
@return False if successful, True if failure
*/
bool SELECT_LEX::record_join_nest_info(List<TABLE_LIST> *tables)
{
TABLE_LIST *table;
List_iterator<TABLE_LIST> li(*tables);
DBUG_ENTER("record_join_nest_info");
while ((table= li++))
{
if (table->nested_join == NULL)
{
if (table->join_cond())
outer_join|= table->map();
continue;
}
if (record_join_nest_info(&table->nested_join->join_list))
DBUG_RETURN(true);
/*
sj_inner_tables is set properly later in pull_out_semijoin_tables().
This assignment is required in case pull_out_semijoin_tables()
is not called.
*/
if (table->sj_cond())
table->sj_inner_tables= table->nested_join->used_tables;
if (table->sj_cond() && sj_nests.push_back(table))
DBUG_RETURN(true);
if (table->join_cond())
outer_join|= table->nested_join->used_tables;
}
DBUG_RETURN(false);
}
static int subq_sj_candidate_cmp(Item_exists_subselect* const *el1,
Item_exists_subselect* const *el2)
{
/*
Remove this assert when we support semijoin on non-IN subqueries.
*/
DBUG_ASSERT((*el1)->substype() == Item_subselect::IN_SUBS &&
(*el2)->substype() == Item_subselect::IN_SUBS);
return ((*el1)->sj_convert_priority < (*el2)->sj_convert_priority) ? 1 :
( ((*el1)->sj_convert_priority == (*el2)->sj_convert_priority)? 0 : -1);
}
/**
Update table reference information for conditions and expressions due to
query blocks having been merged in from derived tables/views and due to
semi-join transformation.
This is needed for two reasons:
1. Since table numbers are changed, we need to update used_tables
information for all conditions and expressions that are possibly touched.
2. For semi-join, some column references are changed from outer references
to local references.
The function needs to recursively walk down into join nests,
in order to cover all conditions and expressions.
For a semi-join, tables from the subquery are added last in the query block.
This means that conditions and expressions from the outer query block
are unaffected. But all conditions inside the semi-join nest, including
join conditions, must have their table numbers changed.
For a derived table/view, tables from the subquery are merged into the
outer query, and this function is called for every derived table that is
merged in. This algorithm only works when derived tables are merged in
the order of their original table numbers.
A hypothetical example with a triple self-join over a mergeable view:
CREATE VIEW v AS SELECT t1.a, t2.b FROM t1 JOIN t2 USING (a);
SELECT v1.a, v1.b, v2.b, v3.b
FROM v AS v1 JOIN v AS v2 ON ... JOIN v AS v3 ON ...;
The analysis starts with three tables v1, v2 and v3 having numbers 0, 1, 2.
First we merge in v1, so we get (t1, t2, v2, v3). v2 and v3 are shifted up.
Tables from v1 need to have their table numbers altered (actually they do not
since both old and new numbers are 0 and 1, but this is a special case).
v2 and v3 are not merged in yet, so we delay pullout on them until they
are merged. Conditions and expressions from the outer query are not resolved
yet, so regular resolving will take of them later.
Then we merge in v2, so we get (t1, t2, t1, t2, v3). The tables from this
view gets numbers 2 and 3, and v3 gets number 4.
Because v2 had a higher number than the tables from v1, the join nest
representing v1 is unaffected. And v3 is still not merged, so the only
join nest we need to consider is v2.
Finally we merge in v3, and then we have tables (t1, t2, t1, t2, t1, t2),
with numbers 0 through 5.
Again, since v3 has higher number than any of the already merged in views,
only this join nest needs the pullout.
@param parent_select Query block being merged into
@param removed_select Query block that is removed (subquery)
@param tr Table object this pullout is applied to
@param table_adjust Number of positions that a derived table nest is
adjusted, used to fix up semi-join related fields.
Tables are adjusted from position N to N+table_adjust
*/
static void fix_tables_after_pullout(st_select_lex *parent_select,
st_select_lex *removed_select,
TABLE_LIST *tr,
uint table_adjust)
{
if (tr->is_merged())
{
// Update select list of merged derived tables:
for (Field_translator *transl= tr->field_translation;
transl < tr->field_translation_end;
transl++)
{
DBUG_ASSERT(transl->item->fixed);
transl->item->fix_after_pullout(parent_select, removed_select);
}
// Update used table info for the WHERE clause of the derived table
DBUG_ASSERT(!tr->derived_where_cond ||
tr->derived_where_cond->fixed);
if (tr->derived_where_cond)
tr->derived_where_cond->fix_after_pullout(parent_select,
removed_select);
}
/*
If join_cond() is fixed, it contains a join condition from a subquery
that has already been resolved. Call fix_after_pullout() to update
used table information since table numbers may have changed.
If join_cond() is not fixed, it contains a condition that was generated
in the derived table merge operation, which will be fixed later.
This condition may also contain a fixed part, but this is saved as
derived_where_cond and is pulled out explicitly.
*/
if (tr->join_cond() && tr->join_cond()->fixed)
tr->join_cond()->fix_after_pullout(parent_select, removed_select);
if (tr->nested_join)
{
// In case a derived table is merged-in, these fields need adjustment:
tr->nested_join->sj_corr_tables<<= table_adjust;
tr->nested_join->sj_depends_on<<= table_adjust;
List_iterator<TABLE_LIST> it(tr->nested_join->join_list);
TABLE_LIST *child;
while ((child= it++))
fix_tables_after_pullout(parent_select, removed_select, child,
table_adjust);
}
}
/**
Convert a subquery predicate of this query block into a TABLE_LIST semi-join
nest.
@param subq_pred Subquery predicate to be converted.
This is either an IN, =ANY or EXISTS predicate.
@retval FALSE OK
@retval TRUE Error
@details
The following transformations are performed:
1. IN/=ANY predicates on the form:
SELECT ...
FROM ot1 ... otN
WHERE (oe1, ... oeM) IN (SELECT ie1, ..., ieM)
FROM it1 ... itK
[WHERE inner-cond])
[AND outer-cond]
[GROUP BY ...] [HAVING ...] [ORDER BY ...]
are transformed into:
SELECT ...
FROM (ot1 ... otN) SJ (it1 ... itK)
ON (oe1, ... oeM) = (ie1, ..., ieM)
[AND inner-cond]
[WHERE outer-cond]
[GROUP BY ...] [HAVING ...] [ORDER BY ...]
Notice that the inner-cond may contain correlated and non-correlated
expressions. Further transformations will analyze and break up such
expressions.
Prepared Statements: the transformation is permanent:
- Changes in TABLE_LIST structures are naturally permanent
- Item tree changes are performed on statement MEM_ROOT:
= we activate statement MEM_ROOT
= this function is called before the first fix_prepare_information call.
This is intended because the criteria for subquery-to-sj conversion remain
constant for the lifetime of the Prepared Statement.
*/
bool
SELECT_LEX::convert_subquery_to_semijoin(Item_exists_subselect *subq_pred)
{
TABLE_LIST *emb_tbl_nest= NULL;
List<TABLE_LIST> *emb_join_list= &top_join_list;
THD *const thd= subq_pred->unit->thd;
DBUG_ENTER("convert_subquery_to_semijoin");
DBUG_ASSERT(subq_pred->substype() == Item_subselect::IN_SUBS);
bool outer_join= false; // True if predicate is inner to an outer join
/*
Find out where to insert the semi-join nest and the generated condition.
For t1 LEFT JOIN t2, embedding_join_nest will be t2.
Note that t2 may be a simple table or may itself be a join nest
(e.g. in the case t1 LEFT JOIN (t2 JOIN t3))
*/
if (subq_pred->embedding_join_nest != NULL)
{
// Is this on inner side of an outer join?
outer_join= subq_pred->embedding_join_nest->is_inner_table_of_outer_join();
if (subq_pred->embedding_join_nest->nested_join)
{
/*
We're dealing with
... [LEFT] JOIN ( ... ) ON (subquery AND condition) ...
The sj-nest will be inserted into the brackets nest.
*/
emb_tbl_nest= subq_pred->embedding_join_nest;
emb_join_list= &emb_tbl_nest->nested_join->join_list;
}
else if (!subq_pred->embedding_join_nest->outer_join)
{
/*
We're dealing with
... INNER JOIN tblX ON (subquery AND condition) ...
The sj-nest will be tblX's "sibling", i.e. another child of its
parent. This is ok because tblX is joined as an inner join.
*/
emb_tbl_nest= subq_pred->embedding_join_nest->embedding;
if (emb_tbl_nest)
emb_join_list= &emb_tbl_nest->nested_join->join_list;
}
else if (!subq_pred->embedding_join_nest->nested_join)
{
TABLE_LIST *outer_tbl= subq_pred->embedding_join_nest;
/*
We're dealing with
... LEFT JOIN tbl ON (on_expr AND subq_pred) ...
we'll need to convert it into:
... LEFT JOIN ( tbl SJ (subq_tables) ) ON (on_expr AND subq_pred) ...
| |
|<----- wrap_nest ---->|
Q: other subqueries may be pointing to this element. What to do?
A1: simple solution: copy *subq_pred->embedding_join_nest= *parent_nest.
But we'll need to fix other pointers.
A2: Another way: have TABLE_LIST::next_ptr so the following
subqueries know the table has been nested.
A3: changes in the TABLE_LIST::outer_join will make everything work
automatically.
*/
TABLE_LIST *const wrap_nest=
TABLE_LIST::new_nested_join(thd->mem_root, "(sj-wrap)",
outer_tbl->embedding, outer_tbl->join_list,
this);
if (wrap_nest == NULL)
DBUG_RETURN(true);
wrap_nest->nested_join->join_list.push_back(outer_tbl);
outer_tbl->embedding= wrap_nest;
outer_tbl->join_list= &wrap_nest->nested_join->join_list;
/*
An important note, if this 'PREPARE stmt'.
The FROM clause of the outer query now looks like
CONCAT(original FROM clause of outer query, sj-nest).
Given that the original FROM clause is reversed, this list is
interpreted as "sj-nest is first".
Thus, at a next execution, setup_natural_join_types() will decide that
the name resolution context of the FROM clause should start at the
first inner table in sj-nest.
However, note that in the present function we do not change
first_name_resolution_table (and friends) of sj-inner tables.
So, at the next execution, name resolution for columns of
outer-table columns is bound to fail (the first inner table does
not have outer tables in its chain of resolution).
Fortunately, Item_field::cached_table, which is set during resolution
of 'PREPARE stmt', gives us the answer and avoids a failing search.
*/
/*
wrap_nest will take place of outer_tbl, so move the outer join flag
and join condition.
*/
wrap_nest->outer_join= outer_tbl->outer_join;
outer_tbl->outer_join= 0;
// There are item-rollback problems in this function: see bug#16926177
wrap_nest->set_join_cond(outer_tbl->join_cond()->real_item());
outer_tbl->set_join_cond(NULL);
List_iterator<TABLE_LIST> li(*wrap_nest->join_list);
TABLE_LIST *tbl;
while ((tbl= li++))
{
if (tbl == outer_tbl)
{
li.replace(wrap_nest);
break;
}
}
/*
Ok now wrap_nest 'contains' outer_tbl and we're ready to add the
semi-join nest into it
*/
emb_join_list= &wrap_nest->nested_join->join_list;
emb_tbl_nest= wrap_nest;
}
}
TABLE_LIST *const sj_nest=
TABLE_LIST::new_nested_join(thd->mem_root, "(sj-nest)",
emb_tbl_nest, emb_join_list, this);
if (sj_nest == NULL)
DBUG_RETURN(true); /* purecov: inspected */
NESTED_JOIN *const nested_join= sj_nest->nested_join;
/* Nests do not participate in those 'chains', so: */
/* sj_nest->next_leaf= sj_nest->next_local= sj_nest->next_global == NULL*/
emb_join_list->push_back(sj_nest);
/*
Natural joins inside a semi-join nest were already processed when the
subquery went through initial preparation.
*/
sj_nest->nested_join->natural_join_processed= true;
/*
nested_join->used_tables and nested_join->not_null_tables are
initialized in simplify_joins().
*/
st_select_lex *const subq_select= subq_pred->unit->first_select();
nested_join->query_block_id= subq_select->select_number;
// Merge tables from underlying query block into this join nest
if (sj_nest->merge_underlying_tables(subq_select))
DBUG_RETURN(true); /* purecov: inspected */
/*
Add tables from subquery at end of leaf table chain.
(This also means that table map for parent query block tables are unchanged)
*/
TABLE_LIST *tl;
for (tl= leaf_tables; tl->next_leaf; tl= tl->next_leaf)
{}
tl->next_leaf= subq_select->leaf_tables;
// Add tables from subquery at end of next_local chain.
for (tl= get_table_list(); tl->next_local; tl= tl->next_local)
{}
tl->next_local= subq_select->get_table_list();
// Note that subquery's tables are already in the next_global chain
// Remove the original subquery predicate from the WHERE/ON
// The subqueries were replaced for Item_int(1) earlier
// @todo also reset the 'with_subselect' there.
// Walk through child's tables and adjust table map
uint table_no= leaf_table_count;
for (tl= subq_select->leaf_tables; tl; tl= tl->next_leaf, table_no++)
tl->set_tableno(table_no);
// Adjust table and expression counts in parent query block:
derived_table_count+= subq_select->derived_table_count;
materialized_derived_table_count+=
subq_select->materialized_derived_table_count;
has_sj_nests|= subq_select->has_sj_nests;
partitioned_table_count+= subq_select->partitioned_table_count;
leaf_table_count+= subq_select->leaf_table_count;
cond_count+= subq_select->cond_count;
between_count+= subq_select->between_count;
if (outer_join)
propagate_nullability(&sj_nest->nested_join->join_list, true);
nested_join->sj_outer_exprs.empty();
nested_join->sj_inner_exprs.empty();
/*
@todo: Add similar conversion for subqueries other than IN.
*/
if (subq_pred->substype() == Item_subselect::IN_SUBS)
{
Item_in_subselect *in_subq_pred= (Item_in_subselect *)subq_pred;
DBUG_ASSERT(is_fixed_or_outer_ref(in_subq_pred->left_expr));
in_subq_pred->exec_method= Item_exists_subselect::EXEC_SEMI_JOIN;
/*
sj_corr_tables is supposed to contain non-trivially correlated tables,
but here it is set to contain all correlated tables.
@todo: Add analysis step that assigns only the set of non-trivially
correlated tables to sj_corr_tables.
*/
nested_join->sj_corr_tables= subq_pred->used_tables();
/*
sj_depends_on contains the set of outer tables referred in the
subquery's WHERE clause as well as tables referred in the IN predicate's
left-hand side.
*/
nested_join->sj_depends_on= subq_pred->used_tables() |
in_subq_pred->left_expr->used_tables();
// Put the subquery's WHERE into semi-join's condition.
Item *sj_cond= subq_select->where_cond();
/*
Create the IN-equalities and inject them into semi-join's ON condition.
Additionally, for LooseScan strategy
- Record the number of IN-equalities.
- Create list of pointers to (oe1, ..., ieN). We'll need the list to
see which of the expressions are bound and which are not (for those
we'll produce a distinct stream of (ie_i1,...ie_ik).
(TODO: can we just create a list of pointers and hope the expressions
will not substitute themselves on fix_fields()? or we need to wrap
them into Item_direct_view_refs and store pointers to those. The
pointers to Item_direct_view_refs are guaranteed to be stable as
Item_direct_view_refs doesn't substitute itself with anything in
Item_direct_view_ref::fix_fields.
We have a special case for IN predicates with a scalar subquery or a
row subquery in the predicand (left operand), such as this:
(SELECT 1,2 FROM t1) IN (SELECT x,y FROM t2)
We cannot make the join condition 1=x AND 2=y, since that might evaluate
to TRUE even if t1 is empty. Instead make the join condition
(SELECT 1,2 FROM t1) = (x,y) in this case.
*/
Item_subselect *left_subquery=
(in_subq_pred->left_expr->type() == Item::SUBSELECT_ITEM) ?
static_cast<Item_subselect *>(in_subq_pred->left_expr) : NULL;
if (left_subquery &&
(left_subquery->substype() == Item_subselect::SINGLEROW_SUBS))
{
List<Item> ref_list;
Item *header= subq_select->ref_pointer_array[0];
for (uint i= 1; i < in_subq_pred->left_expr->cols(); i++)
{
ref_list.push_back(subq_select->ref_pointer_array[i]);
}
Item_row *right_expr= new Item_row(header, ref_list);
if (!right_expr)
DBUG_RETURN(true); /* purecov: inspected */
nested_join->sj_outer_exprs.push_back(in_subq_pred->left_expr);
nested_join->sj_inner_exprs.push_back(right_expr);
Item_func_eq *item_eq=
new Item_func_eq(in_subq_pred->left_expr,
right_expr);
if (item_eq == NULL)
DBUG_RETURN(true); /* purecov: inspected */
sj_cond= and_items(sj_cond, item_eq);
if (sj_cond == NULL)
DBUG_RETURN(true); /* purecov: inspected */
}
else
{
for (uint i= 0; i < in_subq_pred->left_expr->cols(); i++)
{
nested_join->sj_outer_exprs.push_back(in_subq_pred->left_expr->
element_index(i));
nested_join->sj_inner_exprs.push_back(subq_select->ref_pointer_array[i]);
Item_func_eq *item_eq=
new Item_func_eq(in_subq_pred->left_expr->element_index(i),
subq_select->ref_pointer_array[i]);
if (item_eq == NULL)
DBUG_RETURN(true); /* purecov: inspected */
sj_cond= and_items(sj_cond, item_eq);
if (sj_cond == NULL)
DBUG_RETURN(true); /* purecov: inspected */
}
}
// Fix the created equality and AND
Opt_trace_array sj_on_trace(&thd->opt_trace,
"evaluating_constant_semijoin_conditions");
sj_cond->top_level_item();
if (sj_cond->fix_fields(thd, &sj_cond))
DBUG_RETURN(true); /* purecov: inspected */
// Attach semi-join condition to semi-join nest
sj_nest->set_sj_cond(sj_cond);
}
// Unlink the subquery's query expression:
subq_select->master_unit()->exclude_level();
/*
Add Name res objects belonging to subquery to parent query block.
Update all name res objects to have this base query block.
*/
for (Name_resolution_context *ctx= subq_select->first_context;
ctx != NULL;
ctx= ctx->next_context)
{
ctx->select_lex= this;
if (ctx->next_context == NULL)
{
ctx->next_context= first_context;
first_context= subq_select->first_context;
subq_select->first_context= NULL;
break;
}
}
repoint_contexts_of_join_nests(subq_select->top_join_list);
// Update table map for the semi-join condition
sj_nest->sj_cond()->fix_after_pullout(this, subq_select);
// Update table map for semi-join nest's WHERE condition and join conditions
fix_tables_after_pullout(this, subq_select, sj_nest, 0);
//TODO fix QT_
DBUG_EXECUTE("where",
print_where(sj_nest->sj_cond(),"SJ-COND", QT_ORDINARY););
if (emb_tbl_nest)
{
// Inject semi-join condition into parent's join condition
emb_tbl_nest->set_join_cond(and_items(emb_tbl_nest->join_cond(),
sj_nest->sj_cond()));
if (emb_tbl_nest->join_cond() == NULL)
DBUG_RETURN(true);
emb_tbl_nest->join_cond()->top_level_item();
if (!emb_tbl_nest->join_cond()->fixed &&
emb_tbl_nest->join_cond()->fix_fields(thd,
emb_tbl_nest->join_cond_ref()))
DBUG_RETURN(true);
}
else
{
// Inject semi-join condition into parent's WHERE condition
m_where_cond= and_items(m_where_cond, sj_nest->sj_cond());
if (m_where_cond == NULL)
DBUG_RETURN(true);
m_where_cond->top_level_item();
if (m_where_cond->fix_fields(thd, &m_where_cond))
DBUG_RETURN(true);
}
if (subq_select->ftfunc_list->elements &&
add_ftfunc_list(subq_select->ftfunc_list))
DBUG_RETURN(true); /* purecov: inspected */
// This query block has semi-join nests
has_sj_nests= true;
DBUG_RETURN(false);
}
/**
Merge a derived table or view into a query block.
If some constraint prevents the derived table from being merged then do
nothing, which means the table will be prepared for materialization later.
After this call, check is_merged() to see if the table was really merged.
@param thd Thread handler
@param derived_table Derived table which is to be merged.
@return false if successful, true if error
*/
bool SELECT_LEX::merge_derived(THD *thd, TABLE_LIST *derived_table)
{
DBUG_ENTER("SELECT_LEX::merge_derived");
if (!derived_table->is_view_or_derived() || derived_table->is_merged())
DBUG_RETURN(false);
SELECT_LEX_UNIT *const derived_unit= derived_table->derived_unit();
// A derived table must be prepared before we can merge it
DBUG_ASSERT(derived_unit->is_prepared());
LEX *const lex= parent_lex;
// Check whether the outer query allows merged views
if ((master_unit() == lex->unit &&
!lex->can_use_merged()) ||
lex->can_not_use_merged())
DBUG_RETURN(false);
// Check whether derived table is mergeable, and directives allow merging
if (!derived_unit->is_mergeable() ||
derived_table->algorithm == VIEW_ALGORITHM_TEMPTABLE ||
(!thd->optimizer_switch_flag(OPTIMIZER_SWITCH_DERIVED_MERGE) &&
derived_table->algorithm != VIEW_ALGORITHM_MERGE))
DBUG_RETURN(false);
SELECT_LEX *const derived_select= derived_unit->first_select();
/*
If STRAIGHT_JOIN is specified, it is not valid to merge in a query block
that contains semi-join nests
*/
if ((active_options() & SELECT_STRAIGHT_JOIN) && derived_select->has_sj_nests)
DBUG_RETURN(false);
// Check that we have room for the merged tables in the table map:
if (leaf_table_count + derived_select->leaf_table_count - 1 > MAX_TABLES)
DBUG_RETURN(false);
derived_table->set_merged();
DBUG_PRINT("info", ("algorithm: MERGE"));
Opt_trace_context *const trace= &thd->opt_trace;
Opt_trace_object trace_wrapper(trace);
Opt_trace_object trace_derived(trace,
derived_table->is_view() ? "view" : "derived");
trace_derived.add_utf8_table(derived_table).
add("select#", derived_select->select_number).
add("merged", true);
Prepared_stmt_arena_holder ps_arena_holder(thd);
// Save offset for table number adjustment
uint table_adjust= derived_table->tableno();
// Set up permanent list of underlying tables of a merged view
derived_table->merge_underlying_list= derived_select->get_table_list();
if (derived_table->updatable_view &&
(derived_table->merge_underlying_list == NULL ||
derived_table->merge_underlying_list->is_updatable()))
derived_table->set_updatable();
derived_table->effective_with_check=
lex->get_effective_with_check(derived_table);
// Add a nested join object to the derived table object
if (!(derived_table->nested_join=
(NESTED_JOIN *) thd->mem_calloc(sizeof(NESTED_JOIN))))
DBUG_RETURN(true); /* purecov: inspected */
derived_table->nested_join->join_list.empty();//Should be done by constructor!
// Merge tables from underlying query block into this join nest
if (derived_table->merge_underlying_tables(derived_select))
DBUG_RETURN(true); /* purecov: inspected */
// Replace derived table in leaf table list with underlying tables:
for (TABLE_LIST **tl= &leaf_tables; *tl; tl= &(*tl)->next_leaf)
{
if (*tl == derived_table)
{
for (TABLE_LIST *leaf= derived_select->leaf_tables; leaf;
leaf= leaf->next_leaf)
{
if (leaf->next_leaf == NULL)
{
leaf->next_leaf= (*tl)->next_leaf;
break;
}
}
*tl= derived_select->leaf_tables;
break;
}
}
leaf_table_count+= (derived_select->leaf_table_count - 1);
derived_table_count+= derived_select->derived_table_count;
materialized_derived_table_count+=
derived_select->materialized_derived_table_count;
has_sj_nests|= derived_select->has_sj_nests;
partitioned_table_count+= derived_select->partitioned_table_count;
cond_count+= derived_select->cond_count;
between_count+= derived_select->between_count;
// Propagate schema table indication:
// @todo: Add to BASE options instead
if (derived_select->active_options() & OPTION_SCHEMA_TABLE)
add_base_options(OPTION_SCHEMA_TABLE);
// Propagate nullability for derived tables within outer joins:
if (derived_table->is_inner_table_of_outer_join())
propagate_nullability(&derived_table->nested_join->join_list, true);
select_n_having_items+= derived_select->select_n_having_items;
// Merge the WHERE clause into the outer query block
if (derived_table->merge_where(thd))
DBUG_RETURN(true); /* purecov: inspected */
if (derived_table->create_field_translation(thd))
DBUG_RETURN(true); /* purecov: inspected */
// Exclude the derived table query expression from query graph.
derived_unit->exclude_level();
// Don't try to access it:
derived_table->set_derived_unit((SELECT_LEX_UNIT *)1);
/*
Add Name res objects belonging to subquery to parent query block.
Update all name res objects to have this base query block.
*/
for (Name_resolution_context *ctx= derived_select->first_context;
ctx != NULL;
ctx= ctx->next_context)
{
ctx->select_lex= this;
if (ctx->next_context == NULL)
{
ctx->next_context= first_context;
first_context= derived_select->first_context;
derived_select->first_context= NULL;
break;
}
}
repoint_contexts_of_join_nests(derived_select->top_join_list);
// Leaf tables have been shuffled, so update table numbers for them
remap_tables(thd);
// Update table info of referenced expressions after query block is merged
fix_tables_after_pullout(this, derived_select, derived_table, table_adjust);
if (derived_select->is_ordered())
{
/*
An ORDER BY clause is moved to an outer query block
- if the outer query block allows ordering, and
- that refers to this view/derived table only, and
- is not part of a UNION, and
- may have a WHERE clause but is not grouped or aggregated and is not
itself ordered.
Otherwise the ORDER BY clause is ignored.
Up to version 5.6 included, ORDER BY was unconditionally merged.
Currently we only merge in the simple case above, which ensures
backward compatibility for most reasonable use cases.
Note that table numbers in order_list do not need updating, since
the outer query contains only one table reference.
*/
// LIMIT currently blocks derived table merge
DBUG_ASSERT(!derived_select->has_limit());
if (!(master_unit()->is_union() ||
lex->sql_command == SQLCOM_UPDATE_MULTI ||
lex->sql_command == SQLCOM_DELETE_MULTI ||
is_grouped() ||
is_distinct() ||
is_ordered() ||
get_table_list()->next_local != NULL))
order_list.push_back(&derived_select->order_list);
}
// Add any full-text functions from derived table into outer query
if (derived_select->ftfunc_list->elements &&
add_ftfunc_list(derived_select->ftfunc_list))
DBUG_RETURN(true); /* purecov: inspected */
DBUG_RETURN(false);
}
/**
Destructively replaces a sub-condition inside a condition tree. The
parse tree is also altered.
@note Because of current requirements for semijoin flattening, we do not
need to recurse here, hence this function will only examine the top-level
AND conditions. (see SELECT_LEX::prepare, comment starting with "Check if
the subquery predicate can be executed via materialization".)
@param thd thread handler
@param tree Must be the handle to the top level condition. This is needed
when the top-level condition changes.
@param old_cond The condition to be replaced.
@param new_cond The condition to be substituted.
@param do_fix_fields If true, Item::fix_fields(THD*, Item**) is called for
the new condition.
@return error status
@retval true If there was an error.
@retval false If successful.
*/
static bool replace_subcondition(THD *thd, Item **tree,
Item *old_cond, Item *new_cond,
bool do_fix_fields)
{
if (*tree == old_cond)
{
*tree= new_cond;
if (do_fix_fields && new_cond->fix_fields(thd, tree))
return TRUE;
return FALSE;
}
else if ((*tree)->type() == Item::COND_ITEM)
{
List_iterator<Item> li(*((Item_cond*)(*tree))->argument_list());
Item *item;
while ((item= li++))
{
if (item == old_cond)
{
li.replace(new_cond);
if (do_fix_fields && new_cond->fix_fields(thd, li.ref()))
return TRUE;
return FALSE;
}
}
}
else
// If we came here it means there were an error during prerequisites check.
DBUG_ASSERT(FALSE);
return TRUE;
}
/*
Convert semi-join subquery predicates into semi-join join nests
DESCRIPTION
Convert candidate subquery predicates into semi-join join nests. This
transformation is performed once in query lifetime and is irreversible.
Conversion of one subquery predicate
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We start with a join that has a semi-join subquery:
SELECT ...
FROM ot, ...
WHERE oe IN (SELECT ie FROM it1 ... itN WHERE subq_where) AND outer_where
and convert it into a semi-join nest:
SELECT ...
FROM ot SEMI JOIN (it1 ... itN), ...
WHERE outer_where AND subq_where AND oe=ie
that is, in order to do the conversion, we need to
* Create the "SEMI JOIN (it1 .. itN)" part and add it into the parent
query's FROM structure.
* Add "AND subq_where AND oe=ie" into parent query's WHERE (or ON if
the subquery predicate was in an ON expression)
* Remove the subquery predicate from the parent query's WHERE
Considerations when converting many predicates
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A join may have at most MAX_TABLES tables. This may prevent us from
flattening all subqueries when the total number of tables in parent and
child selects exceeds MAX_TABLES. In addition, one slot is reserved per
semi-join nest, in case the subquery needs to be materialized in a
temporary table.
We deal with this problem by flattening children's subqueries first and
then using a heuristic rule to determine each subquery predicate's
"priority".
RETURN
FALSE OK
TRUE Error
*/
bool SELECT_LEX::flatten_subqueries()
{
DBUG_ENTER("flatten_subqueries");
if (sj_candidates->empty())
DBUG_RETURN(FALSE);
Item_exists_subselect **subq,
**subq_begin= sj_candidates->begin(),
**subq_end= sj_candidates->end();
THD *const thd= (*subq_begin)->unit->thd;
Opt_trace_context *const trace= &thd->opt_trace;
/*
Semijoin flattening is bottom-up. Indeed, we have this execution flow,
for SELECT#1 WHERE X IN (SELECT #2 WHERE Y IN (SELECT#3)) :
SELECT_LEX::prepare() (select#1)
-> fix_fields() on IN condition
-> SELECT_LEX::prepare() on subquery (select#2)
-> fix_fields() on IN condition
-> SELECT_LEX::prepare() on subquery (select#3)
<- SELECT_LEX::prepare()
<- fix_fields()
-> flatten_subqueries: merge #3 in #2
<- flatten_subqueries
<- SELECT_LEX::prepare()
<- fix_fields()
-> flatten_subqueries: merge #2 in #1
Note that flattening of #(N) is done by its parent JOIN#(N-1), because
there are cases where flattening is not possible and only the parent can
know.
*/
for (subq= subq_begin; subq < subq_end; subq++)
{
/*
Currently, we only support transformation of IN subqueries.
*/
DBUG_ASSERT((*subq)->substype() == Item_subselect::IN_SUBS);
st_select_lex *child_select= (*subq)->unit->first_select();
// Check that we proceeded bottom-up
DBUG_ASSERT(child_select->sj_candidates == NULL);
(*subq)->sj_convert_priority=
(((*subq)->unit->uncacheable & UNCACHEABLE_DEPENDENT) ? MAX_TABLES : 0) +
child_select->leaf_table_count;
}
/*
2. Pick which subqueries to convert:
sort the subquery array
- prefer correlated subqueries over uncorrelated;
- prefer subqueries that have greater number of outer tables;
*/
my_qsort(subq_begin,
sj_candidates->size(), sj_candidates->element_size(),
reinterpret_cast<qsort_cmp>(subq_sj_candidate_cmp));
// A permanent transformation is going to start, so:
Prepared_stmt_arena_holder ps_arena_holder(thd);
// #tables-in-parent-query + #tables-in-subquery + sj nests <= MAX_TABLES
/* Replace all subqueries to be flattened with Item_int(1) */
uint table_count= leaf_table_count;
for (subq= subq_begin; subq < subq_end; subq++)
{
// Add the tables in the subquery nest plus one in case of materialization:
const uint tables_added=
(*subq)->unit->first_select()->leaf_table_count + 1;
(*subq)->sj_chosen= table_count + tables_added <= MAX_TABLES;
if (!(*subq)->sj_chosen)
continue;
table_count+= tables_added;
// In WHERE/ON of parent query, replace IN(subq) with "1" (<=>TRUE)
Item **tree= ((*subq)->embedding_join_nest == NULL) ?
&m_where_cond :
(*subq)->embedding_join_nest->join_cond_ref();
if (replace_subcondition(thd, tree, *subq, new Item_int(1), FALSE))
DBUG_RETURN(TRUE); /* purecov: inspected */
}
for (subq= subq_begin; subq < subq_end; subq++)
{
if (!(*subq)->sj_chosen)
continue;
OPT_TRACE_TRANSFORM(trace, oto0, oto1,
(*subq)->unit->first_select()->select_number,
"IN (SELECT)", "semijoin");
oto1.add("chosen", true);
if (convert_subquery_to_semijoin(*subq))
DBUG_RETURN(TRUE);
}
/*
3. Finalize the subqueries that we did not convert,
ie. perform IN->EXISTS rewrite.
*/
for (subq= subq_begin; subq < subq_end; subq++)
{
if ((*subq)->sj_chosen)
continue;
{
OPT_TRACE_TRANSFORM(trace, oto0, oto1,
(*subq)->unit->first_select()->select_number,
"IN (SELECT)", "semijoin");
oto1.add("chosen", false);
}
Item_subselect::trans_res res;
(*subq)->changed= 0;
(*subq)->fixed= 0;
SELECT_LEX *save_select_lex= thd->lex->current_select();
thd->lex->set_current_select((*subq)->unit->first_select());
// This is the only part of the function which uses a JOIN.
res= (*subq)->select_transformer((*subq)->unit->first_select());
thd->lex->set_current_select(save_select_lex);
if (res == Item_subselect::RES_ERROR)
DBUG_RETURN(TRUE);
(*subq)->changed= 1;
(*subq)->fixed= 1;
Item *substitute= (*subq)->substitution;
const bool do_fix_fields= !(*subq)->substitution->fixed;
const bool subquery_in_join_clause= (*subq)->embedding_join_nest != NULL;
Item **tree= subquery_in_join_clause ?
((*subq)->embedding_join_nest->join_cond_ref()) : &m_where_cond;
if (replace_subcondition(thd, tree, *subq, substitute, do_fix_fields))
DBUG_RETURN(TRUE);
(*subq)->substitution= NULL;
}
sj_candidates->clear();
DBUG_RETURN(FALSE);
}
/**
Propagate nullability into inner tables of outer join operation
@param tables: List of tables and join nests, start at top_join_list
@param nullable: true: Set all underlying tables as nullable
*/
static void propagate_nullability(List<TABLE_LIST> *tables, bool nullable)
{
List_iterator<TABLE_LIST> li(*tables);
TABLE_LIST *tr;
while ((tr= li++))
{
if (tr->table && !tr->table->is_nullable() && (nullable || tr->outer_join))
tr->table->set_nullable();
if (tr->nested_join == NULL)
continue;
propagate_nullability(&tr->nested_join->join_list,
nullable || tr->outer_join);
}
}
/**
Propagate exclusion from unique table check into all subqueries belonging
to this query block.
This function can be applied to all subqueries of a materialized derived
table or view.
*/
void st_select_lex::propagate_unique_test_exclusion()
{
for (SELECT_LEX_UNIT *unit= first_inner_unit(); unit; unit= unit->next_unit())
for (SELECT_LEX *sl= unit->first_select(); sl; sl= sl->next_select())
sl->propagate_unique_test_exclusion();
exclude_from_table_unique_test= true;
}
/**
Add a list of full-text function elements into a query block.
@param ftfuncs List of full-text function elements to add.
@returns false if success, true if error
*/
bool SELECT_LEX::add_ftfunc_list(List<Item_func_match> *ftfuncs)
{
Item_func_match *ifm;
List_iterator_fast<Item_func_match> li(*ftfuncs);
while ((ifm= li++))
{
if (ftfunc_list->push_front(ifm))
return true; /* purecov: inspected */
}
return false;
}
/**
Go through a list of tables and join nests, recursively, and repoint
its select_lex pointer.
@param join_list List of tables and join nests
*/
void SELECT_LEX::repoint_contexts_of_join_nests(List<TABLE_LIST> join_list)
{
List_iterator_fast<TABLE_LIST> ti(join_list);
TABLE_LIST *tbl;
while ((tbl= ti++))
{
tbl->select_lex= this;
if (tbl->nested_join)
repoint_contexts_of_join_nests(tbl->nested_join->join_list);
}
}
/**
Fix fields referenced from inner query blocks.
@param thd Thread handle
@details
The function serves 3 purposes
- adds fields referenced from inner query blocks to the current select list
- Decides which class to use to reference the items (Item_ref or
Item_direct_ref)
- fixes references (Item_ref objects) to these fields.
If a field isn't already on the select list and the ref_ptrs array
is provided then it is added to the all_fields list and the pointer to
it is saved in the ref_ptrs array.
The class to access the outer field is determined by the following rules:
-#. If the outer field isn't used under an aggregate function then the
Item_ref class should be used.
-#. If the outer field is used under an aggregate function and this
function is, in turn, aggregated in the query block where the outer
field was resolved or some query nested therein, then the
Item_direct_ref class should be used. Also it should be used if we are
grouping by a subquery containing the outer field.
The resolution is done here and not at the fix_fields() stage as
it can be done only after aggregate functions are fixed and pulled up to
selects where they are to be aggregated.
When the class is chosen it substitutes the original field in the
Item_outer_ref object.
After this we proceed with fixing references (Item_outer_ref objects) to
this field from inner subqueries.
@return false if success, true if error
*/
bool SELECT_LEX::fix_inner_refs(THD *thd)
{
Item_outer_ref *ref;
List_iterator<Item_outer_ref> ref_it(inner_refs_list);
while ((ref= ref_it++))
{
bool direct_ref= false;
Item *item= ref->outer_ref;
Item **item_ref= ref->ref;
/*
TODO: this field item already might be present in the select list.
In this case instead of adding new field item we could use an
existing one. The change will lead to less operations for copying fields,
smaller temporary tables and less data passed through filesort.
*/
if (!ref_ptrs.is_null() && !ref->found_in_select_list)
{
int el= all_fields.elements;
ref_ptrs[el]= item;
/* Add the field item to the select list of the current select. */
all_fields.push_front(item);
/*
If it's needed reset each Item_ref item that refers this field with
a new reference taken from ref_pointer_array.
*/
item_ref= &ref_ptrs[el];
}
if (ref->in_sum_func)
{
if (ref->in_sum_func->nest_level > nest_level)
direct_ref= true;
else
{
for (Item_sum *sum_func= ref->in_sum_func;
sum_func && sum_func->aggr_level >= nest_level;
sum_func= sum_func->in_sum_func)
{
if (sum_func->aggr_level == nest_level)
{
direct_ref= true;
break;
}
}
}
}
else
{
/*
Check if GROUP BY item trees contain the outer ref:
in this case we have to use Item_direct_ref instead of Item_ref.
*/
for (ORDER *group= group_list.first; group; group= group->next)
{
if ((*group->item)->walk(&Item::find_item_processor, walk_subquery,
(uchar *) ref))
{
direct_ref= true;
break;
}
}
}
Item_ref *const new_ref= direct_ref ?
new Item_direct_ref(ref->context, item_ref, ref->table_name,
ref->field_name, ref->is_alias_of_expr()) :
new Item_ref(ref->context, item_ref, ref->table_name,
ref->field_name, ref->is_alias_of_expr());
if (!new_ref)
return true; /* purecov: inspected */
ref->outer_ref= new_ref;
ref->ref= &ref->outer_ref;
if (!ref->fixed && ref->fix_fields(thd, 0))
return true; /* purecov: inspected */
thd->lex->used_tables|= item->used_tables();
select_list_tables|= item->used_tables();
}
return false;
}
/**
Since LIMIT is not supported for table subquery predicates
(IN/ALL/EXISTS/etc), the following clauses are redundant for
subqueries:
ORDER BY
DISTINCT
GROUP BY if there are no aggregate functions and no HAVING clause
This removal is permanent. Thus, it only makes sense to call this function
for regular queries and on first execution of SP/PS
@param thd thread handler
@param hidden_group_field_count Number of hidden group fields added
by setup_group().
@param hidden_order_field_count Number of hidden order fields added
by setup_order().
*/
void SELECT_LEX::remove_redundant_subquery_clauses(THD *thd,
int hidden_group_field_count,
int hidden_order_field_count)
{
Item_subselect *subq_predicate= master_unit()->item;
/*
The removal should happen for IN, ALL, ANY and EXISTS subqueries,
which means all but single row subqueries. Example single row
subqueries:
a) SELECT * FROM t1 WHERE t1.a = (<single row subquery>)
b) SELECT a, (<single row subquery) FROM t1
*/
if (subq_predicate->substype() == Item_subselect::SINGLEROW_SUBS)
return;
// A subquery that is not single row should be one of IN/ALL/ANY/EXISTS.
DBUG_ASSERT (subq_predicate->substype() == Item_subselect::EXISTS_SUBS ||
subq_predicate->substype() == Item_subselect::IN_SUBS ||
subq_predicate->substype() == Item_subselect::ALL_SUBS ||
subq_predicate->substype() == Item_subselect::ANY_SUBS);
enum change
{
REMOVE_NONE=0,
REMOVE_ORDER= 1 << 0,
REMOVE_DISTINCT= 1 << 1,
REMOVE_GROUP= 1 << 2
};
uint changelog= 0;
if (order_list.elements)
{
changelog|= REMOVE_ORDER;
empty_order_list(hidden_order_field_count);
}
if (is_distinct())
{
changelog|= REMOVE_DISTINCT;
remove_base_options(SELECT_DISTINCT);
}
// Remove GROUP BY if there are no aggregate functions and no HAVING clause
if (group_list.elements && !agg_func_used() && !having_cond())
{
changelog|= REMOVE_GROUP;
for (ORDER *g= group_list.first; g != NULL; g= g->next)
{
if (*g->item == g->item_ptr)
(*g->item)->walk(&Item::clean_up_after_removal, walk_subquery,
reinterpret_cast<uchar*>(this));
}
group_list.empty();
while (hidden_group_field_count-- > 0)
{
all_fields.pop();
ref_ptrs[all_fields.elements]= NULL;
}
}
if (changelog)
{
Opt_trace_context * trace= &thd->opt_trace;
if (unlikely(trace->is_started()))
{
Opt_trace_object trace_wrapper(trace);
Opt_trace_array trace_changes(trace, "transformations_to_subquery");
if (changelog & REMOVE_ORDER)
trace_changes.add_alnum("removed_ordering");
if (changelog & REMOVE_DISTINCT)
trace_changes.add_alnum("removed_distinct");
if (changelog & REMOVE_GROUP)
trace_changes.add_alnum("removed_grouping");
}
}
}
/**
Empty the ORDER list.
Delete corresponding elements from all_fields and ref_ptrs too.
If ORDER list contain any subqueries, delete them from the query block list.
@param hidden_order_field_count Number of hidden order fields to remove
*/
void SELECT_LEX::empty_order_list(int hidden_order_field_count)
{
for (ORDER *o= order_list.first; o != NULL; o= o->next)
{
if (*o->item == o->item_ptr)
(*o->item)->walk(&Item::clean_up_after_removal, walk_subquery,
reinterpret_cast<uchar*>(this));
}
order_list.empty();
while (hidden_order_field_count-- > 0)
{
all_fields.pop();
ref_ptrs[all_fields.elements]= NULL;
}
}
/*****************************************************************************
Group and order functions
*****************************************************************************/
/**
Resolve an ORDER BY or GROUP BY column reference.
Given a column reference (represented by 'order') from a GROUP BY or ORDER
BY clause, find the actual column it represents. If the column being
resolved is from the GROUP BY clause, the procedure searches the SELECT
list 'fields' and the columns in the FROM list 'tables'. If 'order' is from
the ORDER BY clause, only the SELECT list is being searched.
If 'order' is resolved to an Item, then order->item is set to the found
Item. If there is no item for the found column (that is, it was resolved
into a table field), order->item is 'fixed' and is added to all_fields and
ref_pointer_array.
ref_pointer_array and all_fields are updated.
@param[in] thd Pointer to current thread structure
@param[in,out] ref_pointer_array All select, group and order by fields
@param[in] tables List of tables to search in (usually
FROM clause)
@param[in] order Column reference to be resolved
@param[in] fields List of fields to search in (usually
SELECT list)
@param[in,out] all_fields All select, group and order by fields
@param[in] is_group_field True if order is a GROUP field, false if
ORDER by field
@retval
FALSE if OK
@retval
TRUE if error occurred
*/
static bool
find_order_in_list(THD *thd, Ref_ptr_array ref_pointer_array, TABLE_LIST *tables,
ORDER *order, List<Item> &fields, List<Item> &all_fields,
bool is_group_field)
{
Item *order_item= *order->item; /* The item from the GROUP/ORDER caluse. */
Item::Type order_item_type;
Item **select_item; /* The corresponding item from the SELECT clause. */
Field *from_field; /* The corresponding field from the FROM clause. */
uint counter;
enum_resolution_type resolution;
/*
Local SP variables may be int but are expressions, not positions.
(And they can't be used before fix_fields is called for them).
*/
if (order_item->type() == Item::INT_ITEM && order_item->basic_const_item())
{ /* Order by position */
uint count= (uint) order_item->val_int();
if (!count || count > fields.elements)
{
my_error(ER_BAD_FIELD_ERROR, MYF(0),
order_item->full_name(), thd->where);
return TRUE;
}
order->item= &ref_pointer_array[count - 1];
order->in_field_list= 1;
return FALSE;
}
/* Lookup the current GROUP/ORDER field in the SELECT clause. */
select_item= find_item_in_list(order_item, fields, &counter,
REPORT_EXCEPT_NOT_FOUND, &resolution);
if (!select_item)
return TRUE; /* The item is not unique, or some other error occured. */
/* Check whether the resolved field is not ambiguos. */
if (select_item != not_found_item)
{
Item *view_ref= NULL;
/*
If we have found field not by its alias in select list but by its
original field name, we should additionally check if we have conflict
for this name (in case if we would perform lookup in all tables).
*/
if (resolution == RESOLVED_BEHIND_ALIAS && !order_item->fixed &&
order_item->fix_fields(thd, order->item))
return TRUE;
/* Lookup the current GROUP field in the FROM clause. */
order_item_type= order_item->type();
from_field= (Field*) not_found_field;
if ((is_group_field &&
order_item_type == Item::FIELD_ITEM) ||
order_item_type == Item::REF_ITEM)
{
from_field= find_field_in_tables(thd, (Item_ident*) order_item, tables,
NULL, &view_ref, IGNORE_ERRORS, TRUE,
FALSE);
if (!from_field)
from_field= (Field*) not_found_field;
}
if (from_field == not_found_field ||
(from_field != view_ref_found ?
/* it is field of base table => check that fields are same */
((*select_item)->type() == Item::FIELD_ITEM &&
((Item_field*) (*select_item))->field->eq(from_field)) :
/*
in is field of view table => check that references on translation
table are same
*/
((*select_item)->type() == Item::REF_ITEM &&
view_ref->type() == Item::REF_ITEM &&
((Item_ref *) (*select_item))->ref ==
((Item_ref *) view_ref)->ref)))
{
/*
If there is no such field in the FROM clause, or it is the same field
as the one found in the SELECT clause, then use the Item created for
the SELECT field. As a result if there was a derived field that
'shadowed' a table field with the same name, the table field will be
chosen over the derived field.
If we replace *order->item with one from the select list or
from a table in the FROM list, we should clean up after
removing the old *order->item from the query. The item has not
been fixed (so there are no aggregation functions that need
cleaning up), but it may contain subqueries that should be
unlinked.
*/
if (*order->item != *select_item)
(*order->item)->walk(&Item::clean_up_after_removal, walk_subquery,
NULL);
order->item= &ref_pointer_array[counter];
order->in_field_list=1;
if (resolution == RESOLVED_AGAINST_ALIAS)
order->used_alias= true;
return FALSE;
}
else
{
/*
There is a field with the same name in the FROM clause. This
is the field that will be chosen. In this case we issue a
warning so the user knows that the field from the FROM clause
overshadows the column reference from the SELECT list.
*/
push_warning_printf(thd, Sql_condition::SL_WARNING, ER_NON_UNIQ_ERROR,
ER(ER_NON_UNIQ_ERROR),
((Item_ident*) order_item)->field_name,
current_thd->where);
}
}
order->in_field_list=0;
/*
The call to order_item->fix_fields() means that here we resolve
'order_item' to a column from a table in the list 'tables', or to
a column in some outer query. Exactly because of the second case
we come to this point even if (select_item == not_found_item),
inspite of that fix_fields() calls find_item_in_list() one more
time.
We check order_item->fixed because Item_func_group_concat can put
arguments for which fix_fields already was called.
group_fix_field= TRUE is to resolve aliases from the SELECT list
without creating of Item_ref-s: JOIN::exec() wraps aliased items
in SELECT list with Item_copy items. To re-evaluate such a tree
that includes Item_copy items we have to refresh Item_copy caches,
but:
- filesort() never refresh Item_copy items,
- end_send_group() checks every record for group boundary by the
test_if_group_changed function that obtain data from these
Item_copy items, but the copy_fields function that
refreshes Item copy items is called after group boundaries only -
that is a vicious circle.
So we prevent inclusion of Item_copy items.
*/
bool save_group_fix_field= thd->lex->current_select()->group_fix_field;
if (is_group_field)
thd->lex->current_select()->group_fix_field= TRUE;
bool ret= (!order_item->fixed &&
(order_item->fix_fields(thd, order->item) ||
(order_item= *order->item)->check_cols(1)));
thd->lex->current_select()->group_fix_field= save_group_fix_field;
if (ret)
return TRUE; /* Wrong field. */
uint el= all_fields.elements;
all_fields.push_front(order_item); /* Add new field to field list. */
ref_pointer_array[el]= order_item;
/*
If the order_item is a SUM_FUNC_ITEM, when fix_fields is called
ref_by is set to order->item which is the address of order_item.
But this needs to be address of order_item in the all_fields list.
As a result, when it gets replaced with Item_aggregate_ref
object in Item::split_sum_func2, we will be able to retrieve the
newly created object.
*/
if (order_item->type() == Item::SUM_FUNC_ITEM)
((Item_sum *)order_item)->ref_by= all_fields.head_ref();
/*
Currently, we assume that this assertion holds. If it turns out
that it fails for some query, order->item has changed and the old
item is removed from the query. In that case, we must call walk()
with clean_up_after_removal() on the old order->item.
*/
DBUG_ASSERT(order_item == *order->item);
order->item= &ref_pointer_array[el];
return FALSE;
}
/**
Resolve and setup list of expressions in ORDER BY clause.
Change order to point at item in select list.
If item isn't a number and doesn't exists in the select list, add it to the
the field list.
@param thd Thread handler
@returns false if success, true if error
*/
bool setup_order(THD *thd, Ref_ptr_array ref_pointer_array, TABLE_LIST *tables,
List<Item> &fields, List<Item> &all_fields, ORDER *order)
{
DBUG_ASSERT(order);
SELECT_LEX *const select= thd->lex->current_select();
thd->where="order clause";
const bool for_union= select->master_unit()->is_union() &&
select == select->master_unit()->fake_select_lex;
const bool is_aggregated= select->is_grouped();
for (uint number= 1; order; order=order->next, number++)
{
if (find_order_in_list(thd, ref_pointer_array, tables, order, fields,
all_fields, false))
return true;
if ((*order->item)->with_sum_func)
{
/*
Aggregated expressions in ORDER BY are not supported by SQL standard,
but MySQL has some limited support for them. The limitations are
checked below:
1. A UNION query is not aggregated, so ordering by a set function
is always wrong.
*/
if (for_union)
{
my_error(ER_AGGREGATE_ORDER_FOR_UNION, MYF(0), number);
return true;
}
/*
2. A non-aggregated query combined with a set function in ORDER BY
that does not contain an outer reference is illegal, because it
would cause the query to become aggregated.
(Since is_aggregated is false, this expression would cause
agg_func_used() to become true).
*/
if (!is_aggregated && select->agg_func_used())
{
my_error(ER_AGGREGATE_ORDER_NON_AGG_QUERY, MYF(0), number);
return true;
}
}
}
return false;
}
/**
Runs checks mandated by ONLY_FULL_GROUP_BY
@param thd THD pointer
@returns true if ONLY_FULL_GROUP_BY is violated.
*/
bool SELECT_LEX::check_only_full_group_by(THD *thd)
{
bool rc= false;
if (is_grouped())
{
MEM_ROOT root;
/*
"root" has very short lifetime, and should not consume much
=> not instrumented.
*/
init_sql_alloc(PSI_NOT_INSTRUMENTED, &root, MEM_ROOT_BLOCK_SIZE, 0);
{
Group_check gc(this, &root);
rc= gc.check_query(thd);
gc.to_opt_trace(thd);
} // scope, to let any destructor run before free_root().
free_root(&root, MYF(0));
}
if (!rc &&
is_distinct() &&
// aggregate without GROUP => single-row result => don't bother user
!(!group_list.elements && agg_func_used()))
{
Distinct_check dc(this);
rc= dc.check_query(thd);
}
return rc;
}
/**
Do final setup of ORDER BY clause, after the query block is fully resolved.
Check that ORDER BY clause is not redundant.
Split any aggregate functions.
@param thd Thread handler
@param hidden_order_field_count Number of fields to delete from ref array
if ORDER BY clause is redundant.
@returns false if success, true if error
*/
bool SELECT_LEX::setup_order_final(THD *thd, int hidden_order_field_count)
{
if (is_implicitly_grouped())
{
// Result will contain zero or one row - ordering is redundant
empty_order_list(hidden_order_field_count);
return false;
}
if ((master_unit()->is_union() || master_unit()->fake_select_lex) &&
this != master_unit()->fake_select_lex &&
!(braces && explicit_limit))
{
// Part of UNION which requires global ordering may skip local order
empty_order_list(hidden_order_field_count);
return false;
}
for (ORDER *ord= (ORDER *)order_list.first; ord; ord= ord->next)
{
Item *const item= *ord->item;
if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM)
{
item->split_sum_func(thd, ref_ptrs, all_fields);
if (thd->is_error())
return true; /* purecov: inspected */
}
}
return false;
}
/**
Resolve and set up the GROUP BY list.
@param thd Thread handler
@todo
change ER_WRONG_FIELD_WITH_GROUP to more detailed
ER_NON_GROUPING_FIELD_USED
@returns false if success, true if error
*/
bool SELECT_LEX::setup_group(THD *thd)
{
DBUG_ASSERT(group_list.elements);
thd->where="group statement";
for (ORDER *group= group_list.first; group; group= group->next)
{
if (find_order_in_list(thd, ref_ptrs, get_table_list(), group, fields_list,
all_fields, true))
return true;
if ((*group->item)->with_sum_func)
{
my_error(ER_WRONG_GROUP_FIELD, MYF(0), (*group->item)->full_name());
return true;
}
}
return false;
}
/****************************************************************************
ROLLUP handling
****************************************************************************/
/**
Replace occurrences of group by fields in an expression by ref items.
The function replaces occurrences of group by fields in expr
by ref objects for these fields unless they are under aggregate
functions.
The function also corrects value of the the maybe_null attribute
for the items of all subexpressions containing group by fields.
@b EXAMPLES
@code
SELECT a+1 FROM t1 GROUP BY a WITH ROLLUP
SELECT SUM(a)+a FROM t1 GROUP BY a WITH ROLLUP
@endcode
@b IMPLEMENTATION
The function recursively traverses the tree of the expr expression,
looks for occurrences of the group by fields that are not under
aggregate functions and replaces them for the corresponding ref items.
@note
This substitution is needed GROUP BY queries with ROLLUP if
SELECT list contains expressions over group by attributes.
@param thd reference to the context
@param expr expression to make replacement
@param changed[out] returns true if item contains a replaced field item
@todo
- TODO: Some functions are not null-preserving. For those functions
updating of the maybe_null attribute is an overkill.
@returns false if success, true if error
*/
bool SELECT_LEX::change_group_ref(THD *thd, Item_func *expr, bool *changed)
{
bool arg_changed= false;
for (uint i= 0; i < expr->arg_count; i++)
{
Item **arg= expr->arguments() + i;
Item *const item= *arg;
if (item->type() == Item::FIELD_ITEM || item->type() == Item::REF_ITEM)
{
for (ORDER *group= (ORDER *)group_list.first; group; group= group->next)
{
if (item->eq(*group->item, 0))
{
Item *new_item;
if (!(new_item= new Item_ref(&context, group->item, 0,
item->item_name.ptr())))
return true; /* purecov: inspected */
thd->change_item_tree(arg, new_item);
arg_changed= true;
}
}
}
else if (item->type() == Item::FUNC_ITEM)
{
if (change_group_ref(thd, (Item_func *) item, &arg_changed))
return true;
}
}
if (arg_changed)
{
expr->maybe_null= true;
*changed= true;
}
return false;
}
/**
Resolve items for rollup processing
@param thd Thread handler
@returns false if success, true if error
*/
bool SELECT_LEX::resolve_rollup(THD *thd)
{
List_iterator<Item> it(all_fields);
Item *item;
while ((item= it++))
{
bool found_in_group= false;
for (ORDER *group= (ORDER *)group_list.first; group; group= group->next)
{
if (*group->item == item)
{
item->maybe_null= true;
found_in_group= true;
break;
}
}
if (item->type() == Item::FUNC_ITEM && !found_in_group)
{
bool changed= false;
if (change_group_ref(thd, (Item_func *) item, &changed))
return true; /* purecov: inspected */
/*
We have to prevent creation of a field in a temporary table for
an expression that contains GROUP BY attributes.
Marking the expression item as 'with_sum_func' will ensure this.
*/
if (changed)
item->with_sum_func= true;
}
}
return false;
}
/**
@brief validate_gc_assignment
Check whether the other values except DEFAULT are assigned
for generated columns.
@param thd thread handler
@param fields Item_fields list to be filled
@param values values to fill with
@param table table to be checked
@return Operation status
@retval false OK
@retval true Error occured
@Note: This function must be called after table->write_set has been
filled.
*/
bool
validate_gc_assignment(THD * thd, List<Item> *fields,
List<Item> *values, TABLE *table)
{
Field **fld= NULL;
MY_BITMAP *bitmap= table->write_set;
bool use_table_field= false;
DBUG_ENTER("validate_gc_assignment");
if (!values || (values->elements == 0))
DBUG_RETURN(false);
// If fields has no elements, we use all table fields
if (fields->elements == 0)
{
use_table_field= true;
fld= table->field;
}
List_iterator_fast<Item> f(*fields),v(*values);
Item *value;
while ((value= v++))
{
Field *rfield;
if (!use_table_field)
rfield= ((Item_field *)f++)->field;
else
rfield= *(fld++);
if (rfield->table != table)
continue;
/* skip non marked fields */
if (!bitmap_is_set(bitmap, rfield->field_index))
continue;
if (rfield->gcol_info &&
value->type() != Item::DEFAULT_VALUE_ITEM)
{
my_error(ER_NON_DEFAULT_VALUE_FOR_GENERATED_COLUMN, MYF(0),
rfield->field_name, rfield->table->s->table_name.str);
DBUG_RETURN(true);
}
}
DBUG_RETURN(false);
}
/**
Delete unused columns from merged tables.
This function is called recursively for each join nest and/or table
in the query block. For each merged table that it finds, each column
that contains a subquery and is not marked as used is removed and
the translation item is set to NULL.
@param tables List of tables and join nests
*/
void SELECT_LEX::delete_unused_merged_columns(List<TABLE_LIST> *tables)
{
DBUG_ENTER("delete_unused_merged_columns");
TABLE_LIST *tl;
List_iterator<TABLE_LIST> li(*tables);
while ((tl= li++))
{
if (tl->nested_join == NULL)
continue;
if (tl->is_merged())
{
for (Field_translator *transl= tl->field_translation;
transl < tl->field_translation_end;
transl++)
{
DBUG_ASSERT(transl->item->fixed);
if (transl->item->has_subquery() && !transl->item->is_derived_used())
{
transl->item->walk(&Item::clean_up_after_removal,
walk_subquery, (uchar *)this);
transl->item= NULL;
}
}
}
delete_unused_merged_columns(&tl->nested_join->join_list);
}
DBUG_VOID_RETURN;
}
/**
@} (end of group Query_Resolver)
*/
| ForcerKing/ShaoqunXu-mysql5.7 | sql/sql_resolver.cc | C++ | gpl-2.0 | 121,648 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2009-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.core.soa;
import java.util.Collection;
import java.util.Map;
/**
* ServiceRegistry
*
* @author brozow
* @version $Id: $
*/
public interface ServiceRegistry {
/**
* <p>register</p>
*
* @param serviceProvider a {@link java.lang.Object} object.
* @param services a {@link java.lang.Class} object.
* @return a {@link org.opennms.core.soa.Registration} object.
*/
public Registration register(Object serviceProvider, Class<?>... services);
/**
* <p>register</p>
*
* @param serviceProvider a {@link java.lang.Object} object.
* @param properties a {@link java.util.Map} object.
* @param services a {@link java.lang.Class} object.
* @return a {@link org.opennms.core.soa.Registration} object.
*/
public Registration register(Object serviceProvider, Map<String, String> properties, Class<?>... services);
/**
* <p>findProvider</p>
*
* @param seviceInterface a {@link java.lang.Class} object.
* @param <T> a T object.
* @return a T object.
*/
public <T> T findProvider(Class<T> seviceInterface);
/**
* <p>findProvider</p>
*
* @param serviceInterface a {@link java.lang.Class} object.
* @param filter a {@link java.lang.String} object.
* @param <T> a T object.
* @return a T object.
*/
public <T> T findProvider(Class<T> serviceInterface, String filter);
/**
* <p>findProviders</p>
*
* @param service a {@link java.lang.Class} object.
* @param <T> a T object.
* @return a {@link java.util.Collection} object.
*/
public <T> Collection<T> findProviders(Class<T> service);
/**
* <p>findProviders</p>
*
* @param service a {@link java.lang.Class} object.
* @param filter a {@link java.lang.String} object.
* @param <T> a T object.
* @return a {@link java.util.Collection} object.
*/
public <T> Collection<T> findProviders(Class<T> service, String filter);
/**
* <p>addListener</p>
*
* @param service a {@link java.lang.Class} object.
* @param listener a {@link org.opennms.core.soa.RegistrationListener} object.
* @param <T> a T object.
*/
public <T> void addListener(Class<T> service, RegistrationListener<T> listener);
/**
* <p>addListener</p>
*
* @param service a {@link java.lang.Class} object.
* @param listener a {@link org.opennms.core.soa.RegistrationListener} object.
* @param notifyForExistingProviders a boolean.
* @param <T> a T object.
*/
public <T> void addListener(Class<T> service, RegistrationListener<T> listener, boolean notifyForExistingProviders);
/**
* <p>removeListener</p>
*
* @param service a {@link java.lang.Class} object.
* @param listener a {@link org.opennms.core.soa.RegistrationListener} object.
* @param <T> a T object.
*/
public <T> void removeListener(Class<T> service, RegistrationListener<T> listener);
}
| vishwaAbhinav/OpenNMS | core/soa/src/main/java/org/opennms/core/soa/ServiceRegistry.java | Java | gpl-2.0 | 4,248 |
<div id="<?php echo $iname; ?>messages" class="messages">
<?php
// if there are messages loop through all messages
if ($this->getInput('messages')) {
foreach ($this->getInput('messages') as $message) {
?>
<div class="messageblock">
<div class="header">
<div class="datetime"><?php echo $message["date_time"]; ?></div>
<div class="username">
<span class="name"><?php echo $message["name"]; ?></span>
<span class="said">said...</span>
</div>
</div>
<div class="messagetext"><?php echo $message["message"]; ?></div>
</div>
<?php
}
} // end loop
?>
</div> | peeto/DarkChat | src/web/displaymessages.php | PHP | gpl-2.0 | 667 |
"""
SALTS XBMC Addon
Copyright (C) 2014 tknorris
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/>.
"""
import re
import urllib
import urlparse
import kodi
import dom_parser
from salts_lib import scraper_utils
from salts_lib.constants import FORCE_NO_MATCH
from salts_lib.constants import QUALITIES
from salts_lib.constants import VIDEO_TYPES
import scraper
BASE_URL = 'http://watch8now.me'
class Scraper(scraper.Scraper):
base_url = BASE_URL
def __init__(self, timeout=scraper.DEFAULT_TIMEOUT):
self.timeout = timeout
self.base_url = kodi.get_setting('%s-base_url' % (self.get_name()))
@classmethod
def provides(cls):
return frozenset([VIDEO_TYPES.TVSHOW, VIDEO_TYPES.EPISODE])
@classmethod
def get_name(cls):
return 'Watch8Now'
def resolve_link(self, link):
html = self._http_get(link, cache_limit=.5)
match = re.search('<iframe[^>]*src="([^"]+)', html, re.I)
if match:
return match.group(1)
else:
match = re.search('Nothing in HERE<br>([^<]+)', html, re.I)
if match:
return match.group(1).strip()
return link
def get_sources(self, video):
source_url = self.get_url(video)
hosters = []
if source_url and source_url != FORCE_NO_MATCH:
url = urlparse.urljoin(self.base_url, source_url)
html = self._http_get(url, cache_limit=.5)
for table_cell in dom_parser.parse_dom(html, 'td', {'class': 'domain'}):
match = re.search('href="([^"]+)(?:[^>]+>){2}\s*([^<]+)', table_cell)
if match:
link, host = match.groups()
hoster = {'multi-part': False, 'host': host, 'class': self, 'quality': scraper_utils.get_quality(video, host, QUALITIES.HIGH), 'views': None, 'rating': None, 'url': link, 'direct': False}
hosters.append(hoster)
return hosters
def _get_episode_url(self, show_url, video):
episode_pattern = 'href="([^"]+[sS]%s[eE]%s\.html)"' % (video.season, video.episode)
title_pattern = 'href="(?P<url>[^"]+[sS]\d+[eE]\d+\.html)"(?:[^>]+>){6}(?P<title>[^<]+)'
return self._default_get_episode_url(show_url, video, episode_pattern, title_pattern)
def search(self, video_type, title, year, season=''):
search_url = urlparse.urljoin(self.base_url, '/search?q=')
search_url += urllib.quote_plus(title)
html = self._http_get(search_url, cache_limit=8)
results = []
for item in dom_parser.parse_dom(html, 'h4', {'class': 'media-heading'}):
match = re.search('href="([^"]+)">([^<]+)', item)
if match:
url, match_title = match.groups()
result = {'url': scraper_utils.pathify_url(url), 'title': scraper_utils.cleanse_title(match_title), 'year': ''}
results.append(result)
return results
| felipenaselva/repo.felipe | plugin.video.salts/scrapers/watch8now_scraper.py | Python | gpl-2.0 | 3,576 |
<?php
/**
* http://fusionforge.org/
*
* This file is part of FusionForge. FusionForge 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 Licence, or (at your option)
* any later version.
*
* FusionForge 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 FusionForge; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
// export a group's tracker bugs per artifact in RSS 2.0
// Author: Jutta Horstmann, data in transit <jh@dataintransit.com>
// Created: 01.10.07
// Based on: export/tracker.php, export/rss20_newreleases.php, tracker/ind.php
// Changes:
// Date Author Comment
// 07.11.07 JH show only public group feeds
//
//TO DO: Translations for error messages
//Notes:
// Keep in mind to write "&" in URLs as & in RSS feeds
require_once '../env.inc.php';
require_once $gfcommon.'include/pre.php';
require_once $gfwww.'export/rss_utils.inc';
if (isset($_GET['group_id'])&&!empty($_GET['group_id'])&&is_numeric($_GET['group_id'])) {
$group_id = $_GET['group_id'];
$group =& group_get_object($group_id);
//does group exist? do we get an object?
if (!$group || !is_object($group)) {
beginFeed();
endOnError('Could not get the Group object');
} elseif ($group->isError()) {
beginFeed();
endOnError($group->getErrorMessage());
}
elseif (!$group->isPublic()){
beginFeed();
endOnError('No RSS feed available as group status is set to private.');
}
$groupname = $group->getPublicName();
$link = "/tracker/?group_id=$group_id";
beginFeed($groupname,$link);
//does tracker exist? do we get a factory?
$atf = new ArtifactTypeFactory($group);
if (!$atf || !is_object($atf) || $atf->isError()) {
endOnError('Could Not Get ArtifactTypeFactory');
}
$at_arr =& $atf->getArtifactTypes();
writeFeed($at_arr,$group_id);
endFeed();
}//no group_id in GET
else {
beginFeed();
displayError('Please supply a Group ID with the request.');
endFeed();
}
//**************************************************************++
function beginFeed($groupname = "", $link = "") {
header("Content-Type: text/xml");
print '<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
';
print " <channel>\n";
print " <title>".forge_get_config('forge_name')." Project \"".$groupname."\" Bug Trackers</title>\n";
print " <link>http://".forge_get_config('web_host').$link."</link>\n";
print " <description>".forge_get_config('forge_name')." Bug Trackers of \"".$groupname."\"</description>\n";
print " <language>en-us</language>\n";
print " <copyright>Copyright 2000-".date("Y")." ".forge_get_config('forge_name')."</copyright>\n";
print " <webMaster>".forge_get_config('admin_email')."</webMaster>\n";
print " <lastBuildDate>".gmdate('D, d M Y G:i:s',time())." GMT</lastBuildDate>\n";
print " <docs>http://blogs.law.harvard.edu/tech/rss</docs>\n";
print " <image>\n";
print " <url>http://".forge_get_config('web_host')."/images/bflogo-88.png</url>\n";
print " <title>".forge_get_config('forge_name')." Developer</title>\n";
print " <link>http://".forge_get_config('web_host')."/</link>\n";
print " <width>124</width>\n";
print " <heigth>32</heigth>\n";
print " </image>\n";
}
function writeFeed($at_arr, $group_id){
// ## default limit
//if (isset($limit) ||empty($limit)) $limit = 10;
//if ($limit > 100) $limit = 100;
if (!$at_arr || count($at_arr) < 1) {
endOnError(_("Tracker RSS: No trackers found"));
} else {
// Put the result set (list of trackers for this group) into feed items
// ## item outputs
//$outputtotal = 0;
//loop through the bug trackers
for ($j = 0; $j < count($at_arr); $j++) {
print " <item>\n";
if (!is_object($at_arr[$j])) {
//just skip it
} elseif ($at_arr[$j]->isError()) {
print " <title>Error</title>".
"<description>".rss_description($at_arr[$j]->getErrorMessage())."</decription>";
} else {
print " <title>".$at_arr[$j]->getName()."</title>\n";
print " <link>http://".forge_get_config('web_host')."/tracker?atid=".$at_arr[$j]->getID()."&group_id=".$group_id."&func=browse</link>\n";
print " <description>".
rss_description($at_arr[$j]->getDescription()).
" - Open Bugs: ".(int) $at_arr[$j]->getOpenCount() .
", Total Count: ". (int) $at_arr[$j]->getTotalCount() .
"</description>\n";
print " <author></author>\n";
//print " <comment></comment>\n";
//print " <pubDate>".gmdate('D, d M Y G:i:s',time())." GMT</pubDate>\n";
//print " <guid></guid>\n";
}//else (everything ok)
print " </item>\n";
//$outputtotal++;
//if ($outputtotal >= $limit) break;
}//for loop
}//else (there are trackers)
}
function displayError($errorMessage) {
print " <title>Error</title>".
"<description>".rss_description($errorMessage)."</description>";
}
function endFeed() {
print '</channel></rss>';
exit();
}
function endOnError($errorMessage) {
displayError($errorMessage);
endFeed();
}
?>
| foresthz/fusion5.1 | www/export/rss20_tracker.php | PHP | gpl-2.0 | 5,480 |
<?php
defined('JPATH_PLATFORM') or die;
/**
*
* @package VirtueMart
* @subpackage Plugins - Elements
* @author Valérie Isaksen
* @link http://www.virtuemart.net
* @copyright Copyright (c) 2004 - 2011 VirtueMart Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* VirtueMart is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* @version $Id$
*/
defined('DS') or define('DS', DIRECTORY_SEPARATOR);
if (!class_exists( 'VmConfig' )) require(JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_virtuemart'.DS.'helpers'.DS.'config.php');
/*
* This class is used by VirtueMart Payment or Shipment Plugins
* So It should be an extension of JFormField
* Those plugins cannot be configured through the Plugin Manager anyway.
*/
JFormHelper::loadFieldClass('list');
jimport('joomla.form.formfield');
class JFormFieldVmAcceptedCurrency extends JFormFieldList {
/**
* The form field type.
*
* @var string
* @since 11.1
*/
var $type = 'vmacceptedcurrency';
protected function getOptions() {
VmConfig::loadConfig();
VmConfig::loadJLang('com_virtuemart', false);
$cModel = VmModel::getModel('currency');
$values = $cModel->getVendorAcceptedCurrrenciesList();
$options[] = JHtml::_('select.option', 0, vmText::_('COM_VIRTUEMART_DEFAULT_VENDOR_CURRENCY'));
foreach ($values as $v) {
$options[] = JHtml::_('select.option', $v->virtuemart_currency_id, $v->currency_txt);
}
return $options;
}
} | FabianodeLimaAbreu/conectby | administrator/components/com_virtuemart/fields/vmacceptedcurrency.php | PHP | gpl-2.0 | 1,698 |
/*
* Open-source multi-Physics Phenomena Analyzer (OP2A) ver. 0.1
*
* Copyright (c) 2015 MINKWAN KIM
*
* Initial Developed Date: May 26, 2015
* Author: Minkwan Kim
*
* OP2A_ProblemCommon.hpp
* -
*
*/
#ifndef OP2A_PROBLEMCOMMON_HPP_
#define OP2A_PROBLEMCOMMON_HPP_
#include <string>
#include <vector>
using namespace std;
namespace OP2A{
namespace Setup{
/*
* Class for Basic Problem setup
*
* @author Minkwan Kim
* @version 1.0 25/05/2015
*/
class ProblemBasic
{
public:
string title;
string module;
};
}
}
#endif /* OP2A_PROBLEMCOMMON_HPP_ */
| minkwankim/OP2A | OP2A/Setup/include/OP2A_ProblemCommon.hpp | C++ | gpl-2.0 | 593 |
<?php
/*
* This file is part of SeAT
*
* Copyright (C) 2015 to 2020 Leon Jacobs
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Class CreateCorporationInfosTestTable.
*/
class CreateCorporationInfosTestTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('corporation_infos', function (Blueprint $table) {
$table->bigInteger('corporation_id')->primary();
$table->string('name');
$table->string('ticker');
$table->integer('member_count');
$table->bigInteger('ceo_id');
$table->bigInteger('alliance_id')->nullable();
$table->text('description')->nullable();
$table->double('tax_rate');
$table->dateTime('date_founded')->nullable();
$table->bigInteger('creator_id');
$table->string('url')->nullable();
$table->integer('faction_id')->nullable();
$table->integer('home_station_id')->nullable();
$table->bigInteger('shares')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('corporation_infos');
}
}
| eveseat/web | tests/database/migrations/2020_05_08_085856_create_corporation_infos_test_table.php | PHP | gpl-2.0 | 2,126 |
/*
* Copyright (C) 2005 - 2011 MaNGOS <http://www.getmangos.org/>
*
* Copyright (C) 2008 - 2011 TrinityCore <http://www.trinitycore.org/>
*
* Copyright (C) 2011 - 2012 TrilliumEMU <http://trilliumx.code-engine.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "InstanceScript.h"
#include "DatabaseEnv.h"
#include "Map.h"
#include "Player.h"
#include "GameObject.h"
#include "Creature.h"
#include "CreatureAI.h"
#include "Log.h"
#include "LFGMgr.h"
void InstanceScript::SaveToDB()
{
std::string data = GetSaveData();
if (data.empty())
return;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_INSTANCE_DATA);
stmt->setUInt32(0, GetCompletedEncounterMask());
stmt->setString(1, data);
stmt->setUInt32(2, instance->GetInstanceId());
CharacterDatabase.Execute(stmt);
}
void InstanceScript::HandleGameObject(uint64 GUID, bool open, GameObject *go)
{
if (!go)
go = instance->GetGameObject(GUID);
if (go)
go->SetGoState(open ? GO_STATE_ACTIVE : GO_STATE_READY);
else
sLog->outDebug(LOG_FILTER_TSCR, "TSCR: InstanceScript: HandleGameObject failed");
}
bool InstanceScript::IsEncounterInProgress() const
{
for (std::vector<BossInfo>::const_iterator itr = bosses.begin(); itr != bosses.end(); ++itr)
if (itr->state == IN_PROGRESS)
return true;
return false;
}
void InstanceScript::LoadMinionData(const MinionData *data)
{
while (data->entry)
{
if (data->bossId < bosses.size())
minions.insert(std::make_pair(data->entry, MinionInfo(&bosses[data->bossId])));
++data;
}
sLog->outDebug(LOG_FILTER_TSCR, "InstanceScript::LoadMinionData: " UI64FMTD " minions loaded.", uint64(minions.size()));
}
void InstanceScript::LoadDoorData(const DoorData *data)
{
while (data->entry)
{
if (data->bossId < bosses.size())
doors.insert(std::make_pair(data->entry, DoorInfo(&bosses[data->bossId], data->type, BoundaryType(data->boundary))));
++data;
}
sLog->outDebug(LOG_FILTER_TSCR, "InstanceScript::LoadDoorData: " UI64FMTD " doors loaded.", uint64(doors.size()));
}
void InstanceScript::UpdateMinionState(Creature *minion, EncounterState state)
{
switch (state)
{
case NOT_STARTED:
if (!minion->isAlive())
minion->Respawn();
else if (minion->isInCombat())
minion->AI()->EnterEvadeMode();
break;
case IN_PROGRESS:
if (!minion->isAlive())
minion->Respawn();
else if (!minion->getVictim())
minion->AI()->DoZoneInCombat();
break;
default:
break;
}
}
void InstanceScript::UpdateDoorState(GameObject *door)
{
DoorInfoMap::iterator lower = doors.lower_bound(door->GetEntry());
DoorInfoMap::iterator upper = doors.upper_bound(door->GetEntry());
if (lower == upper)
return;
bool open = true;
for (DoorInfoMap::iterator itr = lower; itr != upper && open; ++itr)
{
switch (itr->second.type)
{
case DOOR_TYPE_ROOM:
open = (itr->second.bossInfo->state != IN_PROGRESS);
break;
case DOOR_TYPE_PASSAGE:
open = (itr->second.bossInfo->state == DONE);
break;
case DOOR_TYPE_SPAWN_HOLE:
open = (itr->second.bossInfo->state == IN_PROGRESS);
break;
default:
break;
}
}
door->SetGoState(open ? GO_STATE_ACTIVE : GO_STATE_READY);
}
void InstanceScript::AddDoor(GameObject *door, bool add)
{
DoorInfoMap::iterator lower = doors.lower_bound(door->GetEntry());
DoorInfoMap::iterator upper = doors.upper_bound(door->GetEntry());
if (lower == upper)
return;
for (DoorInfoMap::iterator itr = lower; itr != upper; ++itr)
{
if (add)
{
itr->second.bossInfo->door[itr->second.type].insert(door);
switch (itr->second.boundary)
{
default:
case BOUNDARY_NONE:
break;
case BOUNDARY_N:
case BOUNDARY_S:
itr->second.bossInfo->boundary[itr->second.boundary] = door->GetPositionX();
break;
case BOUNDARY_E:
case BOUNDARY_W:
itr->second.bossInfo->boundary[itr->second.boundary] = door->GetPositionY();
break;
case BOUNDARY_NW:
case BOUNDARY_SE:
itr->second.bossInfo->boundary[itr->second.boundary] = door->GetPositionX() + door->GetPositionY();
break;
case BOUNDARY_NE:
case BOUNDARY_SW:
itr->second.bossInfo->boundary[itr->second.boundary] = door->GetPositionX() - door->GetPositionY();
break;
}
}
else
itr->second.bossInfo->door[itr->second.type].erase(door);
}
if (add)
UpdateDoorState(door);
}
void InstanceScript::AddMinion(Creature *minion, bool add)
{
MinionInfoMap::iterator itr = minions.find(minion->GetEntry());
if (itr == minions.end())
return;
if (add)
itr->second.bossInfo->minion.insert(minion);
else
itr->second.bossInfo->minion.erase(minion);
}
bool InstanceScript::SetBossState(uint32 id, EncounterState state)
{
if (id < bosses.size())
{
BossInfo *bossInfo = &bosses[id];
if (bossInfo->state == TO_BE_DECIDED) // loading
{
bossInfo->state = state;
//sLog->outError("Inialize boss %u state as %u.", id, (uint32)state);
return false;
}
else
{
if (bossInfo->state == state)
return false;
if (state == DONE)
for (MinionSet::iterator i = bossInfo->minion.begin(); i != bossInfo->minion.end(); ++i)
if ((*i)->isWorldBoss() && (*i)->isAlive())
return false;
bossInfo->state = state;
SaveToDB();
}
for (uint32 type = 0; type < MAX_DOOR_TYPES; ++type)
for (DoorSet::iterator i = bossInfo->door[type].begin(); i != bossInfo->door[type].end(); ++i)
UpdateDoorState(*i);
for (MinionSet::iterator i = bossInfo->minion.begin(); i != bossInfo->minion.end(); ++i)
UpdateMinionState(*i, state);
return true;
}
return false;
}
std::string InstanceScript::LoadBossState(const char * data)
{
if (!data)
return NULL;
std::istringstream loadStream(data);
uint32 buff;
uint32 bossId = 0;
for (std::vector<BossInfo>::iterator i = bosses.begin(); i != bosses.end(); ++i, ++bossId)
{
loadStream >> buff;
if (buff < TO_BE_DECIDED)
SetBossState(bossId, (EncounterState)buff);
}
return loadStream.str();
}
std::string InstanceScript::GetBossSaveData()
{
std::ostringstream saveStream;
for (std::vector<BossInfo>::iterator i = bosses.begin(); i != bosses.end(); ++i)
saveStream << (uint32)i->state << ' ';
return saveStream.str();
}
void InstanceScript::DoUseDoorOrButton(uint64 uiGuid, uint32 uiWithRestoreTime, bool bUseAlternativeState)
{
if (!uiGuid)
return;
GameObject* pGo = instance->GetGameObject(uiGuid);
if (pGo)
{
if (pGo->GetGoType() == GAMEOBJECT_TYPE_DOOR || pGo->GetGoType() == GAMEOBJECT_TYPE_BUTTON)
{
if (pGo->getLootState() == GO_READY)
pGo->UseDoorOrButton(uiWithRestoreTime, bUseAlternativeState);
else if (pGo->getLootState() == GO_ACTIVATED)
pGo->ResetDoorOrButton();
}
else
sLog->outError("SD2: Script call DoUseDoorOrButton, but gameobject entry %u is type %u.", pGo->GetEntry(), pGo->GetGoType());
}
}
void InstanceScript::DoRespawnGameObject(uint64 uiGuid, uint32 uiTimeToDespawn)
{
if (GameObject* pGo = instance->GetGameObject(uiGuid))
{
//not expect any of these should ever be handled
if (pGo->GetGoType() == GAMEOBJECT_TYPE_FISHINGNODE || pGo->GetGoType() == GAMEOBJECT_TYPE_DOOR ||
pGo->GetGoType() == GAMEOBJECT_TYPE_BUTTON || pGo->GetGoType() == GAMEOBJECT_TYPE_TRAP)
return;
if (pGo->isSpawned())
return;
pGo->SetRespawnTime(uiTimeToDespawn);
}
}
void InstanceScript::DoUpdateWorldState(uint32 uiStateId, uint32 uiStateData)
{
Map::PlayerList const& lPlayers = instance->GetPlayers();
if (!lPlayers.isEmpty())
{
for (Map::PlayerList::const_iterator itr = lPlayers.begin(); itr != lPlayers.end(); ++itr)
if (Player *pPlayer = itr->getSource())
pPlayer->SendUpdateWorldState(uiStateId, uiStateData);
}
else
sLog->outDebug(LOG_FILTER_TSCR, "TSCR: DoUpdateWorldState attempt send data but no players in map.");
}
// Send Notify to all players in instance
void InstanceScript::DoSendNotifyToInstance(const char *format, ...)
{
InstanceMap::PlayerList const &PlayerList = instance->GetPlayers();
InstanceMap::PlayerList::const_iterator i;
if (!PlayerList.isEmpty())
{
va_list ap;
va_start(ap, format);
for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
{
if (Player *pPlayer = i->getSource())
if (WorldSession *pSession = pPlayer->GetSession())
pSession->SendNotification(format, ap);
}
va_end(ap);
}
}
// Update Achievement Criteria for all players in instance
void InstanceScript::DoUpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, Unit* unit /*= NULL*/)
{
Map::PlayerList const &PlayerList = instance->GetPlayers();
if (!PlayerList.isEmpty())
for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
if (Player *pPlayer = i->getSource())
pPlayer->UpdateAchievementCriteria(type, miscValue1, miscValue2, unit);
}
// Start timed achievement for all players in instance
void InstanceScript::DoStartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry)
{
Map::PlayerList const &PlayerList = instance->GetPlayers();
if (!PlayerList.isEmpty())
for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
if (Player *pPlayer = i->getSource())
pPlayer->GetAchievementMgr().StartTimedAchievement(type, entry);
}
// Stop timed achievement for all players in instance
void InstanceScript::DoStopTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry)
{
Map::PlayerList const &PlayerList = instance->GetPlayers();
if (!PlayerList.isEmpty())
for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
if (Player *pPlayer = i->getSource())
pPlayer->GetAchievementMgr().RemoveTimedAchievement(type, entry);
}
// Remove Auras due to Spell on all players in instance
void InstanceScript::DoRemoveAurasDueToSpellOnPlayers(uint32 spell)
{
Map::PlayerList const& PlayerList = instance->GetPlayers();
if (!PlayerList.isEmpty())
{
for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr)
{
if (Player* player = itr->getSource())
{
player->RemoveAurasDueToSpell(spell);
if (Pet* pet = player->GetPet())
pet->RemoveAurasDueToSpell(spell);
}
}
}
}
// Cast spell on all players in instance
void InstanceScript::DoCastSpellOnPlayers(uint32 spell)
{
Map::PlayerList const &PlayerList = instance->GetPlayers();
if (!PlayerList.isEmpty())
for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
if (Player* player = i->getSource())
player->CastSpell(player, spell, true);
}
bool InstanceScript::CheckAchievementCriteriaMeet(uint32 criteria_id, Player const* /*source*/, Unit const* /*target*/ /*= NULL*/, uint32 /*miscvalue1*/ /*= 0*/)
{
sLog->outError("Achievement system call InstanceScript::CheckAchievementCriteriaMeet but instance script for map %u not have implementation for achievement criteria %u",
instance->GetId(), criteria_id);
return false;
}
void InstanceScript::SendEncounterUnit(uint32 type, Unit* unit /*= NULL*/, uint8 param1 /*= 0*/, uint8 param2 /*= 0*/)
{
// size of this packet is at most 15 (usually less)
WorldPacket data(SMSG_UPDATE_INSTANCE_ENCOUNTER_UNIT, 15);
data << uint32(type);
switch (type)
{
case ENCOUNTER_FRAME_ADD:
case ENCOUNTER_FRAME_REMOVE:
case 2:
data.append(unit->GetPackGUID());
data << uint8(param1);
break;
case 3:
case 4:
case 6:
data << uint8(param1);
data << uint8(param2);
break;
case 5:
data << uint8(param1);
break;
case 7:
default:
break;
}
instance->SendToPlayers(&data);
}
void InstanceScript::UpdateEncounterState(EncounterCreditType type, uint32 creditEntry, Unit* source)
{
DungeonEncounterList const* encounters = sObjectMgr->GetDungeonEncounterList(instance->GetId(), instance->GetDifficulty());
if (!encounters)
return;
for (DungeonEncounterList::const_iterator itr = encounters->begin(); itr != encounters->end(); ++itr)
{
if ((*itr)->creditType == type && (*itr)->creditEntry == creditEntry)
{
completedEncounters |= 1 << (*itr)->dbcEntry->encounterIndex;
sLog->outDebug(LOG_FILTER_TSCR, "Instance %s (instanceId %u) completed encounter %s", instance->GetMapName(), instance->GetInstanceId(), (*itr)->dbcEntry->encounterName[0]);
if (uint32 dungeonId = (*itr)->lastEncounterDungeon)
{
Map::PlayerList const& players = instance->GetPlayers();
if (!players.isEmpty())
for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i)
if (Player* player = i->getSource())
if (!source || player->IsAtGroupRewardDistance(source))
sLFGMgr->RewardDungeonDonefor (dungeonId, player);
}
return;
}
}
}
| Kr4v3n5/Core | src/server/game/Instances/InstanceScript.cpp | C++ | gpl-2.0 | 15,351 |
<?php
/**
* @file
* Customize the display of a complete webform.
*
* This file may be renamed "webform-form-[nid].tpl.php" to target a specific
* webform on your site. Or you can leave it "webform-form.tpl.php" to affect
* all webforms on your site.
*
* Available variables:
* - $form: The complete form array.
* - $nid: The node ID of the Webform.
*
* The $form array contains two main pieces:
* - $form['submitted']: The main content of the user-created form.
* - $form['details']: Internal information stored by Webform.
*/
?>
<div class="row">
<div class="col-md-4 col-sm-12"></div>
<div class="col-md-4 col-sm-12">
<div id="content-contact-form">
<div id="form-contacto">
<h3>Contáctanos</h3>
<?php
// Print out the main part of the form.
// Feel free to break this up and move the pieces within the array.
print drupal_render($form['submitted']);
// Always print out the entire $form. This renders the remaining pieces of the
// form that haven't yet been rendered above.
print drupal_render_children($form);
?>
</div>
</div>
</div>
<div class="col-md-4 col-sm-12"></div>
</div>
| eforerop2888/fotografias | sites/all/themes/fotografias/templates/webform-form-33.tpl.php | PHP | gpl-2.0 | 1,215 |
import mainUi.main
mainUi.main.main()
| MiiRaGe/cryptanalysis-tools | run.py | Python | gpl-2.0 | 39 |