code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
<?php
/**
* This module contains the XRDS parsing code.
*
* PHP versions 4 and 5
*
* LICENSE: See the COPYING file included in this distribution.
*
* @package OpenID
* @author JanRain, Inc. <openid@janrain.com>
* @copyright 2005-2008 Janrain, Inc.
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache
*/
/**
* Require the XPath implementation.
*/
require_once 'Auth/Yadis/XML.php';
/**
* This match mode means a given service must match ALL filters passed
* to the Auth_Yadis_XRDS::services() call.
*/
define('SERVICES_YADIS_MATCH_ALL', 101);
/**
* This match mode means a given service must match ANY filters (at
* least one) passed to the Auth_Yadis_XRDS::services() call.
*/
define('SERVICES_YADIS_MATCH_ANY', 102);
/**
* The priority value used for service elements with no priority
* specified.
*/
define('SERVICES_YADIS_MAX_PRIORITY', pow(2, 30));
/**
* XRD XML namespace
*/
define('Auth_Yadis_XMLNS_XRD_2_0', 'xri://$xrd*($v*2.0)');
/**
* XRDS XML namespace
*/
define('Auth_Yadis_XMLNS_XRDS', 'xri://$xrds');
function Auth_Yadis_getNSMap()
{
return array('xrds' => Auth_Yadis_XMLNS_XRDS,
'xrd' => Auth_Yadis_XMLNS_XRD_2_0);
}
/**
* @access private
*/
function Auth_Yadis_array_scramble($arr)
{
$result = array();
while (count($arr)) {
$index = array_rand($arr, 1);
$result[] = $arr[$index];
unset($arr[$index]);
}
return $result;
}
/**
* This class represents a <Service> element in an XRDS document.
* Objects of this type are returned by
* Auth_Yadis_XRDS::services() and
* Auth_Yadis_Yadis::services(). Each object corresponds directly
* to a <Service> element in the XRDS and supplies a
* getElements($name) method which you should use to inspect the
* element's contents. See {@link Auth_Yadis_Yadis} for more
* information on the role this class plays in Yadis discovery.
*
* @package OpenID
*/
class Auth_Yadis_Service {
/**
* Creates an empty service object.
*/
function Auth_Yadis_Service()
{
$this->element = null;
$this->parser = null;
}
/**
* Return the URIs in the "Type" elements, if any, of this Service
* element.
*
* @return array $type_uris An array of Type URI strings.
*/
function getTypes()
{
$t = array();
foreach ($this->getElements('xrd:Type') as $elem) {
$c = $this->parser->content($elem);
if ($c) {
$t[] = $c;
}
}
return $t;
}
function matchTypes($type_uris)
{
$result = array();
foreach ($this->getTypes() as $typ) {
if (in_array($typ, $type_uris)) {
$result[] = $typ;
}
}
return $result;
}
/**
* Return the URIs in the "URI" elements, if any, of this Service
* element. The URIs are returned sorted in priority order.
*
* @return array $uris An array of URI strings.
*/
function getURIs()
{
$uris = array();
$last = array();
foreach ($this->getElements('xrd:URI') as $elem) {
$uri_string = $this->parser->content($elem);
$attrs = $this->parser->attributes($elem);
if ($attrs &&
array_key_exists('priority', $attrs)) {
$priority = intval($attrs['priority']);
if (!array_key_exists($priority, $uris)) {
$uris[$priority] = array();
}
$uris[$priority][] = $uri_string;
} else {
$last[] = $uri_string;
}
}
$keys = array_keys($uris);
sort($keys);
// Rebuild array of URIs.
$result = array();
foreach ($keys as $k) {
$new_uris = Auth_Yadis_array_scramble($uris[$k]);
$result = array_merge($result, $new_uris);
}
$result = array_merge($result,
Auth_Yadis_array_scramble($last));
return $result;
}
/**
* Returns the "priority" attribute value of this <Service>
* element, if the attribute is present. Returns null if not.
*
* @return mixed $result Null or integer, depending on whether
* this Service element has a 'priority' attribute.
*/
function getPriority()
{
$attributes = $this->parser->attributes($this->element);
if (array_key_exists('priority', $attributes)) {
return intval($attributes['priority']);
}
return null;
}
/**
* Used to get XML elements from this object's <Service> element.
*
* This is what you should use to get all custom information out
* of this element. This is used by service filter functions to
* determine whether a service element contains specific tags,
* etc. NOTE: this only considers elements which are direct
* children of the <Service> element for this object.
*
* @param string $name The name of the element to look for
* @return array $list An array of elements with the specified
* name which are direct children of the <Service> element. The
* nodes returned by this function can be passed to $this->parser
* methods (see {@link Auth_Yadis_XMLParser}).
*/
function getElements($name)
{
return $this->parser->evalXPath($name, $this->element);
}
}
/*
* Return the expiration date of this XRD element, or None if no
* expiration was specified.
*
* @param $default The value to use as the expiration if no expiration
* was specified in the XRD.
*/
function Auth_Yadis_getXRDExpiration($xrd_element, $default=null)
{
$expires_element = $xrd_element->$parser->evalXPath('/xrd:Expires');
if ($expires_element === null) {
return $default;
} else {
$expires_string = $expires_element->text;
// Will raise ValueError if the string is not the expected
// format
$t = strptime($expires_string, "%Y-%m-%dT%H:%M:%SZ");
if ($t === false) {
return false;
}
// [int $hour [, int $minute [, int $second [,
// int $month [, int $day [, int $year ]]]]]]
return mktime($t['tm_hour'], $t['tm_min'], $t['tm_sec'],
$t['tm_mon'], $t['tm_day'], $t['tm_year']);
}
}
/**
* This class performs parsing of XRDS documents.
*
* You should not instantiate this class directly; rather, call
* parseXRDS statically:
*
* <pre> $xrds = Auth_Yadis_XRDS::parseXRDS($xml_string);</pre>
*
* If the XRDS can be parsed and is valid, an instance of
* Auth_Yadis_XRDS will be returned. Otherwise, null will be
* returned. This class is used by the Auth_Yadis_Yadis::discover
* method.
*
* @package OpenID
*/
class Auth_Yadis_XRDS {
/**
* Instantiate a Auth_Yadis_XRDS object. Requires an XPath
* instance which has been used to parse a valid XRDS document.
*/
function Auth_Yadis_XRDS(&$xmlParser, &$xrdNodes)
{
$this->parser =& $xmlParser;
$this->xrdNode = $xrdNodes[count($xrdNodes) - 1];
$this->allXrdNodes =& $xrdNodes;
$this->serviceList = array();
$this->_parse();
}
/**
* Parse an XML string (XRDS document) and return either a
* Auth_Yadis_XRDS object or null, depending on whether the
* XRDS XML is valid.
*
* @param string $xml_string An XRDS XML string.
* @return mixed $xrds An instance of Auth_Yadis_XRDS or null,
* depending on the validity of $xml_string
*/
function &parseXRDS($xml_string, $extra_ns_map = null)
{
$_null = null;
if (!$xml_string) {
return $_null;
}
$parser = Auth_Yadis_getXMLParser();
$ns_map = Auth_Yadis_getNSMap();
if ($extra_ns_map && is_array($extra_ns_map)) {
$ns_map = array_merge($ns_map, $extra_ns_map);
}
if (!($parser && $parser->init($xml_string, $ns_map))) {
return $_null;
}
// Try to get root element.
$root = $parser->evalXPath('/xrds:XRDS[1]');
if (!$root) {
return $_null;
}
if (is_array($root)) {
$root = $root[0];
}
$attrs = $parser->attributes($root);
if (array_key_exists('xmlns:xrd', $attrs) &&
$attrs['xmlns:xrd'] != Auth_Yadis_XMLNS_XRDS) {
return $_null;
} else if (array_key_exists('xmlns', $attrs) &&
preg_match('/xri/', $attrs['xmlns']) &&
$attrs['xmlns'] != Auth_Yadis_XMLNS_XRD_2_0) {
return $_null;
}
// Get the last XRD node.
$xrd_nodes = $parser->evalXPath('/xrds:XRDS[1]/xrd:XRD');
if (!$xrd_nodes) {
return $_null;
}
$xrds = new Auth_Yadis_XRDS($parser, $xrd_nodes);
return $xrds;
}
/**
* @access private
*/
function _addService($priority, $service)
{
$priority = intval($priority);
if (!array_key_exists($priority, $this->serviceList)) {
$this->serviceList[$priority] = array();
}
$this->serviceList[$priority][] = $service;
}
/**
* Creates the service list using nodes from the XRDS XML
* document.
*
* @access private
*/
function _parse()
{
$this->serviceList = array();
$services = $this->parser->evalXPath('xrd:Service', $this->xrdNode);
foreach ($services as $node) {
$s = new Auth_Yadis_Service();
$s->element = $node;
$s->parser =& $this->parser;
$priority = $s->getPriority();
if ($priority === null) {
$priority = SERVICES_YADIS_MAX_PRIORITY;
}
$this->_addService($priority, $s);
}
}
/**
* Returns a list of service objects which correspond to <Service>
* elements in the XRDS XML document for this object.
*
* Optionally, an array of filter callbacks may be given to limit
* the list of returned service objects. Furthermore, the default
* mode is to return all service objects which match ANY of the
* specified filters, but $filter_mode may be
* SERVICES_YADIS_MATCH_ALL if you want to be sure that the
* returned services match all the given filters. See {@link
* Auth_Yadis_Yadis} for detailed usage information on filter
* functions.
*
* @param mixed $filters An array of callbacks to filter the
* returned services, or null if all services are to be returned.
* @param integer $filter_mode SERVICES_YADIS_MATCH_ALL or
* SERVICES_YADIS_MATCH_ANY, depending on whether the returned
* services should match ALL or ANY of the specified filters,
* respectively.
* @return mixed $services An array of {@link
* Auth_Yadis_Service} objects if $filter_mode is a valid
* mode; null if $filter_mode is an invalid mode (i.e., not
* SERVICES_YADIS_MATCH_ANY or SERVICES_YADIS_MATCH_ALL).
*/
function services($filters = null,
$filter_mode = SERVICES_YADIS_MATCH_ANY)
{
$pri_keys = array_keys($this->serviceList);
sort($pri_keys, SORT_NUMERIC);
// If no filters are specified, return the entire service
// list, ordered by priority.
if (!$filters ||
(!is_array($filters))) {
$result = array();
foreach ($pri_keys as $pri) {
$result = array_merge($result, $this->serviceList[$pri]);
}
return $result;
}
// If a bad filter mode is specified, return null.
if (!in_array($filter_mode, array(SERVICES_YADIS_MATCH_ANY,
SERVICES_YADIS_MATCH_ALL))) {
return null;
}
// Otherwise, use the callbacks in the filter list to
// determine which services are returned.
$filtered = array();
foreach ($pri_keys as $priority_value) {
$service_obj_list = $this->serviceList[$priority_value];
foreach ($service_obj_list as $service) {
$matches = 0;
foreach ($filters as $filter) {
if (call_user_func_array($filter, array($service))) {
$matches++;
if ($filter_mode == SERVICES_YADIS_MATCH_ANY) {
$pri = $service->getPriority();
if ($pri === null) {
$pri = SERVICES_YADIS_MAX_PRIORITY;
}
if (!array_key_exists($pri, $filtered)) {
$filtered[$pri] = array();
}
$filtered[$pri][] = $service;
break;
}
}
}
if (($filter_mode == SERVICES_YADIS_MATCH_ALL) &&
($matches == count($filters))) {
$pri = $service->getPriority();
if ($pri === null) {
$pri = SERVICES_YADIS_MAX_PRIORITY;
}
if (!array_key_exists($pri, $filtered)) {
$filtered[$pri] = array();
}
$filtered[$pri][] = $service;
}
}
}
$pri_keys = array_keys($filtered);
sort($pri_keys, SORT_NUMERIC);
$result = array();
foreach ($pri_keys as $pri) {
$result = array_merge($result, $filtered[$pri]);
}
return $result;
}
}
?> | IYEO/Sweettaste | tmp/install_5680f69da1732/install_5680f6ab093c2/assets/yahoo-yos-social/lib/OpenID/Auth/Yadis/XRDS.php | PHP | gpl-2.0 | 14,321 |
/*
* Copyright (c) 2015, 2015, 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.
*
* 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 org.graalvm.compiler.nodes;
import java.util.List;
import org.graalvm.compiler.graph.NodeClass;
import jdk.vm.ci.meta.Assumptions;
import jdk.vm.ci.meta.ResolvedJavaMethod;
/**
* A {@link StructuredGraph} encoded in a compact binary representation as a byte[] array. See
* {@link GraphEncoder} for a description of the encoding format. Use {@link GraphDecoder} for
* decoding.
*/
public class EncodedGraph {
private final byte[] encoding;
private final long startOffset;
private final Object[] objects;
private final NodeClass<?>[] types;
private final Assumptions assumptions;
private final List<ResolvedJavaMethod> inlinedMethods;
/**
* The "table of contents" of the encoded graph, i.e., the mapping from orderId numbers to the
* offset in the encoded byte[] array. Used as a cache during decoding.
*/
protected long[] nodeStartOffsets;
public EncodedGraph(byte[] encoding, long startOffset, Object[] objects, NodeClass<?>[] types, Assumptions assumptions, List<ResolvedJavaMethod> inlinedMethods) {
this.encoding = encoding;
this.startOffset = startOffset;
this.objects = objects;
this.types = types;
this.assumptions = assumptions;
this.inlinedMethods = inlinedMethods;
}
public byte[] getEncoding() {
return encoding;
}
public long getStartOffset() {
return startOffset;
}
public Object[] getObjects() {
return objects;
}
public NodeClass<?>[] getNodeClasses() {
return types;
}
public Assumptions getAssumptions() {
return assumptions;
}
public List<ResolvedJavaMethod> getInlinedMethods() {
return inlinedMethods;
}
}
| YouDiSN/OpenJDK-Research | jdk9/hotspot/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/EncodedGraph.java | Java | gpl-2.0 | 2,807 |
//
// MessagePack for C++ static resolution routine
//
// Copyright (C) 2008-2009 FURUHASHI Sadayuki
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef MSGPACK_TYPE_NIL_HPP
#define MSGPACK_TYPE_NIL_HPP
#include "msgpack/versioning.hpp"
#include "msgpack/adaptor/adaptor_base.hpp"
namespace msgpack {
/// @cond
MSGPACK_API_VERSION_NAMESPACE(v1) {
/// @endcond
namespace type {
struct nil_t { };
#if !defined(MSGPACK_DISABLE_LEGACY_NIL)
typedef nil_t nil;
#endif // !defined(MSGPACK_DISABLE_LEGACY_NIL)
inline bool operator<(nil_t const& lhs, nil_t const& rhs) {
return &lhs < &rhs;
}
inline bool operator==(nil_t const& lhs, nil_t const& rhs) {
return &lhs == &rhs;
}
} // namespace type
namespace adaptor {
template <>
struct convert<type::nil_t> {
msgpack::object const& operator()(msgpack::object const& o, type::nil_t&) const {
if(o.type != msgpack::type::NIL) { throw msgpack::type_error(); }
return o;
}
};
template <>
struct pack<type::nil_t> {
template <typename Stream>
msgpack::packer<Stream>& operator()(msgpack::packer<Stream>& o, const type::nil_t&) const {
o.pack_nil();
return o;
}
};
template <>
struct object<type::nil_t> {
void operator()(msgpack::object& o, type::nil_t) const {
o.type = msgpack::type::NIL;
}
};
template <>
struct object_with_zone<type::nil_t> {
void operator()(msgpack::object::with_zone& o, type::nil_t v) const {
static_cast<msgpack::object&>(o) << v;
}
};
} // namespace adaptor
template <>
inline void msgpack::object::as<void>() const
{
msgpack::type::nil_t v;
convert(v);
}
/// @cond
} // MSGPACK_API_VERSION_NAMESPACE(v1)
/// @endcond
} // namespace msgpack
#endif // MSGPACK_TYPE_NIL_HPP
| scraperwiki/pdf2msgpack | msgpack-c/include/msgpack/adaptor/nil.hpp | C++ | gpl-2.0 | 1,885 |
/* FCE Ultra - NES/Famicom Emulator
*
* Copyright notice for this file:
* Copyright (C) 2002 Xodnizel
*
* 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 "types.h"
#include "file.h"
#include "utils/endian.h"
#include "netplay.h"
#include "fceu.h"
#include "state.h"
#include "cheat.h"
#include "input.h"
#include "driver.h"
#include "utils/memory.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
//#include <unistd.h> //mbg merge 7/17/06 removed
#include <zlib.h>
int FCEUnetplay=0;
static uint8 netjoy[4]; // Controller cache.
static int numlocal;
static int netdivisor;
static int netdcount;
//NetError should only be called after a FCEUD_*Data function returned 0, in the function
//that called FCEUD_*Data, to prevent it from being called twice.
static void NetError(void)
{
FCEU_DispMessage("Network error/connection lost!",0);
FCEUD_NetworkClose();
}
void FCEUI_NetplayStop(void)
{
if(FCEUnetplay)
{
FCEUnetplay = 0;
FCEU_FlushGameCheats(0,1); //Don't save netplay cheats.
FCEU_LoadGameCheats(0); //Reload our original cheats.
}
else puts("Check your code!");
}
int FCEUI_NetplayStart(int nlocal, int divisor)
{
FCEU_FlushGameCheats(0, 0); //Save our pre-netplay cheats.
FCEU_LoadGameCheats(0); // Load them again, for pre-multiplayer action.
FCEUnetplay = 1;
memset(netjoy,0,sizeof(netjoy));
numlocal = nlocal;
netdivisor = divisor;
netdcount = 0;
return(1);
}
int FCEUNET_SendCommand(uint8 cmd, uint32 len)
{
//mbg merge 7/17/06 changed to alloca
//uint8 buf[numlocal + 1 + 4];
uint8 *buf = (uint8*)alloca(numlocal+1+4);
buf[0] = 0xFF;
FCEU_en32lsb(&buf[numlocal], len);
buf[numlocal + 4] = cmd;
if(!FCEUD_SendData(buf,numlocal + 1 + 4))
{
NetError();
return(0);
}
return(1);
}
void FCEUI_NetplayText(uint8 *text)
{
uint32 len;
len = strlen((char*)text); //mbg merge 7/17/06 added cast
if(!FCEUNET_SendCommand(FCEUNPCMD_TEXT,len)) return;
if(!FCEUD_SendData(text,len))
NetError();
}
int FCEUNET_SendFile(uint8 cmd, char *fn)
{
uint32 len;
uLongf clen;
char *buf, *cbuf;
FILE *fp;
struct stat sb;
if(!(fp=FCEUD_UTF8fopen(fn,"rb"))) return(0);
fstat(fileno(fp),&sb);
len = sb.st_size;
buf = (char*)FCEU_dmalloc(len); //mbg merge 7/17/06 added cast
fread(buf, 1, len, fp);
fclose(fp);
cbuf = (char*)FCEU_dmalloc(4 + len + len / 1000 + 12); //mbg merge 7/17/06 added cast
FCEU_en32lsb((uint8*)cbuf, len); //mbg merge 7/17/06 added cast
compress2((uint8*)cbuf + 4, &clen, (uint8*)buf, len, 7); //mbg merge 7/17/06 added casts
free(buf);
//printf("Sending file: %s, %d, %d\n",fn,len,clen);
len = clen + 4;
if(!FCEUNET_SendCommand(cmd,len))
{
free(cbuf);
return(0);
}
if(!FCEUD_SendData(cbuf, len))
{
NetError();
free(cbuf);
return(0);
}
free(cbuf);
return(1);
}
static FILE *FetchFile(uint32 remlen)
{
uint32 clen = remlen;
char *cbuf;
uLongf len;
char *buf;
FILE *fp;
if(clen > 500000) // Sanity check
{
NetError();
return(0);
}
//printf("Receiving file: %d...\n",clen);
if((fp = tmpfile()))
{
cbuf = (char *)FCEU_dmalloc(clen); //mbg merge 7/17/06 added cast
if(!FCEUD_RecvData(cbuf, clen))
{
NetError();
fclose(fp);
free(cbuf);
return(0);
}
len = FCEU_de32lsb((uint8*)cbuf); //mbg merge 7/17/06 added cast
if(len > 500000) // Another sanity check
{
NetError();
fclose(fp);
free(cbuf);
return(0);
}
buf = (char *)FCEU_dmalloc(len); //mbg merge 7/17/06 added cast
uncompress((uint8*)buf, &len, (uint8*)cbuf + 4, clen - 4); //mbg merge 7/17/06 added casts
fwrite(buf, 1, len, fp);
free(buf);
fseek(fp, 0, SEEK_SET);
return(fp);
}
return(0);
}
void NetplayUpdate(uint8 *joyp)
{
static uint8 buf[5]; /* 4 play states, + command/extra byte */
static uint8 joypb[4];
memcpy(joypb,joyp,4);
/* This shouldn't happen, but just in case. 0xFF is used as a command escape elsewhere. */
if(joypb[0] == 0xFF)
joypb[0] = 0xF;
if(!netdcount)
if(!FCEUD_SendData(joypb,numlocal))
{
NetError();
return;
}
if(!netdcount)
{
do
{
if(!FCEUD_RecvData(buf,5))
{
NetError();
return;
}
switch(buf[4])
{
default: FCEU_DoSimpleCommand(buf[4]);break;
case FCEUNPCMD_TEXT:
{
uint8 *tbuf;
uint32 len = FCEU_de32lsb(buf);
if(len > 100000) // Insanity check!
{
NetError();
return;
}
tbuf = (uint8*)malloc(len + 1); //mbg merge 7/17/06 added cast
tbuf[len] = 0;
if(!FCEUD_RecvData(tbuf, len))
{
NetError();
free(tbuf);
return;
}
FCEUD_NetplayText(tbuf);
free(tbuf);
}
break;
case FCEUNPCMD_SAVESTATE:
{
//mbg todo netplay
//char *fn;
//FILE *fp;
////Send the cheats first, then the save state, since
////there might be a frame or two in between the two sendfile
////commands on the server side.
//fn = strdup(FCEU_MakeFName(FCEUMKF_CHEAT,0,0).c_str());
////why??????
////if(!
// FCEUNET_SendFile(FCEUNPCMD_LOADCHEATS,fn);
//// {
//// free(fn);
//// return;
//// }
//free(fn);
//if(!FCEUnetplay) return;
//fn = strdup(FCEU_MakeFName(FCEUMKF_NPTEMP,0,0).c_str());
//fp = fopen(fn, "wb");
//if(FCEUSS_SaveFP(fp,Z_BEST_COMPRESSION))
//{
// fclose(fp);
// if(!FCEUNET_SendFile(FCEUNPCMD_LOADSTATE, fn))
// {
// unlink(fn);
// free(fn);
// return;
// }
// unlink(fn);
// free(fn);
//}
//else
//{
// fclose(fp);
// FCEUD_PrintError("File error. (K)ill, (M)aim, (D)estroy? Now!");
// unlink(fn);
// free(fn);
// return;
//}
}
break;
case FCEUNPCMD_LOADCHEATS:
{
FILE *fp = FetchFile(FCEU_de32lsb(buf));
if(!fp) return;
FCEU_FlushGameCheats(0,1);
FCEU_LoadGameCheats(fp);
}
break;
//mbg 6/16/08 - netplay doesnt work right now anyway
/*case FCEUNPCMD_LOADSTATE:
{
FILE *fp = FetchFile(FCEU_de32lsb(buf));
if(!fp) return;
if(FCEUSS_LoadFP(fp,SSLOADPARAM_BACKUP))
{
fclose(fp);
FCEU_DispMessage("Remote state loaded.",0);
} else FCEUD_PrintError("File error. (K)ill, (M)aim, (D)estroy?");
}
break;*/
}
} while(buf[4]);
netdcount=(netdcount+1)%netdivisor;
memcpy(netjoy,buf,4);
*(uint32 *)joyp=*(uint32 *)netjoy;
}
}
| zear/fceu320-rzx50 | src/netplay.cpp | C++ | gpl-2.0 | 7,392 |
#ifndef _LINUX_SEQ_FILE_H
#define _LINUX_SEQ_FILE_H
#include <linux/types.h>
#include <linux/string.h>
#include <linux/bug.h>
#include <linux/mutex.h>
#include <linux/cpumask.h>
#include <linux/nodemask.h>
struct seq_operations;
struct file;
struct path;
struct inode;
struct dentry;
struct user_namespace;
struct seq_file {
char *buf;
size_t size;
size_t from;
size_t count;
size_t pad_until;
loff_t index;
loff_t read_pos;
u64 version;
struct mutex lock;
const struct seq_operations *op;
int poll_event;
#ifdef CONFIG_GRKERNSEC_PROC_MEMMAP
u64 exec_id;
#endif
#ifdef CONFIG_USER_NS
struct user_namespace *user_ns;
#endif
void *private;
};
struct seq_operations {
void * (*start) (struct seq_file *m, loff_t *pos);
void (*stop) (struct seq_file *m, void *v);
void * (*next) (struct seq_file *m, void *v, loff_t *pos);
int (*show) (struct seq_file *m, void *v);
};
typedef struct seq_operations __no_const seq_operations_no_const;
#define SEQ_SKIP 1
/**
* seq_get_buf - get buffer to write arbitrary data to
* @m: the seq_file handle
* @bufp: the beginning of the buffer is stored here
*
* Return the number of bytes available in the buffer, or zero if
* there's no space.
*/
static inline size_t seq_get_buf(struct seq_file *m, char **bufp)
{
BUG_ON(m->count > m->size);
if (m->count < m->size)
*bufp = m->buf + m->count;
else
*bufp = NULL;
return m->size - m->count;
}
/**
* seq_commit - commit data to the buffer
* @m: the seq_file handle
* @num: the number of bytes to commit
*
* Commit @num bytes of data written to a buffer previously acquired
* by seq_buf_get. To signal an error condition, or that the data
* didn't fit in the available space, pass a negative @num value.
*/
static inline void seq_commit(struct seq_file *m, int num)
{
if (num < 0) {
m->count = m->size;
} else {
BUG_ON(m->count + num > m->size);
m->count += num;
}
}
/**
* seq_setwidth - set padding width
* @m: the seq_file handle
* @size: the max number of bytes to pad.
*
* Call seq_setwidth() for setting max width, then call seq_printf() etc. and
* finally call seq_pad() to pad the remaining bytes.
*/
static inline void seq_setwidth(struct seq_file *m, size_t size)
{
m->pad_until = m->count + size;
}
void seq_pad(struct seq_file *m, char c);
char *mangle_path(char *s, const char *p, const char *esc);
int seq_open(struct file *, const struct seq_operations *);
int seq_open_restrict(struct file *, const struct seq_operations *);
ssize_t seq_read(struct file *, char __user *, size_t, loff_t *);
loff_t seq_lseek(struct file *, loff_t, int);
int seq_release(struct inode *, struct file *);
int seq_escape(struct seq_file *, const char *, const char *);
int seq_putc(struct seq_file *m, char c);
int seq_puts(struct seq_file *m, const char *s);
int seq_write(struct seq_file *seq, const void *data, size_t len);
__printf(2, 3) int seq_printf(struct seq_file *, const char *, ...);
__printf(2, 0) int seq_vprintf(struct seq_file *, const char *, va_list args);
int seq_path(struct seq_file *, const struct path *, const char *);
int seq_dentry(struct seq_file *, struct dentry *, const char *);
int seq_path_root(struct seq_file *m, const struct path *path,
const struct path *root, const char *esc);
int seq_bitmap(struct seq_file *m, const unsigned long *bits,
unsigned int nr_bits);
static inline int seq_cpumask(struct seq_file *m, const struct cpumask *mask)
{
return seq_bitmap(m, cpumask_bits(mask), nr_cpu_ids);
}
static inline int seq_nodemask(struct seq_file *m, nodemask_t *mask)
{
return seq_bitmap(m, mask->bits, MAX_NUMNODES);
}
int seq_bitmap_list(struct seq_file *m, const unsigned long *bits,
unsigned int nr_bits);
static inline int seq_cpumask_list(struct seq_file *m,
const struct cpumask *mask)
{
return seq_bitmap_list(m, cpumask_bits(mask), nr_cpu_ids);
}
static inline int seq_nodemask_list(struct seq_file *m, nodemask_t *mask)
{
return seq_bitmap_list(m, mask->bits, MAX_NUMNODES);
}
int single_open(struct file *, int (*)(struct seq_file *, void *), void *);
int single_open_restrict(struct file *, int (*)(struct seq_file *, void *), void *);
int single_open_size(struct file *, int (*)(struct seq_file *, void *), void *, size_t);
int single_release(struct inode *, struct file *);
void *__seq_open_private(struct file *, const struct seq_operations *, int);
int seq_open_private(struct file *, const struct seq_operations *, int);
int seq_release_private(struct inode *, struct file *);
int seq_put_decimal_ull(struct seq_file *m, char delimiter,
unsigned long long num);
int seq_put_decimal_ll(struct seq_file *m, char delimiter,
long long num);
static inline struct user_namespace *seq_user_ns(struct seq_file *seq)
{
#ifdef CONFIG_USER_NS
return seq->user_ns;
#else
extern struct user_namespace init_user_ns;
return &init_user_ns;
#endif
}
#define SEQ_START_TOKEN ((void *)1)
/*
* Helpers for iteration over list_head-s in seq_files
*/
extern struct list_head *seq_list_start(struct list_head *head,
loff_t pos);
extern struct list_head *seq_list_start_head(struct list_head *head,
loff_t pos);
extern struct list_head *seq_list_next(void *v, struct list_head *head,
loff_t *ppos);
/*
* Helpers for iteration over hlist_head-s in seq_files
*/
extern struct hlist_node *seq_hlist_start(struct hlist_head *head,
loff_t pos);
extern struct hlist_node *seq_hlist_start_head(struct hlist_head *head,
loff_t pos);
extern struct hlist_node *seq_hlist_next(void *v, struct hlist_head *head,
loff_t *ppos);
extern struct hlist_node *seq_hlist_start_rcu(struct hlist_head *head,
loff_t pos);
extern struct hlist_node *seq_hlist_start_head_rcu(struct hlist_head *head,
loff_t pos);
extern struct hlist_node *seq_hlist_next_rcu(void *v,
struct hlist_head *head,
loff_t *ppos);
/* Helpers for iterating over per-cpu hlist_head-s in seq_files */
extern struct hlist_node *seq_hlist_start_percpu(struct hlist_head __percpu *head, int *cpu, loff_t pos);
extern struct hlist_node *seq_hlist_next_percpu(void *v, struct hlist_head __percpu *head, int *cpu, loff_t *pos);
#endif
| AdaLovelance/lxcGrsecKernels | linux-3.14.37/include/linux/seq_file.h | C | gpl-2.0 | 6,168 |
/*
* Copyright 2006-2015 The MZmine 2 Development Team
*
* This file is part of MZmine 2.
*
* MZmine 2 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.
*
* MZmine 2 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
* MZmine 2; if not, write to the Free Software Foundation, Inc., 51 Franklin St,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.sf.mzmine.modules.peaklistmethods.peakpicking.deconvolution.savitzkygolay;
public final class SGDerivative {
/**
* This method returns the second smoothed derivative values of an array.
*
* @param double[] values
* @param boolean is first derivative
* @param int level of filter (1 - 12)
* @return double[] derivative of values
*/
public static double[] calculateDerivative(double[] values,
boolean firstDerivative, int levelOfFilter) {
double[] derivative = new double[values.length];
int M = 0;
for (int k = 0; k < derivative.length; k++) {
// Determine boundaries
if (k <= levelOfFilter)
M = k;
if (k + M > derivative.length - 1)
M = derivative.length - (k + 1);
// Perform derivative using Savitzky Golay coefficients
for (int i = -M; i <= M; i++) {
derivative[k] += values[k + i]
* getSGCoefficient(M, i, firstDerivative);
}
// if ((Math.abs(derivative[k])) > maxValueDerivative)
// maxValueDerivative = Math.abs(derivative[k]);
}
return derivative;
}
/**
* This method return the Savitzky-Golay 2nd smoothed derivative coefficient
* from an array
*
* @param M
* @param signedC
* @return
*/
private static Double getSGCoefficient(int M, int signedC,
boolean firstDerivate) {
int C = Math.abs(signedC), sign = 1;
if (firstDerivate) {
if (signedC < 0)
sign = -1;
return sign
* SGCoefficients.SGCoefficientsFirstDerivativeQuartic[M][C];
} else {
return SGCoefficients.SGCoefficientsSecondDerivative[M][C];
}
}
}
| DrewG/mzmine2 | src/main/java/net/sf/mzmine/modules/peaklistmethods/peakpicking/deconvolution/savitzkygolay/SGDerivative.java | Java | gpl-2.0 | 2,508 |
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Api;
use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\WebapiAbstract;
use Magento\Webapi\Model\Rest\Config as HttpConstants;
class TaxRuleRepositoryInterfaceTest extends WebapiAbstract
{
const SERVICE_NAME = "taxTaxRuleRepositoryV1";
const SERVICE_VERSION = "V1";
const RESOURCE_PATH = "/V1/taxRules";
/** @var \Magento\Tax\Model\Calculation\Rate[] */
private $fixtureTaxRates;
/** @var \Magento\Tax\Model\ClassModel[] */
private $fixtureTaxClasses;
/** @var \Magento\Tax\Model\Calculation\Rule[] */
private $fixtureTaxRules;
/** @var FilterBuilder */
private $filterBuilder;
/** @var SearchCriteriaBuilder */
private $searchCriteriaBuilder;
/**
* Execute per test initialization.
*/
public function setUp()
{
$this->searchCriteriaBuilder = Bootstrap::getObjectManager()->create(
'Magento\Framework\Api\SearchCriteriaBuilder'
);
$this->filterBuilder = Bootstrap::getObjectManager()->create(
'Magento\Framework\Api\FilterBuilder'
);
$objectManager = Bootstrap::getObjectManager();
$this->searchCriteriaBuilder = $objectManager->create(
'Magento\Framework\Api\SearchCriteriaBuilder'
);
$this->filterBuilder = $objectManager->create(
'Magento\Framework\Api\FilterBuilder'
);
/** Initialize tax classes, tax rates and tax rules defined in fixture Magento/Tax/_files/tax_classes.php */
$this->getFixtureTaxRates();
$this->getFixtureTaxClasses();
$this->getFixtureTaxRules();
}
public function tearDown()
{
$taxRules = $this->getFixtureTaxRules();
if (count($taxRules)) {
$taxRates = $this->getFixtureTaxRates();
$taxClasses = $this->getFixtureTaxClasses();
foreach ($taxRules as $taxRule) {
$taxRule->delete();
}
foreach ($taxRates as $taxRate) {
$taxRate->delete();
}
foreach ($taxClasses as $taxClass) {
$taxClass->delete();
}
}
}
/**
* @magentoApiDataFixture Magento/Tax/_files/tax_classes.php
*/
public function testDeleteTaxRule()
{
$fixtureRule = $this->getFixtureTaxRules()[0];
$taxRuleId = $fixtureRule->getId();
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . "/$taxRuleId",
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'DeleteById',
],
];
$requestData = ['ruleId' => $taxRuleId];
$result = $this->_webApiCall($serviceInfo, $requestData);
$this->assertTrue($result);
/** Ensure that tax rule was actually removed from DB */
/** @var \Magento\Tax\Model\Calculation\Rule $taxRule */
$taxRate = Bootstrap::getObjectManager()->create('Magento\Tax\Model\Calculation\Rate');
$this->assertNull($taxRate->load($taxRuleId)->getId(), 'Tax rule was not deleted from DB.');
}
public function testCreateTaxRule()
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH,
'httpMethod' => HttpConstants::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save',
],
];
$requestData = [
'rule' => [
'code' => 'Test Rule ' . microtime(),
'position' => 10,
'priority' => 5,
'customer_tax_class_ids' => [3],
'product_tax_class_ids' => [2],
'tax_rate_ids' => [1, 2],
'calculate_subtotal' => 1,
],
];
$taxRuleData = $this->_webApiCall($serviceInfo, $requestData);
$this->assertArrayHasKey('id', $taxRuleData, "Tax rule ID is expected");
$this->assertGreaterThan(0, $taxRuleData['id']);
$taxRuleId = $taxRuleData['id'];
unset($taxRuleData['id']);
$this->assertEquals($requestData['rule'], $taxRuleData, "Tax rule is created with invalid data.");
/** Ensure that tax rule was actually created in DB */
/** @var \Magento\Tax\Model\Calculation\Rule $taxRule */
$taxRule = Bootstrap::getObjectManager()->create('Magento\Tax\Model\Calculation\Rule');
$this->assertEquals($taxRuleId, $taxRule->load($taxRuleId)->getId(), 'Tax rule was not created in DB.');
$taxRule->delete();
}
public function testCreateTaxRuleInvalidTaxClassIds()
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH,
'httpMethod' => HttpConstants::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save',
],
];
$requestData = [
'rule' => [
'code' => 'Test Rule ' . microtime(),
'position' => 10,
'priority' => 5,
'customer_tax_class_ids' => [2],
'product_tax_class_ids' => [3],
'tax_rate_ids' => [1, 2],
'calculate_subtotal' => 1,
],
];
try {
$this->_webApiCall($serviceInfo, $requestData);
$this->fail('Did not throw expected InputException');
} catch (\SoapFault $e) {
$this->assertContains('No such entity with customer_tax_class_ids = %fieldValue', $e->getMessage());
} catch (\Exception $e) {
$this->assertContains('No such entity with customer_tax_class_ids = %fieldValue', $e->getMessage());
}
}
public function testCreateTaxRuleExistingCode()
{
$expectedMessage = '%1 already exists.';
$requestData = [
'rule' => [
'code' => 'Test Rule ' . microtime(),
'position' => 10,
'priority' => 5,
'customer_tax_class_ids' => [3],
'product_tax_class_ids' => [2],
'tax_rate_ids' => [1, 2],
'calculate_subtotal' => 0,
],
];
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save',
],
];
$newTaxRuleData = $this->_webApiCall($serviceInfo, $requestData);
try {
$this->_webApiCall($serviceInfo, $requestData);
$this->fail('Expected exception was not raised');
} catch (\SoapFault $e) {
$this->assertContains(
$expectedMessage,
$e->getMessage(),
'SoapFault does not contain expected message.'
);
} catch (\Exception $e) {
$errorObj = $this->processRestExceptionResult($e);
$this->assertEquals($expectedMessage, $errorObj['message']);
$this->assertEquals(['Code'], $errorObj['parameters']);
}
// Clean up the new tax rule so it won't affect other tests
/** @var \Magento\Tax\Model\Calculation\Rule $taxRule */
$taxRule = Bootstrap::getObjectManager()->create('Magento\Tax\Model\Calculation\Rule');
$taxRule->load($newTaxRuleData['id']);
$taxRule->delete();
}
/**
* @magentoApiDataFixture Magento/Tax/_files/tax_classes.php
*/
public function testGetTaxRule()
{
$fixtureRule = $this->getFixtureTaxRules()[0];
$taxRuleId = $fixtureRule->getId();
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . "/$taxRuleId",
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Get',
],
];
$expectedRuleData = [
'id' => $taxRuleId,
'code' => 'Test Rule Duplicate',
'priority' => '0',
'position' => '0',
'customer_tax_class_ids' => array_values(array_unique($fixtureRule->getCustomerTaxClasses())),
'product_tax_class_ids' => array_values(array_unique($fixtureRule->getProductTaxClasses())),
'tax_rate_ids' => array_values(array_unique($fixtureRule->getRates())),
'calculate_subtotal' => false,
];
$requestData = ['ruleId' => $taxRuleId];
$result = $this->_webApiCall($serviceInfo, $requestData);
$this->assertEquals($expectedRuleData, $result);
}
/**
* @magentoApiDataFixture Magento/Tax/_files/tax_classes.php
*/
public function testSearchTaxRulesSimple()
{
// Find rules whose code is 'Test Rule'
$filter = $this->filterBuilder->setField('code')
->setValue('Test Rule')
->create();
$this->searchCriteriaBuilder->addFilters([$filter]);
$fixtureRule = $this->getFixtureTaxRules()[1];
$searchData = $this->searchCriteriaBuilder->create()->__toArray();
$requestData = ['searchCriteria' => $searchData];
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/search' . '?' . http_build_query($requestData),
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GetList',
],
];
/** @var \Magento\Framework\Api\SearchResults $searchResults */
$searchResults = $this->_webApiCall($serviceInfo, $requestData);
$this->assertEquals(1, $searchResults['total_count']);
$expectedRuleData = [
[
'id' => $fixtureRule->getId(),
'code' => 'Test Rule',
'priority' => 0,
'position' => 0,
'calculate_subtotal' => 0,
'customer_tax_class_ids' => array_values(array_unique($fixtureRule->getCustomerTaxClasses())),
'product_tax_class_ids' => array_values(array_unique($fixtureRule->getProductTaxClasses())),
'tax_rate_ids' => array_values(array_unique($fixtureRule->getRates())),
],
];
$this->assertEquals($expectedRuleData, $searchResults['items']);
}
/**
* @magentoApiDataFixture Magento/Tax/_files/tax_classes.php
*/
public function testSearchTaxRulesCodeLike()
{
// Find rules whose code starts with 'Test Rule'
$filter = $this->filterBuilder
->setField('code')
->setValue('Test Rule%')
->setConditionType('like')
->create();
$sortFilter = $this->filterBuilder
->setField('position')
->setValue(0)
->create();
$this->searchCriteriaBuilder->addFilters([$filter, $sortFilter]);
$fixtureRule = $this->getFixtureTaxRules()[1];
$searchData = $this->searchCriteriaBuilder->create()->__toArray();
$requestData = ['searchCriteria' => $searchData];
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/search' . '?' . http_build_query($requestData),
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GetList',
],
];
/** @var \Magento\Framework\Api\SearchResults $searchResults */
$searchResults = $this->_webApiCall($serviceInfo, $requestData);
$this->assertEquals(2, $searchResults['total_count']);
$expectedRuleData = [
[
'id' => $fixtureRule->getId(),
'code' => 'Test Rule',
'priority' => 0,
'position' => 0,
'calculate_subtotal' => 0,
'customer_tax_class_ids' => array_values(array_unique($fixtureRule->getCustomerTaxClasses())),
'product_tax_class_ids' => array_values(array_unique($fixtureRule->getProductTaxClasses())),
'tax_rate_ids' => array_values(array_unique($fixtureRule->getRates())),
],
[
'id' => $this->getFixtureTaxRules()[0]->getId(),
'code' => 'Test Rule Duplicate',
'priority' => 0,
'position' => 0,
'calculate_subtotal' => 0,
'customer_tax_class_ids' => array_values(array_unique($fixtureRule->getCustomerTaxClasses())),
'product_tax_class_ids' => array_values(array_unique($fixtureRule->getProductTaxClasses())),
'tax_rate_ids' => array_values(array_unique($fixtureRule->getRates()))
],
];
$this->assertEquals($expectedRuleData, $searchResults['items']);
}
public function testGetTaxRuleNotExist()
{
$taxRuleId = 37865;
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . "/$taxRuleId",
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Get',
],
];
$requestData = ['ruleId' => $taxRuleId];
try {
$this->_webApiCall($serviceInfo, $requestData);
$this->fail('Expected exception was not raised');
} catch (\Exception $e) {
$expectedMessage = 'No such entity with %fieldName = %fieldValue';
$this->assertContains(
$expectedMessage,
$e->getMessage(),
"Exception does not contain expected message."
);
}
}
/**
* @magentoApiDataFixture Magento/Tax/_files/tax_classes.php
*/
public function testUpdateTaxRule()
{
$fixtureRule = $this->getFixtureTaxRules()[0];
$requestData = [
'rule' => [
'id' => $fixtureRule->getId(),
'code' => 'Test Rule ' . microtime(),
'position' => 10,
'priority' => 5,
'customer_tax_class_ids' => [3],
'product_tax_class_ids' => [2],
'tax_rate_ids' => [1, 2],
'calculate_subtotal' => 1,
],
];
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save',
],
];
$this->_webApiCall($serviceInfo, $requestData);
$expectedRuleData = $requestData['rule'];
/** Ensure that tax rule was actually updated in DB */
/** @var \Magento\Tax\Model\Calculation $taxCalculation */
$taxCalculation = Bootstrap::getObjectManager()->create('Magento\Tax\Model\Calculation');
/** @var \Magento\Tax\Model\Calculation\Rule $taxRule */
$taxRule = Bootstrap::getObjectManager()->create(
'Magento\Tax\Model\Calculation\Rule',
['calculation' => $taxCalculation]
);
$taxRuleModel = $taxRule->load($fixtureRule->getId());
$this->assertEquals($expectedRuleData['id'], $taxRuleModel->getId(), 'Tax rule was not updated in DB.');
$this->assertEquals(
$expectedRuleData['code'],
$taxRuleModel->getCode(),
'Tax rule code was updated incorrectly.'
);
$this->assertEquals(
$expectedRuleData['position'],
$taxRuleModel->getPosition(),
'Tax rule sort order was updated incorrectly.'
);
$this->assertEquals(
$expectedRuleData['priority'],
$taxRuleModel->getPriority(),
'Tax rule priority was updated incorrectly.'
);
$this->assertEquals(
$expectedRuleData['customer_tax_class_ids'],
array_values(array_unique($taxRuleModel->getCustomerTaxClasses())),
'Customer Tax classes were updated incorrectly'
);
$this->assertEquals(
$expectedRuleData['product_tax_class_ids'],
array_values(array_unique($taxRuleModel->getProductTaxClasses())),
'Product Tax classes were updated incorrectly.'
);
$this->assertEquals(
$expectedRuleData['tax_rate_ids'],
array_values(array_unique($taxRuleModel->getRates())),
'Tax rates were updated incorrectly.'
);
}
public function testUpdateTaxRuleNotExisting()
{
$requestData = [
'rule' => [
'id' => 12345,
'code' => 'Test Rule ' . microtime(),
'position' => 10,
'priority' => 5,
'customer_tax_class_ids' => [3],
'product_tax_class_ids' => [2],
'tax_rate_ids' => [1, 2],
],
];
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH,
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'Save',
],
];
try {
$this->_webApiCall($serviceInfo, $requestData);
$this->fail('Expected exception was not raised');
} catch (\Exception $e) {
$expectedMessage = 'No such entity with %fieldName = %fieldValue';
$this->assertContains(
$expectedMessage,
$e->getMessage(),
"Exception does not contain expected message."
);
}
}
/**
* @magentoApiDataFixture Magento/Tax/_files/tax_classes.php
*/
public function testSearchTaxRule()
{
$fixtureRule = $this->getFixtureTaxRules()[0];
$filter = $this->filterBuilder->setField('code')
->setValue($fixtureRule->getCode())
->create();
$this->searchCriteriaBuilder->addFilters([$filter]);
$searchData = $this->searchCriteriaBuilder->create()->__toArray();
$requestData = ['searchCriteria' => $searchData];
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/search' . '?' . http_build_query($requestData),
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'GetList',
],
];
$searchResults = $this->_webApiCall($serviceInfo, $requestData);
$this->assertEquals(1, $searchResults['total_count']);
$this->assertEquals($fixtureRule->getId(), $searchResults['items'][0]["id"]);
$this->assertEquals($fixtureRule->getCode(), $searchResults['items'][0]['code']);
}
/**
* Get tax rates created in Magento\Tax\_files\tax_classes.php
*
* @return \Magento\Tax\Model\Calculation\Rate[]
*/
private function getFixtureTaxRates()
{
if ($this->fixtureTaxRates === null) {
$this->fixtureTaxRates = [];
if ($this->getFixtureTaxRules()) {
$taxRateIds = (array)$this->getFixtureTaxRules()[0]->getRates();
foreach ($taxRateIds as $taxRateId) {
/** @var \Magento\Tax\Model\Calculation\Rate $taxRate */
$taxRate = Bootstrap::getObjectManager()->create('Magento\Tax\Model\Calculation\Rate');
$this->fixtureTaxRates[] = $taxRate->load($taxRateId);
}
}
}
return $this->fixtureTaxRates;
}
/**
* Get tax classes created in Magento\Tax\_files\tax_classes.php
*
* @return \Magento\Tax\Model\ClassModel[]
*/
private function getFixtureTaxClasses()
{
if ($this->fixtureTaxClasses === null) {
$this->fixtureTaxClasses = [];
if ($this->getFixtureTaxRules()) {
$taxClassIds = array_merge(
(array)$this->getFixtureTaxRules()[0]->getCustomerTaxClasses(),
(array)$this->getFixtureTaxRules()[0]->getProductTaxClasses()
);
foreach ($taxClassIds as $taxClassId) {
/** @var \Magento\Tax\Model\ClassModel $taxClass */
$taxClass = Bootstrap::getObjectManager()->create('Magento\Tax\Model\ClassModel');
$this->fixtureTaxClasses[] = $taxClass->load($taxClassId);
}
}
}
return $this->fixtureTaxClasses;
}
/**
* Get tax rule created in Magento\Tax\_files\tax_classes.php
*
* @return \Magento\Tax\Model\Calculation\Rule[]
*/
private function getFixtureTaxRules()
{
if ($this->fixtureTaxRules === null) {
$this->fixtureTaxRules = [];
$taxRuleCodes = ['Test Rule Duplicate', 'Test Rule'];
foreach ($taxRuleCodes as $taxRuleCode) {
/** @var \Magento\Tax\Model\Calculation\Rule $taxRule */
$taxRule = Bootstrap::getObjectManager()->create('Magento\Tax\Model\Calculation\Rule');
$taxRule->load($taxRuleCode, 'code');
if ($taxRule->getId()) {
$this->fixtureTaxRules[] = $taxRule;
}
}
}
return $this->fixtureTaxRules;
}
}
| FPLD/project0 | vendor/magento/magento2-base/dev/tests/api-functional/testsuite/Magento/Tax/Api/TaxRuleRepositoryInterfaceTest.php | PHP | gpl-2.0 | 23,456 |
/* This testcase is part of GDB, the GNU debugger.
Contributed by Intel Corp. <keven.boell@intel.com>
Copyright 2014-2017 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
int
func (int n)
{
int vla[n], i;
for (i = 0; i < n; i++)
vla[i] = i;
return n; /* vla-filled */
}
int
main (void)
{
func (5);
return 0;
}
| totalspectrum/binutils-propeller | gdb/testsuite/gdb.mi/vla.c | C | gpl-2.0 | 982 |
/**
* \file
*
* \brief Instance description for RTC
*
* Copyright (c) 2014 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \asf_license_stop
*
*/
#ifndef _SAMD20_RTC_INSTANCE_
#define _SAMD20_RTC_INSTANCE_
/* ========== Register definition for RTC peripheral ========== */
#if (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
#define REG_RTC_READREQ (0x40001402U) /**< \brief (RTC) Read Request */
#define REG_RTC_STATUS (0x4000140AU) /**< \brief (RTC) Status */
#define REG_RTC_DBGCTRL (0x4000140BU) /**< \brief (RTC) Debug Control */
#define REG_RTC_FREQCORR (0x4000140CU) /**< \brief (RTC) Frequency Correction */
#define REG_RTC_MODE0_CTRL (0x40001400U) /**< \brief (RTC) MODE0 Control */
#define REG_RTC_MODE0_EVCTRL (0x40001404U) /**< \brief (RTC) MODE0 Event Control */
#define REG_RTC_MODE0_INTENCLR (0x40001406U) /**< \brief (RTC) MODE0 Interrupt Enable Clear */
#define REG_RTC_MODE0_INTENSET (0x40001407U) /**< \brief (RTC) MODE0 Interrupt Enable Set */
#define REG_RTC_MODE0_INTFLAG (0x40001408U) /**< \brief (RTC) MODE0 Interrupt Flag Status and Clear */
#define REG_RTC_MODE0_COUNT (0x40001410U) /**< \brief (RTC) MODE0 Counter Value */
#define REG_RTC_MODE0_COMP0 (0x40001418U) /**< \brief (RTC) MODE0 Compare 0 Value */
#define REG_RTC_MODE1_CTRL (0x40001400U) /**< \brief (RTC) MODE1 Control */
#define REG_RTC_MODE1_EVCTRL (0x40001404U) /**< \brief (RTC) MODE1 Event Control */
#define REG_RTC_MODE1_INTENCLR (0x40001406U) /**< \brief (RTC) MODE1 Interrupt Enable Clear */
#define REG_RTC_MODE1_INTENSET (0x40001407U) /**< \brief (RTC) MODE1 Interrupt Enable Set */
#define REG_RTC_MODE1_INTFLAG (0x40001408U) /**< \brief (RTC) MODE1 Interrupt Flag Status and Clear */
#define REG_RTC_MODE1_COUNT (0x40001410U) /**< \brief (RTC) MODE1 Counter Value */
#define REG_RTC_MODE1_PER (0x40001414U) /**< \brief (RTC) MODE1 Counter Period */
#define REG_RTC_MODE1_COMP0 (0x40001418U) /**< \brief (RTC) MODE1 Compare 0 Value */
#define REG_RTC_MODE1_COMP1 (0x4000141AU) /**< \brief (RTC) MODE1 Compare 1 Value */
#define REG_RTC_MODE2_CTRL (0x40001400U) /**< \brief (RTC) MODE2 Control */
#define REG_RTC_MODE2_EVCTRL (0x40001404U) /**< \brief (RTC) MODE2 Event Control */
#define REG_RTC_MODE2_INTENCLR (0x40001406U) /**< \brief (RTC) MODE2 Interrupt Enable Clear */
#define REG_RTC_MODE2_INTENSET (0x40001407U) /**< \brief (RTC) MODE2 Interrupt Enable Set */
#define REG_RTC_MODE2_INTFLAG (0x40001408U) /**< \brief (RTC) MODE2 Interrupt Flag Status and Clear */
#define REG_RTC_MODE2_CLOCK (0x40001410U) /**< \brief (RTC) MODE2 Clock Value */
#define REG_RTC_MODE2_ALARM_ALARM0 (0x40001418U) /**< \brief (RTC) MODE2_ALARM Alarm 0 Value */
#define REG_RTC_MODE2_ALARM_MASK0 (0x4000141CU) /**< \brief (RTC) MODE2_ALARM Alarm 0 Mask */
#else
#define REG_RTC_READREQ (*(RwReg16*)0x40001402U) /**< \brief (RTC) Read Request */
#define REG_RTC_STATUS (*(RwReg8 *)0x4000140AU) /**< \brief (RTC) Status */
#define REG_RTC_DBGCTRL (*(RwReg8 *)0x4000140BU) /**< \brief (RTC) Debug Control */
#define REG_RTC_FREQCORR (*(RwReg8 *)0x4000140CU) /**< \brief (RTC) Frequency Correction */
#define REG_RTC_MODE0_CTRL (*(RwReg16*)0x40001400U) /**< \brief (RTC) MODE0 Control */
#define REG_RTC_MODE0_EVCTRL (*(RwReg16*)0x40001404U) /**< \brief (RTC) MODE0 Event Control */
#define REG_RTC_MODE0_INTENCLR (*(RwReg8 *)0x40001406U) /**< \brief (RTC) MODE0 Interrupt Enable Clear */
#define REG_RTC_MODE0_INTENSET (*(RwReg8 *)0x40001407U) /**< \brief (RTC) MODE0 Interrupt Enable Set */
#define REG_RTC_MODE0_INTFLAG (*(RwReg8 *)0x40001408U) /**< \brief (RTC) MODE0 Interrupt Flag Status and Clear */
#define REG_RTC_MODE0_COUNT (*(RwReg *)0x40001410U) /**< \brief (RTC) MODE0 Counter Value */
#define REG_RTC_MODE0_COMP0 (*(RwReg *)0x40001418U) /**< \brief (RTC) MODE0 Compare 0 Value */
#define REG_RTC_MODE1_CTRL (*(RwReg16*)0x40001400U) /**< \brief (RTC) MODE1 Control */
#define REG_RTC_MODE1_EVCTRL (*(RwReg16*)0x40001404U) /**< \brief (RTC) MODE1 Event Control */
#define REG_RTC_MODE1_INTENCLR (*(RwReg8 *)0x40001406U) /**< \brief (RTC) MODE1 Interrupt Enable Clear */
#define REG_RTC_MODE1_INTENSET (*(RwReg8 *)0x40001407U) /**< \brief (RTC) MODE1 Interrupt Enable Set */
#define REG_RTC_MODE1_INTFLAG (*(RwReg8 *)0x40001408U) /**< \brief (RTC) MODE1 Interrupt Flag Status and Clear */
#define REG_RTC_MODE1_COUNT (*(RwReg16*)0x40001410U) /**< \brief (RTC) MODE1 Counter Value */
#define REG_RTC_MODE1_PER (*(RwReg16*)0x40001414U) /**< \brief (RTC) MODE1 Counter Period */
#define REG_RTC_MODE1_COMP0 (*(RwReg16*)0x40001418U) /**< \brief (RTC) MODE1 Compare 0 Value */
#define REG_RTC_MODE1_COMP1 (*(RwReg16*)0x4000141AU) /**< \brief (RTC) MODE1 Compare 1 Value */
#define REG_RTC_MODE2_CTRL (*(RwReg16*)0x40001400U) /**< \brief (RTC) MODE2 Control */
#define REG_RTC_MODE2_EVCTRL (*(RwReg16*)0x40001404U) /**< \brief (RTC) MODE2 Event Control */
#define REG_RTC_MODE2_INTENCLR (*(RwReg8 *)0x40001406U) /**< \brief (RTC) MODE2 Interrupt Enable Clear */
#define REG_RTC_MODE2_INTENSET (*(RwReg8 *)0x40001407U) /**< \brief (RTC) MODE2 Interrupt Enable Set */
#define REG_RTC_MODE2_INTFLAG (*(RwReg8 *)0x40001408U) /**< \brief (RTC) MODE2 Interrupt Flag Status and Clear */
#define REG_RTC_MODE2_CLOCK (*(RwReg *)0x40001410U) /**< \brief (RTC) MODE2 Clock Value */
#define REG_RTC_MODE2_ALARM_ALARM0 (*(RwReg *)0x40001418U) /**< \brief (RTC) MODE2_ALARM Alarm 0 Value */
#define REG_RTC_MODE2_ALARM_MASK0 (*(RwReg *)0x4000141CU) /**< \brief (RTC) MODE2_ALARM Alarm 0 Mask */
#endif /* (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
/* ========== Instance parameters for RTC peripheral ========== */
#define RTC_ALARM_NUM 1 // Number of Alarms
#define RTC_COMP16_NUM 2 // Number of 16-bit Comparators
#define RTC_COMP32_NUM 1 // Number of 32-bit Comparators
#define RTC_GCLK_ID 2 // Index of Generic Clock
#define RTC_NUM_OF_ALARMS 1 // Number of Alarms (obsolete)
#define RTC_NUM_OF_COMP16 2 // Number of 16-bit Comparators (obsolete)
#define RTC_NUM_OF_COMP32 1 // Number of 32-bit Comparators (obsolete)
#endif /* _SAMD20_RTC_INSTANCE_ */
| TrampolineRTOS/trampoline | machines/simple/armv6m/samd21/CMSIS-Atmel/Device/ATMEL/samd20/include/instance/rtc.h | C | gpl-2.0 | 8,160 |
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef __ASM_POWERPC_CPUTABLE_H
#define __ASM_POWERPC_CPUTABLE_H
#include <linux/types.h>
#include <uapi/asm/cputable.h>
#include <asm/asm-const.h>
#ifndef __ASSEMBLY__
/* This structure can grow, it's real size is used by head.S code
* via the mkdefs mechanism.
*/
struct cpu_spec;
typedef void (*cpu_setup_t)(unsigned long offset, struct cpu_spec* spec);
typedef void (*cpu_restore_t)(void);
enum powerpc_oprofile_type {
PPC_OPROFILE_INVALID = 0,
PPC_OPROFILE_RS64 = 1,
PPC_OPROFILE_POWER4 = 2,
PPC_OPROFILE_G4 = 3,
PPC_OPROFILE_FSL_EMB = 4,
PPC_OPROFILE_CELL = 5,
PPC_OPROFILE_PA6T = 6,
};
enum powerpc_pmc_type {
PPC_PMC_DEFAULT = 0,
PPC_PMC_IBM = 1,
PPC_PMC_PA6T = 2,
PPC_PMC_G4 = 3,
};
struct pt_regs;
extern int machine_check_generic(struct pt_regs *regs);
extern int machine_check_4xx(struct pt_regs *regs);
extern int machine_check_440A(struct pt_regs *regs);
extern int machine_check_e500mc(struct pt_regs *regs);
extern int machine_check_e500(struct pt_regs *regs);
extern int machine_check_e200(struct pt_regs *regs);
extern int machine_check_47x(struct pt_regs *regs);
int machine_check_8xx(struct pt_regs *regs);
int machine_check_83xx(struct pt_regs *regs);
extern void cpu_down_flush_e500v2(void);
extern void cpu_down_flush_e500mc(void);
extern void cpu_down_flush_e5500(void);
extern void cpu_down_flush_e6500(void);
/* NOTE WELL: Update identify_cpu() if fields are added or removed! */
struct cpu_spec {
/* CPU is matched via (PVR & pvr_mask) == pvr_value */
unsigned int pvr_mask;
unsigned int pvr_value;
char *cpu_name;
unsigned long cpu_features; /* Kernel features */
unsigned int cpu_user_features; /* Userland features */
unsigned int cpu_user_features2; /* Userland features v2 */
unsigned int mmu_features; /* MMU features */
/* cache line sizes */
unsigned int icache_bsize;
unsigned int dcache_bsize;
/* flush caches inside the current cpu */
void (*cpu_down_flush)(void);
/* number of performance monitor counters */
unsigned int num_pmcs;
enum powerpc_pmc_type pmc_type;
/* this is called to initialize various CPU bits like L1 cache,
* BHT, SPD, etc... from head.S before branching to identify_machine
*/
cpu_setup_t cpu_setup;
/* Used to restore cpu setup on secondary processors and at resume */
cpu_restore_t cpu_restore;
/* Used by oprofile userspace to select the right counters */
char *oprofile_cpu_type;
/* Processor specific oprofile operations */
enum powerpc_oprofile_type oprofile_type;
/* Bit locations inside the mmcra change */
unsigned long oprofile_mmcra_sihv;
unsigned long oprofile_mmcra_sipr;
/* Bits to clear during an oprofile exception */
unsigned long oprofile_mmcra_clear;
/* Name of processor class, for the ELF AT_PLATFORM entry */
char *platform;
/* Processor specific machine check handling. Return negative
* if the error is fatal, 1 if it was fully recovered and 0 to
* pass up (not CPU originated) */
int (*machine_check)(struct pt_regs *regs);
/*
* Processor specific early machine check handler which is
* called in real mode to handle SLB and TLB errors.
*/
long (*machine_check_early)(struct pt_regs *regs);
};
extern struct cpu_spec *cur_cpu_spec;
extern unsigned int __start___ftr_fixup, __stop___ftr_fixup;
extern void set_cur_cpu_spec(struct cpu_spec *s);
extern struct cpu_spec *identify_cpu(unsigned long offset, unsigned int pvr);
extern void identify_cpu_name(unsigned int pvr);
extern void do_feature_fixups(unsigned long value, void *fixup_start,
void *fixup_end);
extern const char *powerpc_base_platform;
#ifdef CONFIG_JUMP_LABEL_FEATURE_CHECKS
extern void cpu_feature_keys_init(void);
#else
static inline void cpu_feature_keys_init(void) { }
#endif
#endif /* __ASSEMBLY__ */
/* CPU kernel features */
/* Definitions for features that we have on both 32-bit and 64-bit chips */
#define CPU_FTR_COHERENT_ICACHE ASM_CONST(0x00000001)
#define CPU_FTR_ALTIVEC ASM_CONST(0x00000002)
#define CPU_FTR_DBELL ASM_CONST(0x00000004)
#define CPU_FTR_CAN_NAP ASM_CONST(0x00000008)
#define CPU_FTR_DEBUG_LVL_EXC ASM_CONST(0x00000010)
#define CPU_FTR_NODSISRALIGN ASM_CONST(0x00000020)
#define CPU_FTR_FPU_UNAVAILABLE ASM_CONST(0x00000040)
#define CPU_FTR_LWSYNC ASM_CONST(0x00000080)
#define CPU_FTR_NOEXECUTE ASM_CONST(0x00000100)
#define CPU_FTR_EMB_HV ASM_CONST(0x00000200)
/* Definitions for features that only exist on 32-bit chips */
#ifdef CONFIG_PPC32
#define CPU_FTR_601 ASM_CONST(0x00001000)
#define CPU_FTR_L2CR ASM_CONST(0x00002000)
#define CPU_FTR_SPEC7450 ASM_CONST(0x00004000)
#define CPU_FTR_TAU ASM_CONST(0x00008000)
#define CPU_FTR_CAN_DOZE ASM_CONST(0x00010000)
#define CPU_FTR_USE_RTC ASM_CONST(0x00020000)
#define CPU_FTR_L3CR ASM_CONST(0x00040000)
#define CPU_FTR_L3_DISABLE_NAP ASM_CONST(0x00080000)
#define CPU_FTR_NAP_DISABLE_L2_PR ASM_CONST(0x00100000)
#define CPU_FTR_DUAL_PLL_750FX ASM_CONST(0x00200000)
#define CPU_FTR_NO_DPM ASM_CONST(0x00400000)
#define CPU_FTR_476_DD2 ASM_CONST(0x00800000)
#define CPU_FTR_NEED_COHERENT ASM_CONST(0x01000000)
#define CPU_FTR_NO_BTIC ASM_CONST(0x02000000)
#define CPU_FTR_PPC_LE ASM_CONST(0x04000000)
#define CPU_FTR_UNIFIED_ID_CACHE ASM_CONST(0x08000000)
#define CPU_FTR_SPE ASM_CONST(0x10000000)
#define CPU_FTR_NEED_PAIRED_STWCX ASM_CONST(0x20000000)
#define CPU_FTR_INDEXED_DCR ASM_CONST(0x40000000)
#else /* CONFIG_PPC32 */
/* Define these to 0 for the sake of tests in common code */
#define CPU_FTR_601 (0)
#define CPU_FTR_PPC_LE (0)
#endif
/*
* Definitions for the 64-bit processor unique features;
* on 32-bit, make the names available but defined to be 0.
*/
#ifdef __powerpc64__
#define LONG_ASM_CONST(x) ASM_CONST(x)
#else
#define LONG_ASM_CONST(x) 0
#endif
#define CPU_FTR_REAL_LE LONG_ASM_CONST(0x0000000000001000)
#define CPU_FTR_HVMODE LONG_ASM_CONST(0x0000000000002000)
#define CPU_FTR_ARCH_206 LONG_ASM_CONST(0x0000000000008000)
#define CPU_FTR_ARCH_207S LONG_ASM_CONST(0x0000000000010000)
#define CPU_FTR_ARCH_300 LONG_ASM_CONST(0x0000000000020000)
#define CPU_FTR_MMCRA LONG_ASM_CONST(0x0000000000040000)
#define CPU_FTR_CTRL LONG_ASM_CONST(0x0000000000080000)
#define CPU_FTR_SMT LONG_ASM_CONST(0x0000000000100000)
#define CPU_FTR_PAUSE_ZERO LONG_ASM_CONST(0x0000000000200000)
#define CPU_FTR_PURR LONG_ASM_CONST(0x0000000000400000)
#define CPU_FTR_CELL_TB_BUG LONG_ASM_CONST(0x0000000000800000)
#define CPU_FTR_SPURR LONG_ASM_CONST(0x0000000001000000)
#define CPU_FTR_DSCR LONG_ASM_CONST(0x0000000002000000)
#define CPU_FTR_VSX LONG_ASM_CONST(0x0000000004000000)
#define CPU_FTR_SAO LONG_ASM_CONST(0x0000000008000000)
#define CPU_FTR_CP_USE_DCBTZ LONG_ASM_CONST(0x0000000010000000)
#define CPU_FTR_UNALIGNED_LD_STD LONG_ASM_CONST(0x0000000020000000)
#define CPU_FTR_ASYM_SMT LONG_ASM_CONST(0x0000000040000000)
#define CPU_FTR_STCX_CHECKS_ADDRESS LONG_ASM_CONST(0x0000000080000000)
#define CPU_FTR_POPCNTB LONG_ASM_CONST(0x0000000100000000)
#define CPU_FTR_POPCNTD LONG_ASM_CONST(0x0000000200000000)
#define CPU_FTR_PKEY LONG_ASM_CONST(0x0000000400000000)
#define CPU_FTR_VMX_COPY LONG_ASM_CONST(0x0000000800000000)
#define CPU_FTR_TM LONG_ASM_CONST(0x0000001000000000)
#define CPU_FTR_CFAR LONG_ASM_CONST(0x0000002000000000)
#define CPU_FTR_HAS_PPR LONG_ASM_CONST(0x0000004000000000)
#define CPU_FTR_DAWR LONG_ASM_CONST(0x0000008000000000)
#define CPU_FTR_DABRX LONG_ASM_CONST(0x0000010000000000)
#define CPU_FTR_PMAO_BUG LONG_ASM_CONST(0x0000020000000000)
#define CPU_FTR_POWER9_DD2_1 LONG_ASM_CONST(0x0000080000000000)
#define CPU_FTR_P9_TM_HV_ASSIST LONG_ASM_CONST(0x0000100000000000)
#define CPU_FTR_P9_TM_XER_SO_BUG LONG_ASM_CONST(0x0000200000000000)
#define CPU_FTR_P9_TLBIE_STQ_BUG LONG_ASM_CONST(0x0000400000000000)
#define CPU_FTR_P9_TIDR LONG_ASM_CONST(0x0000800000000000)
#define CPU_FTR_P9_TLBIE_ERAT_BUG LONG_ASM_CONST(0x0001000000000000)
#ifndef __ASSEMBLY__
#define CPU_FTR_PPCAS_ARCH_V2 (CPU_FTR_NOEXECUTE | CPU_FTR_NODSISRALIGN)
#define MMU_FTR_PPCAS_ARCH_V2 (MMU_FTR_TLBIEL | MMU_FTR_16M_PAGE)
/* We only set the altivec features if the kernel was compiled with altivec
* support
*/
#ifdef CONFIG_ALTIVEC
#define CPU_FTR_ALTIVEC_COMP CPU_FTR_ALTIVEC
#define PPC_FEATURE_HAS_ALTIVEC_COMP PPC_FEATURE_HAS_ALTIVEC
#else
#define CPU_FTR_ALTIVEC_COMP 0
#define PPC_FEATURE_HAS_ALTIVEC_COMP 0
#endif
/* We only set the VSX features if the kernel was compiled with VSX
* support
*/
#ifdef CONFIG_VSX
#define CPU_FTR_VSX_COMP CPU_FTR_VSX
#define PPC_FEATURE_HAS_VSX_COMP PPC_FEATURE_HAS_VSX
#else
#define CPU_FTR_VSX_COMP 0
#define PPC_FEATURE_HAS_VSX_COMP 0
#endif
/* We only set the spe features if the kernel was compiled with spe
* support
*/
#ifdef CONFIG_SPE
#define CPU_FTR_SPE_COMP CPU_FTR_SPE
#define PPC_FEATURE_HAS_SPE_COMP PPC_FEATURE_HAS_SPE
#define PPC_FEATURE_HAS_EFP_SINGLE_COMP PPC_FEATURE_HAS_EFP_SINGLE
#define PPC_FEATURE_HAS_EFP_DOUBLE_COMP PPC_FEATURE_HAS_EFP_DOUBLE
#else
#define CPU_FTR_SPE_COMP 0
#define PPC_FEATURE_HAS_SPE_COMP 0
#define PPC_FEATURE_HAS_EFP_SINGLE_COMP 0
#define PPC_FEATURE_HAS_EFP_DOUBLE_COMP 0
#endif
/* We only set the TM feature if the kernel was compiled with TM supprt */
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
#define CPU_FTR_TM_COMP CPU_FTR_TM
#define PPC_FEATURE2_HTM_COMP PPC_FEATURE2_HTM
#define PPC_FEATURE2_HTM_NOSC_COMP PPC_FEATURE2_HTM_NOSC
#else
#define CPU_FTR_TM_COMP 0
#define PPC_FEATURE2_HTM_COMP 0
#define PPC_FEATURE2_HTM_NOSC_COMP 0
#endif
/* We need to mark all pages as being coherent if we're SMP or we have a
* 74[45]x and an MPC107 host bridge. Also 83xx and PowerQUICC II
* require it for PCI "streaming/prefetch" to work properly.
* This is also required by 52xx family.
*/
#if defined(CONFIG_SMP) || defined(CONFIG_MPC10X_BRIDGE) \
|| defined(CONFIG_PPC_83xx) || defined(CONFIG_8260) \
|| defined(CONFIG_PPC_MPC52xx)
#define CPU_FTR_COMMON CPU_FTR_NEED_COHERENT
#else
#define CPU_FTR_COMMON 0
#endif
/* The powersave features NAP & DOZE seems to confuse BDI when
debugging. So if a BDI is used, disable theses
*/
#ifndef CONFIG_BDI_SWITCH
#define CPU_FTR_MAYBE_CAN_DOZE CPU_FTR_CAN_DOZE
#define CPU_FTR_MAYBE_CAN_NAP CPU_FTR_CAN_NAP
#else
#define CPU_FTR_MAYBE_CAN_DOZE 0
#define CPU_FTR_MAYBE_CAN_NAP 0
#endif
#define CPU_FTRS_PPC601 (CPU_FTR_COMMON | CPU_FTR_601 | \
CPU_FTR_COHERENT_ICACHE | CPU_FTR_UNIFIED_ID_CACHE | CPU_FTR_USE_RTC)
#define CPU_FTRS_603 (CPU_FTR_COMMON | CPU_FTR_MAYBE_CAN_DOZE | \
CPU_FTR_MAYBE_CAN_NAP | CPU_FTR_PPC_LE)
#define CPU_FTRS_604 (CPU_FTR_COMMON | CPU_FTR_PPC_LE)
#define CPU_FTRS_740_NOTAU (CPU_FTR_COMMON | \
CPU_FTR_MAYBE_CAN_DOZE | CPU_FTR_L2CR | \
CPU_FTR_MAYBE_CAN_NAP | CPU_FTR_PPC_LE)
#define CPU_FTRS_740 (CPU_FTR_COMMON | \
CPU_FTR_MAYBE_CAN_DOZE | CPU_FTR_L2CR | \
CPU_FTR_TAU | CPU_FTR_MAYBE_CAN_NAP | \
CPU_FTR_PPC_LE)
#define CPU_FTRS_750 (CPU_FTR_COMMON | \
CPU_FTR_MAYBE_CAN_DOZE | CPU_FTR_L2CR | \
CPU_FTR_TAU | CPU_FTR_MAYBE_CAN_NAP | \
CPU_FTR_PPC_LE)
#define CPU_FTRS_750CL (CPU_FTRS_750)
#define CPU_FTRS_750FX1 (CPU_FTRS_750 | CPU_FTR_DUAL_PLL_750FX | CPU_FTR_NO_DPM)
#define CPU_FTRS_750FX2 (CPU_FTRS_750 | CPU_FTR_NO_DPM)
#define CPU_FTRS_750FX (CPU_FTRS_750 | CPU_FTR_DUAL_PLL_750FX)
#define CPU_FTRS_750GX (CPU_FTRS_750FX)
#define CPU_FTRS_7400_NOTAU (CPU_FTR_COMMON | \
CPU_FTR_MAYBE_CAN_DOZE | CPU_FTR_L2CR | \
CPU_FTR_ALTIVEC_COMP | \
CPU_FTR_MAYBE_CAN_NAP | CPU_FTR_PPC_LE)
#define CPU_FTRS_7400 (CPU_FTR_COMMON | \
CPU_FTR_MAYBE_CAN_DOZE | CPU_FTR_L2CR | \
CPU_FTR_TAU | CPU_FTR_ALTIVEC_COMP | \
CPU_FTR_MAYBE_CAN_NAP | CPU_FTR_PPC_LE)
#define CPU_FTRS_7450_20 (CPU_FTR_COMMON | \
CPU_FTR_L2CR | CPU_FTR_ALTIVEC_COMP | \
CPU_FTR_L3CR | CPU_FTR_SPEC7450 | \
CPU_FTR_NEED_COHERENT | CPU_FTR_PPC_LE | CPU_FTR_NEED_PAIRED_STWCX)
#define CPU_FTRS_7450_21 (CPU_FTR_COMMON | \
CPU_FTR_MAYBE_CAN_NAP | CPU_FTR_L2CR | CPU_FTR_ALTIVEC_COMP | \
CPU_FTR_L3CR | CPU_FTR_SPEC7450 | \
CPU_FTR_NAP_DISABLE_L2_PR | CPU_FTR_L3_DISABLE_NAP | \
CPU_FTR_NEED_COHERENT | CPU_FTR_PPC_LE | CPU_FTR_NEED_PAIRED_STWCX)
#define CPU_FTRS_7450_23 (CPU_FTR_COMMON | \
CPU_FTR_NEED_PAIRED_STWCX | \
CPU_FTR_MAYBE_CAN_NAP | CPU_FTR_L2CR | CPU_FTR_ALTIVEC_COMP | \
CPU_FTR_L3CR | CPU_FTR_SPEC7450 | \
CPU_FTR_NAP_DISABLE_L2_PR | CPU_FTR_NEED_COHERENT | CPU_FTR_PPC_LE)
#define CPU_FTRS_7455_1 (CPU_FTR_COMMON | \
CPU_FTR_NEED_PAIRED_STWCX | \
CPU_FTR_L2CR | CPU_FTR_ALTIVEC_COMP | CPU_FTR_L3CR | \
CPU_FTR_SPEC7450 | CPU_FTR_NEED_COHERENT | CPU_FTR_PPC_LE)
#define CPU_FTRS_7455_20 (CPU_FTR_COMMON | \
CPU_FTR_NEED_PAIRED_STWCX | \
CPU_FTR_MAYBE_CAN_NAP | CPU_FTR_L2CR | CPU_FTR_ALTIVEC_COMP | \
CPU_FTR_L3CR | CPU_FTR_SPEC7450 | \
CPU_FTR_NAP_DISABLE_L2_PR | CPU_FTR_L3_DISABLE_NAP | \
CPU_FTR_NEED_COHERENT | CPU_FTR_PPC_LE)
#define CPU_FTRS_7455 (CPU_FTR_COMMON | \
CPU_FTR_MAYBE_CAN_NAP | CPU_FTR_L2CR | CPU_FTR_ALTIVEC_COMP | \
CPU_FTR_L3CR | CPU_FTR_SPEC7450 | CPU_FTR_NAP_DISABLE_L2_PR | \
CPU_FTR_NEED_COHERENT | CPU_FTR_PPC_LE | CPU_FTR_NEED_PAIRED_STWCX)
#define CPU_FTRS_7447_10 (CPU_FTR_COMMON | \
CPU_FTR_MAYBE_CAN_NAP | CPU_FTR_L2CR | CPU_FTR_ALTIVEC_COMP | \
CPU_FTR_L3CR | CPU_FTR_SPEC7450 | CPU_FTR_NAP_DISABLE_L2_PR | \
CPU_FTR_NEED_COHERENT | CPU_FTR_NO_BTIC | CPU_FTR_PPC_LE | \
CPU_FTR_NEED_PAIRED_STWCX)
#define CPU_FTRS_7447 (CPU_FTR_COMMON | \
CPU_FTR_MAYBE_CAN_NAP | CPU_FTR_L2CR | CPU_FTR_ALTIVEC_COMP | \
CPU_FTR_L3CR | CPU_FTR_SPEC7450 | CPU_FTR_NAP_DISABLE_L2_PR | \
CPU_FTR_NEED_COHERENT | CPU_FTR_PPC_LE | CPU_FTR_NEED_PAIRED_STWCX)
#define CPU_FTRS_7447A (CPU_FTR_COMMON | \
CPU_FTR_MAYBE_CAN_NAP | CPU_FTR_L2CR | CPU_FTR_ALTIVEC_COMP | \
CPU_FTR_SPEC7450 | CPU_FTR_NAP_DISABLE_L2_PR | \
CPU_FTR_NEED_COHERENT | CPU_FTR_PPC_LE | CPU_FTR_NEED_PAIRED_STWCX)
#define CPU_FTRS_7448 (CPU_FTR_COMMON | \
CPU_FTR_MAYBE_CAN_NAP | CPU_FTR_L2CR | CPU_FTR_ALTIVEC_COMP | \
CPU_FTR_SPEC7450 | CPU_FTR_NAP_DISABLE_L2_PR | \
CPU_FTR_PPC_LE | CPU_FTR_NEED_PAIRED_STWCX)
#define CPU_FTRS_82XX (CPU_FTR_COMMON | CPU_FTR_MAYBE_CAN_DOZE)
#define CPU_FTRS_G2_LE (CPU_FTR_COMMON | CPU_FTR_MAYBE_CAN_DOZE | \
CPU_FTR_MAYBE_CAN_NAP)
#define CPU_FTRS_E300 (CPU_FTR_MAYBE_CAN_DOZE | \
CPU_FTR_MAYBE_CAN_NAP | \
CPU_FTR_COMMON)
#define CPU_FTRS_E300C2 (CPU_FTR_MAYBE_CAN_DOZE | \
CPU_FTR_MAYBE_CAN_NAP | \
CPU_FTR_COMMON | CPU_FTR_FPU_UNAVAILABLE)
#define CPU_FTRS_CLASSIC32 (CPU_FTR_COMMON)
#define CPU_FTRS_8XX (CPU_FTR_NOEXECUTE)
#define CPU_FTRS_40X (CPU_FTR_NODSISRALIGN | CPU_FTR_NOEXECUTE)
#define CPU_FTRS_44X (CPU_FTR_NODSISRALIGN | CPU_FTR_NOEXECUTE)
#define CPU_FTRS_440x6 (CPU_FTR_NODSISRALIGN | CPU_FTR_NOEXECUTE | \
CPU_FTR_INDEXED_DCR)
#define CPU_FTRS_47X (CPU_FTRS_440x6)
#define CPU_FTRS_E200 (CPU_FTR_SPE_COMP | \
CPU_FTR_NODSISRALIGN | CPU_FTR_COHERENT_ICACHE | \
CPU_FTR_UNIFIED_ID_CACHE | CPU_FTR_NOEXECUTE | \
CPU_FTR_DEBUG_LVL_EXC)
#define CPU_FTRS_E500 (CPU_FTR_MAYBE_CAN_DOZE | \
CPU_FTR_SPE_COMP | CPU_FTR_MAYBE_CAN_NAP | CPU_FTR_NODSISRALIGN | \
CPU_FTR_NOEXECUTE)
#define CPU_FTRS_E500_2 (CPU_FTR_MAYBE_CAN_DOZE | \
CPU_FTR_SPE_COMP | CPU_FTR_MAYBE_CAN_NAP | \
CPU_FTR_NODSISRALIGN | CPU_FTR_NOEXECUTE)
#define CPU_FTRS_E500MC (CPU_FTR_NODSISRALIGN | \
CPU_FTR_LWSYNC | CPU_FTR_NOEXECUTE | \
CPU_FTR_DBELL | CPU_FTR_DEBUG_LVL_EXC | CPU_FTR_EMB_HV)
/*
* e5500/e6500 erratum A-006958 is a timebase bug that can use the
* same workaround as CPU_FTR_CELL_TB_BUG.
*/
#define CPU_FTRS_E5500 (CPU_FTR_NODSISRALIGN | \
CPU_FTR_LWSYNC | CPU_FTR_NOEXECUTE | \
CPU_FTR_DBELL | CPU_FTR_POPCNTB | CPU_FTR_POPCNTD | \
CPU_FTR_DEBUG_LVL_EXC | CPU_FTR_EMB_HV | CPU_FTR_CELL_TB_BUG)
#define CPU_FTRS_E6500 (CPU_FTR_NODSISRALIGN | \
CPU_FTR_LWSYNC | CPU_FTR_NOEXECUTE | \
CPU_FTR_DBELL | CPU_FTR_POPCNTB | CPU_FTR_POPCNTD | \
CPU_FTR_DEBUG_LVL_EXC | CPU_FTR_EMB_HV | CPU_FTR_ALTIVEC_COMP | \
CPU_FTR_CELL_TB_BUG | CPU_FTR_SMT)
#define CPU_FTRS_GENERIC_32 (CPU_FTR_COMMON | CPU_FTR_NODSISRALIGN)
/* 64-bit CPUs */
#define CPU_FTRS_PPC970 (CPU_FTR_LWSYNC | \
CPU_FTR_PPCAS_ARCH_V2 | CPU_FTR_CTRL | \
CPU_FTR_ALTIVEC_COMP | CPU_FTR_CAN_NAP | CPU_FTR_MMCRA | \
CPU_FTR_CP_USE_DCBTZ | CPU_FTR_STCX_CHECKS_ADDRESS | \
CPU_FTR_HVMODE | CPU_FTR_DABRX)
#define CPU_FTRS_POWER5 (CPU_FTR_LWSYNC | \
CPU_FTR_PPCAS_ARCH_V2 | CPU_FTR_CTRL | \
CPU_FTR_MMCRA | CPU_FTR_SMT | \
CPU_FTR_COHERENT_ICACHE | CPU_FTR_PURR | \
CPU_FTR_STCX_CHECKS_ADDRESS | CPU_FTR_POPCNTB | CPU_FTR_DABRX)
#define CPU_FTRS_POWER6 (CPU_FTR_LWSYNC | \
CPU_FTR_PPCAS_ARCH_V2 | CPU_FTR_CTRL | \
CPU_FTR_MMCRA | CPU_FTR_SMT | \
CPU_FTR_COHERENT_ICACHE | \
CPU_FTR_PURR | CPU_FTR_SPURR | CPU_FTR_REAL_LE | \
CPU_FTR_DSCR | CPU_FTR_UNALIGNED_LD_STD | \
CPU_FTR_STCX_CHECKS_ADDRESS | CPU_FTR_POPCNTB | CPU_FTR_CFAR | \
CPU_FTR_DABRX)
#define CPU_FTRS_POWER7 (CPU_FTR_LWSYNC | \
CPU_FTR_PPCAS_ARCH_V2 | CPU_FTR_CTRL | CPU_FTR_ARCH_206 |\
CPU_FTR_MMCRA | CPU_FTR_SMT | \
CPU_FTR_COHERENT_ICACHE | \
CPU_FTR_PURR | CPU_FTR_SPURR | CPU_FTR_REAL_LE | \
CPU_FTR_DSCR | CPU_FTR_SAO | CPU_FTR_ASYM_SMT | \
CPU_FTR_STCX_CHECKS_ADDRESS | CPU_FTR_POPCNTB | CPU_FTR_POPCNTD | \
CPU_FTR_CFAR | CPU_FTR_HVMODE | \
CPU_FTR_VMX_COPY | CPU_FTR_HAS_PPR | CPU_FTR_DABRX | CPU_FTR_PKEY)
#define CPU_FTRS_POWER8 (CPU_FTR_LWSYNC | \
CPU_FTR_PPCAS_ARCH_V2 | CPU_FTR_CTRL | CPU_FTR_ARCH_206 |\
CPU_FTR_MMCRA | CPU_FTR_SMT | \
CPU_FTR_COHERENT_ICACHE | \
CPU_FTR_PURR | CPU_FTR_SPURR | CPU_FTR_REAL_LE | \
CPU_FTR_DSCR | CPU_FTR_SAO | \
CPU_FTR_STCX_CHECKS_ADDRESS | CPU_FTR_POPCNTB | CPU_FTR_POPCNTD | \
CPU_FTR_CFAR | CPU_FTR_HVMODE | CPU_FTR_VMX_COPY | \
CPU_FTR_DBELL | CPU_FTR_HAS_PPR | CPU_FTR_DAWR | \
CPU_FTR_ARCH_207S | CPU_FTR_TM_COMP | CPU_FTR_PKEY)
#define CPU_FTRS_POWER8E (CPU_FTRS_POWER8 | CPU_FTR_PMAO_BUG)
#define CPU_FTRS_POWER9 (CPU_FTR_LWSYNC | \
CPU_FTR_PPCAS_ARCH_V2 | CPU_FTR_CTRL | CPU_FTR_ARCH_206 |\
CPU_FTR_MMCRA | CPU_FTR_SMT | \
CPU_FTR_COHERENT_ICACHE | \
CPU_FTR_PURR | CPU_FTR_SPURR | CPU_FTR_REAL_LE | \
CPU_FTR_DSCR | CPU_FTR_SAO | \
CPU_FTR_STCX_CHECKS_ADDRESS | CPU_FTR_POPCNTB | CPU_FTR_POPCNTD | \
CPU_FTR_CFAR | CPU_FTR_HVMODE | CPU_FTR_VMX_COPY | \
CPU_FTR_DBELL | CPU_FTR_HAS_PPR | CPU_FTR_ARCH_207S | \
CPU_FTR_TM_COMP | CPU_FTR_ARCH_300 | CPU_FTR_PKEY | \
CPU_FTR_P9_TLBIE_STQ_BUG | CPU_FTR_P9_TLBIE_ERAT_BUG | CPU_FTR_P9_TIDR)
#define CPU_FTRS_POWER9_DD2_0 CPU_FTRS_POWER9
#define CPU_FTRS_POWER9_DD2_1 (CPU_FTRS_POWER9 | CPU_FTR_POWER9_DD2_1)
#define CPU_FTRS_POWER9_DD2_2 (CPU_FTRS_POWER9 | CPU_FTR_POWER9_DD2_1 | \
CPU_FTR_P9_TM_HV_ASSIST | \
CPU_FTR_P9_TM_XER_SO_BUG)
#define CPU_FTRS_CELL (CPU_FTR_LWSYNC | \
CPU_FTR_PPCAS_ARCH_V2 | CPU_FTR_CTRL | \
CPU_FTR_ALTIVEC_COMP | CPU_FTR_MMCRA | CPU_FTR_SMT | \
CPU_FTR_PAUSE_ZERO | CPU_FTR_CELL_TB_BUG | CPU_FTR_CP_USE_DCBTZ | \
CPU_FTR_UNALIGNED_LD_STD | CPU_FTR_DABRX)
#define CPU_FTRS_PA6T (CPU_FTR_LWSYNC | \
CPU_FTR_PPCAS_ARCH_V2 | CPU_FTR_ALTIVEC_COMP | \
CPU_FTR_PURR | CPU_FTR_REAL_LE | CPU_FTR_DABRX)
#define CPU_FTRS_COMPATIBLE (CPU_FTR_PPCAS_ARCH_V2)
#ifdef __powerpc64__
#ifdef CONFIG_PPC_BOOK3E
#define CPU_FTRS_POSSIBLE (CPU_FTRS_E6500 | CPU_FTRS_E5500)
#else
#ifdef CONFIG_CPU_LITTLE_ENDIAN
#define CPU_FTRS_POSSIBLE \
(CPU_FTRS_POWER7 | CPU_FTRS_POWER8E | CPU_FTRS_POWER8 | \
CPU_FTR_ALTIVEC_COMP | CPU_FTR_VSX_COMP | CPU_FTRS_POWER9 | \
CPU_FTRS_POWER9_DD2_1 | CPU_FTRS_POWER9_DD2_2)
#else
#define CPU_FTRS_POSSIBLE \
(CPU_FTRS_PPC970 | CPU_FTRS_POWER5 | \
CPU_FTRS_POWER6 | CPU_FTRS_POWER7 | CPU_FTRS_POWER8E | \
CPU_FTRS_POWER8 | CPU_FTRS_CELL | CPU_FTRS_PA6T | \
CPU_FTR_VSX_COMP | CPU_FTR_ALTIVEC_COMP | CPU_FTRS_POWER9 | \
CPU_FTRS_POWER9_DD2_1 | CPU_FTRS_POWER9_DD2_2)
#endif /* CONFIG_CPU_LITTLE_ENDIAN */
#endif
#else
enum {
CPU_FTRS_POSSIBLE =
#ifdef CONFIG_PPC_BOOK3S_32
CPU_FTRS_PPC601 | CPU_FTRS_603 | CPU_FTRS_604 | CPU_FTRS_740_NOTAU |
CPU_FTRS_740 | CPU_FTRS_750 | CPU_FTRS_750FX1 |
CPU_FTRS_750FX2 | CPU_FTRS_750FX | CPU_FTRS_750GX |
CPU_FTRS_7400_NOTAU | CPU_FTRS_7400 | CPU_FTRS_7450_20 |
CPU_FTRS_7450_21 | CPU_FTRS_7450_23 | CPU_FTRS_7455_1 |
CPU_FTRS_7455_20 | CPU_FTRS_7455 | CPU_FTRS_7447_10 |
CPU_FTRS_7447 | CPU_FTRS_7447A | CPU_FTRS_82XX |
CPU_FTRS_G2_LE | CPU_FTRS_E300 | CPU_FTRS_E300C2 |
CPU_FTRS_CLASSIC32 |
#else
CPU_FTRS_GENERIC_32 |
#endif
#ifdef CONFIG_PPC_8xx
CPU_FTRS_8XX |
#endif
#ifdef CONFIG_40x
CPU_FTRS_40X |
#endif
#ifdef CONFIG_44x
CPU_FTRS_44X | CPU_FTRS_440x6 |
#endif
#ifdef CONFIG_PPC_47x
CPU_FTRS_47X | CPU_FTR_476_DD2 |
#endif
#ifdef CONFIG_E200
CPU_FTRS_E200 |
#endif
#ifdef CONFIG_E500
CPU_FTRS_E500 | CPU_FTRS_E500_2 |
#endif
#ifdef CONFIG_PPC_E500MC
CPU_FTRS_E500MC | CPU_FTRS_E5500 | CPU_FTRS_E6500 |
#endif
0,
};
#endif /* __powerpc64__ */
#ifdef __powerpc64__
#ifdef CONFIG_PPC_BOOK3E
#define CPU_FTRS_ALWAYS (CPU_FTRS_E6500 & CPU_FTRS_E5500)
#else
#ifdef CONFIG_PPC_DT_CPU_FTRS
#define CPU_FTRS_DT_CPU_BASE \
(CPU_FTR_LWSYNC | \
CPU_FTR_FPU_UNAVAILABLE | \
CPU_FTR_NODSISRALIGN | \
CPU_FTR_NOEXECUTE | \
CPU_FTR_COHERENT_ICACHE | \
CPU_FTR_STCX_CHECKS_ADDRESS | \
CPU_FTR_POPCNTB | CPU_FTR_POPCNTD | \
CPU_FTR_DAWR | \
CPU_FTR_ARCH_206 | \
CPU_FTR_ARCH_207S)
#else
#define CPU_FTRS_DT_CPU_BASE (~0ul)
#endif
#ifdef CONFIG_CPU_LITTLE_ENDIAN
#define CPU_FTRS_ALWAYS \
(CPU_FTRS_POSSIBLE & ~CPU_FTR_HVMODE & CPU_FTRS_POWER7 & \
CPU_FTRS_POWER8E & CPU_FTRS_POWER8 & CPU_FTRS_POWER9 & \
CPU_FTRS_POWER9_DD2_1 & CPU_FTRS_DT_CPU_BASE)
#else
#define CPU_FTRS_ALWAYS \
(CPU_FTRS_PPC970 & CPU_FTRS_POWER5 & \
CPU_FTRS_POWER6 & CPU_FTRS_POWER7 & CPU_FTRS_CELL & \
CPU_FTRS_PA6T & CPU_FTRS_POWER8 & CPU_FTRS_POWER8E & \
~CPU_FTR_HVMODE & CPU_FTRS_POSSIBLE & CPU_FTRS_POWER9 & \
CPU_FTRS_POWER9_DD2_1 & CPU_FTRS_DT_CPU_BASE)
#endif /* CONFIG_CPU_LITTLE_ENDIAN */
#endif
#else
enum {
CPU_FTRS_ALWAYS =
#ifdef CONFIG_PPC_BOOK3S_32
CPU_FTRS_PPC601 & CPU_FTRS_603 & CPU_FTRS_604 & CPU_FTRS_740_NOTAU &
CPU_FTRS_740 & CPU_FTRS_750 & CPU_FTRS_750FX1 &
CPU_FTRS_750FX2 & CPU_FTRS_750FX & CPU_FTRS_750GX &
CPU_FTRS_7400_NOTAU & CPU_FTRS_7400 & CPU_FTRS_7450_20 &
CPU_FTRS_7450_21 & CPU_FTRS_7450_23 & CPU_FTRS_7455_1 &
CPU_FTRS_7455_20 & CPU_FTRS_7455 & CPU_FTRS_7447_10 &
CPU_FTRS_7447 & CPU_FTRS_7447A & CPU_FTRS_82XX &
CPU_FTRS_G2_LE & CPU_FTRS_E300 & CPU_FTRS_E300C2 &
CPU_FTRS_CLASSIC32 &
#else
CPU_FTRS_GENERIC_32 &
#endif
#ifdef CONFIG_PPC_8xx
CPU_FTRS_8XX &
#endif
#ifdef CONFIG_40x
CPU_FTRS_40X &
#endif
#ifdef CONFIG_44x
CPU_FTRS_44X & CPU_FTRS_440x6 &
#endif
#ifdef CONFIG_E200
CPU_FTRS_E200 &
#endif
#ifdef CONFIG_E500
CPU_FTRS_E500 & CPU_FTRS_E500_2 &
#endif
#ifdef CONFIG_PPC_E500MC
CPU_FTRS_E500MC & CPU_FTRS_E5500 & CPU_FTRS_E6500 &
#endif
~CPU_FTR_EMB_HV & /* can be removed at runtime */
CPU_FTRS_POSSIBLE,
};
#endif /* __powerpc64__ */
#define HBP_NUM 1
#endif /* !__ASSEMBLY__ */
#endif /* __ASM_POWERPC_CPUTABLE_H */
| Fe-Pi/linux | arch/powerpc/include/asm/cputable.h | C | gpl-2.0 | 23,577 |
#ifndef BASE_BATTERY_H
#define BASE_BATTERY_H
#include <omnetpp.h>
#include "MiXiMDefs.h"
#include "BaseModule.h"
#include "HostState.h"
/**
* @brief Defines the amount of power drawn by a device from
* a power source.
*
* Used as generic amount parameter for BaseBatteries "draw"-method.
*
* Can be either an instantaneous draw of a certain energy amount
* in mWs (type=ENERGY) or a draw of a certain current in mA over
* time (type=CURRENT).
*
* Can be sub-classed for more complex power draws.
*
* @ingroup baseModules
* @ingroup power
*/
class MIXIM_API DrawAmount {
public:
/** @brief The type of the amount to draw.*/
enum PowerType {
CURRENT, /** @brief Current in mA over time. */
ENERGY /** @brief Single fixed energy draw in mWs */
};
protected:
/** @brief Stores the type of the amount.*/
int type;
/** @brief Stores the actual amount.*/
double value;
public:
/** @brief Initializes with passed type and value.*/
DrawAmount(int type = CURRENT, double value = 0):
type(type),
value(value)
{}
virtual ~DrawAmount()
{}
/** @brief Returns the type of power drawn as PowerType. */
virtual int getType() const { return type; }
/** @brief Returns the actual amount of power drawn. */
virtual double getValue() const { return value; }
/** @brief Sets the type of power drawn. */
virtual void setType(int t) { type = t; }
/** @brief Sets the actual amount of power drawn. */
virtual void setValue(double v) { value = v; }
};
/**
* @brief Base class for any power source.
*
* See "SimpleBattery" for an example implementation.
*
* @ingroup baseModules
* @ingroup power
* @see SimpleBattery
*/
class MIXIM_API BaseBattery : public BaseModule {
private:
/** @brief Copy constructor is not allowed.
*/
BaseBattery(const BaseBattery&);
/** @brief Assignment operator is not allowed.
*/
BaseBattery& operator=(const BaseBattery&);
public:
BaseBattery() : BaseModule()
{}
BaseBattery(unsigned stacksize) : BaseModule(stacksize)
{}
/**
* @brief Registers a power draining device with this battery.
*
* Takes the name of the device as well as a number of accounts
* the devices draws power for (like rx, tx, idle for a radio device).
*
* Returns an ID by which the device can identify itself to the
* battery.
*
* Has to be implemented by actual battery implementations.
*/
virtual int registerDevice(const std::string& name, int numAccounts) = 0;
/**
* @brief Draws power from the battery.
*
* The actual amount and type of power drawn is defined by the passed
* DrawAmount parameter. Can be an fixed single amount or an amount
* drawn over time.
* The drainID identifies the device which drains the power.
* "Account" identifies the account the power is drawn from. It is
* used for statistical evaluation only to see which activity of a
* device has used how much power. It does not affect functionality.
*/
virtual void draw(int drainID, DrawAmount& amount, int account) = 0;
/**
* @name State-of-charge interface
*
* @brief Other host modules should use these interfaces to obtain
* the state-of-charge of the battery. Do NOT use BatteryState
* interfaces, which should be used only by Battery Stats modules.
*/
/*@{*/
/** @brief get voltage (future support for non-voltage regulated h/w */
virtual double getVoltage() const = 0;
/** @brief current state of charge of the battery, relative to its
* rated nominal capacity [0..1]
*/
virtual double estimateResidualRelative() const = 0;
/** @brief current state of charge of the battery (mW-s) */
virtual double estimateResidualAbs() const = 0;
/** @brief Current state of the battery. */
virtual HostState::States getState() const = 0;
/*@}*/
};
#endif
| antoniomolram/Mixim_protocol | src/base/modules/BaseBattery.h | C | gpl-2.0 | 3,755 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Yuri A. Kropachev
* @version $Revision$
*/
package org.apache.harmony.security.provider.crypto;
/**
* This interface contains : <BR>
* - a set of constant values, H0-H4, defined in "SECURE HASH STANDARD", FIPS PUB 180-2 ;<BR>
* - implementation constant values to use in classes using SHA-1 algorithm. <BR>
*/
public interface SHA1_Data {
/**
* constant defined in "SECURE HASH STANDARD"
*/
static final int H0 = 0x67452301;
/**
* constant defined in "SECURE HASH STANDARD"
*/
static final int H1 = 0xEFCDAB89;
/**
* constant defined in "SECURE HASH STANDARD"
*/
static final int H2 = 0x98BADCFE;
/**
* constant defined in "SECURE HASH STANDARD"
*/
static final int H3 = 0x10325476;
/**
* constant defined in "SECURE HASH STANDARD"
*/
static final int H4 = 0xC3D2E1F0;
/**
* offset in buffer to store number of bytes in 0-15 word frame
*/
static final int BYTES_OFFSET = 81;
/**
* offset in buffer to store current hash value
*/
static final int HASH_OFFSET = 82;
/**
* # of bytes in H0-H4 words; <BR>
* in this implementation # is set to 20 (in general # varies from 1 to 20)
*/
static final int DIGEST_LENGTH = 20;
}
| xdajog/samsung_sources_i927 | libcore/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1_Data.java | Java | gpl-2.0 | 2,129 |
/*
* aQuantia Corporation Network Driver
* Copyright (C) 2014-2017 aQuantia Corporation. All rights reserved
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*/
/* File hw_atl_utils.c: Definition of common functions for Atlantic hardware
* abstraction layer.
*/
#include "../aq_hw.h"
#include "../aq_hw_utils.h"
#include "../aq_pci_func.h"
#include "../aq_ring.h"
#include "../aq_vec.h"
#include "hw_atl_utils.h"
#include "hw_atl_llh.h"
#include <linux/random.h>
#define HW_ATL_UCP_0X370_REG 0x0370U
#define HW_ATL_FW_SM_RAM 0x2U
#define HW_ATL_MPI_CONTROL_ADR 0x0368U
#define HW_ATL_MPI_STATE_ADR 0x036CU
#define HW_ATL_MPI_STATE_MSK 0x00FFU
#define HW_ATL_MPI_STATE_SHIFT 0U
#define HW_ATL_MPI_SPEED_MSK 0xFFFFU
#define HW_ATL_MPI_SPEED_SHIFT 16U
static int hw_atl_utils_fw_downld_dwords(struct aq_hw_s *self, u32 a,
u32 *p, u32 cnt)
{
int err = 0;
AQ_HW_WAIT_FOR(reg_glb_cpu_sem_get(self,
HW_ATL_FW_SM_RAM) == 1U,
1U, 10000U);
if (err < 0) {
bool is_locked;
reg_glb_cpu_sem_set(self, 1U, HW_ATL_FW_SM_RAM);
is_locked = reg_glb_cpu_sem_get(self, HW_ATL_FW_SM_RAM);
if (!is_locked) {
err = -ETIME;
goto err_exit;
}
}
aq_hw_write_reg(self, 0x00000208U, a);
for (++cnt; --cnt;) {
u32 i = 0U;
aq_hw_write_reg(self, 0x00000200U, 0x00008000U);
for (i = 1024U;
(0x100U & aq_hw_read_reg(self, 0x00000200U)) && --i;) {
}
*(p++) = aq_hw_read_reg(self, 0x0000020CU);
}
reg_glb_cpu_sem_set(self, 1U, HW_ATL_FW_SM_RAM);
err_exit:
return err;
}
static int hw_atl_utils_fw_upload_dwords(struct aq_hw_s *self, u32 a, u32 *p,
u32 cnt)
{
int err = 0;
bool is_locked;
is_locked = reg_glb_cpu_sem_get(self, HW_ATL_FW_SM_RAM);
if (!is_locked) {
err = -ETIME;
goto err_exit;
}
aq_hw_write_reg(self, 0x00000208U, a);
for (++cnt; --cnt;) {
u32 i = 0U;
aq_hw_write_reg(self, 0x0000020CU, *(p++));
aq_hw_write_reg(self, 0x00000200U, 0xC000U);
for (i = 1024U;
(0x100U & aq_hw_read_reg(self, 0x00000200U)) && --i;) {
}
}
reg_glb_cpu_sem_set(self, 1U, HW_ATL_FW_SM_RAM);
err_exit:
return err;
}
static int hw_atl_utils_ver_match(u32 ver_expected, u32 ver_actual)
{
int err = 0;
const u32 dw_major_mask = 0xff000000U;
const u32 dw_minor_mask = 0x00ffffffU;
err = (dw_major_mask & (ver_expected ^ ver_actual)) ? -EOPNOTSUPP : 0;
if (err < 0)
goto err_exit;
err = ((dw_minor_mask & ver_expected) > (dw_minor_mask & ver_actual)) ?
-EOPNOTSUPP : 0;
err_exit:
return err;
}
static int hw_atl_utils_init_ucp(struct aq_hw_s *self,
struct aq_hw_caps_s *aq_hw_caps)
{
int err = 0;
if (!aq_hw_read_reg(self, 0x370U)) {
unsigned int rnd = 0U;
unsigned int ucp_0x370 = 0U;
get_random_bytes(&rnd, sizeof(unsigned int));
ucp_0x370 = 0x02020202U | (0xFEFEFEFEU & rnd);
aq_hw_write_reg(self, HW_ATL_UCP_0X370_REG, ucp_0x370);
}
reg_glb_cpu_scratch_scp_set(self, 0x00000000U, 25U);
/* check 10 times by 1ms */
AQ_HW_WAIT_FOR(0U != (PHAL_ATLANTIC_A0->mbox_addr =
aq_hw_read_reg(self, 0x360U)), 1000U, 10U);
err = hw_atl_utils_ver_match(aq_hw_caps->fw_ver_expected,
aq_hw_read_reg(self, 0x18U));
if (err < 0)
pr_err("%s: Bad FW version detected: expected=%x, actual=%x\n",
AQ_CFG_DRV_NAME,
aq_hw_caps->fw_ver_expected,
aq_hw_read_reg(self, 0x18U));
return err;
}
#define HW_ATL_RPC_CONTROL_ADR 0x0338U
#define HW_ATL_RPC_STATE_ADR 0x033CU
struct aq_hw_atl_utils_fw_rpc_tid_s {
union {
u32 val;
struct {
u16 tid;
u16 len;
};
};
};
#define hw_atl_utils_fw_rpc_init(_H_) hw_atl_utils_fw_rpc_wait(_H_, NULL)
static int hw_atl_utils_fw_rpc_call(struct aq_hw_s *self, unsigned int rpc_size)
{
int err = 0;
struct aq_hw_atl_utils_fw_rpc_tid_s sw;
if (!IS_CHIP_FEATURE(MIPS)) {
err = -1;
goto err_exit;
}
err = hw_atl_utils_fw_upload_dwords(self, PHAL_ATLANTIC->rpc_addr,
(u32 *)(void *)&PHAL_ATLANTIC->rpc,
(rpc_size + sizeof(u32) -
sizeof(u8)) / sizeof(u32));
if (err < 0)
goto err_exit;
sw.tid = 0xFFFFU & (++PHAL_ATLANTIC->rpc_tid);
sw.len = (u16)rpc_size;
aq_hw_write_reg(self, HW_ATL_RPC_CONTROL_ADR, sw.val);
err_exit:
return err;
}
static int hw_atl_utils_fw_rpc_wait(struct aq_hw_s *self,
struct hw_aq_atl_utils_fw_rpc **rpc)
{
int err = 0;
struct aq_hw_atl_utils_fw_rpc_tid_s sw;
struct aq_hw_atl_utils_fw_rpc_tid_s fw;
do {
sw.val = aq_hw_read_reg(self, HW_ATL_RPC_CONTROL_ADR);
PHAL_ATLANTIC->rpc_tid = sw.tid;
AQ_HW_WAIT_FOR(sw.tid ==
(fw.val =
aq_hw_read_reg(self, HW_ATL_RPC_STATE_ADR),
fw.tid), 1000U, 100U);
if (err < 0)
goto err_exit;
if (fw.len == 0xFFFFU) {
err = hw_atl_utils_fw_rpc_call(self, sw.len);
if (err < 0)
goto err_exit;
}
} while (sw.tid != fw.tid || 0xFFFFU == fw.len);
if (err < 0)
goto err_exit;
if (rpc) {
if (fw.len) {
err =
hw_atl_utils_fw_downld_dwords(self,
PHAL_ATLANTIC->rpc_addr,
(u32 *)(void *)
&PHAL_ATLANTIC->rpc,
(fw.len + sizeof(u32) -
sizeof(u8)) /
sizeof(u32));
if (err < 0)
goto err_exit;
}
*rpc = &PHAL_ATLANTIC->rpc;
}
err_exit:
return err;
}
static int hw_atl_utils_mpi_create(struct aq_hw_s *self,
struct aq_hw_caps_s *aq_hw_caps)
{
int err = 0;
err = hw_atl_utils_init_ucp(self, aq_hw_caps);
if (err < 0)
goto err_exit;
err = hw_atl_utils_fw_rpc_init(self);
if (err < 0)
goto err_exit;
err_exit:
return err;
}
void hw_atl_utils_mpi_read_stats(struct aq_hw_s *self,
struct hw_aq_atl_utils_mbox *pmbox)
{
int err = 0;
err = hw_atl_utils_fw_downld_dwords(self,
PHAL_ATLANTIC->mbox_addr,
(u32 *)(void *)pmbox,
sizeof(*pmbox) / sizeof(u32));
if (err < 0)
goto err_exit;
if (pmbox != &PHAL_ATLANTIC->mbox)
memcpy(pmbox, &PHAL_ATLANTIC->mbox, sizeof(*pmbox));
if (IS_CHIP_FEATURE(REVISION_A0)) {
unsigned int mtu = self->aq_nic_cfg ?
self->aq_nic_cfg->mtu : 1514U;
pmbox->stats.ubrc = pmbox->stats.uprc * mtu;
pmbox->stats.ubtc = pmbox->stats.uptc * mtu;
pmbox->stats.dpc = atomic_read(&PHAL_ATLANTIC_A0->dpc);
} else {
pmbox->stats.dpc = reg_rx_dma_stat_counter7get(self);
}
err_exit:;
}
int hw_atl_utils_mpi_set_speed(struct aq_hw_s *self, u32 speed,
enum hal_atl_utils_fw_state_e state)
{
u32 ucp_0x368 = 0;
ucp_0x368 = (speed << HW_ATL_MPI_SPEED_SHIFT) | state;
aq_hw_write_reg(self, HW_ATL_MPI_CONTROL_ADR, ucp_0x368);
return 0;
}
void hw_atl_utils_mpi_set(struct aq_hw_s *self,
enum hal_atl_utils_fw_state_e state, u32 speed)
{
int err = 0;
u32 transaction_id = 0;
if (state == MPI_RESET) {
hw_atl_utils_mpi_read_stats(self, &PHAL_ATLANTIC->mbox);
transaction_id = PHAL_ATLANTIC->mbox.transaction_id;
AQ_HW_WAIT_FOR(transaction_id !=
(hw_atl_utils_mpi_read_stats
(self, &PHAL_ATLANTIC->mbox),
PHAL_ATLANTIC->mbox.transaction_id),
1000U, 100U);
if (err < 0)
goto err_exit;
}
err = hw_atl_utils_mpi_set_speed(self, speed, state);
err_exit:;
}
int hw_atl_utils_mpi_get_link_status(struct aq_hw_s *self)
{
u32 cp0x036C = aq_hw_read_reg(self, HW_ATL_MPI_STATE_ADR);
u32 link_speed_mask = cp0x036C >> HW_ATL_MPI_SPEED_SHIFT;
struct aq_hw_link_status_s *link_status = &self->aq_link_status;
if (!link_speed_mask) {
link_status->mbps = 0U;
} else {
switch (link_speed_mask) {
case HAL_ATLANTIC_RATE_10G:
link_status->mbps = 10000U;
break;
case HAL_ATLANTIC_RATE_5G:
case HAL_ATLANTIC_RATE_5GSR:
link_status->mbps = 5000U;
break;
case HAL_ATLANTIC_RATE_2GS:
link_status->mbps = 2500U;
break;
case HAL_ATLANTIC_RATE_1G:
link_status->mbps = 1000U;
break;
case HAL_ATLANTIC_RATE_100M:
link_status->mbps = 100U;
break;
default:
return -EBUSY;
}
}
return 0;
}
int hw_atl_utils_get_mac_permanent(struct aq_hw_s *self,
struct aq_hw_caps_s *aq_hw_caps,
u8 *mac)
{
int err = 0;
u32 h = 0U;
u32 l = 0U;
u32 mac_addr[2];
self->mmio = aq_pci_func_get_mmio(self->aq_pci_func);
hw_atl_utils_hw_chip_features_init(self,
&PHAL_ATLANTIC_A0->chip_features);
err = hw_atl_utils_mpi_create(self, aq_hw_caps);
if (err < 0)
goto err_exit;
if (!aq_hw_read_reg(self, HW_ATL_UCP_0X370_REG)) {
unsigned int rnd = 0;
unsigned int ucp_0x370 = 0;
get_random_bytes(&rnd, sizeof(unsigned int));
ucp_0x370 = 0x02020202 | (0xFEFEFEFE & rnd);
aq_hw_write_reg(self, HW_ATL_UCP_0X370_REG, ucp_0x370);
}
err = hw_atl_utils_fw_downld_dwords(self,
aq_hw_read_reg(self, 0x00000374U) +
(40U * 4U),
mac_addr,
AQ_DIMOF(mac_addr));
if (err < 0) {
mac_addr[0] = 0U;
mac_addr[1] = 0U;
err = 0;
} else {
mac_addr[0] = __swab32(mac_addr[0]);
mac_addr[1] = __swab32(mac_addr[1]);
}
ether_addr_copy(mac, (u8 *)mac_addr);
if ((mac[0] & 0x01U) || ((mac[0] | mac[1] | mac[2]) == 0x00U)) {
/* chip revision */
l = 0xE3000000U
| (0xFFFFU & aq_hw_read_reg(self, HW_ATL_UCP_0X370_REG))
| (0x00 << 16);
h = 0x8001300EU;
mac[5] = (u8)(0xFFU & l);
l >>= 8;
mac[4] = (u8)(0xFFU & l);
l >>= 8;
mac[3] = (u8)(0xFFU & l);
l >>= 8;
mac[2] = (u8)(0xFFU & l);
mac[1] = (u8)(0xFFU & h);
h >>= 8;
mac[0] = (u8)(0xFFU & h);
}
err_exit:
return err;
}
unsigned int hw_atl_utils_mbps_2_speed_index(unsigned int mbps)
{
unsigned int ret = 0U;
switch (mbps) {
case 100U:
ret = 5U;
break;
case 1000U:
ret = 4U;
break;
case 2500U:
ret = 3U;
break;
case 5000U:
ret = 1U;
break;
case 10000U:
ret = 0U;
break;
default:
break;
}
return ret;
}
void hw_atl_utils_hw_chip_features_init(struct aq_hw_s *self, u32 *p)
{
u32 chip_features = 0U;
u32 val = reg_glb_mif_id_get(self);
u32 mif_rev = val & 0xFFU;
if ((3U & mif_rev) == 1U) {
chip_features |=
HAL_ATLANTIC_UTILS_CHIP_REVISION_A0 |
HAL_ATLANTIC_UTILS_CHIP_MPI_AQ |
HAL_ATLANTIC_UTILS_CHIP_MIPS;
} else if ((3U & mif_rev) == 2U) {
chip_features |=
HAL_ATLANTIC_UTILS_CHIP_REVISION_B0 |
HAL_ATLANTIC_UTILS_CHIP_MPI_AQ |
HAL_ATLANTIC_UTILS_CHIP_MIPS |
HAL_ATLANTIC_UTILS_CHIP_TPO2 |
HAL_ATLANTIC_UTILS_CHIP_RPF2;
}
*p = chip_features;
}
int hw_atl_utils_hw_deinit(struct aq_hw_s *self)
{
hw_atl_utils_mpi_set(self, MPI_DEINIT, 0x0U);
return 0;
}
int hw_atl_utils_hw_set_power(struct aq_hw_s *self,
unsigned int power_state)
{
hw_atl_utils_mpi_set(self, MPI_POWER, 0x0U);
return 0;
}
int hw_atl_utils_get_hw_stats(struct aq_hw_s *self,
u64 *data, unsigned int *p_count)
{
struct hw_atl_stats_s *stats = NULL;
int i = 0;
hw_atl_utils_mpi_read_stats(self, &PHAL_ATLANTIC->mbox);
stats = &PHAL_ATLANTIC->mbox.stats;
data[i] = stats->uprc + stats->mprc + stats->bprc;
data[++i] = stats->uprc;
data[++i] = stats->mprc;
data[++i] = stats->bprc;
data[++i] = stats->erpt;
data[++i] = stats->uptc + stats->mptc + stats->bptc;
data[++i] = stats->uptc;
data[++i] = stats->mptc;
data[++i] = stats->bptc;
data[++i] = stats->ubrc;
data[++i] = stats->ubtc;
data[++i] = stats->mbrc;
data[++i] = stats->mbtc;
data[++i] = stats->bbrc;
data[++i] = stats->bbtc;
data[++i] = stats->ubrc + stats->mbrc + stats->bbrc;
data[++i] = stats->ubtc + stats->mbtc + stats->bbtc;
data[++i] = stats_rx_dma_good_pkt_counterlsw_get(self);
data[++i] = stats_tx_dma_good_pkt_counterlsw_get(self);
data[++i] = stats_rx_dma_good_octet_counterlsw_get(self);
data[++i] = stats_tx_dma_good_octet_counterlsw_get(self);
data[++i] = stats->dpc;
if (p_count)
*p_count = ++i;
return 0;
}
static const u32 hw_atl_utils_hw_mac_regs[] = {
0x00005580U, 0x00005590U, 0x000055B0U, 0x000055B4U,
0x000055C0U, 0x00005B00U, 0x00005B04U, 0x00005B08U,
0x00005B0CU, 0x00005B10U, 0x00005B14U, 0x00005B18U,
0x00005B1CU, 0x00005B20U, 0x00005B24U, 0x00005B28U,
0x00005B2CU, 0x00005B30U, 0x00005B34U, 0x00005B38U,
0x00005B3CU, 0x00005B40U, 0x00005B44U, 0x00005B48U,
0x00005B4CU, 0x00005B50U, 0x00005B54U, 0x00005B58U,
0x00005B5CU, 0x00005B60U, 0x00005B64U, 0x00005B68U,
0x00005B6CU, 0x00005B70U, 0x00005B74U, 0x00005B78U,
0x00005B7CU, 0x00007C00U, 0x00007C04U, 0x00007C08U,
0x00007C0CU, 0x00007C10U, 0x00007C14U, 0x00007C18U,
0x00007C1CU, 0x00007C20U, 0x00007C40U, 0x00007C44U,
0x00007C48U, 0x00007C4CU, 0x00007C50U, 0x00007C54U,
0x00007C58U, 0x00007C5CU, 0x00007C60U, 0x00007C80U,
0x00007C84U, 0x00007C88U, 0x00007C8CU, 0x00007C90U,
0x00007C94U, 0x00007C98U, 0x00007C9CU, 0x00007CA0U,
0x00007CC0U, 0x00007CC4U, 0x00007CC8U, 0x00007CCCU,
0x00007CD0U, 0x00007CD4U, 0x00007CD8U, 0x00007CDCU,
0x00007CE0U, 0x00000300U, 0x00000304U, 0x00000308U,
0x0000030cU, 0x00000310U, 0x00000314U, 0x00000318U,
0x0000031cU, 0x00000360U, 0x00000364U, 0x00000368U,
0x0000036cU, 0x00000370U, 0x00000374U, 0x00006900U,
};
int hw_atl_utils_hw_get_regs(struct aq_hw_s *self,
struct aq_hw_caps_s *aq_hw_caps,
u32 *regs_buff)
{
unsigned int i = 0U;
for (i = 0; i < aq_hw_caps->mac_regs_count; i++)
regs_buff[i] = aq_hw_read_reg(self,
hw_atl_utils_hw_mac_regs[i]);
return 0;
}
int hw_atl_utils_get_fw_version(struct aq_hw_s *self, u32 *fw_version)
{
*fw_version = aq_hw_read_reg(self, 0x18U);
return 0;
}
| animalcreek/linux | drivers/net/ethernet/aquantia/atlantic/hw_atl/hw_atl_utils.c | C | gpl-2.0 | 13,329 |
// license:BSD-3-Clause
// copyright-holders:Krzysztof Strzecha, Miodrag Milanovic
/***************************************************************************
Galaksija driver by Krzysztof Strzecha and Miodrag Milanovic
22/05/2008 Tape support added (Miodrag Milanovic)
21/05/2008 Galaksija plus initial support (Miodrag Milanovic)
20/05/2008 Added real video implementation (Miodrag Milanovic)
18/04/2005 Possibilty to disable ROM 2. 2k, 22k, 38k and 54k memory
configurations added.
13/03/2005 Memory mapping improved. Palette corrected. Supprort for newer
version of snapshots added. Lot of cleanups. Keyboard mapping
corrected.
19/09/2002 malloc() replaced by image_malloc().
15/09/2002 Snapshot loading fixed. Code cleanup.
31/01/2001 Snapshot loading corrected.
09/01/2001 Fast mode implemented (many thanks to Kevin Thacker).
07/01/2001 Keyboard corrected (still some keys unknown).
Horizontal screen positioning in video subsystem added.
05/01/2001 Keyboard implemented (some keys unknown).
03/01/2001 Snapshot loading added.
01/01/2001 Preliminary driver.
***************************************************************************/
#include "emu.h"
#include "cpu/z80/z80.h"
#include "sound/wave.h"
#include "includes/galaxy.h"
#include "imagedev/snapquik.h"
#include "imagedev/cassette.h"
#include "sound/ay8910.h"
#include "formats/gtp_cas.h"
#include "machine/ram.h"
#include "softlist.h"
static ADDRESS_MAP_START (galaxyp_io, AS_IO, 8, galaxy_state )
ADDRESS_MAP_GLOBAL_MASK(0x01)
ADDRESS_MAP_UNMAP_HIGH
AM_RANGE(0xbe, 0xbe) AM_DEVWRITE("ay8910", ay8910_device, address_w)
AM_RANGE(0xbf, 0xbf) AM_DEVWRITE("ay8910", ay8910_device, data_w)
ADDRESS_MAP_END
static ADDRESS_MAP_START (galaxy_mem, AS_PROGRAM, 8, galaxy_state )
AM_RANGE(0x0000, 0x0fff) AM_ROM
AM_RANGE(0x2000, 0x2037) AM_MIRROR(0x07c0) AM_READ(galaxy_keyboard_r )
AM_RANGE(0x2038, 0x203f) AM_MIRROR(0x07c0) AM_WRITE(galaxy_latch_w )
ADDRESS_MAP_END
static ADDRESS_MAP_START (galaxyp_mem, AS_PROGRAM, 8, galaxy_state )
AM_RANGE(0x0000, 0x0fff) AM_ROM // ROM A
AM_RANGE(0x1000, 0x1fff) AM_ROM // ROM B
AM_RANGE(0x2000, 0x2037) AM_MIRROR(0x07c0) AM_READ(galaxy_keyboard_r )
AM_RANGE(0x2038, 0x203f) AM_MIRROR(0x07c0) AM_WRITE(galaxy_latch_w )
AM_RANGE(0xe000, 0xefff) AM_ROM // ROM C
AM_RANGE(0xf000, 0xffff) AM_ROM // ROM D
ADDRESS_MAP_END
/* 2008-05 FP:
Small note about natural keyboard support. Currently:
- "List" is mapped to 'ESC'
- "Break" is mapped to 'F1'
- "Repeat" is mapped to 'F2' */
static INPUT_PORTS_START (galaxy_common)
PORT_START("LINE0")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_UNUSED)
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_A) PORT_CHAR('A')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_B) PORT_CHAR('B')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_C) PORT_CHAR('C')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_D) PORT_CHAR('D')
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_E) PORT_CHAR('E')
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_F) PORT_CHAR('F')
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_G) PORT_CHAR('G')
PORT_START("LINE1")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_H) PORT_CHAR('H')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_I) PORT_CHAR('I')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_J) PORT_CHAR('J')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_K) PORT_CHAR('K')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_L) PORT_CHAR('L')
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_M) PORT_CHAR('M')
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_N) PORT_CHAR('N')
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_O) PORT_CHAR('O')
PORT_START("LINE2")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_P) PORT_CHAR('P')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_Q) PORT_CHAR('Q')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_R) PORT_CHAR('R')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_S) PORT_CHAR('S')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_T) PORT_CHAR('T')
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_U) PORT_CHAR('U')
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_V) PORT_CHAR('V')
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_W) PORT_CHAR('W')
PORT_START("LINE3")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_X) PORT_CHAR('X')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_Y) PORT_CHAR('Y')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_Z) PORT_CHAR('Z')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_UP) PORT_CHAR(UCHAR_MAMEKEY(UP))
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_DOWN) PORT_CHAR(UCHAR_MAMEKEY(DOWN))
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_LEFT) PORT_CHAR(UCHAR_MAMEKEY(LEFT))
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_RIGHT) PORT_CHAR(UCHAR_MAMEKEY(RIGHT))
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_SPACE) PORT_CHAR(' ')
PORT_START("LINE4")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_0) PORT_CHAR('0') PORT_CHAR('_')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_1) PORT_CHAR('1') PORT_CHAR('!')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_2) PORT_CHAR('2') PORT_CHAR('"')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_3) PORT_CHAR('3') PORT_CHAR('#')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_4) PORT_CHAR('4') PORT_CHAR('$')
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_5) PORT_CHAR('5') PORT_CHAR('%')
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_6) PORT_CHAR('6') PORT_CHAR('&')
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_7) PORT_CHAR('7') PORT_CHAR('\'')
PORT_START("LINE5")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_8) PORT_CHAR('8') PORT_CHAR('(')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_9) PORT_CHAR('9') PORT_CHAR(')')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_COLON) PORT_CHAR(';') PORT_CHAR('+')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_QUOTE) PORT_CHAR(':') PORT_CHAR('*')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_COMMA) PORT_CHAR(',') PORT_CHAR('<')
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_EQUALS) PORT_CHAR('=') PORT_CHAR('-')
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_STOP) PORT_CHAR('.') PORT_CHAR('>')
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_SLASH) PORT_CHAR('/') PORT_CHAR('?')
PORT_START("LINE6")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_ENTER) PORT_CHAR(13)
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("Break") PORT_CODE(KEYCODE_PAUSE) PORT_CHAR(UCHAR_MAMEKEY(F1))
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("Repeat") PORT_CODE(KEYCODE_LALT) PORT_CHAR(UCHAR_MAMEKEY(F2))
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("Delete") PORT_CODE(KEYCODE_BACKSPACE) PORT_CHAR(8)
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("List") PORT_CODE(KEYCODE_ESC) PORT_CHAR(UCHAR_MAMEKEY(ESC))
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_LSHIFT) PORT_CODE(KEYCODE_RSHIFT) PORT_CHAR(UCHAR_SHIFT_1)
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_UNUSED)
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_UNUSED)
INPUT_PORTS_END
static INPUT_PORTS_START( galaxy )
PORT_INCLUDE( galaxy_common )
PORT_START("ROM2")
PORT_CONFNAME(0x01, 0x01, "ROM 2")
PORT_CONFSETTING(0x01, "Installed")
PORT_CONFSETTING(0x00, "Not installed")
INPUT_PORTS_END
static INPUT_PORTS_START( galaxyp )
PORT_INCLUDE( galaxy_common )
INPUT_PORTS_END
#define XTAL 6144000
/* F4 Character Displayer */
static const gfx_layout galaxy_charlayout =
{
8, 16, /* 8 x 16 characters */
128, /* 128 characters */
1, /* 1 bits per pixel */
{ 0 }, /* no bitplanes */
/* x offsets */
{ 7, 6, 5, 4, 3, 2, 1, 0 },
/* y offsets */
{ 0, 1*128*8, 2*128*8, 3*128*8, 4*128*8, 5*128*8, 6*128*8, 7*128*8, 8*128*8, 9*128*8, 10*128*8, 11*128*8, 12*128*8, 13*128*8, 14*128*8, 15*128*8 },
8 /* every char takes 1 x 16 bytes */
};
static GFXDECODE_START( galaxy )
GFXDECODE_ENTRY( "gfx1", 0x0000, galaxy_charlayout, 0, 1 )
GFXDECODE_END
static MACHINE_CONFIG_START( galaxy, galaxy_state )
/* basic machine hardware */
MCFG_CPU_ADD("maincpu", Z80, XTAL / 2)
MCFG_CPU_PROGRAM_MAP(galaxy_mem)
MCFG_CPU_VBLANK_INT_DRIVER("screen", galaxy_state, galaxy_interrupt)
MCFG_CPU_IRQ_ACKNOWLEDGE_DRIVER(galaxy_state,galaxy_irq_callback)
MCFG_SCREEN_ADD("screen", RASTER)
MCFG_SCREEN_REFRESH_RATE(50)
MCFG_SCREEN_PALETTE("palette")
MCFG_MACHINE_RESET_OVERRIDE(galaxy_state, galaxy )
/* video hardware */
MCFG_SCREEN_SIZE(384, 212)
MCFG_SCREEN_VISIBLE_AREA(0, 384-1, 0, 208-1)
MCFG_SCREEN_UPDATE_DRIVER(galaxy_state, screen_update_galaxy)
MCFG_GFXDECODE_ADD("gfxdecode", "palette", galaxy)
MCFG_PALETTE_ADD_MONOCHROME("palette")
/* snapshot */
MCFG_SNAPSHOT_ADD("snapshot", galaxy_state, galaxy, "gal", 0)
MCFG_SPEAKER_STANDARD_MONO("mono")
MCFG_SOUND_WAVE_ADD(WAVE_TAG, "cassette")
MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.25)
MCFG_CASSETTE_ADD( "cassette" )
MCFG_CASSETTE_FORMATS(gtp_cassette_formats)
MCFG_CASSETTE_DEFAULT_STATE(CASSETTE_STOPPED | CASSETTE_SPEAKER_ENABLED | CASSETTE_MOTOR_ENABLED)
MCFG_CASSETTE_INTERFACE("galaxy_cass")
MCFG_SOFTWARE_LIST_ADD("cass_list","galaxy")
/* internal ram */
MCFG_RAM_ADD(RAM_TAG)
MCFG_RAM_DEFAULT_SIZE("6K")
MCFG_RAM_EXTRA_OPTIONS("2K,22K,38K,54K")
MACHINE_CONFIG_END
static MACHINE_CONFIG_START( galaxyp, galaxy_state )
/* basic machine hardware */
MCFG_CPU_ADD("maincpu", Z80, XTAL / 2)
MCFG_CPU_PROGRAM_MAP(galaxyp_mem)
MCFG_CPU_IO_MAP(galaxyp_io)
MCFG_CPU_VBLANK_INT_DRIVER("screen", galaxy_state, galaxy_interrupt)
MCFG_CPU_IRQ_ACKNOWLEDGE_DRIVER(galaxy_state,galaxy_irq_callback)
MCFG_SCREEN_ADD("screen", RASTER)
MCFG_SCREEN_REFRESH_RATE(50)
MCFG_SCREEN_PALETTE("palette")
MCFG_MACHINE_RESET_OVERRIDE(galaxy_state, galaxyp )
/* video hardware */
MCFG_SCREEN_SIZE(384, 208)
MCFG_SCREEN_VISIBLE_AREA(0, 384-1, 0, 208-1)
MCFG_SCREEN_UPDATE_DRIVER(galaxy_state, screen_update_galaxy)
MCFG_PALETTE_ADD_MONOCHROME("palette")
/* snapshot */
MCFG_SNAPSHOT_ADD("snapshot", galaxy_state, galaxy, "gal", 0)
/* sound hardware */
MCFG_SPEAKER_STANDARD_MONO("mono")
MCFG_SOUND_ADD("ay8910", AY8910, XTAL/4)
MCFG_SOUND_WAVE_ADD(WAVE_TAG, "cassette")
MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.25)
MCFG_CASSETTE_ADD( "cassette" )
MCFG_CASSETTE_FORMATS(gtp_cassette_formats)
MCFG_CASSETTE_DEFAULT_STATE(CASSETTE_STOPPED | CASSETTE_SPEAKER_ENABLED | CASSETTE_MOTOR_ENABLED)
MCFG_CASSETTE_INTERFACE("galaxy_cass")
MCFG_SOFTWARE_LIST_ADD("cass_list","galaxy")
/* internal ram */
MCFG_RAM_ADD(RAM_TAG)
MCFG_RAM_DEFAULT_SIZE("38K")
MACHINE_CONFIG_END
ROM_START (galaxy)
ROM_REGION (0x10000, "maincpu", ROMREGION_ERASEFF)
ROM_LOAD ("galrom1.bin", 0x0000, 0x1000, CRC(dc970a32) SHA1(dfc92163654a756b70f5a446daf49d7534f4c739))
ROM_LOAD_OPTIONAL ("galrom2.bin", 0x1000, 0x1000, CRC(5dc5a100) SHA1(5d5ab4313a2d0effe7572bb129193b64cab002c1))
ROM_REGION(0x0800, "gfx1",0)
ROM_LOAD ("galchr.bin", 0x0000, 0x0800, CRC(5c3b5bb5) SHA1(19429a61dc5e55ddec3242a8f695e06dd7961f88))
ROM_END
ROM_START (galaxyp)
ROM_REGION (0x10000, "maincpu", ROMREGION_ERASEFF)
ROM_LOAD ("galrom1.bin", 0x0000, 0x1000, CRC(dc970a32) SHA1(dfc92163654a756b70f5a446daf49d7534f4c739))
ROM_LOAD ("galrom2.bin", 0x1000, 0x1000, CRC(5dc5a100) SHA1(5d5ab4313a2d0effe7572bb129193b64cab002c1))
ROM_LOAD ("galplus.bin", 0xe000, 0x1000, CRC(d4cfab14) SHA1(b507b9026844eeb757547679907394aa42055eee))
ROM_REGION(0x0800, "gfx1",0)
ROM_LOAD ("galchr.bin", 0x0000, 0x0800, CRC(5c3b5bb5) SHA1(19429a61dc5e55ddec3242a8f695e06dd7961f88))
ROM_END
/* YEAR NAME PARENT COMPAT MACHINE INPUT INIT COMPANY FULLNAME */
COMP(1983, galaxy, 0, 0, galaxy, galaxy, galaxy_state, galaxy, "Voja Antonic / Elektronika inzenjering", "Galaksija", 0)
COMP(1985, galaxyp, galaxy, 0, galaxyp,galaxyp, galaxy_state,galaxyp,"Nenad Dunjic", "Galaksija plus", 0)
| RJRetro/mame | src/mame/drivers/galaxy.cpp | C++ | gpl-2.0 | 12,956 |
/* $Id: gazel.c,v 2.19.2.4 2004/01/14 16:04:48 keil Exp $
*
* low level stuff for Gazel isdn cards
*
* Author BeWan Systems
* based on source code from Karsten Keil
* Copyright by BeWan Systems
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
#include <linux/config.h>
#include <linux/init.h>
#include "hisax.h"
#include "isac.h"
#include "hscx.h"
#include "isdnl1.h"
#include "ipac.h"
#include <linux/pci.h>
extern const char *CardType[];
static const char *gazel_revision = "$Revision: 2.19.2.4 $";
#define R647 1
#define R685 2
#define R753 3
#define R742 4
#define PLX_CNTRL 0x50 /* registre de controle PLX */
#define RESET_GAZEL 0x4
#define RESET_9050 0x40000000
#define PLX_INCSR 0x4C /* registre d'IT du 9050 */
#define INT_ISAC_EN 0x8 /* 1 = enable IT isac */
#define INT_ISAC 0x20 /* 1 = IT isac en cours */
#define INT_HSCX_EN 0x1 /* 1 = enable IT hscx */
#define INT_HSCX 0x4 /* 1 = IT hscx en cours */
#define INT_PCI_EN 0x40 /* 1 = enable IT PCI */
#define INT_IPAC_EN 0x3 /* enable IT ipac */
#define byteout(addr,val) outb(val,addr)
#define bytein(addr) inb(addr)
static inline u_char
readreg(unsigned int adr, u_short off)
{
return bytein(adr + off);
}
static inline void
writereg(unsigned int adr, u_short off, u_char data)
{
byteout(adr + off, data);
}
static inline void
read_fifo(unsigned int adr, u_char * data, int size)
{
insb(adr, data, size);
}
static void
write_fifo(unsigned int adr, u_char * data, int size)
{
outsb(adr, data, size);
}
static inline u_char
readreg_ipac(unsigned int adr, u_short off)
{
register u_char ret;
byteout(adr, off);
ret = bytein(adr + 4);
return ret;
}
static inline void
writereg_ipac(unsigned int adr, u_short off, u_char data)
{
byteout(adr, off);
byteout(adr + 4, data);
}
static inline void
read_fifo_ipac(unsigned int adr, u_short off, u_char * data, int size)
{
byteout(adr, off);
insb(adr + 4, data, size);
}
static void
write_fifo_ipac(unsigned int adr, u_short off, u_char * data, int size)
{
byteout(adr, off);
outsb(adr + 4, data, size);
}
/* Interface functions */
static u_char
ReadISAC(struct IsdnCardState *cs, u_char offset)
{
u_short off2 = offset;
switch (cs->subtyp) {
case R647:
off2 = ((off2 << 8 & 0xf000) | (off2 & 0xf));
case R685:
return (readreg(cs->hw.gazel.isac, off2));
case R753:
case R742:
return (readreg_ipac(cs->hw.gazel.ipac, 0x80 + off2));
}
return 0;
}
static void
WriteISAC(struct IsdnCardState *cs, u_char offset, u_char value)
{
u_short off2 = offset;
switch (cs->subtyp) {
case R647:
off2 = ((off2 << 8 & 0xf000) | (off2 & 0xf));
case R685:
writereg(cs->hw.gazel.isac, off2, value);
break;
case R753:
case R742:
writereg_ipac(cs->hw.gazel.ipac, 0x80 + off2, value);
break;
}
}
static void
ReadISACfifo(struct IsdnCardState *cs, u_char * data, int size)
{
switch (cs->subtyp) {
case R647:
case R685:
read_fifo(cs->hw.gazel.isacfifo, data, size);
break;
case R753:
case R742:
read_fifo_ipac(cs->hw.gazel.ipac, 0x80, data, size);
break;
}
}
static void
WriteISACfifo(struct IsdnCardState *cs, u_char * data, int size)
{
switch (cs->subtyp) {
case R647:
case R685:
write_fifo(cs->hw.gazel.isacfifo, data, size);
break;
case R753:
case R742:
write_fifo_ipac(cs->hw.gazel.ipac, 0x80, data, size);
break;
}
}
static void
ReadHSCXfifo(struct IsdnCardState *cs, int hscx, u_char * data, int size)
{
switch (cs->subtyp) {
case R647:
case R685:
read_fifo(cs->hw.gazel.hscxfifo[hscx], data, size);
break;
case R753:
case R742:
read_fifo_ipac(cs->hw.gazel.ipac, hscx * 0x40, data, size);
break;
}
}
static void
WriteHSCXfifo(struct IsdnCardState *cs, int hscx, u_char * data, int size)
{
switch (cs->subtyp) {
case R647:
case R685:
write_fifo(cs->hw.gazel.hscxfifo[hscx], data, size);
break;
case R753:
case R742:
write_fifo_ipac(cs->hw.gazel.ipac, hscx * 0x40, data, size);
break;
}
}
static u_char
ReadHSCX(struct IsdnCardState *cs, int hscx, u_char offset)
{
u_short off2 = offset;
switch (cs->subtyp) {
case R647:
off2 = ((off2 << 8 & 0xf000) | (off2 & 0xf));
case R685:
return (readreg(cs->hw.gazel.hscx[hscx], off2));
case R753:
case R742:
return (readreg_ipac(cs->hw.gazel.ipac, hscx * 0x40 + off2));
}
return 0;
}
static void
WriteHSCX(struct IsdnCardState *cs, int hscx, u_char offset, u_char value)
{
u_short off2 = offset;
switch (cs->subtyp) {
case R647:
off2 = ((off2 << 8 & 0xf000) | (off2 & 0xf));
case R685:
writereg(cs->hw.gazel.hscx[hscx], off2, value);
break;
case R753:
case R742:
writereg_ipac(cs->hw.gazel.ipac, hscx * 0x40 + off2, value);
break;
}
}
/*
* fast interrupt HSCX stuff goes here
*/
#define READHSCX(cs, nr, reg) ReadHSCX(cs, nr, reg)
#define WRITEHSCX(cs, nr, reg, data) WriteHSCX(cs, nr, reg, data)
#define READHSCXFIFO(cs, nr, ptr, cnt) ReadHSCXfifo(cs, nr, ptr, cnt)
#define WRITEHSCXFIFO(cs, nr, ptr, cnt) WriteHSCXfifo(cs, nr, ptr, cnt)
#include "hscx_irq.c"
static irqreturn_t
gazel_interrupt(int intno, void *dev_id, struct pt_regs *regs)
{
#define MAXCOUNT 5
struct IsdnCardState *cs = dev_id;
u_char valisac, valhscx;
int count = 0;
u_long flags;
spin_lock_irqsave(&cs->lock, flags);
do {
valhscx = ReadHSCX(cs, 1, HSCX_ISTA);
if (valhscx)
hscx_int_main(cs, valhscx);
valisac = ReadISAC(cs, ISAC_ISTA);
if (valisac)
isac_interrupt(cs, valisac);
count++;
} while ((valhscx || valisac) && (count < MAXCOUNT));
WriteHSCX(cs, 0, HSCX_MASK, 0xFF);
WriteHSCX(cs, 1, HSCX_MASK, 0xFF);
WriteISAC(cs, ISAC_MASK, 0xFF);
WriteISAC(cs, ISAC_MASK, 0x0);
WriteHSCX(cs, 0, HSCX_MASK, 0x0);
WriteHSCX(cs, 1, HSCX_MASK, 0x0);
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_HANDLED;
}
static irqreturn_t
gazel_interrupt_ipac(int intno, void *dev_id, struct pt_regs *regs)
{
struct IsdnCardState *cs = dev_id;
u_char ista, val;
int count = 0;
u_long flags;
spin_lock_irqsave(&cs->lock, flags);
ista = ReadISAC(cs, IPAC_ISTA - 0x80);
do {
if (ista & 0x0f) {
val = ReadHSCX(cs, 1, HSCX_ISTA);
if (ista & 0x01)
val |= 0x01;
if (ista & 0x04)
val |= 0x02;
if (ista & 0x08)
val |= 0x04;
if (val) {
hscx_int_main(cs, val);
}
}
if (ista & 0x20) {
val = 0xfe & ReadISAC(cs, ISAC_ISTA);
if (val) {
isac_interrupt(cs, val);
}
}
if (ista & 0x10) {
val = 0x01;
isac_interrupt(cs, val);
}
ista = ReadISAC(cs, IPAC_ISTA - 0x80);
count++;
}
while ((ista & 0x3f) && (count < MAXCOUNT));
WriteISAC(cs, IPAC_MASK - 0x80, 0xFF);
WriteISAC(cs, IPAC_MASK - 0x80, 0xC0);
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_HANDLED;
}
static void
release_io_gazel(struct IsdnCardState *cs)
{
unsigned int i;
switch (cs->subtyp) {
case R647:
for (i = 0x0000; i < 0xC000; i += 0x1000)
release_region(i + cs->hw.gazel.hscx[0], 16);
release_region(0xC000 + cs->hw.gazel.hscx[0], 1);
break;
case R685:
release_region(cs->hw.gazel.hscx[0], 0x100);
release_region(cs->hw.gazel.cfg_reg, 0x80);
break;
case R753:
release_region(cs->hw.gazel.ipac, 0x8);
release_region(cs->hw.gazel.cfg_reg, 0x80);
break;
case R742:
release_region(cs->hw.gazel.ipac, 8);
break;
}
}
static int
reset_gazel(struct IsdnCardState *cs)
{
unsigned long plxcntrl, addr = cs->hw.gazel.cfg_reg;
switch (cs->subtyp) {
case R647:
writereg(addr, 0, 0);
HZDELAY(10);
writereg(addr, 0, 1);
HZDELAY(2);
break;
case R685:
plxcntrl = inl(addr + PLX_CNTRL);
plxcntrl |= (RESET_9050 + RESET_GAZEL);
outl(plxcntrl, addr + PLX_CNTRL);
plxcntrl &= ~(RESET_9050 + RESET_GAZEL);
HZDELAY(4);
outl(plxcntrl, addr + PLX_CNTRL);
HZDELAY(10);
outb(INT_ISAC_EN + INT_HSCX_EN + INT_PCI_EN, addr + PLX_INCSR);
break;
case R753:
plxcntrl = inl(addr + PLX_CNTRL);
plxcntrl |= (RESET_9050 + RESET_GAZEL);
outl(plxcntrl, addr + PLX_CNTRL);
plxcntrl &= ~(RESET_9050 + RESET_GAZEL);
WriteISAC(cs, IPAC_POTA2 - 0x80, 0x20);
HZDELAY(4);
outl(plxcntrl, addr + PLX_CNTRL);
HZDELAY(10);
WriteISAC(cs, IPAC_POTA2 - 0x80, 0x00);
WriteISAC(cs, IPAC_ACFG - 0x80, 0xff);
WriteISAC(cs, IPAC_AOE - 0x80, 0x0);
WriteISAC(cs, IPAC_MASK - 0x80, 0xff);
WriteISAC(cs, IPAC_CONF - 0x80, 0x1);
outb(INT_IPAC_EN + INT_PCI_EN, addr + PLX_INCSR);
WriteISAC(cs, IPAC_MASK - 0x80, 0xc0);
break;
case R742:
WriteISAC(cs, IPAC_POTA2 - 0x80, 0x20);
HZDELAY(4);
WriteISAC(cs, IPAC_POTA2 - 0x80, 0x00);
WriteISAC(cs, IPAC_ACFG - 0x80, 0xff);
WriteISAC(cs, IPAC_AOE - 0x80, 0x0);
WriteISAC(cs, IPAC_MASK - 0x80, 0xff);
WriteISAC(cs, IPAC_CONF - 0x80, 0x1);
WriteISAC(cs, IPAC_MASK - 0x80, 0xc0);
break;
}
return (0);
}
static int
Gazel_card_msg(struct IsdnCardState *cs, int mt, void *arg)
{
u_long flags;
switch (mt) {
case CARD_RESET:
spin_lock_irqsave(&cs->lock, flags);
reset_gazel(cs);
spin_unlock_irqrestore(&cs->lock, flags);
return (0);
case CARD_RELEASE:
release_io_gazel(cs);
return (0);
case CARD_INIT:
spin_lock_irqsave(&cs->lock, flags);
inithscxisac(cs, 1);
if ((cs->subtyp==R647)||(cs->subtyp==R685)) {
int i;
for (i=0;i<(2+MAX_WAITING_CALLS);i++) {
cs->bcs[i].hw.hscx.tsaxr0 = 0x1f;
cs->bcs[i].hw.hscx.tsaxr1 = 0x23;
}
}
spin_unlock_irqrestore(&cs->lock, flags);
return (0);
case CARD_TEST:
return (0);
}
return (0);
}
static int
reserve_regions(struct IsdnCard *card, struct IsdnCardState *cs)
{
unsigned int i, j, base = 0, adr = 0, len = 0;
switch (cs->subtyp) {
case R647:
base = cs->hw.gazel.hscx[0];
if (!request_region(adr = (0xC000 + base), len = 1, "gazel"))
goto error;
for (i = 0x0000; i < 0xC000; i += 0x1000) {
if (!request_region(adr = (i + base), len = 16, "gazel"))
goto error;
}
if (i != 0xC000) {
for (j = 0; j < i; j+= 0x1000)
release_region(j + base, 16);
release_region(0xC000 + base, 1);
goto error;
}
break;
case R685:
if (!request_region(adr = cs->hw.gazel.hscx[0], len = 0x100, "gazel"))
goto error;
if (!request_region(adr = cs->hw.gazel.cfg_reg, len = 0x80, "gazel")) {
release_region(cs->hw.gazel.hscx[0],0x100);
goto error;
}
break;
case R753:
if (!request_region(adr = cs->hw.gazel.ipac, len = 0x8, "gazel"))
goto error;
if (!request_region(adr = cs->hw.gazel.cfg_reg, len = 0x80, "gazel")) {
release_region(cs->hw.gazel.ipac, 8);
goto error;
}
break;
case R742:
if (!request_region(adr = cs->hw.gazel.ipac, len = 0x8, "gazel"))
goto error;
break;
}
return 0;
error:
printk(KERN_WARNING "Gazel: %s io ports 0x%x-0x%x already in use\n",
CardType[cs->typ], adr, adr + len);
return 1;
}
static int __init
setup_gazelisa(struct IsdnCard *card, struct IsdnCardState *cs)
{
printk(KERN_INFO "Gazel: ISA PnP card automatic recognition\n");
// we got an irq parameter, assume it is an ISA card
// R742 decodes address even in not started...
// R647 returns FF if not present or not started
// eventually needs improvment
if (readreg_ipac(card->para[1], IPAC_ID) == 1)
cs->subtyp = R742;
else
cs->subtyp = R647;
setup_isac(cs);
cs->hw.gazel.cfg_reg = card->para[1] + 0xC000;
cs->hw.gazel.ipac = card->para[1];
cs->hw.gazel.isac = card->para[1] + 0x8000;
cs->hw.gazel.hscx[0] = card->para[1];
cs->hw.gazel.hscx[1] = card->para[1] + 0x4000;
cs->irq = card->para[0];
cs->hw.gazel.isacfifo = cs->hw.gazel.isac;
cs->hw.gazel.hscxfifo[0] = cs->hw.gazel.hscx[0];
cs->hw.gazel.hscxfifo[1] = cs->hw.gazel.hscx[1];
switch (cs->subtyp) {
case R647:
printk(KERN_INFO "Gazel: Card ISA R647/R648 found\n");
cs->dc.isac.adf2 = 0x87;
printk(KERN_INFO
"Gazel: config irq:%d isac:0x%X cfg:0x%X\n",
cs->irq, cs->hw.gazel.isac, cs->hw.gazel.cfg_reg);
printk(KERN_INFO
"Gazel: hscx A:0x%X hscx B:0x%X\n",
cs->hw.gazel.hscx[0], cs->hw.gazel.hscx[1]);
break;
case R742:
printk(KERN_INFO "Gazel: Card ISA R742 found\n");
test_and_set_bit(HW_IPAC, &cs->HW_Flags);
printk(KERN_INFO
"Gazel: config irq:%d ipac:0x%X\n",
cs->irq, cs->hw.gazel.ipac);
break;
}
return (0);
}
static struct pci_dev *dev_tel __initdata = NULL;
static int __init
setup_gazelpci(struct IsdnCardState *cs)
{
u_int pci_ioaddr0 = 0, pci_ioaddr1 = 0;
u_char pci_irq = 0, found;
u_int nbseek, seekcard;
printk(KERN_WARNING "Gazel: PCI card automatic recognition\n");
found = 0;
seekcard = PCI_DEVICE_ID_PLX_R685;
for (nbseek = 0; nbseek < 4; nbseek++) {
if ((dev_tel = pci_find_device(PCI_VENDOR_ID_PLX,
seekcard, dev_tel))) {
if (pci_enable_device(dev_tel))
return 1;
pci_irq = dev_tel->irq;
pci_ioaddr0 = pci_resource_start(dev_tel, 1);
pci_ioaddr1 = pci_resource_start(dev_tel, 2);
found = 1;
}
if (found)
break;
else {
switch (seekcard) {
case PCI_DEVICE_ID_PLX_R685:
seekcard = PCI_DEVICE_ID_PLX_R753;
break;
case PCI_DEVICE_ID_PLX_R753:
seekcard = PCI_DEVICE_ID_PLX_DJINN_ITOO;
break;
case PCI_DEVICE_ID_PLX_DJINN_ITOO:
seekcard = PCI_DEVICE_ID_PLX_OLITEC;
break;
}
}
}
if (!found) {
printk(KERN_WARNING "Gazel: No PCI card found\n");
return (1);
}
if (!pci_irq) {
printk(KERN_WARNING "Gazel: No IRQ for PCI card found\n");
return 1;
}
cs->hw.gazel.pciaddr[0] = pci_ioaddr0;
cs->hw.gazel.pciaddr[1] = pci_ioaddr1;
setup_isac(cs);
pci_ioaddr1 &= 0xfffe;
cs->hw.gazel.cfg_reg = pci_ioaddr0 & 0xfffe;
cs->hw.gazel.ipac = pci_ioaddr1;
cs->hw.gazel.isac = pci_ioaddr1 + 0x80;
cs->hw.gazel.hscx[0] = pci_ioaddr1;
cs->hw.gazel.hscx[1] = pci_ioaddr1 + 0x40;
cs->hw.gazel.isacfifo = cs->hw.gazel.isac;
cs->hw.gazel.hscxfifo[0] = cs->hw.gazel.hscx[0];
cs->hw.gazel.hscxfifo[1] = cs->hw.gazel.hscx[1];
cs->irq = pci_irq;
cs->irq_flags |= SA_SHIRQ;
switch (seekcard) {
case PCI_DEVICE_ID_PLX_R685:
printk(KERN_INFO "Gazel: Card PCI R685 found\n");
cs->subtyp = R685;
cs->dc.isac.adf2 = 0x87;
printk(KERN_INFO
"Gazel: config irq:%d isac:0x%X cfg:0x%X\n",
cs->irq, cs->hw.gazel.isac, cs->hw.gazel.cfg_reg);
printk(KERN_INFO
"Gazel: hscx A:0x%X hscx B:0x%X\n",
cs->hw.gazel.hscx[0], cs->hw.gazel.hscx[1]);
break;
case PCI_DEVICE_ID_PLX_R753:
case PCI_DEVICE_ID_PLX_DJINN_ITOO:
case PCI_DEVICE_ID_PLX_OLITEC:
printk(KERN_INFO "Gazel: Card PCI R753 found\n");
cs->subtyp = R753;
test_and_set_bit(HW_IPAC, &cs->HW_Flags);
printk(KERN_INFO
"Gazel: config irq:%d ipac:0x%X cfg:0x%X\n",
cs->irq, cs->hw.gazel.ipac, cs->hw.gazel.cfg_reg);
break;
}
return (0);
}
int __init
setup_gazel(struct IsdnCard *card)
{
struct IsdnCardState *cs = card->cs;
char tmp[64];
u_char val;
strcpy(tmp, gazel_revision);
printk(KERN_INFO "Gazel: Driver Revision %s\n", HiSax_getrev(tmp));
if (cs->typ != ISDN_CTYPE_GAZEL)
return (0);
if (card->para[0]) {
if (setup_gazelisa(card, cs))
return (0);
} else {
#ifdef CONFIG_PCI
if (setup_gazelpci(cs))
return (0);
#else
printk(KERN_WARNING "Gazel: Card PCI requested and NO_PCI_BIOS, unable to config\n");
return (0);
#endif /* CONFIG_PCI */
}
if (reserve_regions(card, cs)) {
return (0);
}
if (reset_gazel(cs)) {
printk(KERN_WARNING "Gazel: wrong IRQ\n");
release_io_gazel(cs);
return (0);
}
cs->readisac = &ReadISAC;
cs->writeisac = &WriteISAC;
cs->readisacfifo = &ReadISACfifo;
cs->writeisacfifo = &WriteISACfifo;
cs->BC_Read_Reg = &ReadHSCX;
cs->BC_Write_Reg = &WriteHSCX;
cs->BC_Send_Data = &hscx_fill_fifo;
cs->cardmsg = &Gazel_card_msg;
switch (cs->subtyp) {
case R647:
case R685:
cs->irq_func = &gazel_interrupt;
ISACVersion(cs, "Gazel:");
if (HscxVersion(cs, "Gazel:")) {
printk(KERN_WARNING
"Gazel: wrong HSCX versions check IO address\n");
release_io_gazel(cs);
return (0);
}
break;
case R742:
case R753:
cs->irq_func = &gazel_interrupt_ipac;
val = ReadISAC(cs, IPAC_ID - 0x80);
printk(KERN_INFO "Gazel: IPAC version %x\n", val);
break;
}
return (1);
}
| zrafa/linuxkernel | linux-2.6.17.new/drivers/isdn/hisax/gazel.c | C | gpl-2.0 | 16,305 |
/*
* arch/x86/kernel/nmi-selftest.c
*
* Testsuite for NMI: IPIs
*
* Started by Don Zickus:
* (using lib/locking-selftest.c as a guide)
*
* Copyright (C) 2011 Red Hat, Inc., Don Zickus <dzickus@redhat.com>
*/
#include <linux/smp.h>
#include <linux/cpumask.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/percpu.h>
#include <asm/apic.h>
#include <asm/nmi.h>
#define SUCCESS 0
#define FAILURE 1
#define TIMEOUT 2
static int __initdata nmi_fail;
/* check to see if NMI IPIs work on this machine */
static DECLARE_BITMAP(nmi_ipi_mask, NR_CPUS) __initdata;
static int __initdata testcase_total;
static int __initdata testcase_successes;
static int __initdata expected_testcase_failures;
static int __initdata unexpected_testcase_failures;
static int __initdata unexpected_testcase_unknowns;
static int __init nmi_unk_cb(unsigned int val, struct pt_regs *regs)
{
unexpected_testcase_unknowns++;
return NMI_HANDLED;
}
static void __init init_nmi_testsuite(void)
{
/* trap all the unknown NMIs we may generate */
register_nmi_handler(NMI_UNKNOWN, nmi_unk_cb, 0, "nmi_selftest_unk");
}
static void __init cleanup_nmi_testsuite(void)
{
unregister_nmi_handler(NMI_UNKNOWN, "nmi_selftest_unk");
}
static int __init test_nmi_ipi_callback(unsigned int val, struct pt_regs *regs)
{
int cpu = raw_smp_processor_id();
if (cpumask_test_and_clear_cpu(cpu, to_cpumask(nmi_ipi_mask)))
return NMI_HANDLED;
return NMI_DONE;
}
static void __init test_nmi_ipi(struct cpumask *mask)
{
unsigned long timeout;
if (register_nmi_handler(NMI_LOCAL, test_nmi_ipi_callback,
NMI_FLAG_FIRST, "nmi_selftest")) {
nmi_fail = FAILURE;
return;
}
/* sync above data before sending NMI */
wmb();
apic->send_IPI_mask(mask, NMI_VECTOR);
/* Don't wait longer than a second */
timeout = USEC_PER_SEC;
while (!cpumask_empty(mask) && timeout--)
udelay(1);
/* What happens if we timeout, do we still unregister?? */
unregister_nmi_handler(NMI_LOCAL, "nmi_selftest");
if (!timeout)
nmi_fail = TIMEOUT;
return;
}
static void __init remote_ipi(void)
{
cpumask_copy(to_cpumask(nmi_ipi_mask), cpu_online_mask);
cpumask_clear_cpu(smp_processor_id(), to_cpumask(nmi_ipi_mask));
if (!cpumask_empty(to_cpumask(nmi_ipi_mask)))
test_nmi_ipi(to_cpumask(nmi_ipi_mask));
}
static void __init local_ipi(void)
{
cpumask_clear(to_cpumask(nmi_ipi_mask));
cpumask_set_cpu(smp_processor_id(), to_cpumask(nmi_ipi_mask));
test_nmi_ipi(to_cpumask(nmi_ipi_mask));
}
static void __init reset_nmi(void)
{
nmi_fail = 0;
}
static void __init dotest(void (*testcase_fn)(void), int expected)
{
testcase_fn();
/*
* Filter out expected failures:
*/
if (nmi_fail != expected) {
unexpected_testcase_failures++;
if (nmi_fail == FAILURE)
printk(KERN_CONT "FAILED |");
else if (nmi_fail == TIMEOUT)
printk(KERN_CONT "TIMEOUT|");
else
printk(KERN_CONT "ERROR |");
dump_stack();
} else {
testcase_successes++;
printk(KERN_CONT " ok |");
}
testcase_total++;
reset_nmi();
}
static inline void __init print_testname(const char *testname)
{
printk("%12s:", testname);
}
void __init nmi_selftest(void)
{
init_nmi_testsuite();
/*
* Run the testsuite:
*/
printk("----------------\n");
printk("| NMI testsuite:\n");
printk("--------------------\n");
print_testname("remote IPI");
dotest(remote_ipi, SUCCESS);
printk(KERN_CONT "\n");
print_testname("local IPI");
dotest(local_ipi, SUCCESS);
printk(KERN_CONT "\n");
cleanup_nmi_testsuite();
if (unexpected_testcase_failures) {
printk("--------------------\n");
printk("BUG: %3d unexpected failures (out of %3d) - debugging disabled! |\n",
unexpected_testcase_failures, testcase_total);
printk("-----------------------------------------------------------------\n");
} else if (expected_testcase_failures && testcase_successes) {
printk("--------------------\n");
printk("%3d out of %3d testcases failed, as expected. |\n",
expected_testcase_failures, testcase_total);
printk("----------------------------------------------------\n");
} else if (expected_testcase_failures && !testcase_successes) {
printk("--------------------\n");
printk("All %3d testcases failed, as expected. |\n",
expected_testcase_failures);
printk("----------------------------------------\n");
} else {
printk("--------------------\n");
printk("Good, all %3d testcases passed! |\n",
testcase_successes);
printk("---------------------------------\n");
}
}
| danielgpalmer/linux-picosam9g45 | arch/x86/kernel/nmi_selftest.c | C | gpl-2.0 | 4,533 |
DROP DATABASE IF EXISTS test;
CREATE DATABASE test;
USE test;
CREATE TABLE `test_empty` (
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE `test_full` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`d` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
INSERT INTO `test_full` (`id`, `d`) VALUES
(1, '2');
| fipar/percona-toolkit | t/pt-table-checksum/samples/empty-table-bug-987393.sql | SQL | gpl-2.0 | 430 |
#ifndef MTL_ORIEN_H
#define MTL_ORIEN_H
namespace mtl {
struct row_orien;
struct column_orien;
struct row_major;
struct column_major;
//: Row Orientation
// This is used in matrix_implementation and in the indexer objects
// to map (row,column) to (major,minor).
struct row_orien {
template <int MM, int NN> struct dims { enum { M = MM, N = NN }; };
typedef row_tag orientation;
typedef row_major constructor_tag;
typedef column_orien transpose_type;
template <class Dim>
static typename Dim::size_type row(Dim d) { return d.first(); }
template <class Dim>
static typename Dim::size_type column(Dim d){ return d.second();}
template <class Dim>
static Dim map(Dim d) { return d; }
};
//: Column Orientation
// This is used in matrix_implementation and in the indexer objects
// to map (row,column) to (minor,major).
struct column_orien {
template <int MM, int NN> struct dims { enum { M = NN, N = MM }; };
typedef column_tag orientation;
typedef row_orien transpose_type;
typedef column_major constructor_tag;
template <class Dim>
static typename Dim::size_type row(Dim d) { return d.second(); }
template <class Dim>
static typename Dim::size_type column(Dim d){ return d.first(); }
#if 0
/* the static dim has already been transposed in matrix.h
so no need to do it here */
template <class Dim>
static typename Dim::transpose_type map(Dim d) { return d.transpose(); }
#else
template <class Dim>
static Dim map(Dim d) { return Dim(d.second(), d.first()); }
#endif
};
} /* namespace mtl */
#endif /* MTL_ORIEN_H */
| dilawar/sesc | src_without_LF/libsesctherm/mtl/orien.h | C | gpl-2.0 | 1,568 |
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* 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 "lastexpress/entities/pascale.h"
#include "lastexpress/game/entities.h"
#include "lastexpress/game/logic.h"
#include "lastexpress/game/object.h"
#include "lastexpress/game/savepoint.h"
#include "lastexpress/game/scenes.h"
#include "lastexpress/game/state.h"
#include "lastexpress/sound/queue.h"
#include "lastexpress/lastexpress.h"
namespace LastExpress {
Pascale::Pascale(LastExpressEngine *engine) : Entity(engine, kEntityPascale) {
ADD_CALLBACK_FUNCTION(Pascale, draw);
ADD_CALLBACK_FUNCTION(Pascale, callbackActionRestaurantOrSalon);
ADD_CALLBACK_FUNCTION(Pascale, callbackActionOnDirection);
ADD_CALLBACK_FUNCTION(Pascale, updateFromTime);
ADD_CALLBACK_FUNCTION(Pascale, updatePosition);
ADD_CALLBACK_FUNCTION(Pascale, playSound);
ADD_CALLBACK_FUNCTION(Pascale, draw2);
ADD_CALLBACK_FUNCTION(Pascale, welcomeSophieAndRebecca);
ADD_CALLBACK_FUNCTION(Pascale, sitSophieAndRebecca);
ADD_CALLBACK_FUNCTION(Pascale, welcomeCath);
ADD_CALLBACK_FUNCTION(Pascale, function11);
ADD_CALLBACK_FUNCTION(Pascale, chapter1);
ADD_CALLBACK_FUNCTION(Pascale, getMessageFromAugustToTyler);
ADD_CALLBACK_FUNCTION(Pascale, sitAnna);
ADD_CALLBACK_FUNCTION(Pascale, welcomeAnna);
ADD_CALLBACK_FUNCTION(Pascale, serveTatianaVassili);
ADD_CALLBACK_FUNCTION(Pascale, chapter1Handler);
ADD_CALLBACK_FUNCTION(Pascale, function18);
ADD_CALLBACK_FUNCTION(Pascale, function19);
ADD_CALLBACK_FUNCTION(Pascale, chapter2);
ADD_CALLBACK_FUNCTION(Pascale, chapter3);
ADD_CALLBACK_FUNCTION(Pascale, chapter3Handler);
ADD_CALLBACK_FUNCTION(Pascale, function23);
ADD_CALLBACK_FUNCTION(Pascale, welcomeAbbot);
ADD_CALLBACK_FUNCTION(Pascale, chapter4);
ADD_CALLBACK_FUNCTION(Pascale, chapter4Handler);
ADD_CALLBACK_FUNCTION(Pascale, function27);
ADD_CALLBACK_FUNCTION(Pascale, messageFromAnna);
ADD_CALLBACK_FUNCTION(Pascale, function29);
ADD_CALLBACK_FUNCTION(Pascale, function30);
ADD_CALLBACK_FUNCTION(Pascale, chapter5);
ADD_CALLBACK_FUNCTION(Pascale, chapter5Handler);
ADD_CALLBACK_FUNCTION(Pascale, function33);
ADD_NULL_FUNCTION();
}
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION_S(1, Pascale, draw)
Entity::draw(savepoint, true);
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(2, Pascale, callbackActionRestaurantOrSalon)
Entity::callbackActionRestaurantOrSalon(savepoint);
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(3, Pascale, callbackActionOnDirection)
if (savepoint.action == kActionExcuseMeCath) {
if (!params->param1) {
getSound()->excuseMe(kEntityPascale);
params->param1 = 1;
}
return;
}
Entity::callbackActionOnDirection(savepoint);
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION_I(4, Pascale, updateFromTime, uint32)
Entity::updateFromTime(savepoint);
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION_NOSETUP(5, Pascale, updatePosition)
Entity::updatePosition(savepoint, true);
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION_S(6, Pascale, playSound)
Entity::playSound(savepoint);
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION_NOSETUP(7, Pascale, draw2)
Entity::draw2(savepoint);
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(8, Pascale, welcomeSophieAndRebecca)
switch (savepoint.action) {
default:
break;
case kActionDefault:
getData()->entityPosition = kPosition_850;
getData()->location = kLocationOutsideCompartment;
setCallback(1);
setup_draw("901");
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
switch (getProgress().chapter) {
default:
break;
case kChapter1:
getSound()->playSound(kEntityPascale, "REB1198", kFlagInvalid, 30);
break;
case kChapter3:
getSound()->playSound(kEntityPascale, "REB3001", kFlagInvalid, 30);
break;
case kChapter4:
getSound()->playSound(kEntityPascale, "REB4001", kFlagInvalid, 30);
break;
}
setCallback(2);
setup_sitSophieAndRebecca();
break;
case 2:
getSavePoints()->push(kEntityPascale, kEntityRebecca, kAction157370960);
setCallback(3);
setup_draw("905");
break;
case 3:
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_5900;
ENTITY_PARAM(0, 4) = 0;
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(9, Pascale, sitSophieAndRebecca)
switch (savepoint.action) {
default:
break;
case kActionExitCompartment:
callbackAction();
break;
case kActionDefault:
getEntities()->drawSequenceLeft(kEntityPascale, "012C1");
getEntities()->drawSequenceLeft(kEntityRebecca, "012C2");
getEntities()->drawSequenceLeft(kEntityTables3, "012C3");
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(10, Pascale, welcomeCath)
switch (savepoint.action) {
default:
break;
case kActionNone:
if (params->param1 && !getSoundQueue()->isBuffered(kEntityPascale))
getEntities()->updatePositionExit(kEntityPascale, kCarRestaurant, 64);
break;
case kActionExitCompartment:
if (!params->param2) {
params->param2 = 1;
getSound()->playSound(kEntityPascale, "HED1001A");
getSound()->playSound(kEntityPlayer, "LIB004");
getScenes()->loadSceneFromPosition(kCarRestaurant, 69);
}
callbackAction();
break;
case kAction4:
if (!params->param1) {
params->param1 = 1;
getSound()->playSound(kEntityPascale, "HED1001");
}
break;
case kActionDefault:
getEntities()->updatePositionEnter(kEntityPascale, kCarRestaurant, 64);
getEntities()->drawSequenceRight(kEntityPascale, "035A");
break;
case kActionDrawScene:
if (params->param1 && getEntities()->isPlayerPosition(kCarRestaurant, 64)) {
getSound()->playSound(kEntityPascale, "HED1001A");
getSound()->playSound(kEntityPlayer, "LIB004");
getScenes()->loadSceneFromPosition(kCarRestaurant, 69);
callbackAction();
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(11, Pascale, function11)
switch (savepoint.action) {
default:
break;
case kActionDefault:
getData()->entityPosition = kPosition_5800;
getData()->location = kLocationOutsideCompartment;
getSavePoints()->push(kEntityPascale, kEntityAugust, kAction168046720);
getSavePoints()->push(kEntityPascale, kEntityAnna, kAction168046720);
getSavePoints()->push(kEntityPascale, kEntityAlexei, kAction168046720);
getEntities()->updatePositionEnter(kEntityPascale, kCarRestaurant, 55);
setCallback(1);
setup_welcomeCath();
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
getSavePoints()->push(kEntityPascale, kEntityAugust, kAction168627977);
getSavePoints()->push(kEntityPascale, kEntityAnna, kAction168627977);
getSavePoints()->push(kEntityPascale, kEntityAlexei, kAction168627977);
getEntities()->updatePositionExit(kEntityPascale, kCarRestaurant, 55);
setCallback(2);
setup_draw("905");
break;
case 2:
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_5900;
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(12, Pascale, chapter1)
switch (savepoint.action) {
default:
break;
case kActionNone:
setup_chapter1Handler();
break;
case kActionDefault:
getSavePoints()->addData(kEntityPascale, kAction239072064, 0);
getSavePoints()->addData(kEntityPascale, kAction257489762, 2);
getSavePoints()->addData(kEntityPascale, kAction207769280, 6);
getSavePoints()->addData(kEntityPascale, kAction101824388, 7);
getSavePoints()->addData(kEntityPascale, kAction136059947, 8);
getSavePoints()->addData(kEntityPascale, kAction223262556, 1);
getSavePoints()->addData(kEntityPascale, kAction269479296, 3);
getSavePoints()->addData(kEntityPascale, kAction352703104, 4);
getSavePoints()->addData(kEntityPascale, kAction352768896, 5);
getSavePoints()->addData(kEntityPascale, kAction191604416, 10);
getSavePoints()->addData(kEntityPascale, kAction190605184, 11);
getData()->entityPosition = kPosition_5900;
getData()->location = kLocationOutsideCompartment;
getData()->car = kCarRestaurant;
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(13, Pascale, getMessageFromAugustToTyler)
switch (savepoint.action) {
default:
break;
case kActionDefault:
getData()->entityPosition = kPosition_5800;
getData()->location = kLocationOutsideCompartment;
setCallback(1);
setup_draw("902");
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
if (!ENTITY_PARAM(1, 3)) {
getEntities()->drawSequenceLeft(kEntityPascale, "010E");
getEntities()->drawSequenceLeft(kEntityAugust, "BLANK");
setCallback(2);
setup_playSound("AUG1001");
break;
}
setCallback(3);
setup_draw("905");
break;
case 2:
getEntities()->drawSequenceLeft(kEntityPascale, "010B");
setCallback(3);
setup_draw("905");
break;
case 3:
getData()->entityPosition = kPosition_5900;
getEntities()->clearSequences(kEntityPascale);
getSavePoints()->push(kEntityPascale, kEntityVerges, kActionDeliverMessageToTyler);
ENTITY_PARAM(0, 1) = 0;
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(14, Pascale, sitAnna)
switch (savepoint.action) {
default:
break;
case kActionExitCompartment:
getEntities()->updatePositionExit(kEntityPascale, kCarRestaurant, 62);
callbackAction();
break;
case kActionDefault:
getEntities()->drawSequenceRight(kEntityTables0, "001C3");
getEntities()->drawSequenceRight(kEntityAnna, "001C2");
getEntities()->drawSequenceRight(kEntityPascale, "001C1");
getEntities()->updatePositionEnter(kEntityPascale, kCarRestaurant, 62);
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(15, Pascale, welcomeAnna)
switch (savepoint.action) {
default:
break;
case kActionDefault:
getData()->entityPosition = kPosition_5800;
getData()->location = kLocationOutsideCompartment;
setCallback(1);
setup_draw("901");
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
getSound()->playSound(kEntityPascale, "ANN1047");
setCallback(2);
setup_sitAnna();
break;
case 2:
getSavePoints()->push(kEntityPascale, kEntityAnna, kAction157370960);
setCallback(3);
setup_draw("904");
break;
case 3:
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_5900;
ENTITY_PARAM(0, 2) = 0;
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(16, Pascale, serveTatianaVassili)
switch (savepoint.action) {
default:
break;
case kActionDefault:
getData()->entityPosition = kPosition_5800;
getData()->location = kLocationOutsideCompartment;
setCallback(1);
setup_draw("903");
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
getSavePoints()->push(kEntityPascale, kEntityTatiana, kAction122358304);
getEntities()->drawSequenceLeft(kEntityPascale, "014B");
getEntities()->updatePositionEnter(kEntityPascale, kCarRestaurant, 67);
if (getSoundQueue()->isBuffered("TAT1069A"))
getSoundQueue()->processEntry("TAT1069A");
else if (getSoundQueue()->isBuffered("TAT1069B"))
getSoundQueue()->processEntry("TAT1069B");
setCallback(2);
setup_playSound("TAT1066");
break;
case 2:
getEntities()->updatePositionExit(kEntityPascale, kCarRestaurant, 67);
getSavePoints()->push(kEntityPascale, kEntityTatiana, kAction122288808);
setCallback(3);
setup_draw("906");
break;
case 3:
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_5900;
ENTITY_PARAM(0, 3) = 0;
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(17, Pascale, chapter1Handler)
switch (savepoint.action) {
default:
break;
case kActionNone:
if (!params->param2) {
if (getEntities()->isPlayerPosition(kCarRestaurant, 69)
|| getEntities()->isPlayerPosition(kCarRestaurant, 70)
|| getEntities()->isPlayerPosition(kCarRestaurant, 71))
params->param2 = 1;
if (!params->param2 && getEntities()->isPlayerPosition(kCarRestaurant, 61))
params->param1 = 1;
}
if (!getEntities()->isInKitchen(kEntityPascale))
break;
if (ENTITY_PARAM(0, 5) && ENTITY_PARAM(0, 6)) {
setup_function18();
break;
}
if (!getEntities()->isSomebodyInsideRestaurantOrSalon())
goto label_callback3;
if (params->param1 && !params->param2 && getEntities()->isPlayerPosition(kCarRestaurant, 61)) {
setCallback(1);
setup_function11();
break;
}
label_callback1:
if (ENTITY_PARAM(0, 1) && !ENTITY_PARAM(1, 3)) {
setCallback(2);
setup_getMessageFromAugustToTyler();
break;
}
label_callback2:
if (ENTITY_PARAM(0, 3)) {
setCallback(3);
setup_serveTatianaVassili();
break;
}
label_callback3:
if (ENTITY_PARAM(0, 2)) {
setCallback(4);
setup_welcomeAnna();
break;
}
label_callback4:
if (ENTITY_PARAM(0, 4)) {
setCallback(5);
setup_welcomeSophieAndRebecca();
}
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
params->param1 = 0;
params->param2 = 1;
goto label_callback1;
case 2:
goto label_callback2;
case 3:
goto label_callback3;
case 4:
goto label_callback4;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(18, Pascale, function18)
if (savepoint.action != kActionNone)
return;
if (getState()->time > kTime1242000 && !params->param1) {
params->param1 = 1;
getSavePoints()->push(kEntityPascale, kEntityServers0, kAction101632192);
getSavePoints()->push(kEntityPascale, kEntityServers1, kAction101632192);
getSavePoints()->push(kEntityPascale, kEntityCooks, kAction101632192);
getSavePoints()->push(kEntityPascale, kEntityVerges, kAction101632192);
setup_function19();
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(19, Pascale, function19)
switch (savepoint.action) {
default:
break;
case kActionNone:
if (!params->param1 && getEntityData(kEntityPlayer)->entityPosition < kPosition_3650) {
getObjects()->update(kObject65, kEntityPlayer, kObjectLocation1, kCursorHandKnock, kCursorHand);
getSavePoints()->push(kEntityPascale, kEntityTables0, kActionDrawTablesWithChairs, "001P");
getSavePoints()->push(kEntityPascale, kEntityTables1, kActionDrawTablesWithChairs, "005J");
getSavePoints()->push(kEntityPascale, kEntityTables2, kActionDrawTablesWithChairs, "009G");
getSavePoints()->push(kEntityPascale, kEntityTables3, kActionDrawTablesWithChairs, "010M");
getSavePoints()->push(kEntityPascale, kEntityTables4, kActionDrawTablesWithChairs, "014F");
getSavePoints()->push(kEntityPascale, kEntityTables5, kActionDrawTablesWithChairs, "024D");
params->param1 = 1;
}
break;
case kActionDefault:
getData()->car = kCarRestaurant;
getData()->entityPosition = kPosition_5900;
getData()->location = kLocationOutsideCompartment;
getEntities()->clearSequences(kEntityPascale);
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(20, Pascale, chapter2)
if (savepoint.action == kActionDefault) {
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_5900;
getData()->location = kLocationOutsideCompartment;
getData()->car = kCarRestaurant;
getData()->clothes = kClothes1;
getData()->inventoryItem = kItemNone;
getObjects()->update(kObject65, kEntityPlayer, kObjectLocationNone, kCursorNormal, kCursorForward);
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(21, Pascale, chapter3)
switch (savepoint.action) {
default:
break;
case kActionNone:
setup_chapter3Handler();
break;
case kActionDefault:
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_5900;
getData()->location = kLocationOutsideCompartment;
getData()->car = kCarRestaurant;
getData()->inventoryItem = kItemNone;
ENTITY_PARAM(0, 4) = 0;
ENTITY_PARAM(0, 7) = 0;
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(22, Pascale, chapter3Handler)
switch (savepoint.action) {
default:
break;
case kActionNone:
if (!getEntities()->isInKitchen(kEntityPascale))
break;
if (ENTITY_PARAM(0, 7)) {
setCallback(1);
setup_function23();
break;
}
label_callback:
if (ENTITY_PARAM(0, 4)) {
setCallback(2);
setup_welcomeSophieAndRebecca();
}
break;
case kActionCallback:
if (getCallback() == 1)
goto label_callback;
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(23, Pascale, function23)
switch (savepoint.action) {
default:
break;
case kActionDefault:
getData()->entityPosition = kPosition_5800;
getData()->location = kLocationOutsideCompartment;
getEntities()->updatePositionEnter(kEntityPascale, kCarRestaurant, 67);
setCallback(1);
setup_welcomeAbbot();
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
getEntities()->updatePositionExit(kEntityPascale, kCarRestaurant, 67);
getSavePoints()->push(kEntityPascale, kEntityAbbot, kAction122288808);
setCallback(2);
setup_draw("906");
break;
case 2:
getData()->entityPosition = kPosition_5900;
ENTITY_PARAM(0, 7) = 0;
getEntities()->clearSequences(kEntityPascale);
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(24, Pascale, welcomeAbbot)
switch (savepoint.action) {
default:
break;
case kActionNone:
if (!params->param1) {
getSound()->playSound(kEntityPascale, "ABB3015A");
params->param1 = 1;
}
break;
case kActionExitCompartment:
callbackAction();
break;
case kAction10:
getSavePoints()->push(kEntityPascale, kEntityTables4, kAction136455232);
break;
case kActionDefault:
getSound()->playSound(kEntityPascale, "ABB3015", kFlagInvalid, 105);
getEntities()->drawSequenceRight(kEntityPascale, "029A1");
getEntities()->drawSequenceRight(kEntityAbbot, "029A2");
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(25, Pascale, chapter4)
switch (savepoint.action) {
default:
break;
case kActionNone:
setup_chapter4Handler();
break;
case kActionDefault:
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_5900;
getData()->location = kLocationOutsideCompartment;
getData()->car = kCarRestaurant;
getData()->inventoryItem = kItemNone;
ENTITY_PARAM(0, 4) = 0;
ENTITY_PARAM(0, 8) = 0;
ENTITY_PARAM(1, 1) = 0;
ENTITY_PARAM(1, 2) = 0;
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(26, Pascale, chapter4Handler)
switch (savepoint.action) {
default:
break;
case kActionNone:
if (getState()->time > kTime2511000 && !params->param4) {
params->param2 = 1;
params->param4 = 1;
}
if (!getEntities()->isInKitchen(kEntityPascale))
break;
if (getEntities()->isSomebodyInsideRestaurantOrSalon()) {
if (ENTITY_PARAM(0, 8)) {
setCallback(1);
setup_function27();
break;
}
label_callback1:
if (ENTITY_PARAM(1, 2) && ENTITY_PARAM(1, 4)) {
if (!params->param3)
params->param3 = (uint)(getState()->time + 9000);
if (params->param5 != kTimeInvalid) {
if (params->param3 < getState()->time) {
params->param5 = kTimeInvalid;
setCallback(2);
setup_messageFromAnna();
break;
}
if (!getEntities()->isInRestaurant(kEntityPlayer) || !params->param5)
params->param5 = (uint)getState()->time;
if (params->param5 < getState()->time) {
params->param5 = kTimeInvalid;
setCallback(2);
setup_messageFromAnna();
break;
}
}
}
label_callback2:
if (params->param1 && !params->param2 && getEntities()->isPlayerPosition(kCarRestaurant, 61)) {
setCallback(3);
setup_function11();
break;
}
}
label_callback3:
if (ENTITY_PARAM(0, 4)) {
setCallback(4);
setup_welcomeSophieAndRebecca();
}
break;
case kActionDefault:
if (getEntities()->isPlayerPosition(kCarRestaurant, 69)
|| getEntities()->isPlayerPosition(kCarRestaurant, 70)
|| getEntities()->isPlayerPosition(kCarRestaurant, 71))
params->param2 = 1;
break;
case kActionDrawScene:
if (!params->param2) {
if (getEntities()->isPlayerPosition(kCarRestaurant, 69)
|| getEntities()->isPlayerPosition(kCarRestaurant, 70)
|| getEntities()->isPlayerPosition(kCarRestaurant, 71))
params->param2 = 1;
if (!params->param2 && getEntities()->isPlayerPosition(kCarRestaurant, 61))
params->param1 = 1;
}
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
goto label_callback1;
case 2:
goto label_callback2;
case 3:
params->param1 = 0;
params->param2 = 1;
goto label_callback3;
}
break;
case kAction201431954:
ENTITY_PARAM(0, 4) = 0;
ENTITY_PARAM(0, 8) = 0;
getSavePoints()->push(kEntityPascale, kEntityTables0, kActionDrawTablesWithChairs, "001P");
getSavePoints()->push(kEntityPascale, kEntityTables1, kActionDrawTablesWithChairs, "005J");
getSavePoints()->push(kEntityPascale, kEntityTables2, kActionDrawTablesWithChairs, "009G");
getSavePoints()->push(kEntityPascale, kEntityTables3, kActionDrawTablesWithChairs, "010M");
getSavePoints()->push(kEntityPascale, kEntityTables4, kActionDrawTablesWithChairs, "014F");
getSavePoints()->push(kEntityPascale, kEntityTables5, kActionDrawTablesWithChairs, "024D");
getData()->entityPosition = kPosition_5900;
getData()->location = kLocationOutsideCompartment;
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(27, Pascale, function27)
switch (savepoint.action) {
default:
break;
case kActionNone:
if (ENTITY_PARAM(1, 1)) {
setCallback(2);
setup_updateFromTime(450);
}
break;
case kActionDefault:
setCallback(1);
setup_function29();
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
getEntities()->clearSequences(kEntityPascale);
break;
case 2:
getSavePoints()->push(kEntityPascale, kEntityCoudert, kAction123712592);
setCallback(3);
setup_callbackActionRestaurantOrSalon();
break;
case 3:
setCallback(4);
setup_function30();
break;
case 4:
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_5900;
ENTITY_PARAM(0, 8) = 0;
ENTITY_PARAM(1, 1) = 0;
ENTITY_PARAM(1, 2) = 1;
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(28, Pascale, messageFromAnna)
switch (savepoint.action) {
default:
break;
case kActionDefault:
getData()->entityPosition = kPosition_5800;
getData()->location = kLocationOutsideCompartment;
setCallback(1);
setup_draw("902");
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
getSavePoints()->push(kEntityPascale, kEntityAugust, kAction122358304);
getEntities()->drawSequenceLeft(kEntityPascale, "010E2");
setCallback(2);
setup_playSound("Aug4001");
break;
case 2:
getSavePoints()->push(kEntityPascale, kEntityAugust, kAction123793792);
setCallback(3);
setup_draw("905");
break;
case 3:
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_5900;
ENTITY_PARAM(1, 2) = 0;
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(29, Pascale, function29)
switch (savepoint.action) {
default:
break;
case kActionDefault:
getData()->entityPosition = kPosition_1540;
getData()->location = kLocationOutsideCompartment;
setCallback(1);
setup_draw("817DD");
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
getEntities()->drawSequenceRight(kEntityPascale, "817DS");
if (getEntities()->isInRestaurant(kEntityPlayer))
getEntities()->updateFrame(kEntityPascale);
setCallback(2);
setup_callbackActionOnDirection();
break;
case 2:
getData()->entityPosition = kPosition_850;
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(30, Pascale, function30)
switch (savepoint.action) {
default:
break;
case kActionDefault:
getData()->entityPosition = kPosition_9270;
getData()->location = kLocationOutsideCompartment;
setCallback(1);
setup_draw("817US");
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
getEntities()->drawSequenceRight(kEntityPascale, "817UD");
if (getEntities()->isInSalon(kEntityPlayer))
getEntities()->updateFrame(kEntityPascale);
setCallback(2);
setup_callbackActionOnDirection();
break;
case 2:
getData()->entityPosition = kPosition_5900;
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(31, Pascale, chapter5)
switch (savepoint.action) {
default:
break;
case kActionNone:
setup_chapter5Handler();
break;
case kActionDefault:
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_3969;
getData()->location = kLocationInsideCompartment;
getData()->car = kCarRestaurant;
getData()->inventoryItem = kItemNone;
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(32, Pascale, chapter5Handler)
if (savepoint.action == kActionProceedChapter5)
setup_function33();
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(33, Pascale, function33)
switch (savepoint.action) {
default:
break;
case kActionNone:
if (params->param4) {
if (Entity::updateParameter(params->param5, getState()->time, 4500)) {
getObjects()->update(kObjectCompartmentG, kEntityPascale, kObjectLocation1, kCursorNormal, kCursorNormal);
setCallback(1);
setup_playSound("Wat5010");
break;
}
}
label_callback1:
if (params->param1) {
if (!Entity::updateParameter(params->param6, getState()->timeTicks, 75))
break;
params->param1 = 0;
params->param2 = 2;
getObjects()->update(kObjectCompartmentG, kEntityPascale, kObjectLocation1, kCursorNormal, kCursorNormal);
}
params->param6 = 0;
break;
case kActionKnock:
case kActionOpenDoor:
if (params->param1) {
getObjects()->update(kObjectCompartmentG, kEntityPascale, kObjectLocation1, kCursorNormal, kCursorNormal);
params->param1 = 0;
setCallback(2);
setup_playSound(getSound()->justCheckingCath());
} else {
setCallback(savepoint.action == kActionKnock ? 3 : 4);
setup_playSound(savepoint.action == kActionKnock ? "LIB012" : "LIB013");
}
break;
case kActionDefault:
getData()->car = kCarRedSleeping;
getData()->entityPosition = kPosition_3050;
getData()->location = kLocationInsideCompartment;
getObjects()->update(kObjectCompartmentG, kEntityPascale, kObjectLocation1, kCursorHandKnock, kCursorHand);
break;
case kActionDrawScene:
if (params->param2 || params->param1) {
params->param1 = 0;
params->param2 = 0;
params->param3 = 0;
getObjects()->update(kObjectCompartmentG, kEntityPascale, kObjectLocation1, kCursorHandKnock, kCursorHand);
}
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
getObjects()->update(kObjectCompartmentG, kEntityPascale, kObjectLocation1, kCursorHandKnock, kCursorHand);
goto label_callback1;
case 2:
getObjects()->update(kObjectCompartmentG, kEntityPascale, kObjectLocation1, kCursorHandKnock, kCursorHand);
break;
case 3:
case 4:
params->param3++;
if (params->param3 == 1 || params->param3 == 2) {
getObjects()->update(kObjectCompartmentG, kEntityPascale, kObjectLocation1, kCursorNormal, kCursorNormal);
setCallback(params->param3 == 1 ? 5 : 6);
setup_playSound(params->param3 == 1 ? "Wat5001" : "Wat5002");
}
break;
case 5:
params->param1 = 1;
getObjects()->update(kObjectCompartmentG, kEntityPascale, kObjectLocation1, kCursorTalk, kCursorNormal);
break;
case 6:
params->param2 = 1;
break;
case 7:
params->param4 = 1;
break;
}
break;
case kAction135800432:
setup_nullfunction();
break;
case kAction169750080:
if (getSoundQueue()->isBuffered(kEntityPascale)) {
params->param4 = 1;
} else {
setCallback(7);
setup_playSound("Wat5002");
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_NULL_FUNCTION(34, Pascale)
} // End of namespace LastExpress
| MaddTheSane/scummvm | engines/lastexpress/entities/pascale.cpp | C++ | gpl-2.0 | 31,531 |
/* Copyright (C) 2002-2013 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C 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.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#ifndef _PTHREAD_H
#define _PTHREAD_H 1
#include <features.h>
#include <endian.h>
#include <sched.h>
#include <time.h>
#include <bits/pthreadtypes.h>
#include <bits/setjmp.h>
#include <bits/wordsize.h>
/* Detach state. */
enum
{
PTHREAD_CREATE_JOINABLE,
#define PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_JOINABLE
PTHREAD_CREATE_DETACHED
#define PTHREAD_CREATE_DETACHED PTHREAD_CREATE_DETACHED
};
/* Mutex types. */
enum
{
PTHREAD_MUTEX_TIMED_NP,
PTHREAD_MUTEX_RECURSIVE_NP,
PTHREAD_MUTEX_ERRORCHECK_NP,
PTHREAD_MUTEX_ADAPTIVE_NP
#if defined __USE_UNIX98 || defined __USE_XOPEN2K8
,
PTHREAD_MUTEX_NORMAL = PTHREAD_MUTEX_TIMED_NP,
PTHREAD_MUTEX_RECURSIVE = PTHREAD_MUTEX_RECURSIVE_NP,
PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP,
PTHREAD_MUTEX_DEFAULT = PTHREAD_MUTEX_NORMAL
#endif
#ifdef __USE_GNU
/* For compatibility. */
, PTHREAD_MUTEX_FAST_NP = PTHREAD_MUTEX_TIMED_NP
#endif
};
#ifdef __USE_XOPEN2K
/* Robust mutex or not flags. */
enum
{
PTHREAD_MUTEX_STALLED,
PTHREAD_MUTEX_STALLED_NP = PTHREAD_MUTEX_STALLED,
PTHREAD_MUTEX_ROBUST,
PTHREAD_MUTEX_ROBUST_NP = PTHREAD_MUTEX_ROBUST
};
#endif
#if defined __USE_POSIX199506 || defined __USE_UNIX98
/* Mutex protocols. */
enum
{
PTHREAD_PRIO_NONE,
PTHREAD_PRIO_INHERIT,
PTHREAD_PRIO_PROTECT
};
#endif
/* Mutex initializers. */
#ifdef __PTHREAD_MUTEX_HAVE_PREV
# define PTHREAD_MUTEX_INITIALIZER \
{ { 0, 0, 0, 0, 0, 0, { 0, 0 } } }
# ifdef __USE_GNU
# define PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP \
{ { 0, 0, 0, 0, PTHREAD_MUTEX_RECURSIVE_NP, 0, { 0, 0 } } }
# define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP \
{ { 0, 0, 0, 0, PTHREAD_MUTEX_ERRORCHECK_NP, 0, { 0, 0 } } }
# define PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP \
{ { 0, 0, 0, 0, PTHREAD_MUTEX_ADAPTIVE_NP, 0, { 0, 0 } } }
# endif
#else
# define PTHREAD_MUTEX_INITIALIZER \
{ { 0, 0, 0, 0, 0, { 0 } } }
# ifdef __USE_GNU
# define PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP \
{ { 0, 0, 0, PTHREAD_MUTEX_RECURSIVE_NP, 0, { 0 } } }
# define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP \
{ { 0, 0, 0, PTHREAD_MUTEX_ERRORCHECK_NP, 0, { 0 } } }
# define PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP \
{ { 0, 0, 0, PTHREAD_MUTEX_ADAPTIVE_NP, 0, { 0 } } }
# endif
#endif
/* Read-write lock types. */
#if defined __USE_UNIX98 || defined __USE_XOPEN2K
enum
{
PTHREAD_RWLOCK_PREFER_READER_NP,
PTHREAD_RWLOCK_PREFER_WRITER_NP,
PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP,
PTHREAD_RWLOCK_DEFAULT_NP = PTHREAD_RWLOCK_PREFER_READER_NP
};
/* Define __PTHREAD_RWLOCK_INT_FLAGS_SHARED to 1 if pthread_rwlock_t
has the shared field. All 64-bit architectures have the shared field
in pthread_rwlock_t. */
#ifndef __PTHREAD_RWLOCK_INT_FLAGS_SHARED
# if __WORDSIZE == 64
# define __PTHREAD_RWLOCK_INT_FLAGS_SHARED 1
# endif
#endif
/* Read-write lock initializers. */
# define PTHREAD_RWLOCK_INITIALIZER \
{ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }
# ifdef __USE_GNU
# ifdef __PTHREAD_RWLOCK_INT_FLAGS_SHARED
# define PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP \
{ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP } }
# else
# if __BYTE_ORDER == __LITTLE_ENDIAN
# define PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP \
{ { 0, 0, 0, 0, 0, 0, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP, \
0, 0, 0, 0 } }
# else
# define PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP \
{ { 0, 0, 0, 0, 0, 0, 0, 0, 0, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP,\
0 } }
# endif
# endif
# endif
#endif /* Unix98 or XOpen2K */
/* Scheduler inheritance. */
enum
{
PTHREAD_INHERIT_SCHED,
#define PTHREAD_INHERIT_SCHED PTHREAD_INHERIT_SCHED
PTHREAD_EXPLICIT_SCHED
#define PTHREAD_EXPLICIT_SCHED PTHREAD_EXPLICIT_SCHED
};
/* Scope handling. */
enum
{
PTHREAD_SCOPE_SYSTEM,
#define PTHREAD_SCOPE_SYSTEM PTHREAD_SCOPE_SYSTEM
PTHREAD_SCOPE_PROCESS
#define PTHREAD_SCOPE_PROCESS PTHREAD_SCOPE_PROCESS
};
/* Process shared or private flag. */
enum
{
PTHREAD_PROCESS_PRIVATE,
#define PTHREAD_PROCESS_PRIVATE PTHREAD_PROCESS_PRIVATE
PTHREAD_PROCESS_SHARED
#define PTHREAD_PROCESS_SHARED PTHREAD_PROCESS_SHARED
};
/* Conditional variable handling. */
#define PTHREAD_COND_INITIALIZER { { 0, 0, 0, 0, 0, (void *) 0, 0, 0 } }
/* Cleanup buffers */
struct _pthread_cleanup_buffer
{
void (*__routine) (void *); /* Function to call. */
void *__arg; /* Its argument. */
int __canceltype; /* Saved cancellation type. */
struct _pthread_cleanup_buffer *__prev; /* Chaining of cleanup functions. */
};
/* Cancellation */
enum
{
PTHREAD_CANCEL_ENABLE,
#define PTHREAD_CANCEL_ENABLE PTHREAD_CANCEL_ENABLE
PTHREAD_CANCEL_DISABLE
#define PTHREAD_CANCEL_DISABLE PTHREAD_CANCEL_DISABLE
};
enum
{
PTHREAD_CANCEL_DEFERRED,
#define PTHREAD_CANCEL_DEFERRED PTHREAD_CANCEL_DEFERRED
PTHREAD_CANCEL_ASYNCHRONOUS
#define PTHREAD_CANCEL_ASYNCHRONOUS PTHREAD_CANCEL_ASYNCHRONOUS
};
#define PTHREAD_CANCELED ((void *) -1)
/* Single execution handling. */
#define PTHREAD_ONCE_INIT 0
#ifdef __USE_XOPEN2K
/* Value returned by 'pthread_barrier_wait' for one of the threads after
the required number of threads have called this function.
-1 is distinct from 0 and all errno constants */
# define PTHREAD_BARRIER_SERIAL_THREAD -1
#endif
__BEGIN_DECLS
/* Create a new thread, starting with execution of START-ROUTINE
getting passed ARG. Creation attributed come from ATTR. The new
handle is stored in *NEWTHREAD. */
extern int pthread_create (pthread_t *__restrict __newthread,
const pthread_attr_t *__restrict __attr,
void *(*__start_routine) (void *),
void *__restrict __arg) __THROWNL __nonnull ((1, 3));
/* Terminate calling thread.
The registered cleanup handlers are called via exception handling
so we cannot mark this function with __THROW.*/
extern void pthread_exit (void *__retval) __attribute__ ((__noreturn__));
/* Make calling thread wait for termination of the thread TH. The
exit status of the thread is stored in *THREAD_RETURN, if THREAD_RETURN
is not NULL.
This function is a cancellation point and therefore not marked with
__THROW. */
extern int pthread_join (pthread_t __th, void **__thread_return);
#ifdef __USE_GNU
/* Check whether thread TH has terminated. If yes return the status of
the thread in *THREAD_RETURN, if THREAD_RETURN is not NULL. */
extern int pthread_tryjoin_np (pthread_t __th, void **__thread_return) __THROW;
/* Make calling thread wait for termination of the thread TH, but only
until TIMEOUT. The exit status of the thread is stored in
*THREAD_RETURN, if THREAD_RETURN is not NULL.
This function is a cancellation point and therefore not marked with
__THROW. */
extern int pthread_timedjoin_np (pthread_t __th, void **__thread_return,
const struct timespec *__abstime);
#endif
/* Indicate that the thread TH is never to be joined with PTHREAD_JOIN.
The resources of TH will therefore be freed immediately when it
terminates, instead of waiting for another thread to perform PTHREAD_JOIN
on it. */
extern int pthread_detach (pthread_t __th) __THROW;
/* Obtain the identifier of the current thread. */
extern pthread_t pthread_self (void) __THROW __attribute__ ((__const__));
/* Compare two thread identifiers. */
extern int pthread_equal (pthread_t __thread1, pthread_t __thread2)
__THROW __attribute__ ((__const__));
/* Thread attribute handling. */
/* Initialize thread attribute *ATTR with default attributes
(detachstate is PTHREAD_JOINABLE, scheduling policy is SCHED_OTHER,
no user-provided stack). */
extern int pthread_attr_init (pthread_attr_t *__attr) __THROW __nonnull ((1));
/* Destroy thread attribute *ATTR. */
extern int pthread_attr_destroy (pthread_attr_t *__attr)
__THROW __nonnull ((1));
/* Get detach state attribute. */
extern int pthread_attr_getdetachstate (const pthread_attr_t *__attr,
int *__detachstate)
__THROW __nonnull ((1, 2));
/* Set detach state attribute. */
extern int pthread_attr_setdetachstate (pthread_attr_t *__attr,
int __detachstate)
__THROW __nonnull ((1));
/* Get the size of the guard area created for stack overflow protection. */
extern int pthread_attr_getguardsize (const pthread_attr_t *__attr,
size_t *__guardsize)
__THROW __nonnull ((1, 2));
/* Set the size of the guard area created for stack overflow protection. */
extern int pthread_attr_setguardsize (pthread_attr_t *__attr,
size_t __guardsize)
__THROW __nonnull ((1));
/* Return in *PARAM the scheduling parameters of *ATTR. */
extern int pthread_attr_getschedparam (const pthread_attr_t *__restrict __attr,
struct sched_param *__restrict __param)
__THROW __nonnull ((1, 2));
/* Set scheduling parameters (priority, etc) in *ATTR according to PARAM. */
extern int pthread_attr_setschedparam (pthread_attr_t *__restrict __attr,
const struct sched_param *__restrict
__param) __THROW __nonnull ((1, 2));
/* Return in *POLICY the scheduling policy of *ATTR. */
extern int pthread_attr_getschedpolicy (const pthread_attr_t *__restrict
__attr, int *__restrict __policy)
__THROW __nonnull ((1, 2));
/* Set scheduling policy in *ATTR according to POLICY. */
extern int pthread_attr_setschedpolicy (pthread_attr_t *__attr, int __policy)
__THROW __nonnull ((1));
/* Return in *INHERIT the scheduling inheritance mode of *ATTR. */
extern int pthread_attr_getinheritsched (const pthread_attr_t *__restrict
__attr, int *__restrict __inherit)
__THROW __nonnull ((1, 2));
/* Set scheduling inheritance mode in *ATTR according to INHERIT. */
extern int pthread_attr_setinheritsched (pthread_attr_t *__attr,
int __inherit)
__THROW __nonnull ((1));
/* Return in *SCOPE the scheduling contention scope of *ATTR. */
extern int pthread_attr_getscope (const pthread_attr_t *__restrict __attr,
int *__restrict __scope)
__THROW __nonnull ((1, 2));
/* Set scheduling contention scope in *ATTR according to SCOPE. */
extern int pthread_attr_setscope (pthread_attr_t *__attr, int __scope)
__THROW __nonnull ((1));
/* Return the previously set address for the stack. */
extern int pthread_attr_getstackaddr (const pthread_attr_t *__restrict
__attr, void **__restrict __stackaddr)
__THROW __nonnull ((1, 2)) __attribute_deprecated__;
/* Set the starting address of the stack of the thread to be created.
Depending on whether the stack grows up or down the value must either
be higher or lower than all the address in the memory block. The
minimal size of the block must be PTHREAD_STACK_MIN. */
extern int pthread_attr_setstackaddr (pthread_attr_t *__attr,
void *__stackaddr)
__THROW __nonnull ((1)) __attribute_deprecated__;
/* Return the currently used minimal stack size. */
extern int pthread_attr_getstacksize (const pthread_attr_t *__restrict
__attr, size_t *__restrict __stacksize)
__THROW __nonnull ((1, 2));
/* Add information about the minimum stack size needed for the thread
to be started. This size must never be less than PTHREAD_STACK_MIN
and must also not exceed the system limits. */
extern int pthread_attr_setstacksize (pthread_attr_t *__attr,
size_t __stacksize)
__THROW __nonnull ((1));
#ifdef __USE_XOPEN2K
/* Return the previously set address for the stack. */
extern int pthread_attr_getstack (const pthread_attr_t *__restrict __attr,
void **__restrict __stackaddr,
size_t *__restrict __stacksize)
__THROW __nonnull ((1, 2, 3));
/* The following two interfaces are intended to replace the last two. They
require setting the address as well as the size since only setting the
address will make the implementation on some architectures impossible. */
extern int pthread_attr_setstack (pthread_attr_t *__attr, void *__stackaddr,
size_t __stacksize) __THROW __nonnull ((1));
#endif
#ifdef __USE_GNU
/* Thread created with attribute ATTR will be limited to run only on
the processors represented in CPUSET. */
extern int pthread_attr_setaffinity_np (pthread_attr_t *__attr,
size_t __cpusetsize,
const cpu_set_t *__cpuset)
__THROW __nonnull ((1, 3));
/* Get bit set in CPUSET representing the processors threads created with
ATTR can run on. */
extern int pthread_attr_getaffinity_np (const pthread_attr_t *__attr,
size_t __cpusetsize,
cpu_set_t *__cpuset)
__THROW __nonnull ((1, 3));
/* Initialize thread attribute *ATTR with attributes corresponding to the
already running thread TH. It shall be called on uninitialized ATTR
and destroyed with pthread_attr_destroy when no longer needed. */
extern int pthread_getattr_np (pthread_t __th, pthread_attr_t *__attr)
__THROW __nonnull ((2));
#endif
/* Functions for scheduling control. */
/* Set the scheduling parameters for TARGET_THREAD according to POLICY
and *PARAM. */
extern int pthread_setschedparam (pthread_t __target_thread, int __policy,
const struct sched_param *__param)
__THROW __nonnull ((3));
/* Return in *POLICY and *PARAM the scheduling parameters for TARGET_THREAD. */
extern int pthread_getschedparam (pthread_t __target_thread,
int *__restrict __policy,
struct sched_param *__restrict __param)
__THROW __nonnull ((2, 3));
/* Set the scheduling priority for TARGET_THREAD. */
extern int pthread_setschedprio (pthread_t __target_thread, int __prio)
__THROW;
#ifdef __USE_GNU
/* Get thread name visible in the kernel and its interfaces. */
extern int pthread_getname_np (pthread_t __target_thread, char *__buf,
size_t __buflen)
__THROW __nonnull ((2));
/* Set thread name visible in the kernel and its interfaces. */
extern int pthread_setname_np (pthread_t __target_thread, const char *__name)
__THROW __nonnull ((2));
#endif
#ifdef __USE_UNIX98
/* Determine level of concurrency. */
extern int pthread_getconcurrency (void) __THROW;
/* Set new concurrency level to LEVEL. */
extern int pthread_setconcurrency (int __level) __THROW;
#endif
#ifdef __USE_GNU
/* Yield the processor to another thread or process.
This function is similar to the POSIX `sched_yield' function but
might be differently implemented in the case of a m-on-n thread
implementation. */
extern int pthread_yield (void) __THROW;
/* Limit specified thread TH to run only on the processors represented
in CPUSET. */
extern int pthread_setaffinity_np (pthread_t __th, size_t __cpusetsize,
const cpu_set_t *__cpuset)
__THROW __nonnull ((3));
/* Get bit set in CPUSET representing the processors TH can run on. */
extern int pthread_getaffinity_np (pthread_t __th, size_t __cpusetsize,
cpu_set_t *__cpuset)
__THROW __nonnull ((3));
#endif
/* Functions for handling initialization. */
/* Guarantee that the initialization function INIT_ROUTINE will be called
only once, even if pthread_once is executed several times with the
same ONCE_CONTROL argument. ONCE_CONTROL must point to a static or
extern variable initialized to PTHREAD_ONCE_INIT.
The initialization functions might throw exception which is why
this function is not marked with __THROW. */
extern int pthread_once (pthread_once_t *__once_control,
void (*__init_routine) (void)) __nonnull ((1, 2));
/* Functions for handling cancellation.
Note that these functions are explicitly not marked to not throw an
exception in C++ code. If cancellation is implemented by unwinding
this is necessary to have the compiler generate the unwind information. */
/* Set cancelability state of current thread to STATE, returning old
state in *OLDSTATE if OLDSTATE is not NULL. */
extern int pthread_setcancelstate (int __state, int *__oldstate);
/* Set cancellation state of current thread to TYPE, returning the old
type in *OLDTYPE if OLDTYPE is not NULL. */
extern int pthread_setcanceltype (int __type, int *__oldtype);
/* Cancel THREAD immediately or at the next possibility. */
extern int pthread_cancel (pthread_t __th);
/* Test for pending cancellation for the current thread and terminate
the thread as per pthread_exit(PTHREAD_CANCELED) if it has been
cancelled. */
extern void pthread_testcancel (void);
/* Cancellation handling with integration into exception handling. */
typedef struct
{
struct
{
__jmp_buf __cancel_jmp_buf;
int __mask_was_saved;
} __cancel_jmp_buf[1];
void *__pad[4];
} __pthread_unwind_buf_t __attribute__ ((__aligned__));
/* No special attributes by default. */
#ifndef __cleanup_fct_attribute
# define __cleanup_fct_attribute
#endif
/* Structure to hold the cleanup handler information. */
struct __pthread_cleanup_frame
{
void (*__cancel_routine) (void *);
void *__cancel_arg;
int __do_it;
int __cancel_type;
};
#if defined __GNUC__ && defined __EXCEPTIONS
# ifdef __cplusplus
/* Class to handle cancellation handler invocation. */
class __pthread_cleanup_class
{
void (*__cancel_routine) (void *);
void *__cancel_arg;
int __do_it;
int __cancel_type;
public:
__pthread_cleanup_class (void (*__fct) (void *), void *__arg)
: __cancel_routine (__fct), __cancel_arg (__arg), __do_it (1) { }
~__pthread_cleanup_class () { if (__do_it) __cancel_routine (__cancel_arg); }
void __setdoit (int __newval) { __do_it = __newval; }
void __defer () { pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED,
&__cancel_type); }
void __restore () const { pthread_setcanceltype (__cancel_type, 0); }
};
/* Install a cleanup handler: ROUTINE will be called with arguments ARG
when the thread is canceled or calls pthread_exit. ROUTINE will also
be called with arguments ARG when the matching pthread_cleanup_pop
is executed with non-zero EXECUTE argument.
pthread_cleanup_push and pthread_cleanup_pop are macros and must always
be used in matching pairs at the same nesting level of braces. */
# define pthread_cleanup_push(routine, arg) \
do { \
__pthread_cleanup_class __clframe (routine, arg)
/* Remove a cleanup handler installed by the matching pthread_cleanup_push.
If EXECUTE is non-zero, the handler function is called. */
# define pthread_cleanup_pop(execute) \
__clframe.__setdoit (execute); \
} while (0)
# ifdef __USE_GNU
/* Install a cleanup handler as pthread_cleanup_push does, but also
saves the current cancellation type and sets it to deferred
cancellation. */
# define pthread_cleanup_push_defer_np(routine, arg) \
do { \
__pthread_cleanup_class __clframe (routine, arg); \
__clframe.__defer ()
/* Remove a cleanup handler as pthread_cleanup_pop does, but also
restores the cancellation type that was in effect when the matching
pthread_cleanup_push_defer was called. */
# define pthread_cleanup_pop_restore_np(execute) \
__clframe.__restore (); \
__clframe.__setdoit (execute); \
} while (0)
# endif
# else
/* Function called to call the cleanup handler. As an extern inline
function the compiler is free to decide inlining the change when
needed or fall back on the copy which must exist somewhere
else. */
__extern_inline void
__pthread_cleanup_routine (struct __pthread_cleanup_frame *__frame)
{
if (__frame->__do_it)
__frame->__cancel_routine (__frame->__cancel_arg);
}
/* Install a cleanup handler: ROUTINE will be called with arguments ARG
when the thread is canceled or calls pthread_exit. ROUTINE will also
be called with arguments ARG when the matching pthread_cleanup_pop
is executed with non-zero EXECUTE argument.
pthread_cleanup_push and pthread_cleanup_pop are macros and must always
be used in matching pairs at the same nesting level of braces. */
# define pthread_cleanup_push(routine, arg) \
do { \
struct __pthread_cleanup_frame __clframe \
__attribute__ ((__cleanup__ (__pthread_cleanup_routine))) \
= { .__cancel_routine = (routine), .__cancel_arg = (arg), \
.__do_it = 1 };
/* Remove a cleanup handler installed by the matching pthread_cleanup_push.
If EXECUTE is non-zero, the handler function is called. */
# define pthread_cleanup_pop(execute) \
__clframe.__do_it = (execute); \
} while (0)
# ifdef __USE_GNU
/* Install a cleanup handler as pthread_cleanup_push does, but also
saves the current cancellation type and sets it to deferred
cancellation. */
# define pthread_cleanup_push_defer_np(routine, arg) \
do { \
struct __pthread_cleanup_frame __clframe \
__attribute__ ((__cleanup__ (__pthread_cleanup_routine))) \
= { .__cancel_routine = (routine), .__cancel_arg = (arg), \
.__do_it = 1 }; \
(void) pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED, \
&__clframe.__cancel_type)
/* Remove a cleanup handler as pthread_cleanup_pop does, but also
restores the cancellation type that was in effect when the matching
pthread_cleanup_push_defer was called. */
# define pthread_cleanup_pop_restore_np(execute) \
(void) pthread_setcanceltype (__clframe.__cancel_type, NULL); \
__clframe.__do_it = (execute); \
} while (0)
# endif
# endif
#else
/* Install a cleanup handler: ROUTINE will be called with arguments ARG
when the thread is canceled or calls pthread_exit. ROUTINE will also
be called with arguments ARG when the matching pthread_cleanup_pop
is executed with non-zero EXECUTE argument.
pthread_cleanup_push and pthread_cleanup_pop are macros and must always
be used in matching pairs at the same nesting level of braces. */
# define pthread_cleanup_push(routine, arg) \
do { \
__pthread_unwind_buf_t __cancel_buf; \
void (*__cancel_routine) (void *) = (routine); \
void *__cancel_arg = (arg); \
int __not_first_call = __sigsetjmp ((struct __jmp_buf_tag *) (void *) \
__cancel_buf.__cancel_jmp_buf, 0); \
if (__glibc_unlikely (__not_first_call)) \
{ \
__cancel_routine (__cancel_arg); \
__pthread_unwind_next (&__cancel_buf); \
/* NOTREACHED */ \
} \
\
__pthread_register_cancel (&__cancel_buf); \
do {
extern void __pthread_register_cancel (__pthread_unwind_buf_t *__buf)
__cleanup_fct_attribute;
/* Remove a cleanup handler installed by the matching pthread_cleanup_push.
If EXECUTE is non-zero, the handler function is called. */
# define pthread_cleanup_pop(execute) \
do { } while (0);/* Empty to allow label before pthread_cleanup_pop. */\
} while (0); \
__pthread_unregister_cancel (&__cancel_buf); \
if (execute) \
__cancel_routine (__cancel_arg); \
} while (0)
extern void __pthread_unregister_cancel (__pthread_unwind_buf_t *__buf)
__cleanup_fct_attribute;
# ifdef __USE_GNU
/* Install a cleanup handler as pthread_cleanup_push does, but also
saves the current cancellation type and sets it to deferred
cancellation. */
# define pthread_cleanup_push_defer_np(routine, arg) \
do { \
__pthread_unwind_buf_t __cancel_buf; \
void (*__cancel_routine) (void *) = (routine); \
void *__cancel_arg = (arg); \
int __not_first_call = __sigsetjmp ((struct __jmp_buf_tag *) (void *) \
__cancel_buf.__cancel_jmp_buf, 0); \
if (__glibc_unlikely (__not_first_call)) \
{ \
__cancel_routine (__cancel_arg); \
__pthread_unwind_next (&__cancel_buf); \
/* NOTREACHED */ \
} \
\
__pthread_register_cancel_defer (&__cancel_buf); \
do {
extern void __pthread_register_cancel_defer (__pthread_unwind_buf_t *__buf)
__cleanup_fct_attribute;
/* Remove a cleanup handler as pthread_cleanup_pop does, but also
restores the cancellation type that was in effect when the matching
pthread_cleanup_push_defer was called. */
# define pthread_cleanup_pop_restore_np(execute) \
do { } while (0);/* Empty to allow label before pthread_cleanup_pop. */\
} while (0); \
__pthread_unregister_cancel_restore (&__cancel_buf); \
if (execute) \
__cancel_routine (__cancel_arg); \
} while (0)
extern void __pthread_unregister_cancel_restore (__pthread_unwind_buf_t *__buf)
__cleanup_fct_attribute;
# endif
/* Internal interface to initiate cleanup. */
extern void __pthread_unwind_next (__pthread_unwind_buf_t *__buf)
__cleanup_fct_attribute __attribute__ ((__noreturn__))
# ifndef SHARED
__attribute__ ((__weak__))
# endif
;
#endif
/* Function used in the macros. */
struct __jmp_buf_tag;
extern int __sigsetjmp (struct __jmp_buf_tag *__env, int __savemask) __THROWNL;
/* Mutex handling. */
/* Initialize a mutex. */
extern int pthread_mutex_init (pthread_mutex_t *__mutex,
const pthread_mutexattr_t *__mutexattr)
__THROW __nonnull ((1));
/* Destroy a mutex. */
extern int pthread_mutex_destroy (pthread_mutex_t *__mutex)
__THROW __nonnull ((1));
/* Try locking a mutex. */
extern int pthread_mutex_trylock (pthread_mutex_t *__mutex)
__THROWNL __nonnull ((1));
/* Lock a mutex. */
extern int pthread_mutex_lock (pthread_mutex_t *__mutex)
__THROWNL __nonnull ((1));
#ifdef __USE_XOPEN2K
/* Wait until lock becomes available, or specified time passes. */
extern int pthread_mutex_timedlock (pthread_mutex_t *__restrict __mutex,
const struct timespec *__restrict
__abstime) __THROWNL __nonnull ((1, 2));
#endif
/* Unlock a mutex. */
extern int pthread_mutex_unlock (pthread_mutex_t *__mutex)
__THROWNL __nonnull ((1));
/* Get the priority ceiling of MUTEX. */
extern int pthread_mutex_getprioceiling (const pthread_mutex_t *
__restrict __mutex,
int *__restrict __prioceiling)
__THROW __nonnull ((1, 2));
/* Set the priority ceiling of MUTEX to PRIOCEILING, return old
priority ceiling value in *OLD_CEILING. */
extern int pthread_mutex_setprioceiling (pthread_mutex_t *__restrict __mutex,
int __prioceiling,
int *__restrict __old_ceiling)
__THROW __nonnull ((1, 3));
#ifdef __USE_XOPEN2K8
/* Declare the state protected by MUTEX as consistent. */
extern int pthread_mutex_consistent (pthread_mutex_t *__mutex)
__THROW __nonnull ((1));
# ifdef __USE_GNU
extern int pthread_mutex_consistent_np (pthread_mutex_t *__mutex)
__THROW __nonnull ((1));
# endif
#endif
/* Functions for handling mutex attributes. */
/* Initialize mutex attribute object ATTR with default attributes
(kind is PTHREAD_MUTEX_TIMED_NP). */
extern int pthread_mutexattr_init (pthread_mutexattr_t *__attr)
__THROW __nonnull ((1));
/* Destroy mutex attribute object ATTR. */
extern int pthread_mutexattr_destroy (pthread_mutexattr_t *__attr)
__THROW __nonnull ((1));
/* Get the process-shared flag of the mutex attribute ATTR. */
extern int pthread_mutexattr_getpshared (const pthread_mutexattr_t *
__restrict __attr,
int *__restrict __pshared)
__THROW __nonnull ((1, 2));
/* Set the process-shared flag of the mutex attribute ATTR. */
extern int pthread_mutexattr_setpshared (pthread_mutexattr_t *__attr,
int __pshared)
__THROW __nonnull ((1));
#if defined __USE_UNIX98 || defined __USE_XOPEN2K8
/* Return in *KIND the mutex kind attribute in *ATTR. */
extern int pthread_mutexattr_gettype (const pthread_mutexattr_t *__restrict
__attr, int *__restrict __kind)
__THROW __nonnull ((1, 2));
/* Set the mutex kind attribute in *ATTR to KIND (either PTHREAD_MUTEX_NORMAL,
PTHREAD_MUTEX_RECURSIVE, PTHREAD_MUTEX_ERRORCHECK, or
PTHREAD_MUTEX_DEFAULT). */
extern int pthread_mutexattr_settype (pthread_mutexattr_t *__attr, int __kind)
__THROW __nonnull ((1));
#endif
/* Return in *PROTOCOL the mutex protocol attribute in *ATTR. */
extern int pthread_mutexattr_getprotocol (const pthread_mutexattr_t *
__restrict __attr,
int *__restrict __protocol)
__THROW __nonnull ((1, 2));
/* Set the mutex protocol attribute in *ATTR to PROTOCOL (either
PTHREAD_PRIO_NONE, PTHREAD_PRIO_INHERIT, or PTHREAD_PRIO_PROTECT). */
extern int pthread_mutexattr_setprotocol (pthread_mutexattr_t *__attr,
int __protocol)
__THROW __nonnull ((1));
/* Return in *PRIOCEILING the mutex prioceiling attribute in *ATTR. */
extern int pthread_mutexattr_getprioceiling (const pthread_mutexattr_t *
__restrict __attr,
int *__restrict __prioceiling)
__THROW __nonnull ((1, 2));
/* Set the mutex prioceiling attribute in *ATTR to PRIOCEILING. */
extern int pthread_mutexattr_setprioceiling (pthread_mutexattr_t *__attr,
int __prioceiling)
__THROW __nonnull ((1));
#ifdef __USE_XOPEN2K
/* Get the robustness flag of the mutex attribute ATTR. */
extern int pthread_mutexattr_getrobust (const pthread_mutexattr_t *__attr,
int *__robustness)
__THROW __nonnull ((1, 2));
# ifdef __USE_GNU
extern int pthread_mutexattr_getrobust_np (const pthread_mutexattr_t *__attr,
int *__robustness)
__THROW __nonnull ((1, 2));
# endif
/* Set the robustness flag of the mutex attribute ATTR. */
extern int pthread_mutexattr_setrobust (pthread_mutexattr_t *__attr,
int __robustness)
__THROW __nonnull ((1));
# ifdef __USE_GNU
extern int pthread_mutexattr_setrobust_np (pthread_mutexattr_t *__attr,
int __robustness)
__THROW __nonnull ((1));
# endif
#endif
#if defined __USE_UNIX98 || defined __USE_XOPEN2K
/* Functions for handling read-write locks. */
/* Initialize read-write lock RWLOCK using attributes ATTR, or use
the default values if later is NULL. */
extern int pthread_rwlock_init (pthread_rwlock_t *__restrict __rwlock,
const pthread_rwlockattr_t *__restrict
__attr) __THROW __nonnull ((1));
/* Destroy read-write lock RWLOCK. */
extern int pthread_rwlock_destroy (pthread_rwlock_t *__rwlock)
__THROW __nonnull ((1));
/* Acquire read lock for RWLOCK. */
extern int pthread_rwlock_rdlock (pthread_rwlock_t *__rwlock)
__THROWNL __nonnull ((1));
/* Try to acquire read lock for RWLOCK. */
extern int pthread_rwlock_tryrdlock (pthread_rwlock_t *__rwlock)
__THROWNL __nonnull ((1));
# ifdef __USE_XOPEN2K
/* Try to acquire read lock for RWLOCK or return after specfied time. */
extern int pthread_rwlock_timedrdlock (pthread_rwlock_t *__restrict __rwlock,
const struct timespec *__restrict
__abstime) __THROWNL __nonnull ((1, 2));
# endif
/* Acquire write lock for RWLOCK. */
extern int pthread_rwlock_wrlock (pthread_rwlock_t *__rwlock)
__THROWNL __nonnull ((1));
/* Try to acquire write lock for RWLOCK. */
extern int pthread_rwlock_trywrlock (pthread_rwlock_t *__rwlock)
__THROWNL __nonnull ((1));
# ifdef __USE_XOPEN2K
/* Try to acquire write lock for RWLOCK or return after specfied time. */
extern int pthread_rwlock_timedwrlock (pthread_rwlock_t *__restrict __rwlock,
const struct timespec *__restrict
__abstime) __THROWNL __nonnull ((1, 2));
# endif
/* Unlock RWLOCK. */
extern int pthread_rwlock_unlock (pthread_rwlock_t *__rwlock)
__THROWNL __nonnull ((1));
/* Functions for handling read-write lock attributes. */
/* Initialize attribute object ATTR with default values. */
extern int pthread_rwlockattr_init (pthread_rwlockattr_t *__attr)
__THROW __nonnull ((1));
/* Destroy attribute object ATTR. */
extern int pthread_rwlockattr_destroy (pthread_rwlockattr_t *__attr)
__THROW __nonnull ((1));
/* Return current setting of process-shared attribute of ATTR in PSHARED. */
extern int pthread_rwlockattr_getpshared (const pthread_rwlockattr_t *
__restrict __attr,
int *__restrict __pshared)
__THROW __nonnull ((1, 2));
/* Set process-shared attribute of ATTR to PSHARED. */
extern int pthread_rwlockattr_setpshared (pthread_rwlockattr_t *__attr,
int __pshared)
__THROW __nonnull ((1));
/* Return current setting of reader/writer preference. */
extern int pthread_rwlockattr_getkind_np (const pthread_rwlockattr_t *
__restrict __attr,
int *__restrict __pref)
__THROW __nonnull ((1, 2));
/* Set reader/write preference. */
extern int pthread_rwlockattr_setkind_np (pthread_rwlockattr_t *__attr,
int __pref) __THROW __nonnull ((1));
#endif
/* Functions for handling conditional variables. */
/* Initialize condition variable COND using attributes ATTR, or use
the default values if later is NULL. */
extern int pthread_cond_init (pthread_cond_t *__restrict __cond,
const pthread_condattr_t *__restrict __cond_attr)
__THROW __nonnull ((1));
/* Destroy condition variable COND. */
extern int pthread_cond_destroy (pthread_cond_t *__cond)
__THROW __nonnull ((1));
/* Wake up one thread waiting for condition variable COND. */
extern int pthread_cond_signal (pthread_cond_t *__cond)
__THROWNL __nonnull ((1));
/* Wake up all threads waiting for condition variables COND. */
extern int pthread_cond_broadcast (pthread_cond_t *__cond)
__THROWNL __nonnull ((1));
/* Wait for condition variable COND to be signaled or broadcast.
MUTEX is assumed to be locked before.
This function is a cancellation point and therefore not marked with
__THROW. */
extern int pthread_cond_wait (pthread_cond_t *__restrict __cond,
pthread_mutex_t *__restrict __mutex)
__nonnull ((1, 2));
/* Wait for condition variable COND to be signaled or broadcast until
ABSTIME. MUTEX is assumed to be locked before. ABSTIME is an
absolute time specification; zero is the beginning of the epoch
(00:00:00 GMT, January 1, 1970).
This function is a cancellation point and therefore not marked with
__THROW. */
extern int pthread_cond_timedwait (pthread_cond_t *__restrict __cond,
pthread_mutex_t *__restrict __mutex,
const struct timespec *__restrict __abstime)
__nonnull ((1, 2, 3));
/* Functions for handling condition variable attributes. */
/* Initialize condition variable attribute ATTR. */
extern int pthread_condattr_init (pthread_condattr_t *__attr)
__THROW __nonnull ((1));
/* Destroy condition variable attribute ATTR. */
extern int pthread_condattr_destroy (pthread_condattr_t *__attr)
__THROW __nonnull ((1));
/* Get the process-shared flag of the condition variable attribute ATTR. */
extern int pthread_condattr_getpshared (const pthread_condattr_t *
__restrict __attr,
int *__restrict __pshared)
__THROW __nonnull ((1, 2));
/* Set the process-shared flag of the condition variable attribute ATTR. */
extern int pthread_condattr_setpshared (pthread_condattr_t *__attr,
int __pshared) __THROW __nonnull ((1));
#ifdef __USE_XOPEN2K
/* Get the clock selected for the conditon variable attribute ATTR. */
extern int pthread_condattr_getclock (const pthread_condattr_t *
__restrict __attr,
__clockid_t *__restrict __clock_id)
__THROW __nonnull ((1, 2));
/* Set the clock selected for the conditon variable attribute ATTR. */
extern int pthread_condattr_setclock (pthread_condattr_t *__attr,
__clockid_t __clock_id)
__THROW __nonnull ((1));
#endif
#ifdef __USE_XOPEN2K
/* Functions to handle spinlocks. */
/* Initialize the spinlock LOCK. If PSHARED is nonzero the spinlock can
be shared between different processes. */
extern int pthread_spin_init (pthread_spinlock_t *__lock, int __pshared)
__THROW __nonnull ((1));
/* Destroy the spinlock LOCK. */
extern int pthread_spin_destroy (pthread_spinlock_t *__lock)
__THROW __nonnull ((1));
/* Wait until spinlock LOCK is retrieved. */
extern int pthread_spin_lock (pthread_spinlock_t *__lock)
__THROWNL __nonnull ((1));
/* Try to lock spinlock LOCK. */
extern int pthread_spin_trylock (pthread_spinlock_t *__lock)
__THROWNL __nonnull ((1));
/* Release spinlock LOCK. */
extern int pthread_spin_unlock (pthread_spinlock_t *__lock)
__THROWNL __nonnull ((1));
/* Functions to handle barriers. */
/* Initialize BARRIER with the attributes in ATTR. The barrier is
opened when COUNT waiters arrived. */
extern int pthread_barrier_init (pthread_barrier_t *__restrict __barrier,
const pthread_barrierattr_t *__restrict
__attr, unsigned int __count)
__THROW __nonnull ((1));
/* Destroy a previously dynamically initialized barrier BARRIER. */
extern int pthread_barrier_destroy (pthread_barrier_t *__barrier)
__THROW __nonnull ((1));
/* Wait on barrier BARRIER. */
extern int pthread_barrier_wait (pthread_barrier_t *__barrier)
__THROWNL __nonnull ((1));
/* Initialize barrier attribute ATTR. */
extern int pthread_barrierattr_init (pthread_barrierattr_t *__attr)
__THROW __nonnull ((1));
/* Destroy previously dynamically initialized barrier attribute ATTR. */
extern int pthread_barrierattr_destroy (pthread_barrierattr_t *__attr)
__THROW __nonnull ((1));
/* Get the process-shared flag of the barrier attribute ATTR. */
extern int pthread_barrierattr_getpshared (const pthread_barrierattr_t *
__restrict __attr,
int *__restrict __pshared)
__THROW __nonnull ((1, 2));
/* Set the process-shared flag of the barrier attribute ATTR. */
extern int pthread_barrierattr_setpshared (pthread_barrierattr_t *__attr,
int __pshared)
__THROW __nonnull ((1));
#endif
/* Functions for handling thread-specific data. */
/* Create a key value identifying a location in the thread-specific
data area. Each thread maintains a distinct thread-specific data
area. DESTR_FUNCTION, if non-NULL, is called with the value
associated to that key when the key is destroyed.
DESTR_FUNCTION is not called if the value associated is NULL when
the key is destroyed. */
extern int pthread_key_create (pthread_key_t *__key,
void (*__destr_function) (void *))
__THROW __nonnull ((1));
/* Destroy KEY. */
extern int pthread_key_delete (pthread_key_t __key) __THROW;
/* Return current value of the thread-specific data slot identified by KEY. */
extern void *pthread_getspecific (pthread_key_t __key) __THROW;
/* Store POINTER in the thread-specific data slot identified by KEY. */
extern int pthread_setspecific (pthread_key_t __key,
const void *__pointer) __THROW ;
#ifdef __USE_XOPEN2K
/* Get ID of CPU-time clock for thread THREAD_ID. */
extern int pthread_getcpuclockid (pthread_t __thread_id,
__clockid_t *__clock_id)
__THROW __nonnull ((2));
#endif
/* Install handlers to be called when a new process is created with FORK.
The PREPARE handler is called in the parent process just before performing
FORK. The PARENT handler is called in the parent process just after FORK.
The CHILD handler is called in the child process. Each of the three
handlers can be NULL, meaning that no handler needs to be called at that
point.
PTHREAD_ATFORK can be called several times, in which case the PREPARE
handlers are called in LIFO order (last added with PTHREAD_ATFORK,
first called before FORK), and the PARENT and CHILD handlers are called
in FIFO (first added, first called). */
extern int pthread_atfork (void (*__prepare) (void),
void (*__parent) (void),
void (*__child) (void)) __THROW;
#ifdef __USE_EXTERN_INLINES
/* Optimizations. */
__extern_inline int
__NTH (pthread_equal (pthread_t __thread1, pthread_t __thread2))
{
return __thread1 == __thread2;
}
#endif
__END_DECLS
#endif /* pthread.h */
#ifndef _PTHREAD_H_HPPA_
#define _PTHREAD_H_HPPA_ 1
/* The pthread_cond_t initializer is compatible only with NPTL. We do not
want to be forwards compatible, we eventually want to drop the code
that has to clear the old LT initializer. */
#undef PTHREAD_COND_INITIALIZER
#define PTHREAD_COND_INITIALIZER { { 0, 0, 0, (void *) 0, 0, 0, 0, 0, 0 } }
/* The pthread_mutex_t and pthread_rwlock_t initializers are compatible
only with NPTL. NPTL assumes pthread_rwlock_t is all zero. */
#undef PTHREAD_MUTEX_INITIALIZER
#undef PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
#undef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
#undef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
/* Mutex initializers. */
#define PTHREAD_MUTEX_INITIALIZER \
{ { 0, 0, 0, 0, { 0, 0, 0, 0 }, 0, { 0 }, 0, 0 } }
#ifdef __USE_GNU
# define PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP \
{ { 0, 0, 0, PTHREAD_MUTEX_RECURSIVE_NP, { 0, 0, 0, 0 }, 0, { 0 }, 0, 0 } }
# define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP \
{ { 0, 0, 0, PTHREAD_MUTEX_ERRORCHECK_NP, { 0, 0, 0, 0 }, 0, { 0 }, 0, 0 } }
# define PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP \
{ { 0, 0, 0, PTHREAD_MUTEX_ADAPTIVE_NP, { 0, 0, 0, 0 }, 0, { 0 }, 0, 0 } }
#endif
#undef PTHREAD_RWLOCK_INITIALIZER
#undef PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP
/* Read-write lock initializers. */
#define PTHREAD_RWLOCK_INITIALIZER \
{ { { 0, 0, 0, 0 }, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }
#ifdef __USE_GNU
# define PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP \
{ { { 0, 0, 0, 0 }, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP,\
0, 0, 0 } }
#endif /* Unix98 or XOpen2K */
#endif
| SanDisk-Open-Source/SSD_Dashboard | uefi/userspace/glibc/ports/sysdeps/unix/sysv/linux/hppa/nptl/pthread.h | C | gpl-2.0 | 42,363 |
/*
* Copyright (C) 2002-2015 The DOSBox Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "dosbox.h"
#if C_DEBUG
#include "control.h"
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <curses.h>
#include <string.h>
#include "support.h"
#include "regs.h"
#include "debug.h"
#include "debug_inc.h"
struct _LogGroup {
char const* front;
bool enabled;
};
#include <list>
#include <string>
using namespace std;
#define MAX_LOG_BUFFER 500
static list<string> logBuff;
static list<string>::iterator logBuffPos = logBuff.end();
static _LogGroup loggrp[LOG_MAX]={{"",true},{0,false}};
static FILE* debuglog;
extern int old_cursor_state;
void DEBUG_ShowMsg(char const* format,...) {
char buf[512];
va_list msg;
va_start(msg,format);
vsprintf(buf,format,msg);
va_end(msg);
/* Add newline if not present */
Bitu len=strlen(buf);
if(buf[len-1]!='\n') strcat(buf,"\n");
if(debuglog) fprintf(debuglog,"%s",buf);
if (logBuffPos!=logBuff.end()) {
logBuffPos=logBuff.end();
DEBUG_RefreshPage(0);
// mvwprintw(dbg.win_out,dbg.win_out->_maxy-1, 0, "");
}
logBuff.push_back(buf);
if (logBuff.size() > MAX_LOG_BUFFER)
logBuff.pop_front();
logBuffPos = logBuff.end();
wprintw(dbg.win_out,"%s",buf);
wrefresh(dbg.win_out);
}
void DEBUG_RefreshPage(char scroll) {
if (scroll==-1 && logBuffPos!=logBuff.begin()) logBuffPos--;
else if (scroll==1 && logBuffPos!=logBuff.end()) logBuffPos++;
list<string>::iterator i = logBuffPos;
int maxy, maxx; getmaxyx(dbg.win_out,maxy,maxx);
int rem_lines = maxy;
if(rem_lines == -1) return;
wclear(dbg.win_out);
while (rem_lines > 0 && i!=logBuff.begin()) {
--i;
for (string::size_type posf=0, posl; (posl=(*i).find('\n',posf)) != string::npos ;posf=posl+1)
rem_lines -= (int) ((posl-posf) / maxx) + 1; // len=(posl+1)-posf-1
/* Const cast is needed for pdcurses which has no const char in mvwprintw (bug maybe) */
mvwprintw(dbg.win_out,rem_lines-1, 0, const_cast<char*>((*i).c_str()));
}
mvwprintw(dbg.win_out,maxy-1, 0, "");
wrefresh(dbg.win_out);
}
void LOG::operator() (char const* format, ...){
char buf[512];
va_list msg;
va_start(msg,format);
vsprintf(buf,format,msg);
va_end(msg);
if (d_type>=LOG_MAX) return;
if ((d_severity!=LOG_ERROR) && (!loggrp[d_type].enabled)) return;
DEBUG_ShowMsg("%10u: %s:%s\n",static_cast<Bit32u>(cycle_count),loggrp[d_type].front,buf);
}
static void Draw_RegisterLayout(void) {
mvwaddstr(dbg.win_reg,0,0,"EAX=");
mvwaddstr(dbg.win_reg,1,0,"EBX=");
mvwaddstr(dbg.win_reg,2,0,"ECX=");
mvwaddstr(dbg.win_reg,3,0,"EDX=");
mvwaddstr(dbg.win_reg,0,14,"ESI=");
mvwaddstr(dbg.win_reg,1,14,"EDI=");
mvwaddstr(dbg.win_reg,2,14,"EBP=");
mvwaddstr(dbg.win_reg,3,14,"ESP=");
mvwaddstr(dbg.win_reg,0,28,"DS=");
mvwaddstr(dbg.win_reg,0,38,"ES=");
mvwaddstr(dbg.win_reg,0,48,"FS=");
mvwaddstr(dbg.win_reg,0,58,"GS=");
mvwaddstr(dbg.win_reg,0,68,"SS=");
mvwaddstr(dbg.win_reg,1,28,"CS=");
mvwaddstr(dbg.win_reg,1,38,"EIP=");
mvwaddstr(dbg.win_reg,2,75,"CPL");
mvwaddstr(dbg.win_reg,2,68,"IOPL");
mvwaddstr(dbg.win_reg,1,52,"C Z S O A P D I T ");
}
static void DrawBars(void) {
if (has_colors()) {
attrset(COLOR_PAIR(PAIR_BLACK_BLUE));
}
/* Show the Register bar */
mvaddstr(1-1,0, "---(Register Overview )---");
/* Show the Data Overview bar perhaps with more special stuff in the end */
mvaddstr(6-1,0,"---(Data Overview Scroll: page up/down)---");
/* Show the Code Overview perhaps with special stuff in bar too */
mvaddstr(17-1,0,"---(Code Overview Scroll: up/down )---");
/* Show the Variable Overview bar */
mvaddstr(29-1,0, "---(Variable Overview )---");
/* Show the Output OverView */
mvaddstr(34-1,0, "---(Output Scroll: home/end )---");
attrset(0);
//Match values with below. So we don't need to touch the internal window structures
}
static void MakeSubWindows(void) {
/* The Std output win should go at the bottom */
/* Make all the subwindows */
int win_main_maxy, win_main_maxx; getmaxyx(dbg.win_main,win_main_maxy,win_main_maxx);
int outy=1; //Match values with above
/* The Register window */
dbg.win_reg=subwin(dbg.win_main,4,win_main_maxx,outy,0);
outy+=5; // 6
/* The Data Window */
dbg.win_data=subwin(dbg.win_main,10,win_main_maxx,outy,0);
outy+=11; // 17
/* The Code Window */
dbg.win_code=subwin(dbg.win_main,11,win_main_maxx,outy,0);
outy+=12; // 29
/* The Variable Window */
dbg.win_var=subwin(dbg.win_main,4,win_main_maxx,outy,0);
outy+=5; // 34
/* The Output Window */
dbg.win_out=subwin(dbg.win_main,win_main_maxy-outy,win_main_maxx,outy,0);
if(!dbg.win_reg ||!dbg.win_data || !dbg.win_code || !dbg.win_var || !dbg.win_out) E_Exit("Setting up windows failed");
// dbg.input_y=win_main_maxy-1;
scrollok(dbg.win_out,TRUE);
DrawBars();
Draw_RegisterLayout();
refresh();
}
static void MakePairs(void) {
init_pair(PAIR_BLACK_BLUE, COLOR_BLACK, COLOR_CYAN);
init_pair(PAIR_BYELLOW_BLACK, COLOR_YELLOW /*| FOREGROUND_INTENSITY */, COLOR_BLACK);
init_pair(PAIR_GREEN_BLACK, COLOR_GREEN /*| FOREGROUND_INTENSITY */, COLOR_BLACK);
init_pair(PAIR_BLACK_GREY, COLOR_BLACK /*| FOREGROUND_INTENSITY */, COLOR_WHITE);
init_pair(PAIR_GREY_RED, COLOR_WHITE/*| FOREGROUND_INTENSITY */, COLOR_RED);
}
static void LOG_Destroy(Section*) {
if(debuglog) fclose(debuglog);
}
static void LOG_Init(Section * sec) {
Section_prop * sect=static_cast<Section_prop *>(sec);
const char * blah=sect->Get_string("logfile");
if(blah && blah[0] &&(debuglog = fopen(blah,"wt+"))){
}else{
debuglog=0;
}
sect->AddDestroyFunction(&LOG_Destroy);
char buf[1024];
for (Bitu i=1;i<LOG_MAX;i++) {
strcpy(buf,loggrp[i].front);
buf[strlen(buf)]=0;
lowcase(buf);
loggrp[i].enabled=sect->Get_bool(buf);
}
}
void LOG_StartUp(void) {
/* Setup logging groups */
loggrp[LOG_ALL].front="ALL";
loggrp[LOG_VGA].front="VGA";
loggrp[LOG_VGAGFX].front="VGAGFX";
loggrp[LOG_VGAMISC].front="VGAMISC";
loggrp[LOG_INT10].front="INT10";
loggrp[LOG_SB].front="SBLASTER";
loggrp[LOG_DMACONTROL].front="DMA_CONTROL";
loggrp[LOG_FPU].front="FPU";
loggrp[LOG_CPU].front="CPU";
loggrp[LOG_PAGING].front="PAGING";
loggrp[LOG_FCB].front="FCB";
loggrp[LOG_FILES].front="FILES";
loggrp[LOG_IOCTL].front="IOCTL";
loggrp[LOG_EXEC].front="EXEC";
loggrp[LOG_DOSMISC].front="DOSMISC";
loggrp[LOG_PIT].front="PIT";
loggrp[LOG_KEYBOARD].front="KEYBOARD";
loggrp[LOG_PIC].front="PIC";
loggrp[LOG_MOUSE].front="MOUSE";
loggrp[LOG_BIOS].front="BIOS";
loggrp[LOG_GUI].front="GUI";
loggrp[LOG_MISC].front="MISC";
loggrp[LOG_IO].front="IO";
loggrp[LOG_PCI].front="PCI";
/* Register the log section */
Section_prop * sect=control->AddSection_prop("log",LOG_Init);
Prop_string* Pstring = sect->Add_string("logfile",Property::Changeable::Always,"");
Pstring->Set_help("file where the log messages will be saved to");
char buf[1024];
for (Bitu i=1;i<LOG_MAX;i++) {
strcpy(buf,loggrp[i].front);
lowcase(buf);
Prop_bool* Pbool = sect->Add_bool(buf,Property::Changeable::Always,true);
Pbool->Set_help("Enable/Disable logging of this type.");
}
// MSG_Add("LOG_CONFIGFILE_HELP","Logging related options for the debugger.\n");
}
void DBGUI_StartUp(void) {
/* Start the main window */
dbg.win_main=initscr();
cbreak(); /* take input chars one at a time, no wait for \n */
noecho(); /* don't echo input */
nodelay(dbg.win_main,true);
keypad(dbg.win_main,true);
#ifndef WIN32
printf("\e[8;50;80t");
fflush(NULL);
resizeterm(50,80);
touchwin(dbg.win_main);
#endif
old_cursor_state = curs_set(0);
start_color();
cycle_count=0;
MakePairs();
MakeSubWindows();
}
#endif
| danielrh/dosbox3d | src/debug/debug_gui.cpp | C++ | gpl-2.0 | 8,366 |
/*
* drivers/gpu/drm/omapdrm/omap_plane.c
*
* Copyright (C) 2011 Texas Instruments
* Author: Rob Clark <rob.clark@linaro.org>
*
* 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 published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* 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 "drm_flip_work.h"
#include "omap_drv.h"
#include "omap_dmm_tiler.h"
/* some hackery because omapdss has an 'enum omap_plane' (which would be
* better named omap_plane_id).. and compiler seems unhappy about having
* both a 'struct omap_plane' and 'enum omap_plane'
*/
#define omap_plane _omap_plane
/*
* plane funcs
*/
struct callback {
void (*fxn)(void *);
void *arg;
};
#define to_omap_plane(x) container_of(x, struct omap_plane, base)
struct omap_plane {
struct drm_plane base;
int id; /* TODO rename omap_plane -> omap_plane_id in omapdss so I can use the enum */
const char *name;
struct omap_overlay_info info;
struct omap_drm_apply apply;
/* position/orientation of scanout within the fb: */
struct omap_drm_window win;
bool enabled;
/* last fb that we pinned: */
struct drm_framebuffer *pinned_fb;
uint32_t nformats;
uint32_t formats[32];
struct omap_drm_irq error_irq;
/* for deferring bo unpin's until next post_apply(): */
struct drm_flip_work unpin_work;
// XXX maybe get rid of this and handle vblank in crtc too?
struct callback apply_done_cb;
};
static void unpin_worker(struct drm_flip_work *work, void *val)
{
struct omap_plane *omap_plane =
container_of(work, struct omap_plane, unpin_work);
struct drm_device *dev = omap_plane->base.dev;
/*
* omap_framebuffer_pin/unpin are always called from priv->wq,
* so there's no need for locking here.
*/
omap_framebuffer_unpin(val);
mutex_lock(&dev->mode_config.mutex);
drm_framebuffer_unreference(val);
mutex_unlock(&dev->mode_config.mutex);
}
/* update which fb (if any) is pinned for scanout */
static int update_pin(struct drm_plane *plane, struct drm_framebuffer *fb)
{
struct omap_plane *omap_plane = to_omap_plane(plane);
struct drm_framebuffer *pinned_fb = omap_plane->pinned_fb;
if (pinned_fb != fb) {
int ret = 0;
DBG("%p -> %p", pinned_fb, fb);
if (fb) {
drm_framebuffer_reference(fb);
ret = omap_framebuffer_pin(fb);
}
if (pinned_fb)
drm_flip_work_queue(&omap_plane->unpin_work, pinned_fb);
if (ret) {
dev_err(plane->dev->dev, "could not swap %p -> %p\n",
omap_plane->pinned_fb, fb);
drm_framebuffer_unreference(fb);
omap_plane->pinned_fb = NULL;
return ret;
}
omap_plane->pinned_fb = fb;
}
return 0;
}
static void omap_plane_pre_apply(struct omap_drm_apply *apply)
{
struct omap_plane *omap_plane =
container_of(apply, struct omap_plane, apply);
struct omap_drm_window *win = &omap_plane->win;
struct drm_plane *plane = &omap_plane->base;
struct drm_device *dev = plane->dev;
struct omap_overlay_info *info = &omap_plane->info;
struct drm_crtc *crtc = plane->crtc;
enum omap_channel channel;
bool enabled = omap_plane->enabled && crtc;
bool ilace, replication;
int ret;
DBG("%s, enabled=%d", omap_plane->name, enabled);
/* if fb has changed, pin new fb: */
update_pin(plane, enabled ? plane->fb : NULL);
if (!enabled) {
dispc_ovl_enable(omap_plane->id, false);
return;
}
channel = omap_crtc_channel(crtc);
/* update scanout: */
omap_framebuffer_update_scanout(plane->fb, win, info);
DBG("%dx%d -> %dx%d (%d)", info->width, info->height,
info->out_width, info->out_height,
info->screen_width);
DBG("%d,%d %pad %pad", info->pos_x, info->pos_y,
&info->paddr, &info->p_uv_addr);
/* TODO: */
ilace = false;
replication = false;
dispc_ovl_set_channel_out(omap_plane->id, channel);
/* and finally, update omapdss: */
ret = dispc_ovl_setup(omap_plane->id, info,
replication, omap_crtc_timings(crtc), false);
if (ret) {
dev_err(dev->dev, "dispc_ovl_setup failed: %d\n", ret);
return;
}
dispc_ovl_enable(omap_plane->id, true);
}
static void omap_plane_post_apply(struct omap_drm_apply *apply)
{
struct omap_plane *omap_plane =
container_of(apply, struct omap_plane, apply);
struct drm_plane *plane = &omap_plane->base;
struct omap_drm_private *priv = plane->dev->dev_private;
struct omap_overlay_info *info = &omap_plane->info;
struct callback cb;
cb = omap_plane->apply_done_cb;
omap_plane->apply_done_cb.fxn = NULL;
drm_flip_work_commit(&omap_plane->unpin_work, priv->wq);
if (cb.fxn)
cb.fxn(cb.arg);
if (omap_plane->enabled) {
omap_framebuffer_flush(plane->fb, info->pos_x, info->pos_y,
info->out_width, info->out_height);
}
}
static int apply(struct drm_plane *plane)
{
if (plane->crtc) {
struct omap_plane *omap_plane = to_omap_plane(plane);
return omap_crtc_apply(plane->crtc, &omap_plane->apply);
}
return 0;
}
int omap_plane_mode_set(struct drm_plane *plane,
struct drm_crtc *crtc, struct drm_framebuffer *fb,
int crtc_x, int crtc_y,
unsigned int crtc_w, unsigned int crtc_h,
uint32_t src_x, uint32_t src_y,
uint32_t src_w, uint32_t src_h,
void (*fxn)(void *), void *arg)
{
struct omap_plane *omap_plane = to_omap_plane(plane);
struct omap_drm_window *win = &omap_plane->win;
int i;
/*
* Check whether this plane supports the fb pixel format.
* I don't think this should really be needed, but it looks like the
* drm core only checks the format for planes, not for the crtc. So
* when setting the format for crtc, without this check we would
* get an error later when trying to program the color format into the
* HW.
*/
for (i = 0; i < plane->format_count; i++)
if (fb->pixel_format == plane->format_types[i])
break;
if (i == plane->format_count) {
DBG("Invalid pixel format %s",
drm_get_format_name(fb->pixel_format));
return -EINVAL;
}
win->crtc_x = crtc_x;
win->crtc_y = crtc_y;
win->crtc_w = crtc_w;
win->crtc_h = crtc_h;
/* src values are in Q16 fixed point, convert to integer: */
win->src_x = src_x >> 16;
win->src_y = src_y >> 16;
win->src_w = src_w >> 16;
win->src_h = src_h >> 16;
if (fxn) {
/* omap_crtc should ensure that a new page flip
* isn't permitted while there is one pending:
*/
BUG_ON(omap_plane->apply_done_cb.fxn);
omap_plane->apply_done_cb.fxn = fxn;
omap_plane->apply_done_cb.arg = arg;
}
plane->fb = fb;
plane->crtc = crtc;
return apply(plane);
}
static int omap_plane_update(struct drm_plane *plane,
struct drm_crtc *crtc, struct drm_framebuffer *fb,
int crtc_x, int crtc_y,
unsigned int crtc_w, unsigned int crtc_h,
uint32_t src_x, uint32_t src_y,
uint32_t src_w, uint32_t src_h)
{
struct omap_plane *omap_plane = to_omap_plane(plane);
omap_plane->enabled = true;
if (plane->fb)
drm_framebuffer_unreference(plane->fb);
drm_framebuffer_reference(fb);
/* omap_plane_mode_set() takes adjusted src */
switch (omap_plane->win.rotation & 0xf) {
case BIT(DRM_ROTATE_90):
case BIT(DRM_ROTATE_270):
swap(src_w, src_h);
break;
}
return omap_plane_mode_set(plane, crtc, fb,
crtc_x, crtc_y, crtc_w, crtc_h,
src_x, src_y, src_w, src_h,
NULL, NULL);
}
static int omap_plane_disable(struct drm_plane *plane)
{
struct omap_plane *omap_plane = to_omap_plane(plane);
omap_plane->win.rotation = BIT(DRM_ROTATE_0);
return omap_plane_dpms(plane, DRM_MODE_DPMS_OFF);
}
static void omap_plane_destroy(struct drm_plane *plane)
{
struct omap_plane *omap_plane = to_omap_plane(plane);
DBG("%s", omap_plane->name);
omap_irq_unregister(plane->dev, &omap_plane->error_irq);
omap_plane_disable(plane);
drm_plane_cleanup(plane);
drm_flip_work_cleanup(&omap_plane->unpin_work);
kfree(omap_plane);
}
int omap_plane_dpms(struct drm_plane *plane, int mode)
{
struct omap_plane *omap_plane = to_omap_plane(plane);
bool enabled = (mode == DRM_MODE_DPMS_ON);
int ret = 0;
if (enabled != omap_plane->enabled) {
omap_plane->enabled = enabled;
ret = apply(plane);
}
return ret;
}
/* helper to install properties which are common to planes and crtcs */
void omap_plane_install_properties(struct drm_plane *plane,
struct drm_mode_object *obj)
{
struct drm_device *dev = plane->dev;
struct omap_drm_private *priv = dev->dev_private;
struct drm_property *prop;
if (priv->has_dmm) {
prop = priv->rotation_prop;
if (!prop) {
const struct drm_prop_enum_list props[] = {
{ DRM_ROTATE_0, "rotate-0" },
{ DRM_ROTATE_90, "rotate-90" },
{ DRM_ROTATE_180, "rotate-180" },
{ DRM_ROTATE_270, "rotate-270" },
{ DRM_REFLECT_X, "reflect-x" },
{ DRM_REFLECT_Y, "reflect-y" },
};
prop = drm_property_create_bitmask(dev, 0, "rotation",
props, ARRAY_SIZE(props));
if (prop == NULL)
return;
priv->rotation_prop = prop;
}
drm_object_attach_property(obj, prop, 0);
}
prop = priv->zorder_prop;
if (!prop) {
prop = drm_property_create_range(dev, 0, "zorder", 0, 3);
if (prop == NULL)
return;
priv->zorder_prop = prop;
}
drm_object_attach_property(obj, prop, 0);
}
int omap_plane_set_property(struct drm_plane *plane,
struct drm_property *property, uint64_t val)
{
struct omap_plane *omap_plane = to_omap_plane(plane);
struct omap_drm_private *priv = plane->dev->dev_private;
int ret = -EINVAL;
if (property == priv->rotation_prop) {
DBG("%s: rotation: %02x", omap_plane->name, (uint32_t)val);
omap_plane->win.rotation = val;
ret = apply(plane);
} else if (property == priv->zorder_prop) {
DBG("%s: zorder: %02x", omap_plane->name, (uint32_t)val);
omap_plane->info.zorder = val;
ret = apply(plane);
}
return ret;
}
static const struct drm_plane_funcs omap_plane_funcs = {
.update_plane = omap_plane_update,
.disable_plane = omap_plane_disable,
.destroy = omap_plane_destroy,
.set_property = omap_plane_set_property,
};
static void omap_plane_error_irq(struct omap_drm_irq *irq, uint32_t irqstatus)
{
struct omap_plane *omap_plane =
container_of(irq, struct omap_plane, error_irq);
DRM_ERROR_RATELIMITED("%s: errors: %08x\n", omap_plane->name,
irqstatus);
}
static const char *plane_names[] = {
[OMAP_DSS_GFX] = "gfx",
[OMAP_DSS_VIDEO1] = "vid1",
[OMAP_DSS_VIDEO2] = "vid2",
[OMAP_DSS_VIDEO3] = "vid3",
};
static const uint32_t error_irqs[] = {
[OMAP_DSS_GFX] = DISPC_IRQ_GFX_FIFO_UNDERFLOW,
[OMAP_DSS_VIDEO1] = DISPC_IRQ_VID1_FIFO_UNDERFLOW,
[OMAP_DSS_VIDEO2] = DISPC_IRQ_VID2_FIFO_UNDERFLOW,
[OMAP_DSS_VIDEO3] = DISPC_IRQ_VID3_FIFO_UNDERFLOW,
};
/* initialize plane */
struct drm_plane *omap_plane_init(struct drm_device *dev,
int id, bool private_plane)
{
struct omap_drm_private *priv = dev->dev_private;
struct drm_plane *plane = NULL;
struct omap_plane *omap_plane;
struct omap_overlay_info *info;
int ret;
DBG("%s: priv=%d", plane_names[id], private_plane);
omap_plane = kzalloc(sizeof(*omap_plane), GFP_KERNEL);
if (!omap_plane)
goto fail;
ret = drm_flip_work_init(&omap_plane->unpin_work, 16,
"unpin", unpin_worker);
if (ret) {
dev_err(dev->dev, "could not allocate unpin FIFO\n");
goto fail;
}
omap_plane->nformats = omap_framebuffer_get_formats(
omap_plane->formats, ARRAY_SIZE(omap_plane->formats),
dss_feat_get_supported_color_modes(id));
omap_plane->id = id;
omap_plane->name = plane_names[id];
plane = &omap_plane->base;
omap_plane->apply.pre_apply = omap_plane_pre_apply;
omap_plane->apply.post_apply = omap_plane_post_apply;
omap_plane->error_irq.irqmask = error_irqs[id];
omap_plane->error_irq.irq = omap_plane_error_irq;
omap_irq_register(dev, &omap_plane->error_irq);
drm_plane_init(dev, plane, (1 << priv->num_crtcs) - 1, &omap_plane_funcs,
omap_plane->formats, omap_plane->nformats, private_plane);
omap_plane_install_properties(plane, &plane->base);
/* get our starting configuration, set defaults for parameters
* we don't currently use, etc:
*/
info = &omap_plane->info;
info->rotation_type = OMAP_DSS_ROT_DMA;
info->rotation = OMAP_DSS_ROT_0;
info->global_alpha = 0xff;
info->mirror = 0;
/* Set defaults depending on whether we are a CRTC or overlay
* layer.
* TODO add ioctl to give userspace an API to change this.. this
* will come in a subsequent patch.
*/
if (private_plane)
omap_plane->info.zorder = 0;
else
omap_plane->info.zorder = id;
return plane;
fail:
if (plane)
omap_plane_destroy(plane);
return NULL;
}
| ninjablocks/kernel-VAR-SOM-AMxx | drivers/gpu/drm/omapdrm/omap_plane.c | C | gpl-2.0 | 12,702 |
/*
* Copyright © 2018 Google, Inc.
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER 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 COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Google Author(s): Garret Rieger
*/
#ifndef HB_SUBSET_GLYF_HH
#define HB_SUBSET_GLYF_HH
#include "hb.hh"
#include "hb-subset.hh"
HB_INTERNAL bool
hb_subset_glyf_and_loca (hb_subset_plan_t *plan,
bool *use_short_loca, /* OUT */
hb_blob_t **glyf_prime /* OUT */,
hb_blob_t **loca_prime /* OUT */);
#endif /* HB_SUBSET_GLYF_HH */
| md-5/jdk10 | src/java.desktop/share/native/libfontmanager/harfbuzz/hb-subset-glyf.hh | C++ | gpl-2.0 | 1,511 |
<?php
namespace Drupal\Tests\system\Kernel\Theme;
use Drupal\KernelTests\KernelTestBase;
use Twig\TemplateWrapper;
/**
* Tests Twig namespaces.
*
* @group Theme
*/
class TwigNamespaceTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['twig_theme_test', 'twig_namespace_a', 'twig_namespace_b', 'node'];
/**
* @var \Drupal\Core\Template\TwigEnvironment
*/
protected $twig;
protected function setUp() {
parent::setUp();
\Drupal::service('theme_installer')->install(['test_theme', 'bartik']);
$this->twig = \Drupal::service('twig');
}
/**
* Checks to see if a value is a twig template.
*/
public function assertTwigTemplate($value, $message = '', $group = 'Other') {
$this->assertTrue($value instanceof TemplateWrapper, $message, $group);
}
/**
* Tests template discovery using namespaces.
*/
public function testTemplateDiscovery() {
// Tests resolving namespaced templates in modules.
$this->assertTwigTemplate($this->twig->load('@node/node.html.twig'), 'Found node.html.twig in node module.');
// Tests resolving namespaced templates in themes.
$this->assertTwigTemplate($this->twig->load('@bartik/page.html.twig'), 'Found page.html.twig in Bartik theme.');
}
/**
* Tests template extension and includes using namespaces.
*/
public function testTwigNamespaces() {
// Test twig @extends and @include in template files.
$test = ['#theme' => 'twig_namespace_test'];
$this->setRawContent(\Drupal::service('renderer')->renderRoot($test));
$this->assertText('This line is from twig_namespace_a/templates/test.html.twig');
$this->assertText('This line is from twig_namespace_b/templates/test.html.twig');
}
}
| drozas/cecan | core/modules/system/tests/src/Kernel/Theme/TwigNamespaceTest.php | PHP | gpl-2.0 | 1,783 |
function widget:GetInfo()
return {
name = "Lua Metal Decals",
desc = "Draws a decal on each metal spot",
author = "Bluestone (based on the Lua Metal Spots widget by Cheesecan)",
date = "April 2014",
license = "GPL v3 or later",
layer = 5,
enabled = true -- loaded by default?
}
end
local MEX_TEXTURE = "luaui/images/metal_spot.png"
local MEX_WIDTH = 80
local MEX_HEIGHT = 80
local displayList = 0
local mexRotation = {}
function drawPatches()
local mSpots = WG.metalSpots
-- Switch to texture matrix mode
gl.MatrixMode(GL.TEXTURE)
gl.PolygonOffset(-25, -2)
gl.Culling(GL.BACK)
gl.DepthTest(true)
gl.Texture(MEX_TEXTURE)
gl.Color(1, 1, 1, 0.85) -- fix color from other widgets
for i = 1, #mSpots do
mexRotation[i] = mexRotation[i] or math.random(0, 360)
gl.PushMatrix()
gl.Translate(0.5, 0.5, 0)
gl.Rotate(mexRotation[i], 0, 0, 1)
gl.DrawGroundQuad(mSpots[i].x - MEX_WIDTH/2, mSpots[i].z - MEX_HEIGHT/2, mSpots[i].x + MEX_WIDTH/2, mSpots[i].z + MEX_HEIGHT/2, false, -0.5, -0.5, 0.5, 0.5)
gl.PopMatrix()
end
gl.Texture(false)
gl.DepthTest(false)
gl.Culling(false)
gl.PolygonOffset(false)
-- Restore Modelview matrix
gl.MatrixMode(GL.MODELVIEW)
end
function widget:DrawWorldPreUnit()
local mode = Spring.GetMapDrawMode()
if (mode ~= "height" and mode ~= "path") then
gl.CallList(displayList)
end
end
function widget:Initialize()
if not (WG.metalSpots and Spring.GetGameRulesParam("mex_need_drawing")) then
widgetHandler:RemoveWidget(self)
return
end
displayList = gl.CreateList(drawPatches)
end
function widget:GameFrame(n)
if n%15 == 0 then
-- Update display to take terraform into account
displayList = gl.CreateList(drawPatches)
end
end
function widget:Shutdown()
gl.DeleteList(displayList)
end
| RyMarq/Zero-K | LuaUI/Widgets/gfx_dynamic_metal.lua | Lua | gpl-2.0 | 1,810 |
INCLUDE(CheckCSourceCompiles)
MACRO(CHECK_VARIABLE_IN_HEADERS _SYMBOL _HEADER _RESULT)
SET(_INCLUDE_FILES)
FOREACH (it ${_HEADER})
SET(_INCLUDE_FILES "${_INCLUDE_FILES}#include <${it}>\n")
ENDFOREACH (it)
SET(_CHECK_PROTO_EXISTS_SOURCE_CODE "
${_INCLUDE_FILES}
void cmakeRequireSymbol(int dummy,...){(void)dummy;}
int main()
{
int i = ${_SYMBOL};
return 0;
}
")
CHECK_C_SOURCE_COMPILES("${_CHECK_PROTO_EXISTS_SOURCE_CODE}" ${_RESULT})
IF("${_RESULT}")
FILE(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
"Variable ${_SYMBOL} was found in headers\n")
ELSE("${_RESULT}")
FILE(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
"Failed to find variable ${_SYMBOL}. Source: ${_CHECK_PROTO_EXISTS_SOURCE_CODE}\n")
ENDIF("${_RESULT}")
ENDMACRO(CHECK_VARIABLE_IN_HEADERS _SYMBOL _HEADER _RESULT)
| overmetal61/ettercap_debug | cmake/Modules/CheckVariableInHeaders.cmake | CMake | gpl-2.0 | 865 |
#include "git-compat-util.h"
#include "cache.h"
#include "branch.h"
#include "refs.h"
#include "remote.h"
#include "commit.h"
#include "worktree.h"
struct tracking {
struct refspec spec;
char *src;
const char *remote;
int matches;
};
static int find_tracked_branch(struct remote *remote, void *priv)
{
struct tracking *tracking = priv;
if (!remote_find_tracking(remote, &tracking->spec)) {
if (++tracking->matches == 1) {
tracking->src = tracking->spec.src;
tracking->remote = remote->name;
} else {
free(tracking->spec.src);
if (tracking->src) {
free(tracking->src);
tracking->src = NULL;
}
}
tracking->spec.src = NULL;
}
return 0;
}
static int should_setup_rebase(const char *origin)
{
switch (autorebase) {
case AUTOREBASE_NEVER:
return 0;
case AUTOREBASE_LOCAL:
return origin == NULL;
case AUTOREBASE_REMOTE:
return origin != NULL;
case AUTOREBASE_ALWAYS:
return 1;
}
return 0;
}
void install_branch_config(int flag, const char *local, const char *origin, const char *remote)
{
const char *shortname = NULL;
struct strbuf key = STRBUF_INIT;
int rebasing = should_setup_rebase(origin);
if (skip_prefix(remote, "refs/heads/", &shortname)
&& !strcmp(local, shortname)
&& !origin) {
warning(_("Not setting branch %s as its own upstream."),
local);
return;
}
strbuf_addf(&key, "branch.%s.remote", local);
git_config_set(key.buf, origin ? origin : ".");
strbuf_reset(&key);
strbuf_addf(&key, "branch.%s.merge", local);
git_config_set(key.buf, remote);
if (rebasing) {
strbuf_reset(&key);
strbuf_addf(&key, "branch.%s.rebase", local);
git_config_set(key.buf, "true");
}
strbuf_release(&key);
if (flag & BRANCH_CONFIG_VERBOSE) {
if (shortname) {
if (origin)
printf_ln(rebasing ?
_("Branch %s set up to track remote branch %s from %s by rebasing.") :
_("Branch %s set up to track remote branch %s from %s."),
local, shortname, origin);
else
printf_ln(rebasing ?
_("Branch %s set up to track local branch %s by rebasing.") :
_("Branch %s set up to track local branch %s."),
local, shortname);
} else {
if (origin)
printf_ln(rebasing ?
_("Branch %s set up to track remote ref %s by rebasing.") :
_("Branch %s set up to track remote ref %s."),
local, remote);
else
printf_ln(rebasing ?
_("Branch %s set up to track local ref %s by rebasing.") :
_("Branch %s set up to track local ref %s."),
local, remote);
}
}
}
/*
* This is called when new_ref is branched off of orig_ref, and tries
* to infer the settings for branch.<new_ref>.{remote,merge} from the
* config.
*/
static int setup_tracking(const char *new_ref, const char *orig_ref,
enum branch_track track, int quiet)
{
struct tracking tracking;
int config_flags = quiet ? 0 : BRANCH_CONFIG_VERBOSE;
memset(&tracking, 0, sizeof(tracking));
tracking.spec.dst = (char *)orig_ref;
if (for_each_remote(find_tracked_branch, &tracking))
return 1;
if (!tracking.matches)
switch (track) {
case BRANCH_TRACK_ALWAYS:
case BRANCH_TRACK_EXPLICIT:
case BRANCH_TRACK_OVERRIDE:
break;
default:
return 1;
}
if (tracking.matches > 1)
return error(_("Not tracking: ambiguous information for ref %s"),
orig_ref);
install_branch_config(config_flags, new_ref, tracking.remote,
tracking.src ? tracking.src : orig_ref);
free(tracking.src);
return 0;
}
int read_branch_desc(struct strbuf *buf, const char *branch_name)
{
char *v = NULL;
struct strbuf name = STRBUF_INIT;
strbuf_addf(&name, "branch.%s.description", branch_name);
if (git_config_get_string(name.buf, &v)) {
strbuf_release(&name);
return -1;
}
strbuf_addstr(buf, v);
free(v);
strbuf_release(&name);
return 0;
}
int validate_new_branchname(const char *name, struct strbuf *ref,
int force, int attr_only)
{
if (strbuf_check_branch_ref(ref, name))
die(_("'%s' is not a valid branch name."), name);
if (!ref_exists(ref->buf))
return 0;
else if (!force && !attr_only)
die(_("A branch named '%s' already exists."), ref->buf + strlen("refs/heads/"));
if (!attr_only) {
const char *head;
unsigned char sha1[20];
head = resolve_ref_unsafe("HEAD", 0, sha1, NULL);
if (!is_bare_repository() && head && !strcmp(head, ref->buf))
die(_("Cannot force update the current branch."));
}
return 1;
}
static int check_tracking_branch(struct remote *remote, void *cb_data)
{
char *tracking_branch = cb_data;
struct refspec query;
memset(&query, 0, sizeof(struct refspec));
query.dst = tracking_branch;
return !remote_find_tracking(remote, &query);
}
static int validate_remote_tracking_branch(char *ref)
{
return !for_each_remote(check_tracking_branch, ref);
}
static const char upstream_not_branch[] =
N_("Cannot setup tracking information; starting point '%s' is not a branch.");
static const char upstream_missing[] =
N_("the requested upstream branch '%s' does not exist");
static const char upstream_advice[] =
N_("\n"
"If you are planning on basing your work on an upstream\n"
"branch that already exists at the remote, you may need to\n"
"run \"git fetch\" to retrieve it.\n"
"\n"
"If you are planning to push out a new local branch that\n"
"will track its remote counterpart, you may want to use\n"
"\"git push -u\" to set the upstream config as you push.");
void create_branch(const char *head,
const char *name, const char *start_name,
int force, int reflog, int clobber_head,
int quiet, enum branch_track track)
{
struct commit *commit;
unsigned char sha1[20];
char *real_ref, msg[PATH_MAX + 20];
struct strbuf ref = STRBUF_INIT;
int forcing = 0;
int dont_change_ref = 0;
int explicit_tracking = 0;
if (track == BRANCH_TRACK_EXPLICIT || track == BRANCH_TRACK_OVERRIDE)
explicit_tracking = 1;
if (validate_new_branchname(name, &ref, force,
track == BRANCH_TRACK_OVERRIDE ||
clobber_head)) {
if (!force)
dont_change_ref = 1;
else
forcing = 1;
}
real_ref = NULL;
if (get_sha1(start_name, sha1)) {
if (explicit_tracking) {
if (advice_set_upstream_failure) {
error(_(upstream_missing), start_name);
advise(_(upstream_advice));
exit(1);
}
die(_(upstream_missing), start_name);
}
die(_("Not a valid object name: '%s'."), start_name);
}
switch (dwim_ref(start_name, strlen(start_name), sha1, &real_ref)) {
case 0:
/* Not branching from any existing branch */
if (explicit_tracking)
die(_(upstream_not_branch), start_name);
break;
case 1:
/* Unique completion -- good, only if it is a real branch */
if (!starts_with(real_ref, "refs/heads/") &&
validate_remote_tracking_branch(real_ref)) {
if (explicit_tracking)
die(_(upstream_not_branch), start_name);
else
real_ref = NULL;
}
break;
default:
die(_("Ambiguous object name: '%s'."), start_name);
break;
}
if ((commit = lookup_commit_reference(sha1)) == NULL)
die(_("Not a valid branch point: '%s'."), start_name);
hashcpy(sha1, commit->object.oid.hash);
if (forcing)
snprintf(msg, sizeof msg, "branch: Reset to %s",
start_name);
else if (!dont_change_ref)
snprintf(msg, sizeof msg, "branch: Created from %s",
start_name);
if (reflog)
log_all_ref_updates = 1;
if (!dont_change_ref) {
struct ref_transaction *transaction;
struct strbuf err = STRBUF_INIT;
transaction = ref_transaction_begin(&err);
if (!transaction ||
ref_transaction_update(transaction, ref.buf,
sha1, forcing ? NULL : null_sha1,
0, msg, &err) ||
ref_transaction_commit(transaction, &err))
die("%s", err.buf);
ref_transaction_free(transaction);
strbuf_release(&err);
}
if (real_ref && track)
setup_tracking(ref.buf + 11, real_ref, track, quiet);
strbuf_release(&ref);
free(real_ref);
}
void remove_branch_state(void)
{
unlink(git_path_cherry_pick_head());
unlink(git_path_revert_head());
unlink(git_path_merge_head());
unlink(git_path_merge_rr());
unlink(git_path_merge_msg());
unlink(git_path_merge_mode());
unlink(git_path_squash_msg());
}
void die_if_checked_out(const char *branch)
{
char *existing;
existing = find_shared_symref("HEAD", branch);
if (existing) {
skip_prefix(branch, "refs/heads/", &branch);
die(_("'%s' is already checked out at '%s'"), branch, existing);
}
}
| formorer/pkg-cgit | git/branch.c | C | gpl-2.0 | 8,331 |
/* Copyright (c) 2009-2011, Code Aurora Forum. 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 version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
*/
#ifndef __ASM__ARCH_CAMERA_H
#define __ASM__ARCH_CAMERA_H
#include <linux/list.h>
#include <linux/poll.h>
#include <linux/cdev.h>
#include <linux/platform_device.h>
#include <linux/wakelock.h>
#include "linux/types.h"
#include <mach/board.h>
#include <media/msm_camera-tenderloin.h>
//#define CONFIG_MSM_CAMERA_DEBUG
#ifdef CONFIG_MSM_CAMERA_DEBUG
#define CDBG(fmt, args...) printk(KERN_INFO "msm_camera: " fmt, ##args)
#else
#define CDBG(fmt, args...) do { } while (0)
#endif
#define MSM_CAMERA_MSG 0
#define MSM_CAMERA_EVT 1
#define NUM_WB_EXP_NEUTRAL_REGION_LINES 4
#define NUM_WB_EXP_STAT_OUTPUT_BUFFERS 3
#define NUM_AUTOFOCUS_MULTI_WINDOW_GRIDS 16
#define NUM_STAT_OUTPUT_BUFFERS 3
#define NUM_AF_STAT_OUTPUT_BUFFERS 3
#define max_control_command_size 150
#define CROP_LEN 36
enum msm_queue {
MSM_CAM_Q_CTRL, /* control command or control command status */
MSM_CAM_Q_VFE_EVT, /* adsp event */
MSM_CAM_Q_VFE_MSG, /* adsp message */
MSM_CAM_Q_V4L2_REQ, /* v4l2 request */
MSM_CAM_Q_VPE_MSG, /* adsp message */
};
enum vfe_resp_msg {
VFE_EVENT,
VFE_MSG_GENERAL,
VFE_MSG_SNAPSHOT,
VFE_MSG_OUTPUT_P, /* preview (continuous mode ) */
VFE_MSG_OUTPUT_T, /* thumbnail (snapshot mode )*/
VFE_MSG_OUTPUT_S, /* main image (snapshot mode )*/
VFE_MSG_OUTPUT_V, /* video (continuous mode ) */
VFE_MSG_STATS_AEC,
VFE_MSG_STATS_AF,
VFE_MSG_STATS_AWB,
VFE_MSG_STATS_RS,
VFE_MSG_STATS_CS,
VFE_MSG_STATS_IHIST,
VFE_MSG_STATS_SKIN,
VFE_MSG_STATS_WE, /* AEC + AWB */
VFE_MSG_SYNC_TIMER0,
VFE_MSG_SYNC_TIMER1,
VFE_MSG_SYNC_TIMER2,
};
enum vpe_resp_msg {
VPE_EVENT,
VPE_MSG_GENERAL,
VPE_MSG_SNAPSHOT,
VPE_MSG_OUTPUT_P, /* preview (continuous mode ) */
VPE_MSG_OUTPUT_T, /* thumbnail (snapshot mode )*/
VPE_MSG_OUTPUT_S, /* main image (snapshot mode )*/
VPE_MSG_OUTPUT_V, /* video (continuous mode ) */
};
struct msm_vpe_phy_info {
uint32_t sbuf_phy;
uint32_t y_phy;
uint32_t cbcr_phy;
uint8_t output_id; /* VFE31_OUTPUT_MODE_PT/S/V */
uint32_t frame_id;
};
#define VFE31_OUTPUT_MODE_PT (0x1 << 0)
#define VFE31_OUTPUT_MODE_S (0x1 << 1)
#define VFE31_OUTPUT_MODE_V (0x1 << 2)
struct msm_vfe_phy_info {
uint32_t sbuf_phy;
uint32_t y_phy;
uint32_t cbcr_phy;
uint8_t output_id; /* VFE31_OUTPUT_MODE_PT/S/V */
uint32_t frame_id;
};
struct video_crop_t{
uint32_t in1_w;
uint32_t out1_w;
uint32_t in1_h;
uint32_t out1_h;
uint32_t in2_w;
uint32_t out2_w;
uint32_t in2_h;
uint32_t out2_h;
uint8_t update_flag;
};
struct msm_vpe_buf_info {
uint32_t y_phy;
uint32_t cbcr_phy;
struct timespec ts;
uint32_t frame_id;
struct video_crop_t vpe_crop;
};
struct msm_vfe_resp {
enum vfe_resp_msg type;
struct msm_vfe_evt_msg evt_msg;
struct msm_vfe_phy_info phy;
struct msm_vpe_buf_info vpe_bf;
void *extdata;
int32_t extlen;
};
struct msm_vpe_resp {
enum vpe_resp_msg type;
struct msm_vpe_evt_msg evt_msg;
struct msm_vpe_phy_info phy;
void *extdata;
int32_t extlen;
};
struct msm_vpe_callback {
void (*vpe_resp)(struct msm_vpe_resp *,
enum msm_queue, void *syncdata,
void *time_stamp, gfp_t gfp);
void* (*vpe_alloc)(int, void *syncdata, gfp_t gfp);
void (*vpe_free)(void *ptr);
};
struct msm_vfe_callback {
void (*vfe_resp)(struct msm_vfe_resp *,
enum msm_queue, void *syncdata,
gfp_t gfp);
void* (*vfe_alloc)(int, void *syncdata, gfp_t gfp);
void (*vfe_free)(void *ptr);
};
struct msm_camvfe_fn {
int (*vfe_init)(struct msm_vfe_callback *, struct platform_device *);
int (*vfe_enable)(struct camera_enable_cmd *);
int (*vfe_config)(struct msm_vfe_cfg_cmd *, void *);
int (*vfe_disable)(struct camera_enable_cmd *,
struct platform_device *dev);
void (*vfe_release)(struct platform_device *);
void (*vfe_stop)(void);
};
struct msm_camvpe_fn {
int (*vpe_reg)(struct msm_vpe_callback *);
int (*vpe_cfg_update) (void *);
void (*send_frame_to_vpe) (uint32_t y_phy, uint32_t cbcr_phy,
struct timespec *ts);
int (*vpe_config)(struct msm_vpe_cfg_cmd *, void *);
int *dis;
};
struct msm_sensor_ctrl {
int (*s_init)(const struct msm_camera_sensor_info *);
int (*s_release)(void);
int (*s_config)(void __user *);
enum msm_camera_type s_camera_type;
uint32_t s_mount_angle;
};
struct msm_strobe_flash_ctrl {
int (*strobe_flash_init)
(struct msm_camera_sensor_strobe_flash_data *);
int (*strobe_flash_release)
(struct msm_camera_sensor_strobe_flash_data *, int32_t);
int (*strobe_flash_charge)(int32_t, int32_t, uint32_t);
};
/* this structure is used in kernel */
struct msm_queue_cmd {
struct list_head list_config;
struct list_head list_control;
struct list_head list_frame;
struct list_head list_pict;
struct list_head list_vpe_frame;
enum msm_queue type;
void *command;
atomic_t on_heap;
struct timespec ts;
uint32_t error_code;
};
struct msm_device_queue {
struct list_head list;
spinlock_t lock;
wait_queue_head_t wait;
int max;
int len;
const char *name;
};
struct msm_sync {
/* These two queues are accessed from a process context only
* They contain pmem descriptors for the preview frames and the stats
* coming from the camera sensor.
*/
struct hlist_head pmem_frames;
struct hlist_head pmem_stats;
/* The message queue is used by the control thread to send commands
* to the config thread, and also by the DSP to send messages to the
* config thread. Thus it is the only queue that is accessed from
* both interrupt and process context.
*/
struct msm_device_queue event_q;
/* This queue contains preview frames. It is accessed by the DSP (in
* in interrupt context, and by the frame thread.
*/
struct msm_device_queue frame_q;
int unblock_poll_frame;
/* This queue contains snapshot frames. It is accessed by the DSP (in
* interrupt context, and by the control thread.
*/
struct msm_device_queue pict_q;
int get_pic_abort;
struct msm_device_queue vpe_q;
struct msm_camera_sensor_info *sdata;
struct msm_camvfe_fn vfefn;
struct msm_camvpe_fn vpefn;
struct msm_sensor_ctrl sctrl;
struct msm_strobe_flash_ctrl sfctrl;
struct wake_lock wake_lock;
struct platform_device *pdev;
int16_t ignore_qcmd_type;
uint8_t ignore_qcmd;
uint8_t opencnt;
void *cropinfo;
int croplen;
int core_powered_on;
struct fd_roi_info fdroiinfo;
atomic_t vpe_enable;
uint32_t pp_mask;
uint8_t pp_frame_avail;
struct msm_queue_cmd *pp_prev;
struct msm_queue_cmd *pp_snap;
struct msm_queue_cmd *pp_thumb;
int video_fd;
const char *apps_id;
struct mutex lock;
struct list_head list;
uint8_t liveshot_enabled;
struct msm_cam_v4l2_device *pcam_sync;
spinlock_t pmem_frame_spinlock;
spinlock_t pmem_stats_spinlock;
spinlock_t abort_pict_lock;
};
#define MSM_APPS_ID_V4L2 "msm_v4l2"
#define MSM_APPS_ID_PROP "msm_qct"
struct msm_cam_device {
struct msm_sync *sync; /* most-frequently accessed */
struct device *device;
struct cdev cdev;
/* opened is meaningful only for the config and frame nodes,
* which may be opened only once.
*/
atomic_t opened;
};
struct msm_control_device {
struct msm_cam_device *pmsm;
/* Used for MSM_CAM_IOCTL_CTRL_CMD_DONE responses */
uint8_t ctrl_data[max_control_command_size];
struct msm_ctrl_cmd ctrl;
struct msm_queue_cmd qcmd;
/* This queue used by the config thread to send responses back to the
* control thread. It is accessed only from a process context.
*/
struct msm_device_queue ctrl_q;
};
struct register_address_value_pair {
uint16_t register_address;
uint16_t register_value;
};
struct msm_pmem_region {
struct hlist_node list;
unsigned long paddr;
unsigned long len;
struct file *file;
struct msm_pmem_info info;
struct ion_handle *handle;
};
struct axidata {
uint32_t bufnum1;
uint32_t bufnum2;
uint32_t bufnum3;
struct msm_pmem_region *region;
};
#ifdef CONFIG_MSM_CAMERA_FLASH
int msm_camera_flash_set_led_state(
struct msm_camera_sensor_flash_data *fdata,
unsigned led_state);
int msm_strobe_flash_init(struct msm_sync *sync, uint32_t sftype);
int msm_flash_ctrl(struct msm_camera_sensor_info *sdata,
struct flash_ctrl_data *flash_info);
#else
static inline int msm_camera_flash_set_led_state(
struct msm_camera_sensor_flash_data *fdata,
unsigned led_state)
{
return -ENOTSUPP;
}
static inline int msm_strobe_flash_init(
struct msm_sync *sync, uint32_t sftype)
{
return -ENOTSUPP;
}
static inline int msm_flash_ctrl(
struct msm_camera_sensor_info *sdata,
struct flash_ctrl_data *flash_info)
{
return -ENOTSUPP;
}
#endif
/* Below functions are added for V4L2 kernel APIs */
struct msm_v4l2_driver {
struct msm_sync *sync;
int (*open)(struct msm_sync *, const char *apps_id, int);
int (*release)(struct msm_sync *);
int (*ctrl)(struct msm_sync *, struct msm_ctrl_cmd *);
int (*reg_pmem)(struct msm_sync *, struct msm_pmem_info *);
int (*get_frame) (struct msm_sync *, struct msm_frame *);
int (*put_frame) (struct msm_sync *, struct msm_frame *);
int (*get_pict) (struct msm_sync *, struct msm_ctrl_cmd *);
unsigned int (*drv_poll) (struct msm_sync *, struct file *,
struct poll_table_struct *);
};
int msm_v4l2_register(struct msm_v4l2_driver *);
int msm_v4l2_unregister(struct msm_v4l2_driver *);
void msm_camvfe_init(void);
int msm_camvfe_check(void *);
void msm_camvfe_fn_init(struct msm_camvfe_fn *, void *);
void msm_camvpe_fn_init(struct msm_camvpe_fn *, void *);
int msm_camera_drv_start(struct platform_device *dev,
int (*sensor_probe)(const struct msm_camera_sensor_info *,
struct msm_sensor_ctrl *));
enum msm_camio_clk_type {
CAMIO_VFE_MDC_CLK,
CAMIO_MDC_CLK,
CAMIO_VFE_CLK,
CAMIO_VFE_AXI_CLK,
CAMIO_VFE_CAMIF_CLK,
CAMIO_VFE_PBDG_CLK,
CAMIO_CAM_MCLK_CLK,
CAMIO_CAMIF_PAD_PBDG_CLK,
CAMIO_CSI0_VFE_CLK,
CAMIO_CSI1_VFE_CLK,
CAMIO_VFE_PCLK,
CAMIO_CSI_SRC_CLK,
CAMIO_CSI0_CLK,
CAMIO_CSI1_CLK,
CAMIO_CSI0_PCLK,
CAMIO_CSI1_PCLK,
CAMIO_JPEG_CLK,
CAMIO_JPEG_PCLK,
CAMIO_VPE_CLK,
CAMIO_VPE_PCLK,
CAMIO_MAX_CLK
};
enum msm_camio_clk_src_type {
MSM_CAMIO_CLK_SRC_INTERNAL,
MSM_CAMIO_CLK_SRC_EXTERNAL,
MSM_CAMIO_CLK_SRC_MAX
};
enum msm_s_test_mode {
S_TEST_OFF,
S_TEST_1,
S_TEST_2,
S_TEST_3
};
enum msm_s_resolution {
S_QTR_SIZE,
S_FULL_SIZE,
S_INVALID_SIZE
};
enum msm_s_reg_update {
/* Sensor egisters that need to be updated during initialization */
S_REG_INIT,
/* Sensor egisters that needs periodic I2C writes */
S_UPDATE_PERIODIC,
/* All the sensor Registers will be updated */
S_UPDATE_ALL,
/* Not valid update */
S_UPDATE_INVALID
};
enum msm_s_setting {
S_RES_PREVIEW,
S_RES_CAPTURE
};
enum msm_bus_perf_setting {
S_INIT,
S_PREVIEW,
S_VIDEO,
S_CAPTURE,
S_DEFAULT,
S_EXIT
};
int msm_camio_enable(struct platform_device *dev);
int msm_camio_jpeg_clk_enable(void);
int msm_camio_jpeg_clk_disable(void);
int msm_camio_vpe_clk_enable(void);
int msm_camio_vpe_clk_disable(void);
int msm_camio_clk_enable(enum msm_camio_clk_type clk);
int msm_camio_clk_disable(enum msm_camio_clk_type clk);
int msm_camio_clk_config(uint32_t freq);
void msm_camio_clk_rate_set(int rate);
void msm_camio_vfe_clk_rate_set(int rate);
void msm_camio_clk_rate_set_2(struct clk *clk, int rate);
void msm_camio_clk_set_min_rate(struct clk *clk, int rate);
void msm_camio_clk_axi_rate_set(int rate);
void msm_camio_vfe_clk_set(enum msm_s_setting);
void msm_disable_io_gpio_clk(struct platform_device *);
void msm_camio_camif_pad_reg_reset(void);
void msm_camio_camif_pad_reg_reset_2(void);
void msm_camio_vfe_blk_reset(void);
void msm_camio_clk_sel(enum msm_camio_clk_src_type);
void msm_camio_disable(struct platform_device *);
int msm_camio_probe_on(struct platform_device *);
int msm_camio_probe_off(struct platform_device *);
int msm_camio_sensor_clk_off(struct platform_device *);
int msm_camio_sensor_clk_on(struct platform_device *);
int msm_camio_csi_config(struct msm_camera_csi_params *csi_params);
int add_axi_qos(void);
int update_axi_qos(uint32_t freq);
void release_axi_qos(void);
void msm_io_w(u32 data, void __iomem *addr);
void msm_io_w_mb(u32 data, void __iomem *addr);
u32 msm_io_r(void __iomem *addr);
u32 msm_io_r_mb(void __iomem *addr);
void msm_io_dump(void __iomem *addr, int size);
void msm_io_memcpy(void __iomem *dest_addr, void __iomem *src_addr, u32 len);
void msm_camio_set_perf_lvl(enum msm_bus_perf_setting);
#endif
| chucktr/android_kernel_htc_msm8960 | arch/arm/mach-msm/include/mach/camera-tenderloin.h | C | gpl-2.0 | 12,982 |
/***************************************************************************
qgsalgorithmlayouttopdf.cpp
---------------------
begin : June 2020
copyright : (C) 2020 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 "qgsalgorithmlayouttopdf.h"
#include "qgslayout.h"
#include "qgslayoutitemmap.h"
#include "qgsprintlayout.h"
#include "qgsprocessingoutputs.h"
#include "qgslayoutexporter.h"
///@cond PRIVATE
QString QgsLayoutToPdfAlgorithm::name() const
{
return QStringLiteral( "printlayouttopdf" );
}
QString QgsLayoutToPdfAlgorithm::displayName() const
{
return QObject::tr( "Export print layout as PDF" );
}
QStringList QgsLayoutToPdfAlgorithm::tags() const
{
return QObject::tr( "layout,composer,composition,save" ).split( ',' );
}
QString QgsLayoutToPdfAlgorithm::group() const
{
return QObject::tr( "Cartography" );
}
QString QgsLayoutToPdfAlgorithm::groupId() const
{
return QStringLiteral( "cartography" );
}
QString QgsLayoutToPdfAlgorithm::shortDescription() const
{
return QObject::tr( "Exports a print layout as a PDF." );
}
QString QgsLayoutToPdfAlgorithm::shortHelpString() const
{
return QObject::tr( "This algorithm outputs a print layout as a PDF file." );
}
void QgsLayoutToPdfAlgorithm::initAlgorithm( const QVariantMap & )
{
addParameter( new QgsProcessingParameterLayout( QStringLiteral( "LAYOUT" ), QObject::tr( "Print layout" ) ) );
std::unique_ptr< QgsProcessingParameterMultipleLayers > layersParam = std::make_unique< QgsProcessingParameterMultipleLayers>( QStringLiteral( "LAYERS" ), QObject::tr( "Map layers to assign to unlocked map item(s)" ), QgsProcessing::TypeMapLayer, QVariant(), true );
layersParam->setFlags( layersParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
addParameter( layersParam.release() );
std::unique_ptr< QgsProcessingParameterNumber > dpiParam = std::make_unique< QgsProcessingParameterNumber >( QStringLiteral( "DPI" ), QObject::tr( "DPI (leave blank for default layout DPI)" ), QgsProcessingParameterNumber::Double, QVariant(), true, 0 );
dpiParam->setFlags( dpiParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
addParameter( dpiParam.release() );
std::unique_ptr< QgsProcessingParameterBoolean > forceVectorParam = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "FORCE_VECTOR" ), QObject::tr( "Always export as vectors" ), false );
forceVectorParam->setFlags( forceVectorParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
addParameter( forceVectorParam.release() );
std::unique_ptr< QgsProcessingParameterBoolean > appendGeorefParam = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "GEOREFERENCE" ), QObject::tr( "Append georeference information" ), true );
appendGeorefParam->setFlags( appendGeorefParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
addParameter( appendGeorefParam.release() );
std::unique_ptr< QgsProcessingParameterBoolean > exportRDFParam = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "INCLUDE_METADATA" ), QObject::tr( "Export RDF metadata (title, author, etc.)" ), true );
exportRDFParam->setFlags( exportRDFParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
addParameter( exportRDFParam.release() );
std::unique_ptr< QgsProcessingParameterBoolean > disableTiled = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "DISABLE_TILED" ), QObject::tr( "Disable tiled raster layer exports" ), false );
disableTiled->setFlags( disableTiled->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
addParameter( disableTiled.release() );
std::unique_ptr< QgsProcessingParameterBoolean > simplify = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "SIMPLIFY" ), QObject::tr( "Simplify geometries to reduce output file size" ), true );
simplify->setFlags( simplify->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
addParameter( simplify.release() );
QStringList textExportOptions
{
QObject::tr( "Always Export Text as Paths (Recommended)" ),
QObject::tr( "Always Export Text as Text Objects" )
};
std::unique_ptr< QgsProcessingParameterEnum > textFormat = std::make_unique< QgsProcessingParameterEnum >( QStringLiteral( "TEXT_FORMAT" ), QObject::tr( "Text export" ), textExportOptions, false, 0 );
textFormat->setFlags( textFormat->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
addParameter( textFormat.release() );
std::unique_ptr< QgsProcessingParameterBoolean > layeredExport = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "SEPARATE_LAYERS" ), QObject::tr( "Export layers as separate PDF files" ), false );
layeredExport->setFlags( layeredExport->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
addParameter( layeredExport.release() );
addParameter( new QgsProcessingParameterFileDestination( QStringLiteral( "OUTPUT" ), QObject::tr( "PDF file" ), QObject::tr( "PDF Format" ) + " (*.pdf *.PDF)" ) );
}
QgsProcessingAlgorithm::Flags QgsLayoutToPdfAlgorithm::flags() const
{
return QgsProcessingAlgorithm::flags() | FlagNoThreading;
}
QgsLayoutToPdfAlgorithm *QgsLayoutToPdfAlgorithm::createInstance() const
{
return new QgsLayoutToPdfAlgorithm();
}
QVariantMap QgsLayoutToPdfAlgorithm::processAlgorithm( const QVariantMap ¶meters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
{
// this needs to be done in main thread, layouts are not thread safe
QgsPrintLayout *l = parameterAsLayout( parameters, QStringLiteral( "LAYOUT" ), context );
if ( !l )
throw QgsProcessingException( QObject::tr( "Cannot find layout with name \"%1\"" ).arg( parameters.value( QStringLiteral( "LAYOUT" ) ).toString() ) );
std::unique_ptr< QgsPrintLayout > layout( l->clone() );
const QList< QgsMapLayer * > layers = parameterAsLayerList( parameters, QStringLiteral( "LAYERS" ), context );
if ( layers.size() > 0 )
{
const QList<QGraphicsItem *> items = layout->items();
for ( QGraphicsItem *graphicsItem : items )
{
QgsLayoutItem *item = dynamic_cast<QgsLayoutItem *>( graphicsItem );
QgsLayoutItemMap *map = dynamic_cast<QgsLayoutItemMap *>( item );
if ( map && !map->followVisibilityPreset() && !map->keepLayerSet() )
{
map->setKeepLayerSet( true );
map->setLayers( layers );
}
}
}
const QString dest = parameterAsFileOutput( parameters, QStringLiteral( "OUTPUT" ), context );
QgsLayoutExporter exporter( layout.get() );
QgsLayoutExporter::PdfExportSettings settings;
if ( parameters.value( QStringLiteral( "DPI" ) ).isValid() )
{
settings.dpi = parameterAsDouble( parameters, QStringLiteral( "DPI" ), context );
}
settings.forceVectorOutput = parameterAsBool( parameters, QStringLiteral( "FORCE_VECTOR" ), context );
settings.appendGeoreference = parameterAsBool( parameters, QStringLiteral( "GEOREFERENCE" ), context );
settings.exportMetadata = parameterAsBool( parameters, QStringLiteral( "INCLUDE_METADATA" ), context );
settings.exportMetadata = parameterAsBool( parameters, QStringLiteral( "INCLUDE_METADATA" ), context );
settings.simplifyGeometries = parameterAsBool( parameters, QStringLiteral( "SIMPLIFY" ), context );
settings.textRenderFormat = parameterAsEnum( parameters, QStringLiteral( "TEXT_FORMAT" ), context ) == 0 ? QgsRenderContext::TextFormatAlwaysOutlines : QgsRenderContext::TextFormatAlwaysText;
settings.exportLayersAsSeperateFiles = parameterAsBool( parameters, QStringLiteral( "SEPARATE_LAYERS" ), context ); //#spellok
if ( parameterAsBool( parameters, QStringLiteral( "DISABLE_TILED" ), context ) )
settings.flags = settings.flags | QgsLayoutRenderContext::FlagDisableTiledRasterLayerRenders;
else
settings.flags = settings.flags & ~QgsLayoutRenderContext::FlagDisableTiledRasterLayerRenders;
switch ( exporter.exportToPdf( dest, settings ) )
{
case QgsLayoutExporter::Success:
{
feedback->pushInfo( QObject::tr( "Successfully exported layout to %1" ).arg( QDir::toNativeSeparators( dest ) ) );
break;
}
case QgsLayoutExporter::FileError:
throw QgsProcessingException( QObject::tr( "Cannot write to %1.\n\nThis file may be open in another application." ).arg( QDir::toNativeSeparators( dest ) ) );
case QgsLayoutExporter::PrintError:
throw QgsProcessingException( QObject::tr( "Could not create print device." ) );
case QgsLayoutExporter::MemoryError:
throw QgsProcessingException( QObject::tr( "Exporting the PDF "
"resulted in a memory overflow.\n\n"
"Please try a lower resolution or a smaller paper size." ) );
case QgsLayoutExporter::SvgLayerError:
case QgsLayoutExporter::IteratorError:
case QgsLayoutExporter::Canceled:
// no meaning for PDF exports, will not be encountered
break;
}
feedback->setProgress( 100 );
QVariantMap outputs;
outputs.insert( QStringLiteral( "OUTPUT" ), dest );
return outputs;
}
///@endcond
| NaturalGIS/naturalgis_qgis | src/analysis/processing/qgsalgorithmlayouttopdf.cpp | C++ | gpl-2.0 | 9,906 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Tool
* @subpackage Framework
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Tool_Project_Context_Filesystem_File
*/
#require_once 'Zend/Tool/Project/Context/Filesystem/File.php';
/**
* This class is the front most class for utilizing Zend_Tool_Project
*
* A profile is a hierarchical set of resources that keep track of
* items within a specific project.
*
* @category Zend
* @package Zend_Tool
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Tool_Project_Context_Zf_TestLibraryFile extends Zend_Tool_Project_Context_Filesystem_File
{
/**
* @var string
*/
protected $_forClassName = '';
/**
* getName()
*
* @return string
*/
public function getName()
{
return 'TestLibraryFile';
}
/**
* init()
*
* @return Zend_Tool_Project_Context_Zf_TestLibraryFile
*/
public function init()
{
$this->_forClassName = $this->_resource->getAttribute('forClassName');
$this->_filesystemName = ucfirst(ltrim(strrchr($this->_forClassName, '_'), '_')) . 'Test.php';
parent::init();
return $this;
}
/**
* getContents()
*
* @return string
*/
public function getContents()
{
$filter = new Zend_Filter_Word_DashToCamelCase();
$className = $filter->filter($this->_forClassName) . 'Test';
$codeGenFile = new Zend_CodeGenerator_Php_File(array(
'requiredFiles' => array(
'PHPUnit/Framework/TestCase.php'
),
'classes' => array(
new Zend_CodeGenerator_Php_Class(array(
'name' => $className,
'extendedClass' => 'PHPUnit_Framework_TestCase',
'methods' => array(
new Zend_CodeGenerator_Php_Method(array(
'name' => 'setUp',
'body' => ' /* Setup Routine */'
)),
new Zend_CodeGenerator_Php_Method(array(
'name' => 'tearDown',
'body' => ' /* Tear Down Routine */'
))
)
))
)
));
return $codeGenFile->generate();
}
}
| T0MM0R/magento | web/lib/Zend/Tool/Project/Context/Zf/TestLibraryFile.php | PHP | gpl-2.0 | 3,128 |
/*--------------------------------------------------------------------*/
/*--- Signal-related libc stuff. m_libcsignal.c ---*/
/*--------------------------------------------------------------------*/
/*
This file is part of Valgrind, a dynamic binary instrumentation
framework.
Copyright (C) 2000-2017 Julian Seward
jseward@acm.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.
The GNU General Public License is contained in the file COPYING.
*/
#include "pub_core_basics.h"
#include "pub_core_debuglog.h"
#include "pub_core_vki.h"
#include "pub_core_vkiscnums.h"
#include "pub_core_libcbase.h"
#include "pub_core_libcassert.h"
#include "pub_core_syscall.h"
#include "pub_core_libcsignal.h" /* self */
#if !defined(VGO_solaris)
# define _VKI_MAXSIG (_VKI_NSIG - 1)
#endif
STATIC_ASSERT((_VKI_MAXSIG % _VKI_NSIG_BPW) != 0);
/* IMPORTANT: on Darwin it is essential to use the _nocancel versions
of syscalls rather than the vanilla version, if a _nocancel version
is available. See docs/internals/Darwin-notes.txt for the reason
why. */
/* sigemptyset, sigfullset, sigaddset and sigdelset return 0 on
success and -1 on error. */
/* In the sigset routines below, be aware that _VKI_NSIG_BPW can be
either 32 or 64, and hence the sig[] words can either be 32- or
64-bits. And which they are it doesn't necessarily follow from the
host word size. */
/* Functions VG_(isemptysigset) and VG_(isfullsigset) check only bits that
represent valid signals (i.e. signals <= _VKI_MAXSIG). The same applies
for the comparison in VG_(iseqsigset). This is important because when
a signal set is received from an operating system then bits which represent
signals > _VKI_MAXSIG can have unexpected values for Valgrind. This is
mainly specific to the Solaris kernel which clears these bits. */
Int VG_(sigfillset)( vki_sigset_t* set )
{
Int i;
if (set == NULL)
return -1;
for (i = 0; i < _VKI_NSIG_WORDS; i++)
set->sig[i] = ~0;
return 0;
}
Int VG_(sigemptyset)( vki_sigset_t* set )
{
Int i;
if (set == NULL)
return -1;
for (i = 0; i < _VKI_NSIG_WORDS; i++)
set->sig[i] = 0;
return 0;
}
Bool VG_(isemptysigset)( const vki_sigset_t* set )
{
Int i;
vg_assert(set != NULL);
for (i = 0; i < _VKI_NSIG_WORDS; i++) {
if (_VKI_NSIG_BPW * (i + 1) <= (_VKI_MAXSIG + 1)) {
/* Full word check. */
if (set->sig[i] != 0) return False;
}
else {
/* Partial word check. */
ULong mask = ((ULong)1UL << (_VKI_MAXSIG % _VKI_NSIG_BPW)) - 1;
if ((set->sig[i] & mask) != 0) return False;
break;
}
}
return True;
}
Bool VG_(isfullsigset)( const vki_sigset_t* set )
{
Int i;
vg_assert(set != NULL);
for (i = 0; i < _VKI_NSIG_WORDS; i++) {
if (_VKI_NSIG_BPW * (i + 1) <= (_VKI_MAXSIG + 1)) {
/* Full word check. */
if (set->sig[i] != ~0) return False;
}
else {
/* Partial word check. */
ULong mask = ((ULong)1UL << (_VKI_MAXSIG % _VKI_NSIG_BPW)) - 1;
if ((set->sig[i] & mask) != mask) return False;
break;
}
}
return True;
}
Bool VG_(iseqsigset)( const vki_sigset_t* set1, const vki_sigset_t* set2 )
{
Int i;
vg_assert(set1 != NULL && set2 != NULL);
for (i = 0; i < _VKI_NSIG_WORDS; i++) {
if (_VKI_NSIG_BPW * (i + 1) <= (_VKI_MAXSIG + 1)) {
/* Full word comparison. */
if (set1->sig[i] != set2->sig[i]) return False;
}
else {
/* Partial word comparison. */
ULong mask = ((ULong)1UL << (_VKI_MAXSIG % _VKI_NSIG_BPW)) - 1;
if ((set1->sig[i] & mask) != (set2->sig[i] & mask)) return False;
break;
}
}
return True;
}
Int VG_(sigaddset)( vki_sigset_t* set, Int signum )
{
if (set == NULL)
return -1;
if (signum < 1 || signum > _VKI_NSIG)
return -1;
signum--;
set->sig[signum / _VKI_NSIG_BPW] |= (1ULL << (signum % _VKI_NSIG_BPW));
return 0;
}
Int VG_(sigdelset)( vki_sigset_t* set, Int signum )
{
if (set == NULL)
return -1;
if (signum < 1 || signum > _VKI_NSIG)
return -1;
signum--;
set->sig[signum / _VKI_NSIG_BPW] &= ~(1ULL << (signum % _VKI_NSIG_BPW));
return 0;
}
Int VG_(sigismember) ( const vki_sigset_t* set, Int signum )
{
if (set == NULL)
return 0;
if (signum < 1 || signum > _VKI_NSIG)
return 0;
signum--;
if (1 & ((set->sig[signum / _VKI_NSIG_BPW]) >> (signum % _VKI_NSIG_BPW)))
return 1;
else
return 0;
}
/* Add all signals in src to dst. */
void VG_(sigaddset_from_set)( vki_sigset_t* dst, const vki_sigset_t* src )
{
Int i;
vg_assert(dst != NULL && src != NULL);
for (i = 0; i < _VKI_NSIG_WORDS; i++)
dst->sig[i] |= src->sig[i];
}
/* Remove all signals in src from dst. */
void VG_(sigdelset_from_set)( vki_sigset_t* dst, const vki_sigset_t* src )
{
Int i;
vg_assert(dst != NULL && src != NULL);
for (i = 0; i < _VKI_NSIG_WORDS; i++)
dst->sig[i] &= ~(src->sig[i]);
}
/* dst = dst `intersect` src. */
void VG_(sigintersectset)( vki_sigset_t* dst, const vki_sigset_t* src )
{
Int i;
vg_assert(dst != NULL && src != NULL);
for (i = 0; i < _VKI_NSIG_WORDS; i++)
dst->sig[i] &= src->sig[i];
}
/* dst = ~src */
void VG_(sigcomplementset)( vki_sigset_t* dst, const vki_sigset_t* src )
{
Int i;
vg_assert(dst != NULL && src != NULL);
for (i = 0; i < _VKI_NSIG_WORDS; i++)
dst->sig[i] = ~ src->sig[i];
}
/* The functions sigaction, sigprocmask, sigpending and sigsuspend
return 0 on success and -1 on error.
*/
Int VG_(sigprocmask)( Int how, const vki_sigset_t* set, vki_sigset_t* oldset)
{
# if defined(VGO_linux) || defined(VGO_solaris)
# if defined(__NR_rt_sigprocmask)
SysRes res = VG_(do_syscall4)(__NR_rt_sigprocmask,
how, (UWord)set, (UWord)oldset,
_VKI_NSIG_WORDS * sizeof(UWord));
# else
SysRes res = VG_(do_syscall3)(__NR_sigprocmask,
how, (UWord)set, (UWord)oldset);
# endif
# elif defined(VGO_darwin)
/* On Darwin, __NR_sigprocmask appears to affect the entire
process, not just this thread. Hence need to use
__NR___pthread_sigmask instead. */
SysRes res = VG_(do_syscall3)(__NR___pthread_sigmask,
how, (UWord)set, (UWord)oldset);
# else
# error "Unknown OS"
# endif
return sr_isError(res) ? -1 : 0;
}
#if defined(VGO_darwin)
/* A helper function for sigaction on Darwin. */
static
void darwin_signal_demux(void* a1, UWord a2, UWord a3, void* a4, void* a5) {
VG_(debugLog)(2, "libcsignal",
"PRE demux sig, a2 = %lu, signo = %lu\n", a2, a3);
if (a2 == 1)
((void(*)(int))a1) (a3);
else
((void(*)(int,void*,void*))a1) (a3,a4,a5);
VG_(debugLog)(2, "libcsignal",
"POST demux sig, a2 = %lu, signo = %lu\n", a2, a3);
VG_(do_syscall2)(__NR_sigreturn, (UWord)a5, 0x1E);
/* NOTREACHED */
__asm__ __volatile__("ud2");
}
#endif
Int VG_(sigaction) ( Int signum,
const vki_sigaction_toK_t* act,
vki_sigaction_fromK_t* oldact)
{
# if defined(VGO_linux)
/* Normal case: vki_sigaction_toK_t and vki_sigaction_fromK_t are
identical types. */
SysRes res = VG_(do_syscall4)(__NR_rt_sigaction,
signum, (UWord)act, (UWord)oldact,
_VKI_NSIG_WORDS * sizeof(UWord));
return sr_isError(res) ? -1 : 0;
# elif defined(VGO_darwin)
/* If we're passing a new action to the kernel, make a copy of the
new action, install our own sa_tramp field in it, and ignore
whatever we were provided with. This is OK because all the
sigaction requests come from m_signals, and are not directly
what the client program requested, so there is no chance that we
will inadvertently ignore the sa_tramp field requested by the
client. (In fact m_signals does ignore it when building signal
frames for the client, but that's a completely different
matter).
If we're receiving an old action from the kernel, be very
paranoid and make sure the kernel doesn't trash bits of memory
that we don't expect it to. */
SysRes res;
vki_sigaction_toK_t actCopy;
struct {
ULong before[2];
vki_sigaction_fromK_t oa;
ULong after[2];
}
oldactCopy;
vki_sigaction_toK_t* real_act;
vki_sigaction_fromK_t* real_oldact;
real_act = act ? &actCopy : NULL;
real_oldact = oldact ? &oldactCopy.oa : NULL;
VG_(memset)(&oldactCopy, 0x55, sizeof(oldactCopy));
if (real_act) {
*real_act = *act;
real_act->sa_tramp = (void*)&darwin_signal_demux;
}
res = VG_(do_syscall3)(__NR_sigaction,
signum, (UWord)real_act, (UWord)real_oldact);
if (real_oldact) {
vg_assert(oldactCopy.before[0] == 0x5555555555555555ULL);
vg_assert(oldactCopy.before[1] == 0x5555555555555555ULL);
vg_assert(oldactCopy.after[0] == 0x5555555555555555ULL);
vg_assert(oldactCopy.after[1] == 0x5555555555555555ULL);
*oldact = *real_oldact;
}
return sr_isError(res) ? -1 : 0;
# elif defined(VGO_solaris)
/* vki_sigaction_toK_t and vki_sigaction_fromK_t are identical types. */
SysRes res = VG_(do_syscall3)(__NR_sigaction,
signum, (UWord)act, (UWord)oldact);
return sr_isError(res) ? -1 : 0;
# else
# error "Unsupported OS"
# endif
}
/* See explanation in pub_core_libcsignal.h. */
void
VG_(convert_sigaction_fromK_to_toK)( const vki_sigaction_fromK_t* fromK,
/*OUT*/vki_sigaction_toK_t* toK )
{
# if defined(VGO_linux) || defined(VGO_solaris)
*toK = *fromK;
# elif defined(VGO_darwin)
toK->ksa_handler = fromK->ksa_handler;
toK->sa_tramp = NULL; /* the cause of all the difficulty */
toK->sa_mask = fromK->sa_mask;
toK->sa_flags = fromK->sa_flags;
# else
# error "Unsupported OS"
# endif
}
Int VG_(kill)( Int pid, Int signo )
{
# if defined(VGO_linux) || defined(VGO_solaris)
SysRes res = VG_(do_syscall2)(__NR_kill, pid, signo);
# elif defined(VGO_darwin)
SysRes res = VG_(do_syscall3)(__NR_kill,
pid, signo, 1/*posix-compliant*/);
# else
# error "Unsupported OS"
# endif
return sr_isError(res) ? -1 : 0;
}
Int VG_(tkill)( Int lwpid, Int signo )
{
# if defined(__NR_tkill)
SysRes res = VG_(mk_SysRes_Error)(VKI_ENOSYS);
res = VG_(do_syscall2)(__NR_tkill, lwpid, signo);
if (sr_isError(res) && sr_Err(res) == VKI_ENOSYS)
res = VG_(do_syscall2)(__NR_kill, lwpid, signo);
return sr_isError(res) ? -1 : 0;
# elif defined(VGO_darwin)
// Note that the __pthread_kill syscall takes a Mach thread, not a pthread.
SysRes res;
res = VG_(do_syscall2)(__NR___pthread_kill, lwpid, signo);
return sr_isError(res) ? -1 : 0;
# elif defined(VGO_solaris)
SysRes res;
# if defined(SOLARIS_LWP_SIGQUEUE_SYSCALL)
# if defined(SOLARIS_LWP_SIGQUEUE_SYSCALL_TAKES_PID)
res = VG_(do_syscall6)(__NR_lwp_sigqueue, 0, lwpid, signo,
0, VKI_SI_LWP, 0);
# else
res = VG_(do_syscall5)(__NR_lwp_sigqueue, lwpid, signo,
0, VKI_SI_LWP, 0);
# endif
# else
res = VG_(do_syscall2)(__NR_lwp_kill, lwpid, signo);
# endif
return sr_isError(res) ? -1 : 0;
# else
# error "Unsupported plat"
# endif
}
/* ---------------------- sigtimedwait_zero ----------------------- */
/* A cut-down version of POSIX sigtimedwait: poll for pending signals
mentioned in the sigset_t, and if any are present, select one
arbitrarily, return its number (which must be > 0), and put
auxiliary info about it in the siginfo_t, and make it
not-pending-any-more. If none are pending, return zero. The _zero
refers to the fact that there is zero timeout, so if no signals are
pending it returns immediately. Perhaps a better name would be
'sigpoll'. Returns -1 on error, 0 if no signals pending, and n > 0
if signal n was selected.
The Linux implementation is trivial: do the corresponding syscall.
The Darwin implementation is horrible and probably broken in a dozen
obscure ways. I suspect it's only thread-safe because V forces
single-threadedness. */
/* ---------- sigtimedwait_zero: Linux ----------- */
#if defined(VGO_linux)
Int VG_(sigtimedwait_zero)( const vki_sigset_t *set,
vki_siginfo_t *info )
{
static const struct vki_timespec zero = { 0, 0 };
SysRes res = VG_(do_syscall4)(__NR_rt_sigtimedwait, (UWord)set, (UWord)info,
(UWord)&zero, sizeof(*set));
return sr_isError(res) ? -1 : sr_Res(res);
}
/* ---------- sigtimedwait_zero: Darwin ----------- */
#elif defined(VGO_darwin)
//static void show_set ( HChar* str, const vki_sigset_t* set ) {
// Int i;
// VG_(printf)("%s { ", str);
// for (i = 1; i <= _VKI_NSIG; i++) {
// if (VG_(sigismember)(set, i))
// VG_(printf)("%u ", i);
// }
// VG_(printf)("}\n");
//}
/* The general idea is:
- use sigpending to find out which signals are pending
- choose one
- temporarily set its handler to sigtimedwait_zero_handler
- use sigsuspend atomically unblock it and wait for the signal.
Upon return, sigsuspend restores the signal mask to what it
was to start with.
- Restore the handler for the signal to whatever it was before.
*/
/* A signal handler which does nothing (it doesn't need to). It does
however check that it's not handing a sync signal for which
returning is meaningless. */
static void sigtimedwait_zero_handler ( Int sig )
{
/* XXX this is wrong -- get rid of these. We could
get _any_ signal here */
vg_assert(sig != VKI_SIGILL);
vg_assert(sig != VKI_SIGSEGV);
vg_assert(sig != VKI_SIGBUS);
vg_assert(sig != VKI_SIGTRAP);
/* do nothing */
}
Int VG_(sigtimedwait_zero)( const vki_sigset_t *set,
vki_siginfo_t *info )
{
const Bool debug = False;
Int i, ir;
SysRes sr;
vki_sigset_t pending, blocked, allbutone;
vki_sigaction_toK_t sa, saved_sa2;
vki_sigaction_fromK_t saved_sa;
//show_set("STWZ: looking for", set);
/* Find out what's pending: Darwin sigpending */
sr = VG_(do_syscall1)(__NR_sigpending, (UWord)&pending);
vg_assert(!sr_isError(sr));
/* don't try for signals not in 'set' */
/* pending = pending `intersect` set */
VG_(sigintersectset)(&pending, (const vki_sigset_t*)set);
/* don't try for signals not blocked at the moment */
ir = VG_(sigprocmask)(VKI_SIG_SETMASK, NULL, &blocked);
vg_assert(ir == 0);
/* pending = pending `intersect` blocked */
VG_(sigintersectset)(&pending, &blocked);
/* decide which signal we're going to snarf */
for (i = 1; i < _VKI_NSIG; i++)
if (VG_(sigismember)(&pending,i))
break;
if (i == _VKI_NSIG)
return 0;
if (debug)
VG_(debugLog)(0, "libcsignal",
"sigtimedwait_zero: snarfing signal %d\n", i );
/* fetch signal i.
pre: i is blocked and pending
pre: we are the only thread running
*/
/* Set up alternative signal handler */
VG_(sigfillset)(&sa.sa_mask);
sa.ksa_handler = &sigtimedwait_zero_handler;
sa.sa_flags = 0;
ir = VG_(sigaction)(i, &sa, &saved_sa);
vg_assert(ir == 0);
/* Switch signal masks and wait for the signal. This should happen
immediately, since we've already established it is pending and
blocked. */
VG_(sigfillset)(&allbutone);
VG_(sigdelset)(&allbutone, i);
/* Note: pass the sig mask by value here, not reference (!) */
vg_assert(_VKI_NSIG_WORDS == 1);
sr = VG_(do_syscall3)(__NR_sigsuspend_nocancel,
(UWord)allbutone.sig[0], 0,0);
if (debug)
VG_(debugLog)(0, "libcsignal",
"sigtimedwait_zero: sigsuspend got "
"res: %s %#lx\n",
sr_isError(sr) ? "FAIL" : "SUCCESS",
sr_isError(sr) ? sr_Err(sr) : sr_Res(sr));
vg_assert(sr_isError(sr));
vg_assert(sr_Err(sr) == VKI_EINTR);
/* Restore signal's handler to whatever it was before */
VG_(convert_sigaction_fromK_to_toK)( &saved_sa, &saved_sa2 );
ir = VG_(sigaction)(i, &saved_sa2, NULL);
vg_assert(ir == 0);
/* This is bogus - we could get more info from the sighandler. */
VG_(memset)( info, 0, sizeof(*info) );
info->si_signo = i;
return i;
}
#elif defined(VGO_solaris)
Int VG_(sigtimedwait_zero)( const vki_sigset_t *set, vki_siginfo_t *info )
{
/* Trivial as on Linux. */
static const struct vki_timespec zero = { 0, 0 };
SysRes res = VG_(do_syscall3)(__NR_sigtimedwait, (UWord)set, (UWord)info,
(UWord)&zero);
return sr_isError(res) ? -1 : sr_Res(res);
}
#else
# error "Unknown OS"
#endif
/*--------------------------------------------------------------------*/
/*--- end ---*/
/*--------------------------------------------------------------------*/
| bmerry/datagrind | coregrind/m_libcsignal.c | C | gpl-2.0 | 17,995 |
<?php
/**
* @file
* Definition of Drupal\search\Tests\SearchBlockTest.
*/
namespace Drupal\search\Tests;
/**
* Tests the rendering of the search block.
*/
class SearchBlockTest extends SearchTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('block');
public static function getInfo() {
return array(
'name' => 'Block availability',
'description' => 'Check if the search form block is available.',
'group' => 'Search',
);
}
function setUp() {
parent::setUp();
// Create and login user.
$admin_user = $this->drupalCreateUser(array('administer blocks', 'search content'));
$this->drupalLogin($admin_user);
}
/**
* Test that the search form block can be placed and works.
*/
protected function testSearchFormBlock() {
// Test availability of the search block in the admin "Place blocks" list.
$this->drupalGet('admin/structure/block');
$this->assertLinkByHref('/admin/structure/block/add/search_form_block/stark', 0,
'Did not find the search block in block candidate list.');
$block = $this->drupalPlaceBlock('search_form_block');
$this->drupalGet('');
$this->assertText($block->label(), 'Block title was found.');
// Test a normal search via the block form, from the front page.
$terms = array('search_block_form' => 'test');
$this->drupalPostForm('', $terms, t('Search'));
$this->assertResponse(200);
$this->assertText('Your search yielded no results');
// Test a search from the block on a 404 page.
$this->drupalGet('foo');
$this->assertResponse(404);
$this->drupalPostForm(NULL, $terms, t('Search'));
$this->assertResponse(200);
$this->assertText('Your search yielded no results');
$visibility = $block->get('visibility');
$visibility['path']['pages'] = 'search';
$block->set('visibility', $visibility);
$this->drupalPostForm('', $terms, t('Search'));
$this->assertResponse(200);
$this->assertText('Your search yielded no results');
// Confirm that the user is redirected to the search page.
$this->assertEqual(
$this->getUrl(),
url('search/node/' . $terms['search_block_form'], array('absolute' => TRUE)),
'Redirected to correct url.'
);
// Test an empty search via the block form, from the front page.
$terms = array('search_block_form' => '');
$this->drupalPostForm('', $terms, t('Search'));
$this->assertResponse(200);
$this->assertText('Please enter some keywords');
// Confirm that the user is redirected to the search page, when form is
// submitted empty.
$this->assertEqual(
$this->getUrl(),
url('search/node/', array('absolute' => TRUE)),
'Redirected to correct url.'
);
}
}
| glibey/drupal8 | core/modules/search/lib/Drupal/search/Tests/SearchBlockTest.php | PHP | gpl-2.0 | 2,805 |
define(["../../buildControl"], function(bc){
if(bc.stripConsole){
var consoleMethods = "assert|count|debug|dir|dirxml|group|groupEnd|info|profile|profileEnd|time|timeEnd|trace|log";
if(bc.stripConsole === "warn"){
consoleMethods += "|warn";
}else if(bc.stripConsole === "all"){
consoleMethods += "|warn|error";
}
// Match on "window.console" and plain "console" but not things like "myconsole" or "my.console"
var stripConsoleRe = new RegExp("([^\\w\\.]|^)((window.)?console\\.(" + consoleMethods + ")\\s*\\()", "g");
return function(text){
return text.replace(stripConsoleRe, "$1 0 && $2");
};
}else{
return function(text){
return text;
};
}
}); | avz-cmf/zaboy-middleware | www/js/util/build/transforms/optimizer/stripConsole.js | JavaScript | gpl-3.0 | 681 |
#!/bin/sh
# verify that ls -lL works when applied to a symlink to an ACL'd file
# Copyright (C) 2011-2016 Free Software Foundation, Inc.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
. "${srcdir=.}/tests/init.sh"; path_prepend_ ./src
print_ver_ ls
require_setfacl_
touch k || framework_failure_
setfacl -m user::r-- k || framework_failure_
ln -s k s || framework_failure_
set _ $(ls -Log s); shift; link=$1
set _ $(ls -og k); shift; reg=$1
test "$link" = "$reg" || fail=1
Exit $fail
| sunny256/coreutils | tests/ls/slink-acl.sh | Shell | gpl-3.0 | 1,078 |
/**
* This file contains JS functionality required by mforms and is included automatically
* when required.
*/
// Namespace for the form bits and bobs
M.form = M.form || {};
/**
* Initialises the show advanced functionality and events.
* This should only ever happen ONCE per page.
*
* @param {YUI} Y
* @param {object} config
*/
M.form.initShowAdvanced = function(Y, config) {
if (M.form.showAdvanced) {
return M.form.showAdvanced;
}
var showAdvanced = function(config) {
showAdvanced.superclass.constructor.apply(this, arguments);
};
showAdvanced.prototype = {
_advButtons : [],
_advAreas : [],
_stateInput : null,
initializer : function() {
this._advAreas = Y.all('form .advanced');
this._advButtons = Y.all('.showadvancedbtn');
if (this._advButtons.size() > 0) {
this._stateInput = new Y.NodeList(document.getElementsByName('mform_showadvanced_last'));
this._advButtons.on('click', this.switchState, this);
}
},
/**
* Toggles between showing advanced items and hiding them.
* Should be fired by an event.
*/
switchState : function(e) {
e.preventDefault();
if (this._stateInput.get('value')=='1') {
this._stateInput.set('value', '0');
this._advButtons.setAttribute('value', M.str.form.showadvanced);
this._advAreas.addClass('hide');
} else {
this._stateInput.set('value', '1');
this._advButtons.setAttribute('value', M.str.form.hideadvanced);
this._advAreas.removeClass('hide');
}
}
};
// Extend it with the YUI widget fw.
Y.extend(showAdvanced, Y.Base, showAdvanced.prototype, {
NAME : 'mform-showAdvanced'
});
M.form.showAdvanced = new showAdvanced(config);
return M.form.showAdvanced;
};
/**
* Initialises a manager for a forms dependencies.
* This should happen once per form.
*/
M.form.initFormDependencies = function(Y, formid, dependencies) {
// If the dependencies isn't an array or object we don't want to
// know about it
if (!Y.Lang.isArray(dependencies) && !Y.Lang.isObject(dependencies)) {
return false;
}
/**
* Fixes an issue with YUI's processing method of form.elements property
* in Internet Explorer.
* http://yuilibrary.com/projects/yui3/ticket/2528030
*/
Y.Node.ATTRS.elements = {
getter: function() {
return Y.all(new Y.Array(this._node.elements, 0, true));
}
};
// Define the dependency manager if it hasn't already been defined.
M.form.dependencyManager = M.form.dependencyManager || (function(){
var dependencyManager = function(config) {
dependencyManager.superclass.constructor.apply(this, arguments);
};
dependencyManager.prototype = {
_form : null,
_depElements : [],
_nameCollections : [],
initializer : function(config) {
var i = 0, nodeName;
this._form = Y.one('#'+formid);
for (i in dependencies) {
this._depElements[i] = this.elementsByName(i);
if (this._depElements[i].size() == 0) {
continue;
}
this._depElements[i].each(function(node){
nodeName = node.get('nodeName').toUpperCase();
if (nodeName == 'INPUT') {
if (node.getAttribute('type').match(/^(button|submit|radio|checkbox)$/)) {
node.on('click', this.checkDependencies, this);
} else {
node.on('blur', this.checkDependencies, this);
}
node.on('change', this.checkDependencies, this);
} else if (nodeName == 'SELECT') {
node.on('change', this.checkDependencies, this);
} else {
node.on('click', this.checkDependencies, this);
node.on('blur', this.checkDependencies, this);
node.on('change', this.checkDependencies, this);
}
}, this);
}
this._form.get('elements').each(function(input){
if (input.getAttribute('type')=='reset') {
input.on('click', function(){
this._form.reset();
this.checkDependencies();
}, this);
}
}, this);
return this.checkDependencies(null);
},
/**
* Gets all elements in the form by thier name and returns
* a YUI NodeList
* @return Y.NodeList
*/
elementsByName : function(name) {
if (!this._nameCollections[name]) {
var elements = [];
this._form.get('elements').each(function(){
if (this.getAttribute('name') == name) {
elements.push(this);
}
});
this._nameCollections[name] = new Y.NodeList(elements);
}
return this._nameCollections[name];
},
/**
* Checks the dependencies the form has an makes any changes to the
* form that are required.
*
* Changes are made by functions title _dependency_{dependencytype}
* and more can easily be introduced by defining further functions.
*/
checkDependencies : function(e) {
var tolock = [],
tohide = [],
dependon, condition, value,
lock, hide, checkfunction, result;
for (dependon in dependencies) {
if (this._depElements[dependon].size() == 0) {
continue;
}
for (condition in dependencies[dependon]) {
for (value in dependencies[dependon][condition]) {
lock = false;
hide = false;
checkfunction = '_dependency_'+condition;
if (Y.Lang.isFunction(this[checkfunction])) {
result = this[checkfunction].apply(this, [this._depElements[dependon], value, e]);
} else {
result = this._dependency_default(this._depElements[dependon], value, e);
}
lock = result.lock || false;
hide = result.hide || false;
for (var ei in dependencies[dependon][condition][value]) {
var eltolock = dependencies[dependon][condition][value][ei];
if (hide) {
tohide[eltolock] = true;
}
if (tolock[eltolock] != null) {
tolock[eltolock] = lock || tolock[eltolock];
} else {
tolock[eltolock] = lock;
}
}
}
}
}
for (var el in tolock) {
this._disableElement(el, tolock[el]);
if (tohide.propertyIsEnumerable(el)) {
this._hideElement(el, tohide[el]);
}
}
return true;
},
/**
* Disabled all form elements with the given name
*/
_disableElement : function(name, disabled) {
var els = this.elementsByName(name);
els.each(function(){
if (disabled) {
this.setAttribute('disabled', 'disabled');
} else {
this.removeAttribute('disabled');
}
})
},
/**
* Hides all elements with the given name.
*/
_hideElement : function(name, hidden) {
var els = this.elementsByName(name);
els.each(function(){
var e = els.ancestor('.fitem');
if (e) {
e.setStyles({
display : (hidden)?'none':''
})
}
});
},
_dependency_notchecked : function(elements, value) {
var lock = false;
elements.each(function(){
if (this.getAttribute('type').toLowerCase()=='radio' && this.get('value') != value) {
return;
}
lock = lock || !Y.Node.getDOMNode(this).checked;
});
return {
lock : lock,
hide : false
}
},
_dependency_checked : function(elements, value) {
var lock = false;
elements.each(function(){
if (this.getAttribute('type').toLowerCase()=='radio' && this.get('value') != value) {
return;
}
lock = lock || Y.Node.getDOMNode(this).checked;
});
return {
lock : lock,
hide : false
}
},
_dependency_noitemselected : function(elements, value) {
var lock = false;
elements.each(function(){
lock = lock || this.get('selectedIndex') == -1;
});
return {
lock : lock,
hide : false
}
},
_dependency_eq : function(elements, value) {
var lock = false;
elements.each(function(){
if (this.getAttribute('type').toLowerCase()=='radio' && !Y.Node.getDOMNode(this).checked) {
return;
} else if (this.getAttribute('type').toLowerCase() == 'checkbox' && !Y.Node.getDOMNode(this).checked) {
return;
}
lock = lock || this.get('value') == value;
});
return {
lock : lock,
hide : false
}
},
_dependency_hide : function(elements, value) {
return {
lock : false,
hide : true
}
},
_dependency_default : function(elements, value, ev) {
var lock = false;
elements.each(function(){
if (this.getAttribute('type').toLowerCase()=='radio' && !Y.Node.getDOMNode(this).checked) {
return;
} else if (this.getAttribute('type').toLowerCase() == 'checkbox' && !Y.Node.getDOMNode(this).checked) {
return;
}
lock = lock || this.get('value') != value;
});
return {
lock : lock,
hide : false
}
}
};
Y.extend(dependencyManager, Y.Base, dependencyManager.prototype, {
NAME : 'mform-dependency-manager'
});
return dependencyManager;
})();
return new M.form.dependencyManager();
}; | dhamma-dev/SEA | web/lib/form/form.js | JavaScript | gpl-3.0 | 12,220 |
#ifndef __XRDCMSBLACKLIST_HH__
#define __XRDCMSBLACKLIST_HH__
/******************************************************************************/
/* */
/* X r d C m s B l a c k L i s t . h h */
/* */
/* (c) 2014 by the Board of Trustees of the Leland Stanford, Jr., University */
/* All Rights Reserved */
/* Produced by Andrew Hanushevsky for Stanford University under contract */
/* DE-AC02-76-SFO0515 with the Department of Energy */
/* */
/* This file is part of the XRootD software suite. */
/* */
/* XRootD is free software: you can redistribute it and/or modify it under */
/* the terms of the GNU Lesser General Public License as published by the */
/* Free Software Foundation, either version 3 of the License, or (at your */
/* option) any later version. */
/* */
/* XRootD 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 XRootD in a file called COPYING.LESSER (LGPL license) and file */
/* COPYING (GPL license). If not, see <http://www.gnu.org/licenses/>. */
/* */
/* The copyright holder's institutional names and contributor's names may not */
/* be used to endorse or promote products derived from this software without */
/* specific prior written permission of the institution or contributor. */
/******************************************************************************/
#include "Xrd/XrdJob.hh"
class XrdCmsCluster;
class XrdOucTList;
class XrdScheduler;
class BL_Grip;
class XrdCmsBlackList : public XrdJob
{
public:
//------------------------------------------------------------------------------
//! Time driven method for checking black list file.
//------------------------------------------------------------------------------
void DoIt();
//------------------------------------------------------------------------------
//! Initialize the black list
//!
//! @param sP Pointer to the scheduler object.
//! @param cP Pointer to the cluster object.
//! @param blfn The path to the black list file or null.
//! @param chkt Seconds between checks for blacklist changes. If the value
//! is negative, the blacklist is treated as a whitelist.
//------------------------------------------------------------------------------
static void Init(XrdScheduler *sP, XrdCmsCluster *cP,
const char *blfn, int chkt=600);
//------------------------------------------------------------------------------
//! Check if host is in the black list and how it should be managed.
//!
//! @param hName Pointer to the host name or address.
//! @param bList Optional pointer to a private black list.
//! @param rbuff Pointer to the buffer to contain the redirect response. If
//! nil, the host is not redirected.
//! @param rblen The size of rbuff. If zero or insufficiently large the host
//! is not redirected.
//!
//! @return < -1 Host is in the black list and would be redirected;
//! but either rbuff was nil or the buffer was too small. The
//! abs(returned value) is the size the buffer should have been.
//! @return = -1 Host is in the black list and should not be redirected.
//! @return = 0 Host not in the black list.
//! @return > 0 Host is in the black list and should be redirected.
//! The return value is the size of the redirect response placed
//! in the supplied buffer.
//------------------------------------------------------------------------------
static int Present(const char *hName, XrdOucTList *bList=0,
char *rbuff=0, int rblen=0);
//------------------------------------------------------------------------------
//! Constructor and Destructor
//------------------------------------------------------------------------------
XrdCmsBlackList() : XrdJob("Black List Check") {}
~XrdCmsBlackList() {}
private:
static bool AddBL(BL_Grip &bAnchor, char *hSpec,
BL_Grip *rAnchor, char *rSpec);
static int AddRD(BL_Grip *rAnchor, char *rSpec, char *hSpec);
static bool AddRD(XrdOucTList **rList, char *rSpec, char *hSpec);
static
XrdOucTList *Flatten(XrdOucTList *tList, int tPort);
static bool GetBL(XrdOucTList *&bList, XrdOucTList **&rList, int &rcnt);
};
#endif
| alja/xrootd | src/XrdCms/XrdCmsBlackList.hh | C++ | gpl-3.0 | 5,380 |
/*
#########################################################################
#
# Copyright (C) 2019 OSGeo
#
# 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/>.
#
#########################################################################
*/
export default 'ALERT_SETTINGS';
| tomkralidis/geonode | geonode/monitoring/frontend/monitoring/src/pages/alerts-settings/constants.js | JavaScript | gpl-3.0 | 853 |
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* see https://github.com/bitpay/php-bitpay-client/blob/master/LICENSE
*/
namespace Bitpay;
/**
* Invoice
*
* @package Bitpay
*/
interface InvoiceInterface
{
/**
* An invoice starts in this state. When in this state and only in this state, payments
* to the associated bitcoin address are credited to the invoice. If an invoice has
* received a partial payment, it will still reflect a status of new to the merchant
* (from a merchant system perspective, an invoice is either paid or not paid, partial
* payments and over payments are handled by bitpay.com by either refunding the
* customer or applying the funds to a new invoice.
*/
const STATUS_NEW = 'new';
/**
* As soon as full payment (or over payment) is received, an invoice goes into the
* paid status.
*/
const STATUS_PAID = 'paid';
/**
* The transaction speed preference of an invoice determines when an invoice is
* confirmed. For the high speed setting, it will be confirmed as soon as full
* payment is received on the bitcoin network (note, the invoice will go from a status
* of new to confirmed, bypassing the paid status). For the medium speed setting,
* the invoice is confirmed after the payment transaction(s) have been confirmed by
* 1 block on the bitcoin network. For the low speed setting, 6 blocks on the bitcoin
* network are required. Invoices are considered complete after 6 blocks on the
* bitcoin network, therefore an invoice will go from a paid status directly to a
* complete status if the transaction speed is set to low.
*/
const STATUS_CONFIRMED = 'confirmed';
/**
* When an invoice is complete, it means that BitPay.com has credited the
* merchant’s account for the invoice. Currently, 6 confirmation blocks on the
* bitcoin network are required for an invoice to be complete. Note, in the future (for
* qualified payers), invoices may move to a complete status immediately upon
* payment, in which case the invoice will move directly from a new status to a
* complete status.
*/
const STATUS_COMPLETE = 'complete';
/**
* An expired invoice is one where payment was not received and the 15 minute
* payment window has elapsed.
*/
const STATUS_EXPIRED = 'expired';
/**
* An invoice is considered invalid when it was paid, but payment was not confirmed
* within 1 hour after receipt. It is possible that some transactions on the bitcoin
* network can take longer than 1 hour to be included in a block. In such
* circumstances, once payment is confirmed, BitPay.com will make arrangements
* with the merchant regarding the funds (which can either be credited to the
* merchant account on another invoice, or returned to the buyer).
*/
const STATUS_INVALID = 'invalid';
/**
* Code comment for each transaction speed
*/
const TRANSACTION_SPEED_HIGH = 'high';
const TRANSACTION_SPEED_MEDIUM = 'medium';
const TRANSACTION_SPEED_LOW = 'low';
/**
* This is the amount that is required to be collected from the buyer. Note, if this is
* specified in a currency other than BTC, the price will be converted into BTC at
* market exchange rates to determine the amount collected from the buyer.
*
* @return string
*/
public function getPrice();
/**
* This is the currency code set for the price setting. The pricing currencies
* currently supported are USD, EUR, BTC, and all of the codes listed on this page:
* https://bitpay.com/bitcoinexchangerates
*
* @return CurrencyInterface
*/
public function getCurrency();
/**
* @return ItemInterface
*/
public function getItem();
/**
* @return BuyerInterface
*/
public function getBuyer();
/**
* default value: set in your https://bitpay.com/ordersettings, the default value set in
* your merchant dashboard is “medium”.
*
* ● “high”: An invoice is considered to be "confirmed" immediately upon
* receipt of payment.
* ● “medium”: An invoice is considered to be "confirmed" after 1 block
* confirmation (~10 minutes).
* ● “low”: An invoice is considered to be "confirmed" after 6 block
* confirmations (~1 hour).
*
* NOTE: Orders are posted to your Account Summary after 6 block confirmations
* regardless of this setting.
*
* @return string
*/
public function getTransactionSpeed();
/**
* Bitpay.com will send an email to this email address when the invoice status
* changes.
*
* @return string
*/
public function getNotificationEmail();
/**
* A URL to send status update messages to your server (this must be an https
* URL, unencrypted http URLs or any other type of URL is not supported).
* Bitpay.com will send a POST request with a JSON encoding of the invoice to
* this URL when the invoice status changes.
*
* @return string
*/
public function getNotificationUrl();
/**
* This is the URL for a return link that is displayed on the receipt, to return the
* shopper back to your website after a successful purchase. This could be a page
* specific to the order, or to their account.
*
* @return string
*/
public function getRedirectUrl();
/**
* A passthru variable provided by the merchant and designed to be used by the
* merchant to correlate the invoice with an order or other object in their system.
* Maximum string length is 100 characters.
*
* @return array|object
*/
public function getPosData();
/**
* The current invoice status. The possible states are described earlier in this
* document.
*
* @return string
*/
public function getStatus();
/**
* default value: true
* ● true: Notifications will be sent on every status change.
* ● false: Notifications are only sent when an invoice is confirmed (according
* to the “transactionSpeed” setting).
*
* @return boolean
*/
public function isFullNotifications();
/**
* default value: false
* ● true: Notifications will also be sent for expired invoices and refunds.
* ● false: Notifications will not be sent for expired invoices and refunds
*
* @return boolean
*/
public function isExtendedNotifications();
/**
* The unique id of the invoice assigned by bitpay.com
*
* @return string
*/
public function getId();
/**
* An https URL where the invoice can be viewed.
*
* @return string
*/
public function getUrl();
/**
* The amount of bitcoins being requested for payment of this invoice (same as the
* price if the merchant set the price in BTC).
*
* @return string
*/
public function getBtcPrice();
/**
* The time the invoice was created in milliseconds since midnight January 1,
* 1970. Time format is “20140101T19:01:01.123Z”.
*
* @return DateTime
*/
public function getInvoiceTime();
/**
* The time at which the invoice expires and no further payment will be accepted (in
* milliseconds since midnight January 1, 1970). Currently, all invoices are valid for
* 15 minutes. Time format is “20140101T19:01:01.123Z”.
*
* @return DateTime
*/
public function getExpirationTime();
/**
* The current time on the BitPay.com system (by subtracting the current time from
* the expiration time, the amount of time remaining for payment can be
* determined). Time format is “20140101T19:01:01.123Z”.
*
* @return DateTime
*/
public function getCurrentTime();
/**
* Used to display your public order number to the buyer on the BitPay invoice. In
* the merchant Account Summary page, this value is used to identify the ledger
* entry. Maximum string length is 100 characters.
*
* @return string
*/
public function getOrderId();
/**
* Used to display an item description to the buyer. Maximum string length is 100
* characters.
*
* @deprecated
* @return string
*/
public function getItemDesc();
/**
* Used to display an item SKU code or part number to the buyer. Maximum string
* length is 100 characters.
*
* @deprecated
* @return string
*/
public function getItemCode();
/**
* default value: false
* ● true: Indicates a physical item will be shipped (or picked up)
* ● false: Indicates that nothing is to be shipped for this order
*
* @deprecated
* @return boolean
*/
public function isPhysical();
/**
* These fields are used for display purposes only and will be shown on the invoice
* if provided. Maximum string length of each field is 100 characters.
*
* @deprecated
* @return string
*/
public function getBuyerName();
/**
* These fields are used for display purposes only and will be shown on the invoice
* if provided. Maximum string length of each field is 100 characters.
*
* @deprecated
* @return string
*/
public function getBuyerAddress1();
/**
* These fields are used for display purposes only and will be shown on the invoice
* if provided. Maximum string length of each field is 100 characters.
*
* @deprecated
* @return string
*/
public function getBuyerAddress2();
/**
* These fields are used for display purposes only and will be shown on the invoice
* if provided. Maximum string length of each field is 100 characters.
*
* @deprecated
* @return string
*/
public function getBuyerCity();
/**
* These fields are used for display purposes only and will be shown on the invoice
* if provided. Maximum string length of each field is 100 characters.
*
* @deprecated
* @return string
*/
public function getBuyerState();
/**
* These fields are used for display purposes only and will be shown on the invoice
* if provided. Maximum string length of each field is 100 characters.
*
* @deprecated
* @return string
*/
public function getBuyerZip();
/**
* These fields are used for display purposes only and will be shown on the invoice
* if provided. Maximum string length of each field is 100 characters.
*
* @deprecated
* @return string
*/
public function getBuyerCountry();
/**
* These fields are used for display purposes only and will be shown on the invoice
* if provided. Maximum string length of each field is 100 characters.
*
* @deprecated
* @return string
*/
public function getBuyerEmail();
/**
* These fields are used for display purposes only and will be shown on the invoice
* if provided. Maximum string length of each field is 100 characters.
*
* @deprecated
* @return string
*/
public function getBuyerPhone();
/**
*/
public function getExceptionStatus();
/**
*/
public function getBtcPaid();
/**
*/
public function getRate();
/**
*/
public function getToken();
/**
* An array containing all bitcoin addresses linked to the invoice.
* Only filled when doing a getInvoice using the Merchant facade.
* The array contains
* [refundAddress] => Array
* [type] => string (e.g. "PaymentProtocol")
* [date] => datetime string
*
* @return array|object
*/
public function getRefundAddresses();
}
| yclas/yclas | oc/vendor/bitpay/vendor/bitpay/php-client/src/Bitpay/InvoiceInterface.php | PHP | gpl-3.0 | 12,475 |
// ***************************************************************** -*- C++ -*-
/*
* Copyright (C) 2004-2015 Andreas Huggel <ahuggel@gmx.net>
*
* This program is part of the Exiv2 distribution.
*
* 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, 5th Floor, Boston, MA 02110-1301 USA.
*/
/*!
@file asfvideo.hpp
@brief An Image subclass to support ASF video files
@version $Rev$
@author Abhinav Badola for GSoC 2012
<a href="mailto:mail.abu.to@gmail.com">mail.abu.to@gmail.com</a>
@date 08-Aug-12, AB: created
*/
#ifndef ASFVIDEO_HPP
#define ASFVIDEO_HPP
// *****************************************************************************
// included header files
#include "exif.hpp"
#include "image.hpp"
#include "tags_int.hpp"
// *****************************************************************************
// namespace extensions
using namespace Exiv2::Internal;
namespace Exiv2 {
// *****************************************************************************
// class definitions
// Add ASF to the supported image formats
namespace ImageType {
const int asf = 24; //!< Treating asf as an image type>
}
/*!
@brief Class to access ASF video files.
*/
class EXIV2API AsfVideo:public Image
{
public:
//! @name Creators
//@{
/*!
@brief Constructor for a ASF video. Since the constructor
can not return a result, callers should check the good() method
after object construction to determine success or failure.
@param io An auto-pointer that owns a BasicIo instance used for
reading and writing image metadata. \b Important: The constructor
takes ownership of the passed in BasicIo instance through the
auto-pointer. Callers should not continue to use the BasicIo
instance after it is passed to this method. Use the Image::io()
method to get a temporary reference.
*/
AsfVideo(BasicIo::AutoPtr io);
//@}
//! @name Manipulators
//@{
void readMetadata();
void writeMetadata();
//@}
//! @name Accessors
//@{
std::string mimeType() const;
//@}
protected:
/*!
@brief Check for a valid tag and decode the block at the current IO
position. Calls tagDecoder() or skips to next tag, if required.
*/
void decodeBlock();
/*!
@brief Interpret tag information, and call the respective function
to save it in the respective XMP container. Decodes a Tag
Information and saves it in the respective XMP container, if
the block size is small.
@param tv Pointer to current tag,
@param size Size of the data block used to store Tag Information.
*/
void tagDecoder(const TagVocabulary* tv, uint64_t size);
/*!
@brief Interpret File_Properties tag information, and save it in
the respective XMP container.
*/
void fileProperties();
/*!
@brief Interpret Stream_Properties tag information, and save it
in the respective XMP container.
*/
void streamProperties();
/*!
@brief Interpret Codec_List tag information, and save it in
the respective XMP container.
*/
void codecList();
/*!
@brief Interpret Content_Description tag information, and save it
in the respective XMP container.
@param size Size of the data block used to store Tag Data.
*/
void contentDescription(uint64_t size);
/*!
@brief Interpret Extended_Stream_Properties tag information, and
save it in the respective XMP container.
@param size Size of the data block used to store Tag Data.
*/
void extendedStreamProperties(uint64_t size);
/*!
@brief Interpret Header_Extension tag information, and save it in
the respective XMP container.
@param size Size of the data block used to store Tag Data.
*/
void headerExtension(uint64_t size);
/*!
@brief Interpret Metadata, Extended_Content_Description,
Metadata_Library tag information, and save it in the respective
XMP container.
@param meta A default integer which helps to overload the function
for various Tags that have a similar method of decoding.
*/
void metadataHandler(int meta = 1);
/*!
@brief Calculates Aspect Ratio of a video, and stores it in the
respective XMP container.
*/
void aspectRatio();
private:
//! @name NOT Implemented
//@{
//! Copy constructor
AsfVideo(const AsfVideo& rhs);
//! Assignment operator
AsfVideo& operator=(const AsfVideo& rhs);
//@}
private:
//! Variable to check the end of metadata traversing.
bool continueTraversing_;
//! Variable which stores current position of the read pointer.
uint64_t localPosition_;
//! Variable which stores current stream being processsed.
int streamNumber_;
//! Variable to store height and width of a video frame.
uint64_t height_, width_;
}; //Class AsfVideo
// *****************************************************************************
// template, inline and free functions
// These could be static private functions on Image subclasses but then
// ImageFactory needs to be made a friend.
/*!
@brief Create a new AsfVideo instance and return an auto-pointer to it.
Caller owns the returned object and the auto-pointer ensures that
it will be deleted.
*/
EXIV2API Image::AutoPtr newAsfInstance(BasicIo::AutoPtr io, bool create);
//! Check if the file iIo is a Windows Asf Video.
EXIV2API bool isAsfType(BasicIo& iIo, bool advance);
} // namespace Exiv2
#endif // #ifndef ASFVIDEO_HPP_
| gnidorah/xpiks | vendors/exiv2-0.25/include/exiv2/asfvideo.hpp | C++ | gpl-3.0 | 6,875 |
/*
* Copyright (c) 2006 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/*!
@header IOPMKeys.h
IOPMKeys.h defines C strings for use accessing power management data.
Note that all of these C strings must be converted to CFStrings before use. You can wrap
them with the CFSTR() macro, or create a CFStringRef (that you must later CFRelease()) using CFStringCreateWithCString()
*/
#ifndef _IOPMKEYS_H_
#define _IOPMKEYS_H_
/*
* Types of power event
* These are potential arguments to IOPMSchedulePowerEvent().
* These are all potential values of the kIOPMPowerEventTypeKey in the CFDictionaries
* returned by IOPMCopyScheduledPowerEvents().
*/
/*!
@define kIOPMAutoWake
@abstract Value for scheduled wake from sleep.
*/
#define kIOPMAutoWake "wake"
/*!
@define kIOPMAutoPowerOn
@abstract Value for scheduled power on from off state.
*/
#define kIOPMAutoPowerOn "poweron"
/*!
@define kIOPMAutoWakeOrPowerOn
@abstract Value for scheduled wake from sleep, or power on. The system will either wake OR
power on, whichever is necessary.
*/
#define kIOPMAutoWakeOrPowerOn "wakepoweron"
/*!
@define kIOPMAutoSleep
@abstract Value for scheduled sleep.
*/
#define kIOPMAutoSleep "sleep"
/*!
@define kIOPMAutoShutdown
@abstract Value for scheduled shutdown.
*/
#define kIOPMAutoShutdown "shutdown"
/*!
@define kIOPMAutoRestart
@abstract Value for scheduled restart.
*/
#define kIOPMAutoRestart "restart"
/*
* Keys for evaluating the CFDictionaries returned by IOPMCopyScheduledPowerEvents()
*/
/*!
@define kIOPMPowerEventTimeKey
@abstract Key for the time of the scheduled power event. Value is a CFDateRef.
*/
#define kIOPMPowerEventTimeKey "time"
/*!
@define kIOPMPowerEventAppNameKey
@abstract Key for the CFBundleIdentifier of the app that scheduled the power event. Value is a CFStringRef.
*/
#define kIOPMPowerEventAppNameKey "scheduledby"
/*!
@define kIOPMPowerEventTypeKey
@abstract Key for the type of power event. Value is a CFStringRef, with the c-string value of one of the "kIOPMAuto" strings.
*/
#define kIOPMPowerEventTypeKey "eventtype"
#endif
| x56/pris0nbarake | untethers/include/IOKit/pwr_mgt/IOPMKeys.h | C | gpl-3.0 | 3,342 |
import bpy
camera = bpy.context.edit_movieclip.tracking.camera
camera.sensor_width = 23.6
camera.units = 'MILLIMETERS'
camera.pixel_aspect = 1
camera.k1 = 0.0
camera.k2 = 0.0
camera.k3 = 0.0
| Microvellum/Fluid-Designer | win64-vc/2.78/scripts/presets/tracking_camera/Nikon_DX.py | Python | gpl-3.0 | 192 |
"""
Tools and data structures for working with genomic intervals (or sets of
regions on a line in general) efficiently.
"""
# For compatiblity with existing stuff
from bx.intervals.intersection import * | dnanexus/rseqc | rseqc/lib/bx/intervals/__init__.py | Python | gpl-3.0 | 204 |
# -*- coding: utf-8 -*-
from ..internal.DeadCrypter import DeadCrypter
class Movie2KTo(DeadCrypter):
__name__ = "Movie2KTo"
__type__ = "crypter"
__version__ = "0.56"
__status__ = "stable"
__pattern__ = r'http://(?:www\.)?movie2k\.to/(.+)\.html'
__config__ = [("activated", "bool", "Activated", True)]
__description__ = """Movie2k.to decrypter plugin"""
__license__ = "GPLv3"
__authors__ = [("4Christopher", "4Christopher@gmx.de")]
| TheBraveWarrior/pyload | module/plugins/crypter/Movie2KTo.py | Python | gpl-3.0 | 472 |
<?php
/**
* @package Mautic
* @copyright 2014 Mautic Contributors. All rights reserved.
* @author Mautic
* @link http://mautic.org
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
namespace Mautic\EmailBundle\EventListener;
use Mautic\ConfigBundle\ConfigEvents;
use Mautic\ConfigBundle\Event\ConfigEvent;
use Mautic\ConfigBundle\Event\ConfigBuilderEvent;
use Mautic\CoreBundle\EventListener\CommonSubscriber;
/**
* Class ConfigSubscriber
*
* @package Mautic\CoreBundle\EventListener
*/
class ConfigSubscriber extends CommonSubscriber
{
/**
* @return array
*/
static public function getSubscribedEvents()
{
return array(
ConfigEvents::CONFIG_ON_GENERATE => array('onConfigGenerate', 0),
ConfigEvents::CONFIG_PRE_SAVE => array('onConfigBeforeSave', 0)
);
}
public function onConfigGenerate(ConfigBuilderEvent $event)
{
$event->addForm(array(
'bundle' => 'EmailBundle',
'formAlias' => 'emailconfig',
'formTheme' => 'MauticEmailBundle:FormTheme\Config',
'parameters' => $event->getParametersFromConfig('MauticEmailBundle')
));
}
public function onConfigBeforeSave(ConfigEvent $event)
{
$event->unsetIfEmpty(
array(
'mailer_password'
)
);
$data = $event->getConfig('emailconfig');
// Get the original data so that passwords aren't lost
$monitoredEmail = $this->factory->getParameter('monitored_email');
if (isset($data['monitored_email'])) {
foreach ($data['monitored_email'] as $key => $monitor) {
if (empty($monitor['password']) && !empty($monitoredEmail[$key]['password'])) {
$data['monitored_email'][$key]['password'] = $monitoredEmail[$key]['password'];
}
if ($key != 'general') {
if (empty($monitor['host']) || empty($monitor['address']) || empty($monitor['folder'])) {
$data['monitored_email'][$key]['override_settings'] = '';
$data['monitored_email'][$key]['address'] = '';
$data['monitored_email'][$key]['host'] = '';
$data['monitored_email'][$key]['user'] = '';
$data['monitored_email'][$key]['password'] = '';
$data['monitored_email'][$key]['ssl'] = '1';
$data['monitored_email'][$key]['port'] = '993';
}
}
}
}
// Ensure that percent signs are decoded in the unsubscribe/webview settings
$decode = array(
'unsubscribe_text',
'webview_text',
'unsubscribe_message',
'resubscribe_message'
);
foreach ($decode as $key) {
if (strpos($data[$key], '%') !== false) {
$data[$key] = urldecode($data[$key]);
if (preg_match_all('/([^%]|^)(%{1}[^%]\S+[^%]%{1})([^%]|$)/i', $data[$key], $matches)) {
// Encode any left over to prevent Symfony from crashing
foreach ($matches[0] as $matchKey => $match) {
$replaceWith = $matches[1][$matchKey].'%'.$matches[2][$matchKey].'%'.$matches[3][$matchKey];
$data[$key] = str_replace($match, $replaceWith, $data[$key]);
}
}
}
}
$event->setConfig($data, 'emailconfig');
}
}
| chandon/mautic | app/bundles/EmailBundle/EventListener/ConfigSubscriber.php | PHP | gpl-3.0 | 3,706 |
/* keydb.h - Key database
* Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG 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.
*
* GnuPG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GNUPG_KEYDB_H
#define GNUPG_KEYDB_H
#include <ksba.h>
#include "../kbx/keybox-search-desc.h"
typedef struct keydb_handle *KEYDB_HANDLE;
/* Flag value used with KEYBOX_FLAG_VALIDITY. */
#define VALIDITY_REVOKED (1<<5)
/*-- keydb.c --*/
int keydb_add_resource (const char *url, int force, int secret,
int *auto_created);
KEYDB_HANDLE keydb_new (int secret);
void keydb_release (KEYDB_HANDLE hd);
int keydb_set_ephemeral (KEYDB_HANDLE hd, int yes);
const char *keydb_get_resource_name (KEYDB_HANDLE hd);
gpg_error_t keydb_lock (KEYDB_HANDLE hd);
#if 0 /* pgp stuff */
int keydb_get_keyblock (KEYDB_HANDLE hd, KBNODE *ret_kb);
int keydb_update_keyblock (KEYDB_HANDLE hd, KBNODE kb);
int keydb_insert_keyblock (KEYDB_HANDLE hd, KBNODE kb);
#endif
gpg_error_t keydb_get_flags (KEYDB_HANDLE hd, int which, int idx,
unsigned int *value);
gpg_error_t keydb_set_flags (KEYDB_HANDLE hd, int which, int idx,
unsigned int value);
int keydb_get_cert (KEYDB_HANDLE hd, ksba_cert_t *r_cert);
int keydb_insert_cert (KEYDB_HANDLE hd, ksba_cert_t cert);
int keydb_update_cert (KEYDB_HANDLE hd, ksba_cert_t cert);
int keydb_delete (KEYDB_HANDLE hd, int unlock);
int keydb_locate_writable (KEYDB_HANDLE hd, const char *reserved);
void keydb_rebuild_caches (void);
int keydb_search_reset (KEYDB_HANDLE hd);
int keydb_search (KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc, size_t ndesc);
int keydb_search_first (KEYDB_HANDLE hd);
int keydb_search_next (KEYDB_HANDLE hd);
int keydb_search_kid (KEYDB_HANDLE hd, u32 *kid);
int keydb_search_fpr (KEYDB_HANDLE hd, const byte *fpr);
int keydb_search_issuer (KEYDB_HANDLE hd, const char *issuer);
int keydb_search_issuer_sn (KEYDB_HANDLE hd,
const char *issuer, const unsigned char *serial);
int keydb_search_subject (KEYDB_HANDLE hd, const char *issuer);
int keydb_classify_name (const char *name, KEYDB_SEARCH_DESC *desc);
int keydb_store_cert (ksba_cert_t cert, int ephemeral, int *existed);
gpg_error_t keydb_set_cert_flags (ksba_cert_t cert, int ephemeral,
int which, int idx,
unsigned int mask, unsigned int value);
void keydb_clear_some_cert_flags (ctrl_t ctrl, strlist_t names);
#endif /*GNUPG_KEYDB_H*/
| TextusData/Mover | thirdparty/gnupg-2.0.22/sm/keydb.h | C | gpl-3.0 | 3,104 |
/* refchg.f -- translated by f2c (version 19980913).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
#include "f2c.h"
/* Table of constant values */
static integer c__2 = 2;
/* $Procedure REFCHG (Reference frame Change) */
/* Subroutine */ int refchg_(integer *frame1, integer *frame2, doublereal *et,
doublereal *rotate)
{
/* System generated locals */
integer i__1, i__2, i__3, i__4, i__5, i__6, i__7;
/* Builtin functions */
integer s_rnge(char *, integer, char *, integer);
/* Local variables */
integer node;
logical done;
integer cent, this__;
extern /* Subroutine */ int zznofcon_(doublereal *, integer *, integer *,
integer *, integer *, char *, ftnlen);
integer i__, j, frame[10];
extern /* Subroutine */ int chkin_(char *, ftnlen), ident_(doublereal *);
integer class__;
logical found;
integer relto;
extern /* Subroutine */ int xpose_(doublereal *, doublereal *), zzrxr_(
doublereal *, integer *, doublereal *);
extern logical failed_(void);
integer cmnode;
extern integer isrchi_(integer *, integer *, integer *);
integer clssid;
extern /* Subroutine */ int frinfo_(integer *, integer *, integer *,
integer *, logical *);
logical gotone;
char errmsg[1840];
extern /* Subroutine */ int chkout_(char *, ftnlen), setmsg_(char *,
ftnlen), errint_(char *, integer *, ftnlen), sigerr_(char *,
ftnlen), rotget_(integer *, doublereal *, doublereal *, integer *,
logical *);
extern logical return_(void);
doublereal tmprot[9] /* was [3][3] */;
integer inc, get;
doublereal rot[126] /* was [3][3][14] */;
integer put;
doublereal rot2[18] /* was [3][3][2] */;
/* $ Abstract */
/* Return the transformation matrix from one */
/* frame to another. */
/* $ Disclaimer */
/* THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */
/* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */
/* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */
/* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */
/* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */
/* TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */
/* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */
/* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */
/* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */
/* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */
/* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */
/* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */
/* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */
/* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */
/* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */
/* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */
/* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */
/* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */
/* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */
/* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */
/* $ Required_Reading */
/* None. */
/* $ Keywords */
/* FRAMES */
/* $ Declarations */
/* $ Disclaimer */
/* THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */
/* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */
/* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */
/* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */
/* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */
/* TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */
/* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */
/* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */
/* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */
/* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */
/* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */
/* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */
/* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */
/* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */
/* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */
/* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */
/* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */
/* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */
/* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */
/* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */
/* Include File: SPICELIB Error Handling Parameters */
/* errhnd.inc Version 2 18-JUN-1997 (WLT) */
/* The size of the long error message was */
/* reduced from 25*80 to 23*80 so that it */
/* will be accepted by the Microsoft Power Station */
/* FORTRAN compiler which has an upper bound */
/* of 1900 for the length of a character string. */
/* errhnd.inc Version 1 29-JUL-1997 (NJB) */
/* Maximum length of the long error message: */
/* Maximum length of the short error message: */
/* End Include File: SPICELIB Error Handling Parameters */
/* $ Abstract */
/* The parameters below form an enumerated list of the recognized */
/* frame types. They are: INERTL, PCK, CK, TK, DYN. The meanings */
/* are outlined below. */
/* $ Disclaimer */
/* THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */
/* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */
/* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */
/* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */
/* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */
/* TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */
/* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */
/* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */
/* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */
/* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */
/* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */
/* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */
/* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */
/* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */
/* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */
/* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */
/* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */
/* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */
/* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */
/* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */
/* $ Parameters */
/* INERTL an inertial frame that is listed in the routine */
/* CHGIRF and that requires no external file to */
/* compute the transformation from or to any other */
/* inertial frame. */
/* PCK is a frame that is specified relative to some */
/* INERTL frame and that has an IAU model that */
/* may be retrieved from the PCK system via a call */
/* to the routine TISBOD. */
/* CK is a frame defined by a C-kernel. */
/* TK is a "text kernel" frame. These frames are offset */
/* from their associated "relative" frames by a */
/* constant rotation. */
/* DYN is a "dynamic" frame. These currently are */
/* parameterized, built-in frames where the full frame */
/* definition depends on parameters supplied via a */
/* frame kernel. */
/* ALL indicates any of the above classes. This parameter */
/* is used in APIs that fetch information about frames */
/* of a specified class. */
/* $ Author_and_Institution */
/* N.J. Bachman (JPL) */
/* W.L. Taber (JPL) */
/* $ Literature_References */
/* None. */
/* $ Version */
/* - SPICELIB Version 4.0.0, 08-MAY-2012 (NJB) */
/* The parameter ALL was added to support frame fetch APIs. */
/* - SPICELIB Version 3.0.0, 28-MAY-2004 (NJB) */
/* The parameter DYN was added to support the dynamic frame class. */
/* - SPICELIB Version 2.0.0, 12-DEC-1996 (WLT) */
/* Various unused frames types were removed and the */
/* frame time TK was added. */
/* - SPICELIB Version 1.0.0, 10-DEC-1995 (WLT) */
/* -& */
/* End of INCLUDE file frmtyp.inc */
/* $ Brief_I/O */
/* VARIABLE I/O DESCRIPTION */
/* -------- --- -------------------------------------------------- */
/* FRAME1 I the frame id-code for some reference frame */
/* FRAME2 I the frame id-code for some reference frame */
/* ET I an epoch in TDB seconds past J2000. */
/* ROTATE O a rotation matrix */
/* $ Detailed_Input */
/* FRAME1 is the frame id-code in which some positions */
/* are known. */
/* FRAME2 is the frame id-code for some frame in which you */
/* would like to represent positions. */
/* ET is the epoch at which to compute the transformation */
/* matrix. This epoch should be in TDB seconds past */
/* the ephemeris epoch of J2000. */
/* $ Detailed_Output */
/* ROTATE is a 3 x 3 rotaion matrix that can be used to */
/* transform positions relative to the frame */
/* correspsonding to frame FRAME2 to positions relative */
/* to the frame FRAME2. More explicitely, if POS is */
/* the position of some object relative to the */
/* reference frame of FRAME1 then POS2 is the position */
/* of the same object relative to FRAME2 where POS2 is */
/* computed via the subroutine call below */
/* CALL MXV ( ROTATE, POS, POS2 ) */
/* $ Parameters */
/* None. */
/* $ Exceptions */
/* 1) If either of the reference frames is unrecognized, the error */
/* SPICE(UNKNOWNFRAME) will be signalled. */
/* 2) If the auxillary information needed to compute a non-inertial */
/* frame is not available an error will be diagnosed and signalled */
/* by a routine in the call tree of this routine. */
/* $ Files */
/* None. */
/* $ Particulars */
/* This routine allows you to compute the rotation matrix */
/* between two reference frames. */
/* $ Examples */
/* Suppose that you have a position POS1 at epoch ET */
/* relative to FRAME1 and wish to determine its representation */
/* POS2 relative to FRAME2. The following subroutine calls */
/* would suffice to make this rotation. */
/* CALL REFCHG ( FRAME1, FRAME2, ET, ROTATE ) */
/* CALL MXV ( ROTATE, POS1, POS2 ) */
/* $ Restrictions */
/* None. */
/* $ Literature_References */
/* None. */
/* $ Author_and_Institution */
/* W.L. Taber (JPL) */
/* $ Version */
/* - SPICELIB Version 2.0.0, 14-DEC-2008 (NJB) */
/* Upgraded long error message associated with frame */
/* connection failure. */
/* - SPICELIB Version 1.2.0, 26-APR-2004 (NJB) */
/* Another typo was corrected in the long error message, and */
/* in a comment. */
/* - SPICELIB Version 1.1.0, 23-MAY-2000 (WLT) */
/* A typo was corrected in the long error message. */
/* - SPICELIB Version 1.0.0, 9-JUL-1998 (WLT) */
/* -& */
/* $ Index_Entries */
/* Rotate positions from one frame to another */
/* -& */
/* SPICE functions */
/* Local Paramters */
/* The root of all reference frames is J2000 (Frame ID = 1). */
/* Local Variables */
/* ROT contains the rotations from FRAME1 to FRAME2 */
/* ROT(1...3,1...3,I) has the rotation from FRAME(I) */
/* to FRAME(I+1). We make extra room in ROT because we */
/* plan to add rotations beyond the obvious chain from */
/* FRAME1 to a root node. */
/* ROT2 is used to store intermediate rotation from */
/* FRAME2 to some node in the chain from FRAME1 to PCK or */
/* INERTL frames. */
/* FRAME contains the frames we transform from in going from */
/* FRAME1 to FRAME2. FRAME(1) = FRAME1 by construction. */
/* NODE counts the number of rotations needed to go */
/* from FRAME1 to FRAME2. */
/* Standard SPICE error handling. */
if (return_()) {
return 0;
}
chkin_("REFCHG", (ftnlen)6);
/* Do the obvious thing first. If FRAME1 and FRAME2 are the */
/* same then we simply return the identity matrix. */
if (*frame1 == *frame2) {
ident_(rotate);
chkout_("REFCHG", (ftnlen)6);
return 0;
}
/* Now perform the obvious check to make sure that both */
/* frames are recognized. */
frinfo_(frame1, ¢, &class__, &clssid, &found);
if (! found) {
setmsg_("The number # is not a recognized id-code for a reference fr"
"ame. ", (ftnlen)64);
errint_("#", frame1, (ftnlen)1);
sigerr_("SPICE(UNKNOWNFRAME)", (ftnlen)19);
chkout_("REFCHG", (ftnlen)6);
return 0;
}
frinfo_(frame2, ¢, &class__, &clssid, &found);
if (! found) {
setmsg_("The number # is not a recognized id-code for a reference fr"
"ame. ", (ftnlen)64);
errint_("#", frame2, (ftnlen)1);
sigerr_("SPICE(UNKNOWNFRAME)", (ftnlen)19);
chkout_("REFCHG", (ftnlen)6);
return 0;
}
node = 1;
frame[(i__1 = node - 1) < 10 && 0 <= i__1 ? i__1 : s_rnge("frame", i__1,
"refchg_", (ftnlen)287)] = *frame1;
found = TRUE_;
/* Follow the chain of rotations until we run into */
/* one that rotates to J2000 (frame id = 1) or we hit FRAME2. */
while(frame[(i__1 = node - 1) < 10 && 0 <= i__1 ? i__1 : s_rnge("frame",
i__1, "refchg_", (ftnlen)293)] != 1 && node < 10 && frame[(i__2 =
node - 1) < 10 && 0 <= i__2 ? i__2 : s_rnge("frame", i__2, "refc"
"hg_", (ftnlen)293)] != *frame2 && found) {
/* Find out what rotation is available for this */
/* frame. */
rotget_(&frame[(i__1 = node - 1) < 10 && 0 <= i__1 ? i__1 : s_rnge(
"frame", i__1, "refchg_", (ftnlen)301)], et, &rot[(i__2 = (
node * 3 + 1) * 3 - 12) < 126 && 0 <= i__2 ? i__2 : s_rnge(
"rot", i__2, "refchg_", (ftnlen)301)], &frame[(i__3 = node) <
10 && 0 <= i__3 ? i__3 : s_rnge("frame", i__3, "refchg_", (
ftnlen)301)], &found);
if (found) {
/* We found a rotation matrix. ROT(1,1,NODE) */
/* now contains the rotation from FRAME(NODE) */
/* to FRAME(NODE+1). We need to look up the information */
/* for the next NODE. */
++node;
}
}
done = frame[(i__1 = node - 1) < 10 && 0 <= i__1 ? i__1 : s_rnge("frame",
i__1, "refchg_", (ftnlen)317)] == 1 || frame[(i__2 = node - 1) <
10 && 0 <= i__2 ? i__2 : s_rnge("frame", i__2, "refchg_", (ftnlen)
317)] == *frame2 || ! found;
while(! done) {
/* The only way to get to this point is to have run out of */
/* room in the array of reference frame rotation */
/* buffers. We will now build the rotation from */
/* the previous NODE to whatever the next node in the */
/* chain is. We'll do this until we get to one of the */
/* root classes or we run into FRAME2. */
rotget_(&frame[(i__1 = node - 1) < 10 && 0 <= i__1 ? i__1 : s_rnge(
"frame", i__1, "refchg_", (ftnlen)331)], et, &rot[(i__2 = (
node * 3 + 1) * 3 - 12) < 126 && 0 <= i__2 ? i__2 : s_rnge(
"rot", i__2, "refchg_", (ftnlen)331)], &relto, &found);
if (found) {
/* Recall that ROT(1,1,NODE-1) contains the rotation */
/* from FRAME(NODE-1) to FRAME(NODE). We are going to replace */
/* FRAME(NODE) with the frame indicated by RELTO. This means */
/* that ROT(1,1,NODE-1) should be replaced with the */
/* rotation from FRAME(NODE) to RELTO. */
frame[(i__1 = node - 1) < 10 && 0 <= i__1 ? i__1 : s_rnge("frame",
i__1, "refchg_", (ftnlen)342)] = relto;
zzrxr_(&rot[(i__1 = ((node - 1) * 3 + 1) * 3 - 12) < 126 && 0 <=
i__1 ? i__1 : s_rnge("rot", i__1, "refchg_", (ftnlen)343)]
, &c__2, tmprot);
for (i__ = 1; i__ <= 3; ++i__) {
for (j = 1; j <= 3; ++j) {
rot[(i__1 = i__ + (j + (node - 1) * 3) * 3 - 13) < 126 &&
0 <= i__1 ? i__1 : s_rnge("rot", i__1, "refchg_",
(ftnlen)347)] = tmprot[(i__2 = i__ + j * 3 - 4) <
9 && 0 <= i__2 ? i__2 : s_rnge("tmprot", i__2,
"refchg_", (ftnlen)347)];
}
}
}
/* We are done if the class of the last frame is J2000 */
/* or if the last frame is FRAME2 or if we simply couldn't get */
/* another rotation. */
done = frame[(i__1 = node - 1) < 10 && 0 <= i__1 ? i__1 : s_rnge(
"frame", i__1, "refchg_", (ftnlen)357)] == 1 || frame[(i__2 =
node - 1) < 10 && 0 <= i__2 ? i__2 : s_rnge("frame", i__2,
"refchg_", (ftnlen)357)] == *frame2 || ! found;
}
/* Right now we have the following situation. We have in hand */
/* a collection of rotations between frames. (Assuming */
/* that is that NODE .GT. 1. If NODE .EQ. 1 then we have */
/* no rotations computed yet. */
/* ROT(1...3, 1...3, 1 ) rotates FRAME1 to FRAME(2) */
/* ROT(1...3, 1...3, 2 ) rotates FRAME(2) to FRAME(3) */
/* ROT(1...3, 1...3, 3 ) rotates FRAME(3) to FRAME(4) */
/* . */
/* . */
/* . */
/* ROT(1...3, 1...3, NODE-1 ) rotates FRAME(NODE-1) */
/* to FRAME(NODE) */
/* One of the following situations is true. */
/* 1) FRAME(NODE) is the root of all frames, J2000. */
/* 2) FRAME(NODE) is the same as FRAME2 */
/* 3) There is no rotation from FRAME(NODE) to another */
/* more fundamental frame. The chain of rotations */
/* from FRAME1 stops at FRAME(NODE). This means that the */
/* "frame atlas" is incomplete because we can't get to the */
/* root frame. */
/* We now have to do essentially the same thing for FRAME2. */
if (frame[(i__1 = node - 1) < 10 && 0 <= i__1 ? i__1 : s_rnge("frame",
i__1, "refchg_", (ftnlen)395)] == *frame2) {
/* We can handle this one immediately with the private routine */
/* ZZRXR which multiplies a series of matrices. */
i__1 = node - 1;
zzrxr_(rot, &i__1, rotate);
chkout_("REFCHG", (ftnlen)6);
return 0;
}
/* We didn't luck out above. So we follow the chain of */
/* rotation for FRAME2. Note that at the moment the */
/* chain of rotations from FRAME2 to other frames */
/* does not share a node in the chain for FRAME1. */
/* ( GOTONE = .FALSE. ) . */
this__ = *frame2;
gotone = FALSE_;
/* First see if there is any chain to follow. */
done = this__ == 1;
/* Set up the matrices ROT2(,,1) and ROT(,,2) and set up */
/* PUT and GET pointers so that we know where to GET the partial */
/* rotation from and where to PUT partial results. */
if (! done) {
put = 1;
get = 1;
inc = 1;
}
/* Follow the chain of rotations until we run into */
/* one that rotates to the root frame or we land in the */
/* chain of nodes for FRAME1. */
/* Note that this time we will simply keep track of the full */
/* rotation from FRAME2 to the last node. */
while(! done) {
/* Find out what rotation is available for this */
/* frame. */
if (this__ == *frame2) {
/* This is the first pass, just put the rotation */
/* directly into ROT2(,,PUT). */
rotget_(&this__, et, &rot2[(i__1 = (put * 3 + 1) * 3 - 12) < 18 &&
0 <= i__1 ? i__1 : s_rnge("rot2", i__1, "refchg_", (
ftnlen)452)], &relto, &found);
if (found) {
this__ = relto;
get = put;
put += inc;
inc = -inc;
cmnode = isrchi_(&this__, &node, frame);
gotone = cmnode > 0;
}
} else {
/* Fetch the rotation into a temporary spot TMPROT */
rotget_(&this__, et, tmprot, &relto, &found);
if (found) {
/* Next multiply TMPROT on the right by the last partial */
/* product (in ROT2(,,GET) ). We do this in line. */
for (i__ = 1; i__ <= 3; ++i__) {
for (j = 1; j <= 3; ++j) {
rot2[(i__1 = i__ + (j + put * 3) * 3 - 13) < 18 && 0
<= i__1 ? i__1 : s_rnge("rot2", i__1, "refch"
"g_", (ftnlen)478)] = tmprot[(i__2 = i__ - 1) <
9 && 0 <= i__2 ? i__2 : s_rnge("tmprot",
i__2, "refchg_", (ftnlen)478)] * rot2[(i__3 =
(j + get * 3) * 3 - 12) < 18 && 0 <= i__3 ?
i__3 : s_rnge("rot2", i__3, "refchg_", (
ftnlen)478)] + tmprot[(i__4 = i__ + 2) < 9 &&
0 <= i__4 ? i__4 : s_rnge("tmprot", i__4,
"refchg_", (ftnlen)478)] * rot2[(i__5 = (j +
get * 3) * 3 - 11) < 18 && 0 <= i__5 ? i__5 :
s_rnge("rot2", i__5, "refchg_", (ftnlen)478)]
+ tmprot[(i__6 = i__ + 5) < 9 && 0 <= i__6 ?
i__6 : s_rnge("tmprot", i__6, "refchg_", (
ftnlen)478)] * rot2[(i__7 = (j + get * 3) * 3
- 10) < 18 && 0 <= i__7 ? i__7 : s_rnge("rot2"
, i__7, "refchg_", (ftnlen)478)];
}
}
/* Adjust GET and PUT so that GET points to the slots */
/* where we just stored the result of our multiply and */
/* so that PUT points to the next available storage */
/* locations. */
get = put;
put += inc;
inc = -inc;
this__ = relto;
cmnode = isrchi_(&this__, &node, frame);
gotone = cmnode > 0;
}
}
/* See if we have a common node and determine whether or not */
/* we are done with this loop. */
done = this__ == 1 || gotone || ! found;
}
/* There are two possible scenarios. Either the chain of */
/* rotations from FRAME2 ran into a node in the chain for */
/* FRAME1 or it didn't. (The common node might very well be */
/* the root node.) If we didn't run into a common one, then */
/* the two chains don't intersect and there is no way to */
/* get from FRAME1 to FRAME2. */
if (! gotone) {
zznofcon_(et, frame1, &frame[(i__1 = node - 1) < 10 && 0 <= i__1 ?
i__1 : s_rnge("frame", i__1, "refchg_", (ftnlen)525)], frame2,
&this__, errmsg, (ftnlen)1840);
if (failed_()) {
/* We were unable to create the error message. This */
/* unfortunate situation could arise if a frame kernel */
/* is corrupted. */
chkout_("REFCHG", (ftnlen)6);
return 0;
}
/* The normal case: signal an error with a descriptive long */
/* error message. */
setmsg_(errmsg, (ftnlen)1840);
sigerr_("SPICE(NOFRAMECONNECT)", (ftnlen)21);
chkout_("REFCHG", (ftnlen)6);
return 0;
}
/* Recall that we have the following. */
/* ROT(1...3, 1...3, 1 ) rotates FRAME(1) to FRAME(2) */
/* ROT(1...3, 1...3, 2 ) rotates FRAME(2) to FRAME(3) */
/* ROT(1...3, 1...3, 3 ) rotates FRAME(3) to FRAME(4) */
/* ROT(1...3, 1...3, CMNODE-1) rotates FRAME(CMNODE-1) */
/* to FRAME(CMNODE) */
/* and that ROT2(1,1,GET) rotates from FRAME2 to CMNODE. */
/* Hence the inverse of ROT2(1,1,GET) rotates from CMNODE */
/* to FRAME2. */
/* If we compute the inverse of ROT2 and store it in */
/* the next available slot of ROT (.i.e. ROT(1,1,CMNODE) */
/* we can simply apply our custom routine that multiplies a */
/* sequence of rotation matrices together to get the */
/* result from FRAME1 to FRAME2. */
xpose_(&rot2[(i__1 = (get * 3 + 1) * 3 - 12) < 18 && 0 <= i__1 ? i__1 :
s_rnge("rot2", i__1, "refchg_", (ftnlen)568)], &rot[(i__2 = (
cmnode * 3 + 1) * 3 - 12) < 126 && 0 <= i__2 ? i__2 : s_rnge(
"rot", i__2, "refchg_", (ftnlen)568)]);
zzrxr_(rot, &cmnode, rotate);
chkout_("REFCHG", (ftnlen)6);
return 0;
} /* refchg_ */
| darioizzo/pykep | src/third_party/cspice/refchg.c | C | gpl-3.0 | 24,383 |
/**
* Model that represents our form template.
*
* @package Ninja Forms client
* @copyright (c) 2017 WP Ninjas
* @since 3.0
*/
define( [], function() {
var model = Backbone.Model.extend( {
defaults: {
objectType: 'template',
id: 'none',
title: 'unknown'
},
initialize: function() {
this.set( 'desc', this.get( 'template-desc' ) );
}
} );
return model;
} ); | dexxtr/osbb-web-manager | www/wp-content/plugins/ninja-forms/client/dashboard/models/formTemplateModel.js | JavaScript | gpl-3.0 | 441 |
package org.thoughtcrime.securesms.video;
import android.media.MediaDataSource;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import org.thoughtcrime.securesms.crypto.AttachmentSecret;
import org.thoughtcrime.securesms.crypto.ClassicDecryptingPartInputStream;
import org.thoughtcrime.securesms.util.Util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@RequiresApi(23)
final class ClassicEncryptedMediaDataSource extends MediaDataSource {
private final AttachmentSecret attachmentSecret;
private final File mediaFile;
private final long length;
ClassicEncryptedMediaDataSource(@NonNull AttachmentSecret attachmentSecret, @NonNull File mediaFile, long length) {
this.attachmentSecret = attachmentSecret;
this.mediaFile = mediaFile;
this.length = length;
}
@Override
public int readAt(long position, byte[] bytes, int offset, int length) throws IOException {
try (InputStream inputStream = ClassicDecryptingPartInputStream.createFor(attachmentSecret, mediaFile)) {
byte[] buffer = new byte[4096];
long headerRemaining = position;
while (headerRemaining > 0) {
int read = inputStream.read(buffer, 0, Util.toIntExact(Math.min((long)buffer.length, headerRemaining)));
if (read == -1) return -1;
headerRemaining -= read;
}
return inputStream.read(bytes, offset, length);
}
}
@Override
public long getSize() {
return length;
}
@Override
public void close() {}
}
| jtracey/Signal-Android | src/org/thoughtcrime/securesms/video/ClassicEncryptedMediaDataSource.java | Java | gpl-3.0 | 1,585 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2018, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
DOCUMENTATION = r'''
---
module: bigip_ike_peer
short_description: Manage IPSec IKE Peer configuration on BIG-IP
description:
- Manage IPSec IKE Peer configuration on BIG-IP.
version_added: 2.8
options:
name:
description:
- Specifies the name of the IKE peer.
required: True
description:
description:
- Description of the IKE peer.
version:
description:
- Specifies which version of IKE is used.
- If the system you are configuring is the IPsec initiator, and you select
both versions, the system tries using IKEv2 for negotiation. If the remote
peer does not support IKEv2, the IPsec tunnel fails. To use IKEv1 in this
case, you must deselect Version 2 and try again.
- If the system you are configuring is the IPsec responder, and you select
both versions, the IPsec initiator system determines which IKE version to use.
- When creating a new IKE peer, this value is required.
choices:
- v1
- v2
presented_id_type:
description:
- Specifies the identifier type that the local system uses to identify
itself to the peer during IKE Phase 1 negotiations.
choices:
- address
- asn1dn
- fqdn
- keyid-tag
- user-fqdn
- override
presented_id_value:
description:
- This is a required value when C(version) includes (Cv2).
- Specifies a value for the identity when using a C(presented_id_type) of
C(override).
verified_id_type:
description:
- Specifies the identifier type that the local system uses to identify
the peer during IKE Phase 1 negotiation.
- This is a required value when C(version) includes (Cv2).
- When C(user-fqdn), value of C(verified_id_value) must be in the form of
User @ DNS domain string.
choices:
- address
- asn1dn
- fqdn
- keyid-tag
- user-fqdn
- override
verified_id_value:
description:
- This is a required value when C(version) includes (Cv2).
- Specifies a value for the identity when using a C(verified_id_type) of
C(override).
phase1_auth_method:
description:
- Specifies the authentication method for phase 1 negotiation.
- When creating a new IKE peer, if this value is not specified, the default is
C(rsa-signature).
choices:
- pre-shared-key
- rsa-signature
phase1_cert:
description:
- Specifies the digital certificate to use for the RSA signature.
- When creating a new IKE peer, if this value is not specified, and
C(phase1_auth_method) is C(rsa-signature), the default is C(default.crt).
- This parameter is invalid when C(phase1_auth_method) is C(pre-shared-key).
phase1_key:
description:
- Specifies the public key that the digital certificate contains.
- When creating a new IKE peer, if this value is not specified, and
C(phase1_auth_method) is C(rsa-signature), the default is C(default.key).
- This parameter is invalid when C(phase1_auth_method) is C(pre-shared-key).
phase1_verify_peer_cert:
description:
- In IKEv2, specifies whether the certificate sent by the IKE peer is verified
using the Trusted Certificate Authorities, a CRL, and/or a peer certificate.
- In IKEv1, specifies whether the identifier sent by the peer is verified with
the credentials in the certificate, in the following manner - ASN1DN; specifies
that the entire certificate subject name is compared with the identifier.
Address, FQDN, or User FQDN; specifies that the certificate's subjectAltName is
compared with the identifier. If the two do not match, the negotiation fails.
- When creating a new IKE peer, if this value is not specified, and
C(phase1_auth_method) is C(rsa-signature), the default is C(no).
- This parameter is invalid when C(phase1_auth_method) is C(pre-shared-key).
type: bool
preshared_key:
description:
- Specifies a string that the IKE peers share for authenticating each other.
- This parameter is only relevant when C(phase1_auth_method) is C(pre-shared-key).
- This parameter is invalid when C(phase1_auth_method) is C(rsa-signature).
remote_address:
description:
- Displays the IP address of the BIG-IP system that is remote to the system
you are configuring.
phase1_encryption_algorithm:
description:
- Specifies the algorithm to use for IKE encryption.
- IKE C(version) C(v2) does not support C(blowfish), C(camellia), or C(cast128).
choices:
- 3des
- des
- blowfish
- cast128
- aes128
- aes192
- aes256
- camellia
phase1_hash_algorithm:
description:
- Specifies the algorithm to use for IKE authentication.
choices:
- sha1
- md5
- sha256
- sha384
- sha512
phase1_perfect_forward_secrecy:
description:
- Specifies the Diffie-Hellman group to use for IKE Phase 1 and Phase 2 negotiations.
choices:
- ecp256
- ecp384
- ecp521
- modp768
- modp1024
- modp1536
- modp2048
- modp3072
- modp4096
- modp6144
- modp8192
update_password:
description:
- C(always) will allow to update passwords if the user chooses to do so.
C(on_create) will only set the password for newly created IKE peers.
default: always
choices:
- always
- on_create
partition:
description:
- Device partition to manage resources on.
default: Common
state:
description:
- When C(present), ensures that the resource exists.
- When C(absent), ensures the resource is removed.
default: present
choices:
- present
- absent
extends_documentation_fragment: f5
author:
- Tim Rupp (@caphrim007)
- Wojciech Wypior (@wojtek0806)
'''
EXAMPLES = r'''
- name: Create a ...
bigip_ike_peer:
name: foo
provider:
password: secret
server: lb.mydomain.com
user: admin
delegate_to: localhost
'''
RETURN = r'''
presented_id_type:
description: The new Presented ID Type value of the resource.
returned: changed
type: string
sample: address
verified_id_type:
description: The new Verified ID Type value of the resource.
returned: changed
type: string
sample: address
phase1_auth_method:
description: The new IKE Phase 1 Credentials Authentication Method value of the resource.
returned: changed
type: string
sample: rsa-signature
remote_address:
description: The new Remote Address value of the resource.
returned: changed
type: string
sample: 1.2.2.1
version:
description: The new list of IKE versions.
returned: changed
type: list
sample: ['v1', 'v2']
phase1_encryption_algorithm:
description: The new IKE Phase 1 Encryption Algorithm.
returned: changed
type: string
sample: 3des
phase1_hash_algorithm:
description: The new IKE Phase 1 Authentication Algorithm.
returned: changed
type: string
sample: sha256
phase1_perfect_forward_secrecy:
description: The new IKE Phase 1 Perfect Forward Secrecy.
returned: changed
type: string
sample: modp1024
phase1_cert:
description: The new IKE Phase 1 Certificate Credentials.
returned: changed
type: string
sample: /Common/cert1.crt
phase1_key:
description: The new IKE Phase 1 Key Credentials.
returned: changed
type: string
sample: /Common/cert1.key
phase1_verify_peer_cert:
description: The new IKE Phase 1 Key Verify Peer Certificate setting.
returned: changed
type: bool
sample: yes
verified_id_value:
description: The new Verified ID Value setting for the Verified ID Type.
returned: changed
type: string
sample: 1.2.3.1
presented_id_value:
description: The new Presented ID Value setting for the Presented ID Type.
returned: changed
type: string
sample: 1.2.3.1
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback
try:
from library.module_utils.network.f5.bigip import F5RestClient
from library.module_utils.network.f5.common import F5ModuleError
from library.module_utils.network.f5.common import AnsibleF5Parameters
from library.module_utils.network.f5.common import cleanup_tokens
from library.module_utils.network.f5.common import fq_name
from library.module_utils.network.f5.common import f5_argument_spec
from library.module_utils.network.f5.common import exit_json
from library.module_utils.network.f5.common import fail_json
from library.module_utils.network.f5.common import transform_name
from library.module_utils.network.f5.common import flatten_boolean
from library.module_utils.network.f5.compare import cmp_str_with_none
except ImportError:
from ansible.module_utils.network.f5.bigip import F5RestClient
from ansible.module_utils.network.f5.common import F5ModuleError
from ansible.module_utils.network.f5.common import AnsibleF5Parameters
from ansible.module_utils.network.f5.common import cleanup_tokens
from ansible.module_utils.network.f5.common import fq_name
from ansible.module_utils.network.f5.common import f5_argument_spec
from ansible.module_utils.network.f5.common import exit_json
from ansible.module_utils.network.f5.common import fail_json
from ansible.module_utils.network.f5.common import transform_name
from ansible.module_utils.network.f5.common import flatten_boolean
from ansible.module_utils.network.f5.compare import cmp_str_with_none
class Parameters(AnsibleF5Parameters):
api_map = {
'myIdType': 'presented_id_type',
'peersIdType': 'verified_id_type',
'phase1AuthMethod': 'phase1_auth_method',
'presharedKeyEncrypted': 'preshared_key',
'remoteAddress': 'remote_address',
'version': 'version',
'phase1EncryptAlgorithm': 'phase1_encryption_algorithm',
'phase1HashAlgorithm': 'phase1_hash_algorithm',
'phase1PerfectForwardSecrecy': 'phase1_perfect_forward_secrecy',
'myCertFile': 'phase1_cert',
'myCertKeyFile': 'phase1_key',
'verifyCert': 'phase1_verify_peer_cert',
'peersIdValue': 'verified_id_value',
'myIdValue': 'presented_id_value',
}
api_attributes = [
'myIdType',
'peersIdType',
'phase1AuthMethod',
'presharedKeyEncrypted',
'remoteAddress',
'version',
'phase1EncryptAlgorithm',
'phase1HashAlgorithm',
'phase1PerfectForwardSecrecy',
'myCertFile',
'myCertKeyFile',
'verifyCert',
'peersIdValue',
'myIdValue',
'description',
]
returnables = [
'presented_id_type',
'verified_id_type',
'phase1_auth_method',
'preshared_key',
'remote_address',
'version',
'phase1_encryption_algorithm',
'phase1_hash_algorithm',
'phase1_perfect_forward_secrecy',
'phase1_cert',
'phase1_key',
'phase1_verify_peer_cert',
'verified_id_value',
'presented_id_value',
'description',
]
updatables = [
'presented_id_type',
'verified_id_type',
'phase1_auth_method',
'preshared_key',
'remote_address',
'version',
'phase1_encryption_algorithm',
'phase1_hash_algorithm',
'phase1_perfect_forward_secrecy',
'phase1_cert',
'phase1_key',
'phase1_verify_peer_cert',
'verified_id_value',
'presented_id_value',
'description',
]
@property
def phase1_verify_peer_cert(self):
return flatten_boolean(self._values['phase1_verify_peer_cert'])
class ApiParameters(Parameters):
@property
def description(self):
if self._values['description'] in [None, 'none']:
return None
return self._values['description']
class ModuleParameters(Parameters):
@property
def phase1_cert(self):
if self._values['phase1_cert'] is None:
return None
if self._values['phase1_cert'] in ['', 'none']:
return ''
return fq_name(self.partition, self._values['phase1_cert'])
@property
def phase1_key(self):
if self._values['phase1_key'] is None:
return None
if self._values['phase1_key'] in ['', 'none']:
return ''
return fq_name(self.partition, self._values['phase1_key'])
@property
def description(self):
if self._values['description'] is None:
return None
elif self._values['description'] in ['none', '']:
return ''
return self._values['description']
class Changes(Parameters):
def to_return(self):
result = {}
try:
for returnable in self.returnables:
result[returnable] = getattr(self, returnable)
result = self._filter_params(result)
except Exception:
pass
return result
class UsableChanges(Changes):
@property
def phase1_verify_peer_cert(self):
if self._values['phase1_verify_peer_cert'] is None:
return None
elif self._values['phase1_verify_peer_cert'] == 'yes':
return 'true'
else:
return 'false'
class ReportableChanges(Changes):
@property
def phase1_verify_peer_cert(self):
return flatten_boolean(self._values['phase1_verify_peer_cert'])
@property
def preshared_key(self):
return None
class Difference(object):
def __init__(self, want, have=None):
self.want = want
self.have = have
def compare(self, param):
try:
result = getattr(self, param)
return result
except AttributeError:
return self.__default(param)
def __default(self, param):
attr1 = getattr(self.want, param)
try:
attr2 = getattr(self.have, param)
if attr1 != attr2:
return attr1
except AttributeError:
return attr1
@property
def description(self):
return cmp_str_with_none(self.want.description, self.have.description)
class ModuleManager(object):
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.want = ModuleParameters(params=self.module.params)
self.have = ApiParameters()
self.changes = UsableChanges()
def _set_changed_options(self):
changed = {}
for key in Parameters.returnables:
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = UsableChanges(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
updatables = Parameters.updatables
changed = dict()
for k in updatables:
change = diff.compare(k)
if change is None:
continue
else:
if isinstance(change, dict):
changed.update(change)
else:
changed[k] = change
if changed:
self.changes = UsableChanges(params=changed)
return True
return False
def should_update(self):
result = self._update_changed_options()
if result:
return True
return False
def exec_module(self):
changed = False
result = dict()
state = self.want.state
if state == "present":
changed = self.present()
elif state == "absent":
changed = self.absent()
reportable = ReportableChanges(params=self.changes.to_return())
changes = reportable.to_return()
result.update(**changes)
result.update(dict(changed=changed))
self._announce_deprecations(result)
return result
def _announce_deprecations(self, result):
warnings = result.pop('__warnings', [])
for warning in warnings:
self.client.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
def present(self):
if self.exists():
return self.update()
else:
return self.create()
def exists(self):
uri = "https://{0}:{1}/mgmt/tm/net/ipsec/ike-peer/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
)
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError:
return False
if resp.status == 404 or 'code' in response and response['code'] == 404:
return False
return True
def update(self):
self.have = self.read_current_from_device()
if self.changes.version is not None and len(self.changes.version) == 0:
raise F5ModuleError(
"At least one version value must be specified."
)
if self.changes.phase1_auth_method == 'pre-shared-key':
if self.changes.preshared_key is None and self.have.preshared_key is None:
raise F5ModuleError(
"A 'preshared_key' must be specified when changing 'phase1_auth_method' "
"to 'pre-shared-key'."
)
if self.want.update_password == 'always':
self.want.update({'preshared_key': self.want.preshared_key})
else:
if self.want.preshared_key:
del self.want._values['preshared_key']
if not self.should_update():
return False
if self.module.check_mode:
return True
self.update_on_device()
return True
def remove(self):
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
raise F5ModuleError("Failed to delete the resource.")
return True
def create(self):
self._set_changed_options()
if self.changes.version is None:
raise F5ModuleError(
"The 'version' parameter is required when creating a new IKE peer."
)
if self.changes.phase1_auth_method is None:
self.changes.update({'phase1_auth_method': 'rsa-signature'})
if self.changes.phase1_cert is None:
self.changes.update({'phase1_cert': 'default.crt'})
if self.changes.phase1_key is None:
self.changes.update({'phase1_key': 'default.key'})
if self.module.check_mode:
return True
self.create_on_device()
return True
def create_on_device(self):
params = self.changes.api_params()
params['name'] = self.want.name
params['partition'] = self.want.partition
uri = "https://{0}:{1}/mgmt/tm/net/ipsec/ike-peer/".format(
self.client.provider['server'],
self.client.provider['server_port']
)
resp = self.client.api.post(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] in [400, 403]:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
def update_on_device(self):
params = self.changes.api_params()
uri = "https://{0}:{1}/mgmt/tm/net/ipsec/ike-peer/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
)
resp = self.client.api.patch(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
def absent(self):
if self.exists():
return self.remove()
return False
def remove_from_device(self):
uri = "https://{0}:{1}/mgmt/tm/net/ipsec/ike-peer/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
)
resp = self.client.api.delete(uri)
if resp.status == 200:
return True
def read_current_from_device(self):
uri = "https://{0}:{1}/mgmt/tm/net/ipsec/ike-peer/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
)
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
return ApiParameters(params=response)
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
argument_spec = dict(
name=dict(required=True),
presented_id_type=dict(
choices=['address', 'asn1dn', 'fqdn', 'keyid-tag', 'user-fqdn', 'override']
),
presented_id_value=dict(),
verified_id_type=dict(
choices=['address', 'asn1dn', 'fqdn', 'keyid-tag', 'user-fqdn', 'override']
),
verified_id_value=dict(),
phase1_auth_method=dict(
choices=[
'pre-shared-key', 'rsa-signature'
]
),
preshared_key=dict(no_log=True),
remote_address=dict(),
version=dict(
type='list',
choices=['v1', 'v2']
),
phase1_encryption_algorithm=dict(
choices=[
'3des', 'des', 'blowfish', 'cast128', 'aes128', 'aes192',
'aes256', 'camellia'
]
),
phase1_hash_algorithm=dict(
choices=[
'sha1', 'md5', 'sha256', 'sha384', 'sha512'
]
),
phase1_perfect_forward_secrecy=dict(
choices=[
'ecp256', 'ecp384', 'ecp521', 'modp768', 'modp1024', 'modp1536',
'modp2048', 'modp3072', 'modp4096', 'modp6144', 'modp8192'
]
),
phase1_cert=dict(),
phase1_key=dict(),
phase1_verify_peer_cert=dict(type='bool'),
update_password=dict(
default='always',
choices=['always', 'on_create']
),
description=dict(),
state=dict(default='present', choices=['absent', 'present']),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
)
)
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
self.required_if = [
['presented_id_type', 'fqdn', ['presented_id_value']],
['presented_id_type', 'keyid-tag', ['presented_id_value']],
['presented_id_type', 'user-fqdn', ['presented_id_value']],
['presented_id_type', 'override', ['presented_id_value']],
['verified_id_type', 'fqdn', ['verified_id_value']],
['verified_id_type', 'keyid-tag', ['verified_id_value']],
['verified_id_type', 'user-fqdn', ['verified_id_value']],
['verified_id_type', 'override', ['verified_id_value']],
]
self.required_together = [
['phase1_cert', 'phase1_key']
]
def main():
spec = ArgumentSpec()
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
required_if=spec.required_if,
required_together=spec.required_together,
)
client = F5RestClient(**module.params)
try:
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
exit_json(module, results, client)
except F5ModuleError as ex:
cleanup_tokens(client)
fail_json(module, ex, client)
if __name__ == '__main__':
main()
| yfried/ansible | lib/ansible/modules/network/f5/bigip_ike_peer.py | Python | gpl-3.0 | 25,483 |
/*
* The JTS Topology Suite is a collection of Java classes that
* implement the fundamental operations required to validate a given
* geo-spatial data set to a known topological specification.
*
* Copyright (C) 2001 Vivid Solutions
*
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* For more information, contact:
*
* Vivid Solutions
* Suite #1A
* 2328 Government Street
* Victoria BC V8T 5G5
* Canada
*
* (250)385-6040
* www.vividsolutions.com
*/
package com.vividsolutions.jts.index.chain;
import java.util.*;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geomgraph.Quadrant;
/**
* Constructs {@link MonotoneChain}s
* for sequences of {@link Coordinate}s.
*
* @version 1.7
*/
public class MonotoneChainBuilder {
public static int[] toIntArray(List list)
{
int[] array = new int[list.size()];
for (int i = 0; i < array.length; i++) {
array[i] = ((Integer) list.get(i)).intValue();
}
return array;
}
public static List getChains(Coordinate[] pts)
{
return getChains(pts, null);
}
/**
* Return a list of the {@link MonotoneChain}s
* for the given list of coordinates.
*/
public static List getChains(Coordinate[] pts, Object context)
{
List mcList = new ArrayList();
int[] startIndex = getChainStartIndices(pts);
for (int i = 0; i < startIndex.length - 1; i++) {
MonotoneChain mc = new MonotoneChain(pts, startIndex[i], startIndex[i + 1], context);
mcList.add(mc);
}
return mcList;
}
/**
* Return an array containing lists of start/end indexes of the monotone chains
* for the given list of coordinates.
* The last entry in the array points to the end point of the point array,
* for use as a sentinel.
*/
public static int[] getChainStartIndices(Coordinate[] pts)
{
// find the startpoint (and endpoints) of all monotone chains in this edge
int start = 0;
List startIndexList = new ArrayList();
startIndexList.add(new Integer(start));
do {
int last = findChainEnd(pts, start);
startIndexList.add(new Integer(last));
start = last;
} while (start < pts.length - 1);
// copy list to an array of ints, for efficiency
int[] startIndex = toIntArray(startIndexList);
return startIndex;
}
/**
* Finds the index of the last point in a monotone chain
* starting at a given point.
* Any repeated points (0-length segments) will be included
* in the monotone chain returned.
*
* @return the index of the last point in the monotone chain
* starting at <code>start</code>.
*/
private static int findChainEnd(Coordinate[] pts, int start)
{
int safeStart = start;
// skip any zero-length segments at the start of the sequence
// (since they cannot be used to establish a quadrant)
while (safeStart < pts.length - 1 && pts[safeStart].equals2D(pts[safeStart + 1])) {
safeStart++;
}
// check if there are NO non-zero-length segments
if (safeStart >= pts.length - 1) {
return pts.length - 1;
}
// determine overall quadrant for chain (which is the starting quadrant)
int chainQuad = Quadrant.quadrant(pts[safeStart], pts[safeStart + 1]);
int last = start + 1;
while (last < pts.length) {
// skip zero-length segments, but include them in the chain
if (! pts[last - 1].equals2D(pts[last])) {
// compute quadrant for next possible segment in chain
int quad = Quadrant.quadrant(pts[last - 1], pts[last]);
if (quad != chainQuad) break;
}
last++;
}
return last - 1;
}
public MonotoneChainBuilder() {
}
}
| Jules-/terraingis | src/TerrainGIS/src/com/vividsolutions/jts/index/chain/MonotoneChainBuilder.java | Java | gpl-3.0 | 4,504 |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#pragma once
#include <QtGlobal>
namespace QmlDesigner {
inline double round(double value, int digits)
{
double factor = digits * 10.;
return double(qRound64(value * factor)) / factor;
}
}
| pivonroll/Qt_Creator | src/plugins/qmldesigner/designercore/include/mathutils.h | C | gpl-3.0 | 1,396 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration |
\\ / A nd | For copyright notice see file Copyright
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
foam-extend is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with foam-extend. If not, see <http://www.gnu.org/licenses/>.
Description
\*---------------------------------------------------------------------------*/
#include "writeFuns.H"
#include "interpolatePointToCell.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Store List in dest
template<class Type>
void Foam::writeFuns::insert
(
const List<Type>& source,
DynamicList<floatScalar>& dest
)
{
forAll(source, i)
{
insert(source[i], dest);
}
}
//// Store List (indexed through map) in dest
//template<class Type>
//void Foam::writeFuns::insert
//(
// const labelList& map,
// const List<Type>& source,
// DynamicList<floatScalar>& dest
//)
//{
// forAll(map, i)
// {
// insert(source[map[i]], dest);
// }
//}
template<class Type>
void Foam::writeFuns::write
(
std::ostream& os,
const bool binary,
const GeometricField<Type, fvPatchField, volMesh>& vvf,
const vtkMesh& vMesh
)
{
const fvMesh& mesh = vMesh.mesh();
const labelList& superCells = vMesh.topo().superCells();
label nValues = mesh.nCells() + superCells.size();
os << vvf.name() << ' ' << pTraits<Type>::nComponents << ' '
<< nValues << " float" << std::endl;
DynamicList<floatScalar> fField(pTraits<Type>::nComponents*nValues);
insert(vvf.internalField(), fField);
forAll(superCells, superCellI)
{
label origCellI = superCells[superCellI];
insert(vvf[origCellI], fField);
}
write(os, binary, fField);
}
template<class Type>
void Foam::writeFuns::write
(
std::ostream& os,
const bool binary,
const GeometricField<Type, pointPatchField, pointMesh>& pvf,
const vtkMesh& vMesh
)
{
const fvMesh& mesh = vMesh.mesh();
const vtkTopo& topo = vMesh.topo();
const labelList& addPointCellLabels = topo.addPointCellLabels();
const label nTotPoints = mesh.nPoints() + addPointCellLabels.size();
os << pvf.name() << ' ' << pTraits<Type>::nComponents << ' '
<< nTotPoints << " float" << std::endl;
DynamicList<floatScalar> fField(pTraits<Type>::nComponents*nTotPoints);
insert(pvf, fField);
forAll(addPointCellLabels, api)
{
label origCellI = addPointCellLabels[api];
insert(interpolatePointToCell(pvf, origCellI), fField);
}
write(os, binary, fField);
}
template<class Type>
void Foam::writeFuns::write
(
std::ostream& os,
const bool binary,
const GeometricField<Type, fvPatchField, volMesh>& vvf,
const GeometricField<Type, pointPatchField, pointMesh>& pvf,
const vtkMesh& vMesh
)
{
const fvMesh& mesh = vMesh.mesh();
const vtkTopo& topo = vMesh.topo();
const labelList& addPointCellLabels = topo.addPointCellLabels();
const label nTotPoints = mesh.nPoints() + addPointCellLabels.size();
os << vvf.name() << ' ' << pTraits<Type>::nComponents << ' '
<< nTotPoints << " float" << std::endl;
DynamicList<floatScalar> fField(pTraits<Type>::nComponents*nTotPoints);
insert(pvf, fField);
forAll(addPointCellLabels, api)
{
label origCellI = addPointCellLabels[api];
insert(vvf[origCellI], fField);
}
write(os, binary, fField);
}
template<class Type, template<class> class PatchField, class GeoMesh>
void Foam::writeFuns::write
(
std::ostream& os,
const bool binary,
const PtrList<GeometricField<Type, PatchField, GeoMesh> >& flds,
const vtkMesh& vMesh
)
{
forAll(flds, i)
{
write(os, binary, flds[i], vMesh);
}
}
template<class Type>
void Foam::writeFuns::write
(
std::ostream& os,
const bool binary,
const volPointInterpolation& pInterp,
const PtrList<GeometricField<Type, fvPatchField, volMesh> >& flds,
const vtkMesh& vMesh
)
{
forAll(flds, i)
{
write(os, binary, flds[i], pInterp.interpolate(flds[i])(), vMesh);
}
}
// ************************************************************************* //
| WensiWu/openfoam-extend-foam-extend-3.1 | applications/utilities/postProcessing/dataConversion/foamToVTK/writeFunsTemplates.C | C++ | gpl-3.0 | 5,008 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('sites', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('object_pk', models.TextField(verbose_name='object ID')),
('user_name', models.CharField(max_length=50, verbose_name="user's name", blank=True)),
('user_email', models.EmailField(max_length=254, verbose_name="user's email address", blank=True)),
('user_url', models.URLField(verbose_name="user's URL", blank=True)),
('comment', models.TextField(max_length=3000, verbose_name='comment')),
('submit_date', models.DateTimeField(default=None, verbose_name='date/time submitted', db_index=True)),
('ip_address', models.GenericIPAddressField(unpack_ipv4=True, null=True, verbose_name='IP address', blank=True)),
('is_public', models.BooleanField(default=True, help_text='Uncheck this box to make the comment effectively disappear from the site.', verbose_name='is public')),
('is_removed', models.BooleanField(default=False, help_text='Check this box if the comment is inappropriate. A "This comment has been removed" message will be displayed instead.', verbose_name='is removed')),
('content_type', models.ForeignKey(related_name='content_type_set_for_comment', verbose_name='content type', to='contenttypes.ContentType', on_delete=models.CASCADE)),
('site', models.ForeignKey(to='sites.Site', on_delete=models.CASCADE)),
('user', models.ForeignKey(related_name='comment_comments', verbose_name='user', blank=True, to=settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)),
],
options={
'ordering': ('submit_date',),
'abstract': False,
'verbose_name': 'comment',
'verbose_name_plural': 'comments',
'permissions': [('can_moderate', 'Can moderate comments')],
},
),
]
| claudep/pootle | pootle/apps/pootle_comment/migrations/0001_initial.py | Python | gpl-3.0 | 2,477 |
class AddImmutableToUserfiles < ActiveRecord::Migration
def change
add_column :userfiles, :immutable, :boolean, :default => false
end
end
| crocodoyle/cbrain | BrainPortal/db/migrate/20130805152115_add_immutable_to_userfiles.rb | Ruby | gpl-3.0 | 146 |
########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: Krzysztof.Ciba@NOSPAMgmail.com
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: Krzysztof.Ciba@NOSPAMgmail.com
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author Krzysztof.Ciba@NOSPAMgmail.com
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
| Sbalbp/DIRAC | RequestManagementSystem/Service/ReqProxyHandler.py | Python | gpl-3.0 | 7,200 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('trans', '0045_auto_20150916_1007'),
]
operations = [
migrations.CreateModel(
name='Billing',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
],
),
migrations.CreateModel(
name='Plan',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(unique=True, max_length=100)),
('price', models.IntegerField()),
('limit_strings', models.IntegerField()),
('limit_languages', models.IntegerField()),
('limit_repositories', models.IntegerField()),
('limit_projects', models.IntegerField()),
],
options={
'ordering': ['name'],
},
),
migrations.AddField(
model_name='billing',
name='plan',
field=models.ForeignKey(to='billing.Plan'),
),
migrations.AddField(
model_name='billing',
name='projects',
field=models.ManyToManyField(to='trans.Project', blank=True),
),
migrations.AddField(
model_name='billing',
name='user',
field=models.OneToOneField(to=settings.AUTH_USER_MODEL),
),
]
| miumok98/weblate | weblate/billing/migrations/0001_initial.py | Python | gpl-3.0 | 1,726 |
/**
* Aptana Studio
* Copyright (c) 2005-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions).
* Please see the license.html included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package com.aptana.ide.ui.io.navigator;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.viewers.Viewer;
import com.aptana.core.util.ArrayUtil;
import com.aptana.ide.core.io.CoreIOPlugin;
import com.aptana.ui.util.UIUtils;
public class ProjectExplorerContentProvider extends FileTreeContentProvider
{
private static final String LOCAL_SHORTCUTS_ID = "com.aptana.ide.core.io.localShortcuts"; //$NON-NLS-1$
private Viewer treeViewer;
private IResourceChangeListener resourceListener = new IResourceChangeListener()
{
public void resourceChanged(IResourceChangeEvent event)
{
// to fix https://jira.appcelerator.org/browse/TISTUD-1695, we need to force a selection update when a
// project is closed or opened
if (shouldUpdateActions(event.getDelta()))
{
UIUtils.getDisplay().asyncExec(new Runnable()
{
public void run()
{
treeViewer.setSelection(treeViewer.getSelection());
}
});
}
}
};
public ProjectExplorerContentProvider()
{
ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceListener, IResourceChangeEvent.POST_CHANGE);
}
@Override
public void dispose()
{
ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceListener);
super.dispose();
}
@Override
public Object[] getChildren(Object parentElement)
{
if (parentElement instanceof IResource)
{
return ArrayUtil.NO_OBJECTS;
}
return super.getChildren(parentElement);
}
@Override
public Object[] getElements(Object inputElement)
{
if (inputElement instanceof IWorkspaceRoot)
{
List<Object> children = new ArrayList<Object>();
children.add(LocalFileSystems.getInstance());
children.add(CoreIOPlugin.getConnectionPointManager().getConnectionPointCategory(LOCAL_SHORTCUTS_ID));
return children.toArray(new Object[children.size()]);
}
return super.getElements(inputElement);
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput)
{
treeViewer = viewer;
super.inputChanged(viewer, oldInput, newInput);
}
private boolean shouldUpdateActions(IResourceDelta delta)
{
if (delta.getFlags() == IResourceDelta.OPEN)
{
return true;
}
IResourceDelta[] children = delta.getAffectedChildren();
for (IResourceDelta child : children)
{
if (shouldUpdateActions(child))
{
return true;
}
}
return false;
}
}
| HossainKhademian/Studio3 | plugins/com.aptana.ui.io/src/com/aptana/ide/ui/io/navigator/ProjectExplorerContentProvider.java | Java | gpl-3.0 | 3,028 |
---------------------------------------------
-- Stasis
--
-- Description: Paralyzes targets in an area of effect.
-- Type: Enfeebling
-- Utsusemi/Blink absorb: Ignores shadows
-- Range: 10' radial
-- Notes:
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local shadows = MOBPARAM_1_SHADOW;
local dmg = MobFinalAdjustments(10,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,shadows);
local typeEffect = EFFECT_PARALYSIS;
mob:resetEnmity(target);
if(MobPhysicalHit(skill)) then
target:addStatusEffect(typeEffect,40,0,60);
skill:setMsg(MSG_ENFEEB_IS);
return typeEffect;
end
return shadows;
end;
| greasydeal/darkstar | scripts/globals/mobskills/Stasis.lua | Lua | gpl-3.0 | 912 |
<pre class="docs-method-signature"><code>util.uuid()</code></pre><p>Return a pseudo-<a href="http://en.wikipedia.org/wiki/Universally_unique_identifier">UUID</a>.</p> | chill117/joint | docs/src/joint/api/util/uuid.html | HTML | mpl-2.0 | 166 |
require_relative "../client"
require_relative "../request"
require_relative "../response"
module Vault
class Client
# A proxy to the {Sys} methods.
# @return [Sys]
def sys
@sys ||= Sys.new(self)
end
end
class Sys < Request; end
end
require_relative "sys/audit"
require_relative "sys/auth"
require_relative "sys/init"
require_relative "sys/leader"
require_relative "sys/lease"
require_relative "sys/mount"
require_relative "sys/policy"
require_relative "sys/seal"
| NicheProject/vault-ruby | lib/vault/api/sys.rb | Ruby | mpl-2.0 | 494 |
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/language/v1beta2/language_service.proto
namespace Google\Cloud\Language\V1beta2;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* The entity analysis request message.
*
* Generated from protobuf message <code>google.cloud.language.v1beta2.AnalyzeEntitiesRequest</code>
*/
class AnalyzeEntitiesRequest extends \Google\Protobuf\Internal\Message
{
/**
* Input document.
*
* Generated from protobuf field <code>.google.cloud.language.v1beta2.Document document = 1;</code>
*/
private $document = null;
/**
* The encoding type used by the API to calculate offsets.
*
* Generated from protobuf field <code>.google.cloud.language.v1beta2.EncodingType encoding_type = 2;</code>
*/
private $encoding_type = 0;
public function __construct() {
\GPBMetadata\Google\Cloud\Language\V1Beta2\LanguageService::initOnce();
parent::__construct();
}
/**
* Input document.
*
* Generated from protobuf field <code>.google.cloud.language.v1beta2.Document document = 1;</code>
* @return \Google\Cloud\Language\V1beta2\Document
*/
public function getDocument()
{
return $this->document;
}
/**
* Input document.
*
* Generated from protobuf field <code>.google.cloud.language.v1beta2.Document document = 1;</code>
* @param \Google\Cloud\Language\V1beta2\Document $var
* @return $this
*/
public function setDocument($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Language\V1beta2\Document::class);
$this->document = $var;
return $this;
}
/**
* The encoding type used by the API to calculate offsets.
*
* Generated from protobuf field <code>.google.cloud.language.v1beta2.EncodingType encoding_type = 2;</code>
* @return int
*/
public function getEncodingType()
{
return $this->encoding_type;
}
/**
* The encoding type used by the API to calculate offsets.
*
* Generated from protobuf field <code>.google.cloud.language.v1beta2.EncodingType encoding_type = 2;</code>
* @param int $var
* @return $this
*/
public function setEncodingType($var)
{
GPBUtil::checkEnum($var, \Google\Cloud\Language\V1beta2\EncodingType::class);
$this->encoding_type = $var;
return $this;
}
}
| wlwwt/shopware | vendor/google/proto-client/src/Google/Cloud/Language/V1beta2/AnalyzeEntitiesRequest.php | PHP | agpl-3.0 | 2,541 |
Traducción
Traducción por cesar
hola
Hola
| gallir/Meneame | vendor/crodas/haanga/tests/assert_templates/trans.html | HTML | agpl-3.0 | 44 |
/* This file is part of VoltDB.
* Copyright (C) 2008-2015 VoltDB Inc.
*
* This program 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.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.groovy;
import static java.lang.Character.toLowerCase;
import static java.lang.Character.toUpperCase;
import groovy.lang.Closure;
import groovy.lang.GString;
import groovy.lang.GroovyObjectSupport;
import java.util.NavigableMap;
import org.voltdb.VoltTable;
import org.voltdb.VoltType;
import com.google_voltpatches.common.collect.ImmutableSortedMap;
/**
* Groovy table access expediter. It allows you to easily navigate a VoltTable,
* and access its column values.
* <p>
* Example usage on a query that returns results for the :
* <code><pre>
* cr = client.callProcedure('@AdHoc','select INTEGER_COL, STRING_COL from FOO')
* tuplerator(cr.results[0]).eachRow {
*
* integerColValueByIndex = it[0]
* stringColValueByIndex = it[1]
*
* integerColValueByName = it['integerCol']
* stringColValyeByName = it['stringCol']
*
* integerColValueByField = it.integerCol
* stringColValyeByField = it.stringCol
* }
*
* </code></pre>
*
*/
public class Tuplerator extends GroovyObjectSupport {
private final VoltTable table;
private final VoltType [] byIndex;
private final NavigableMap<String, Integer> byName;
public static Tuplerator newInstance(VoltTable table) {
return new Tuplerator(table);
}
public Tuplerator(final VoltTable table) {
this.table = table;
this.byIndex = new VoltType[table.getColumnCount()];
ImmutableSortedMap.Builder<String, Integer> byNameBuilder =
ImmutableSortedMap.naturalOrder();
for (int c = 0; c < byIndex.length; ++c) {
VoltType cType = table.getColumnType(c);
StringBuilder cName = new StringBuilder(table.getColumnName(c));
byIndex[c] = cType;
boolean upperCaseIt = false;
for (int i = 0; i < cName.length();) {
char chr = cName.charAt(i);
if (chr == '_' || chr == '.' || chr == '$') {
cName.deleteCharAt(i);
upperCaseIt = true;
} else {
chr = upperCaseIt ? toUpperCase(chr) : toLowerCase(chr);
cName.setCharAt(i, chr);
upperCaseIt = false;
++i;
}
}
byNameBuilder.put(cName.toString(),c);
}
byName = byNameBuilder.build();
}
/**
* It calls the given closure on each row of the underlying table by passing itself
* as the only closure parameter
*
* @param c the self instance of Tuplerator
*/
public void eachRow(Closure<Void> c) {
while (table.advanceRow()) {
c.call(this);
}
table.resetRowPosition();
}
/**
* It calls the given closure on each row of the underlying table for up to the specified limit,
* by passing itself as the only closure parameter
*
* @param maxRows maximum rows to call the closure on
* @param c closure
*/
public void eachRow(int maxRows, Closure<Void> c) {
while (--maxRows >= 0 && table.advanceRow()) {
c.call(this);
}
}
public Object getAt(int cidx) {
Object cval = table.get(cidx, byIndex[cidx]);
if (table.wasNull()) cval = null;
return cval;
}
public Object getAt(String cname) {
Integer cidx = byName.get(cname);
if (cidx == null) {
throw new IllegalArgumentException("No Column named '" + cname + "'");
}
return getAt(cidx);
}
public Object getAt(GString cname) {
return getAt(cname.toString());
}
@Override
public Object getProperty(String name) {
return getAt(name);
}
/**
* Sets the table row cursor to the given position
* @param num row number to set the row cursor to
* @return an instance of self
*/
public Tuplerator atRow(int num) {
table.advanceToRow(num);
return this;
}
/**
* Resets the table row cursor
* @return an instance of self
*/
public Tuplerator reset() {
table.resetRowPosition();
return this;
}
/**
* Returns the underlying table
* @return the underlying table
*/
public VoltTable getTable() {
return table;
}
}
| wolffcm/voltdb | src/frontend/org/voltdb/groovy/Tuplerator.java | Java | agpl-3.0 | 5,058 |
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
function additionalDetailsCampaign($fields) {
static $mod_strings;
if(empty($mod_strings)) {
global $current_language;
$mod_strings = return_module_language($current_language, 'Campaigns');
}
$overlib_string = '';
if(!empty($fields['START_DATE']))
$overlib_string .= '<b>'. $mod_strings['LBL_CAMPAIGN_START_DATE'] . '</b> ' . $fields['START_DATE'] . '<br>';
if(!empty($fields['TRACKER_TEXT']))
$overlib_string .= '<b>'. $mod_strings['LBL_TRACKER_TEXT'] . '</b> ' . $fields['TRACKER_TEXT'] . '<br>';
if(!empty($fields['REFER_URL']))
$overlib_string .= '<a target=_blank href='. $fields['REFER_URL'] . '>' . $fields['REFER_URL'] . '</a><br>';
if(!empty($fields['OBJECTIVE'])) {
$overlib_string .= '<b>'. $mod_strings['LBL_CAMPAIGN_OBJECTIVE'] . '</b> ' . substr($fields['OBJECTIVE'], 0, 300);
if(strlen($fields['OBJECTIVE']) > 300) $overlib_string .= '...';
$overlib_string .= '<br>';
}
if(!empty($fields['CONTENT'])) {
$overlib_string .= '<b>'. $mod_strings['LBL_CAMPAIGN_CONTENT'] . '</b> ' . substr($fields['CONTENT'], 0, 300);
if(strlen($fields['CONTENT']) > 300) $overlib_string .= '...';
}
return array('fieldToAddTo' => 'NAME',
'string' => $overlib_string,
'editLink' => "index.php?action=EditView&module=Campaigns&return_module=Campaigns&record={$fields['ID']}",
'viewLink' => "index.php?action=DetailView&module=Campaigns&return_module=Campaigns&record={$fields['ID']}");
}
?>
| shahrooz33ce/sugarcrm | modules/Campaigns/metadata/additionalDetails.php | PHP | agpl-3.0 | 3,552 |
/**
* Copyright 2007-2015, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaazing.k3po.driver.internal.behavior.handler.codec.http;
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.US_ASCII;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.kaazing.k3po.driver.internal.behavior.handler.codec.ConfigEncoder;
import org.kaazing.k3po.driver.internal.behavior.handler.codec.MessageEncoder;
import org.kaazing.k3po.driver.internal.netty.bootstrap.http.HttpChannelConfig;
public class HttpStatusEncoder implements ConfigEncoder {
private final MessageEncoder codeEncoder;
private final MessageEncoder reasonEncoder;
public HttpStatusEncoder(MessageEncoder codeEncoder, MessageEncoder reasonEncoder) {
this.codeEncoder = codeEncoder;
this.reasonEncoder = reasonEncoder;
}
@Override
public void encode(Channel channel) throws Exception {
HttpChannelConfig httpConfig = (HttpChannelConfig) channel.getConfig();
int code = Integer.parseInt(codeEncoder.encode().toString(US_ASCII));
String reason = reasonEncoder.encode().toString(US_ASCII);
HttpResponseStatus status = new HttpResponseStatus(code, reason);
httpConfig.setStatus(status);
}
@Override
public String toString() {
return format("http:status %s %s", codeEncoder, reasonEncoder);
}
}
| mgherghe/k3po | driver/src/main/java/org/kaazing/k3po/driver/internal/behavior/handler/codec/http/HttpStatusEncoder.java | Java | agpl-3.0 | 2,014 |
/*
* Slimey - SLIdeshow Microformat Editor - http://slimey.sourceforge.net
* Copyright (C) 2007 - 2008 Ignacio de Soto
*
* Base Action definitions.
*/
/**
* abstract class SlimeyAction - Actions on the editor
* name: name of the action
*/
var SlimeyAction = function(name, slimey) {
this.name = name;
this.slimey = slimey;
}
/**
* returns the action's name.
*/
SlimeyAction.prototype.getName = function() {
return this.name;
}
/**
* base perform() implementation
*/
SlimeyAction.prototype.perform = function() {
}
/**
* base undo() implementation
*/
SlimeyAction.prototype.undo = function() {
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyInsertAction - Handles insertion of new elements
* tagname: HTML tagname of the element to be inserted
*/
var SlimeyInsertAction = function(slimey, tagname) {
SlimeyAction.call(this, 'insert', slimey);
var elem = this.slimey.editor.getContainer().ownerDocument.createElement(tagname);
/* set element attributes */
elem.slimey = this.slimey;
elem.className = 'slimeyElement';
elem.style.position = 'absolute';
elem.style.left = '40%';
elem.style.top = '30%';
elem.style.lineHeight = '1.';
elem.style.cursor = 'move';
elem.style.fontFamily = 'sans-serif';
elem.style.fontSize = '160%';
elem.style.margin = '0px';
elem.style.padding = '0px';
elem.style.border = '0px';
elem.style.zIndex = 10000;
if (elem.tagName == 'DIV') {
elem.style.left = '5%';
elem.style.top = '15%';
elem.style.width = '90%';
elem.style.height = '10%';
elem.innerHTML = lang("some text");
elem.style.textAlign = 'center';
elem.resizable = true;
elem.editable = true;
} else if (elem.tagName == 'IMG') {
elem.style.width = '20%';
elem.style.height = '20%';
elem.resizable = true;
elem.title = lang("drag the bottom right corner to resize");
} else {
if (elem.tagName == 'UL') {
elem.innerHTML = '<li>' + lang("some text") + '</li>';
} else if (elem.tagName == 'OL') {
elem.innerHTML = '<li>' + lang("some text") + '</li>';
} else {
elem.innerHTML = lang("some text");
}
elem.editable = true;
elem.title = lang("double click to edit content");
}
/* event handlers */
setEventHandler(elem, "mousedown", slimeyDrag);
setEventHandler(elem, "click", slimeyClick);
setEventHandler(elem, "dblclick", slimeyEdit);
setEventHandler(elem, "mouseover", slimeyHighlight);
setEventHandler(elem, "mouseout", slimeyLowshadow);
this.element = elem;
}
/**
* SlimeyInsertAction extends SlimeyAction
*/
SlimeyInsertAction.prototype = new SlimeyAction();
/**
* returns the element created by this action
*/
SlimeyInsertAction.prototype.getElement = function() {
return this.element;
}
/**
* adds the created element to the editor
*/
SlimeyInsertAction.prototype.perform = function() {
this.slimey.editor.getContainer().appendChild(this.element);
}
/**
* removes the created element from the editor
*/
SlimeyInsertAction.prototype.undo = function() {
this.slimey.editor.getContainer().removeChild(this.element);
var selected = this.slimey.editor.getSelected();
if (selected == this.element) {
this.slimey.editor.deselect();
}
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyEditContentAction - edits the contents of the selected element in the editor
* content: HTML content to set to the element
*/
var SlimeyEditContentAction = function(slimey, content, element) {
SlimeyAction.call(this, 'editContent', slimey);
if (element) {
this.element = element;
} else {
this.element = this.slimey.editor.getSelected();
}
this.content = content;
}
/**
* SlimeyInsertAction extends SlimeyAction
*/
SlimeyEditContentAction.prototype = new SlimeyAction();
/**
* edits the contents of the selected item in the editor
*/
SlimeyEditContentAction.prototype.perform = function() {
this.previousContent = this.element.innerHTML;
this.element.innerHTML = this.content;
}
/**
* restores the elements original content
*/
SlimeyEditContentAction.prototype.undo = function() {
this.element.innerHTML = this.previousContent;
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyEditStyleAction - edits a style property of the selected element in the editor
* property: CSS property to be modified (i.e. fontFamily)
* value: Value to set to the property (i.e. sans-serif)
*/
var SlimeyEditStyleAction = function(slimey, property, value) {
SlimeyAction.call(this, 'editStyle', slimey);
this.element = this.slimey.editor.getSelected();
this.property = property;
this.value = value;
}
/**
* SlimeyInsertAction extends SlimeyAction
*/
SlimeyEditStyleAction.prototype = new SlimeyAction();
/**
* edits the contents of the selected item in the editor
*/
SlimeyEditStyleAction.prototype.perform = function() {
this.previousValue = this.element.style[this.property];
this.element.style[this.property] = this.value;
}
/**
* restores the elements original content
*/
SlimeyEditStyleAction.prototype.undo = function() {
this.element.style[this.property] = this.previousValue;
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyDeleteAction - Deletes the selected element
*/
var SlimeyDeleteAction = function(slimey) {
SlimeyAction.call(this, 'delete', slimey);
var selected = this.slimey.editor.getSelected();
this.element = selected;
}
/**
* SlimeyDeleteAction extends SlimeyAction
*/
SlimeyDeleteAction.prototype = new SlimeyAction();
/**
* removes the selected element from the editor
*/
SlimeyDeleteAction.prototype.perform = function() {
this.slimey.editor.getContainer().removeChild(this.element);
this.slimey.editor.deselect();
}
/**
* adds the previously deleted element to the editor
*/
SlimeyDeleteAction.prototype.undo = function() {
this.slimey.editor.getContainer().appendChild(this.element);
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyMoveAction - Moves the selected element
* newx: new horizontal position
* newy: new vertical position
* oldx: (optional) previous horizontal position if different than current
* oldy: (optional) previous vertical position if different than current
*/
var SlimeyMoveAction = function(slimey, newx, newy, oldx, oldy) {
SlimeyAction.call(this, 'move', slimey);
var selected = this.slimey.editor.getSelected();
this.newx = newx;
this.newy = newy;
if (oldx) {
this.oldx = oldx;
} else {
this.oldx = selected.style.left;
}
if (oldy) {
this.oldy = oldy;
} else {
this.oldy = selected.style.top;
}
this.element = selected;
}
/**
* SlimeyMoveAction extends SlimeyAction
*/
SlimeyMoveAction.prototype = new SlimeyAction();
/**
* moves the selected element to the new position
*/
SlimeyMoveAction.prototype.perform = function() {
this.element.style.left = this.newx;
this.element.style.top = this.newy;
}
/**
* returns the moved element to its original position
*/
SlimeyMoveAction.prototype.undo = function() {
this.element.style.left = this.oldx;
this.element.style.top = this.oldy;
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyResizeAction - Resizes the selected element
* neww: new width
* newh: new height
* oldw: (optional) previous width if different than current
* oldh: (optional) previous height if different than current
*/
var SlimeyResizeAction = function(slimey, neww, newh, oldw, oldh) {
SlimeyAction.call(this, 'resize', slimey);
var selected = this.slimey.editor.getSelected();
this.neww = neww;
this.newh = newh;
if (oldw) {
this.oldw = oldw;
} else {
this.oldw = selected.style.width;
}
if (oldh) {
this.oldh = oldh;
} else {
this.oldh = selected.style.height;
}
this.element = selected;
}
/**
* SlimeyResizeAction extends SlimeyAction
*/
SlimeyResizeAction.prototype = new SlimeyAction();
/**
* resizes the selected element
*/
SlimeyResizeAction.prototype.perform = function() {
this.element.style.width = this.neww;
this.element.style.height = this.newh;
}
/**
* returns the element to its original size
*/
SlimeyResizeAction.prototype.undo = function() {
this.element.style.width = this.oldw;
this.element.style.height = this.oldh;
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeySendToBackAction - Sends the selected element to the back
*/
var SlimeySendToBackAction = function(slimey) {
SlimeyAction.call(this, 'sendToBack', slimey);
var selected = this.slimey.editor.getSelected();
this.element = selected;
}
/**
* SlimeySendToBackAction extends SlimeyAction
*/
SlimeySendToBackAction.prototype = new SlimeyAction();
/**
* sends the selected element to the back
*/
SlimeySendToBackAction.prototype.perform = function() {
var minZ = 100000000;
for (var elem = this.slimey.editor.getContainer().firstChild; elem; elem = elem.nextSibling) {
if (elem.nodeType == 1) {
thisZ = parseInt(elem.style.zIndex);
if (thisZ < minZ) {
minZ = thisZ;
}
}
}
this.oldZ = this.element.style.zIndex;
this.element.style.zIndex = minZ - 1;
}
/**
* sends the selected element back ot the previous z-index
*/
SlimeySendToBackAction.prototype.undo = function() {
this.element.style.zIndex = this.oldZ;
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyBringToFrontAction - Brings the selected element to the front
*/
var SlimeyBringToFrontAction = function(slimey) {
SlimeyAction.call(this, 'bringToFront', slimey);
var selected = this.slimey.editor.getSelected();
this.element = selected;
}
/**
* SlimeyBringToFrontAction extends SlimeyAction
*/
SlimeyBringToFrontAction.prototype = new SlimeyAction();
/**
* brings the selected element to the front
*/
SlimeyBringToFrontAction.prototype.perform = function() {
var maxZ = 0;
for (var elem = this.slimey.editor.getContainer().firstChild; elem; elem = elem.nextSibling) {
if (elem.nodeType == 1) {
thisZ = parseInt(elem.style.zIndex);
if (thisZ > maxZ) {
maxZ = thisZ;
}
}
}
this.oldZ = this.element.style.zIndex;
this.element.style.zIndex = maxZ + 1;
}
/**
* returns the element to its original z-index
*/
SlimeyBringToFrontAction.prototype.undo = function() {
this.element.style.zIndex = this.oldZ;
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyChangeSlideAction - Changes the current slide
* num: Slide number to change to
*/
var SlimeyChangeSlideAction = function(slimey, num) {
SlimeyAction.call(this, 'changeSlide', slimey);
this.num = num;
}
/**
* SlimeyChangeSlideAction extends SlimeyAction
*/
SlimeyChangeSlideAction.prototype = new SlimeyAction();
/**
* changes the current slide
*/
SlimeyChangeSlideAction.prototype.perform = function() {
this.previousSlide = this.slimey.navigation.currentSlide;
this.slimey.navigation.getSlide(this.num);
}
/**
* returns to the previous slide
*/
SlimeyChangeSlideAction.prototype.undo = function() {
this.slimey.navigation.getSlide(this.previousSlide);
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyInsertSlideAction - Inserts a new slide
* num: Position where to insert the new slide
*/
var SlimeyInsertSlideAction = function(slimey, num) {
SlimeyAction.call(this, 'insertSlide', slimey);
this.num = num;
}
/**
* SlimeyInsertSlideAction extends SlimeyAction
*/
SlimeyInsertSlideAction.prototype = new SlimeyAction();
/**
* insert the new slide
*/
SlimeyInsertSlideAction.prototype.perform = function() {
this.slimey.navigation.insertNewSlide(this.num);
}
/**
* remove the inserted slide
*/
SlimeyInsertSlideAction.prototype.undo = function() {
this.slimey.navigation.deleteSlide(this.num);
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyDeleteSlideAction - Deletes the current slide
* num: Number of the slide to be deleted
*/
var SlimeyDeleteSlideAction = function(slimey, num) {
SlimeyAction.call(this, 'deleteSlide', slimey);
this.num = num;
}
/**
* SlimeyDeleteSlideAction extends SlimeyAction
*/
SlimeyDeleteSlideAction.prototype = new SlimeyAction();
/**
* delete the current slide
*/
SlimeyDeleteSlideAction.prototype.perform = function() {
this.html = this.slimey.editor.getHTML();
this.dom = document.createElement('div');
this.slimey.editor.getDOM(this.dom);
this.slimey.navigation.deleteSlide(this.num);
}
/**
* reinsert the deleted slide
*/
SlimeyDeleteSlideAction.prototype.undo = function() {
this.slimey.navigation.insertNewSlide(this.num, this.html, this.dom);
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyMoveSlideAction - Moves the current slide to a new position
* from: Number of the slide to be moved
* to: The new position of the slide
*/
var SlimeyMoveSlideAction = function(slimey, from, to) {
SlimeyAction.call(this, 'moveSlide', slimey);
this.from = from;
this.to = to;
}
/**
* SlimeyMoveSlideAction extends SlimeyAction
*/
SlimeyMoveSlideAction.prototype = new SlimeyAction();
/**
* move the slide to the new position
*/
SlimeyMoveSlideAction.prototype.perform = function() {
this.slimey.navigation.moveSlide(this.from, this.to);
}
/**
* move the slide back to its original position
*/
SlimeyMoveSlideAction.prototype.undo = function() {
this.slimey.navigation.moveSlide(this.to, this.from);
}
/*---------------------------------------------------------------------------*/ | maestrano/fengoffice | public/assets/javascript/slimey/actions.js | JavaScript | agpl-3.0 | 14,292 |
#
# Copyright (C) 2011 Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas 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, version 3 of the License.
#
# Canvas 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 this program. If not, see <http://www.gnu.org/licenses/>.
#
require File.expand_path(File.dirname(__FILE__) + '/api_spec_helper')
require 'nokogiri'
describe UserContent, type: :request do
before :once do
course_with_teacher(:active_all => true)
attachment_model
end
it "should translate course file download links to directly-downloadable urls" do
@assignment = @course.assignments.create!(:title => "first assignment", :description => <<-HTML)
<p>
Hello, students.<br>
This will explain everything: <img src="/courses/#{@course.id}/files/#{@attachment.id}/download" alt="important">
</p>
HTML
json = api_call(:get,
"/api/v1/courses/#{@course.id}/assignments/#{@assignment.id}",
{ :controller => 'assignments_api', :action => 'show',
:format => 'json', :course_id => @course.id.to_s, :id => @assignment.id.to_s })
doc = Nokogiri::HTML::DocumentFragment.parse(json['description'])
expect(doc.at_css('img')['src']).to eq "http://www.example.com/courses/#{@course.id}/files/#{@attachment.id}/download?verifier=#{@attachment.uuid}"
end
it "should translate group file download links to directly-downloadable urls" do
@group = @course.groups.create!(:name => "course group")
attachment_model(:context => @group)
@group.add_user(@teacher)
@group_topic = @group.discussion_topics.create!(:title => "group topic", :user => @teacher, :message => <<-HTML)
<p>
Hello, students.<br>
This will explain everything: <img src="/groups/#{@group.id}/files/#{@attachment.id}/download" alt="important">
</p>
HTML
json = api_call(:get,
"/api/v1/groups/#{@group.id}/discussion_topics/#{@group_topic.id}",
{ :controller => 'discussion_topics_api', :action => 'show',
:format => 'json', :group_id => @group.id.to_s, :topic_id => @group_topic.id.to_s })
doc = Nokogiri::HTML::DocumentFragment.parse(json['message'])
expect(doc.at_css('img')['src']).to eq "http://www.example.com/groups/#{@group.id}/files/#{@attachment.id}/download?verifier=#{@attachment.uuid}"
end
it "should translate file download links to directly-downloadable urls for deleted and replaced files" do
@attachment.destroy
attachment2 = Attachment.create!(:folder => @attachment.folder, :context => @attachment.context, :filename => @attachment.filename, :uploaded_data => StringIO.new("first"))
expect(@context.attachments.find(@attachment.id).id).to eq attachment2.id
@assignment = @course.assignments.create!(:title => "first assignment", :description => <<-HTML)
<p>
Hello, students.<br>
This will explain everything: <img src="/courses/#{@course.id}/files/#{@attachment.id}/download" alt="important">
</p>
HTML
json = api_call(:get,
"/api/v1/courses/#{@course.id}/assignments/#{@assignment.id}",
{ :controller => 'assignments_api', :action => 'show',
:format => 'json', :course_id => @course.id.to_s, :id => @assignment.id.to_s })
doc = Nokogiri::HTML::DocumentFragment.parse(json['description'])
expect(doc.at_css('img')['src']).to eq "http://www.example.com/courses/#{@course.id}/files/#{attachment2.id}/download?verifier=#{attachment2.uuid}"
end
it "should not corrupt absolute links" do
attachment_model(:context => @course)
@topic = @course.discussion_topics.create!(:title => "course topic", :user => @teacher, :message => <<-HTML)
<p>
Hello, students.<br>
This will explain everything: <img src="http://www.example.com/courses/#{@course.id}/files/#{@attachment.id}/download" alt="important">
</p>
HTML
json = api_call(:get,
"/api/v1/courses/#{@course.id}/discussion_topics/#{@topic.id}",
{ :controller => 'discussion_topics_api', :action => 'show',
:format => 'json', :course_id => @course.id.to_s, :topic_id => @topic.id.to_s })
doc = Nokogiri::HTML::DocumentFragment.parse(json['message'])
expect(doc.at_css('img')['src']).to eq "http://www.example.com/courses/#{@course.id}/files/#{@attachment.id}/download?verifier=#{@attachment.uuid}"
end
it "should not remove wrap parameter on file download links" do
attachment_model(:context => @course)
@topic = @course.discussion_topics.create!(:title => "course topic", :user => @teacher, :message => <<-HTML)
<p>
Hello, students.<br>
This will explain everything: <img src="/courses/#{@course.id}/files/#{@attachment.id}/download?wrap=1" alt="important">
</p>
HTML
json = api_call(:get,
"/api/v1/courses/#{@course.id}/discussion_topics/#{@topic.id}",
{ :controller => 'discussion_topics_api', :action => 'show',
:format => 'json', :course_id => @course.id.to_s, :topic_id => @topic.id.to_s })
doc = Nokogiri::HTML::DocumentFragment.parse(json['message'])
expect(doc.at_css('img')['src']).to eq "http://www.example.com/courses/#{@course.id}/files/#{@attachment.id}/download?verifier=#{@attachment.uuid}&wrap=1"
end
it "should translate file preview links to directly-downloadable preview urls" do
@assignment = @course.assignments.create!(:title => "first assignment", :description => <<-HTML)
<p>
Hello, students.<br>
This will explain everything: <img src="/courses/#{@course.id}/files/#{@attachment.id}/preview" alt="important">
</p>
HTML
json = api_call(:get,
"/api/v1/courses/#{@course.id}/assignments/#{@assignment.id}",
{ :controller => 'assignments_api', :action => 'show',
:format => 'json', :course_id => @course.id.to_s, :id => @assignment.id.to_s })
doc = Nokogiri::HTML::DocumentFragment.parse(json['description'])
expect(doc.at_css('img')['src']).to eq "http://www.example.com/courses/#{@course.id}/files/#{@attachment.id}/preview?verifier=#{@attachment.uuid}"
end
it "should translate media comment links to embedded video tags" do
@assignment = @course.assignments.create!(:title => "first assignment", :description => <<-HTML)
<p>
Hello, students.<br>
Watch this awesome video: <a href="/media_objects/qwerty" class="instructure_inline_media_comment video_comment" id="media_comment_qwerty"><img></a>
</p>
HTML
json = api_call(:get,
"/api/v1/courses/#{@course.id}/assignments/#{@assignment.id}",
{ :controller => 'assignments_api', :action => 'show',
:format => 'json', :course_id => @course.id.to_s, :id => @assignment.id.to_s })
doc = Nokogiri::HTML::DocumentFragment.parse(json['description'])
video = doc.at_css('video')
expect(video).to be_present
expect(video['class']).to match(/\binstructure_inline_media_comment\b/)
expect(video['data-media_comment_type']).to eq 'video'
expect(video['data-media_comment_id']).to eq 'qwerty'
expect(video['poster']).to match(%r{http://www.example.com/media_objects/qwerty/thumbnail})
expect(video['src']).to match(%r{http://www.example.com/courses/#{@course.id}/media_download})
expect(video['src']).to match(%r{entryId=qwerty})
# we leave width/height out of it, since browsers tend to have good
# defaults and it makes it easier to set via client css rules
expect(video['width']).to be_nil
expect(video['height']).to be_nil
end
it "should translate media comment audio tags" do
@assignment = @course.assignments.create!(:title => "first assignment", :description => <<-HTML)
<p>
Hello, students.<br>
Listen up: <a href="/media_objects/abcde" class="instructure_inline_media_comment audio_comment" id="media_comment_abcde"><img></a>
</p>
HTML
json = api_call(:get,
"/api/v1/courses/#{@course.id}/assignments/#{@assignment.id}",
{ :controller => 'assignments_api', :action => 'show',
:format => 'json', :course_id => @course.id.to_s, :id => @assignment.id.to_s })
doc = Nokogiri::HTML::DocumentFragment.parse(json['description'])
audio = doc.at_css('audio')
expect(audio).to be_present
expect(audio['class']).to match(/\binstructure_inline_media_comment\b/)
expect(audio['data-media_comment_type']).to eq 'audio'
expect(audio['data-media_comment_id']).to eq 'abcde'
expect(audio['poster']).to be_blank
expect(audio['src']).to match(%r{http://www.example.com/courses/#{@course.id}/media_download})
expect(audio['src']).to match(%r{entryId=abcde})
end
it "should not translate links in content not viewable by user" do
@assignment = @course.assignments.create!(:title => "first assignment", :description => <<-HTML)
<p>
Hello, students.<br>
This will explain everything: <img src="/courses/#{@course.id}/files/#{@attachment.id}/preview" alt="important">
</p>
HTML
# put a student in the course. this will be the active user during the API
# call (necessary since the teacher has manage content rights and will thus
# ignore the lock). lock the attachment so the student can't view it.
student_in_course(:course => @course, :active_all => true)
@attachment.locked = true
@attachment.save
json = api_call(:get,
"/api/v1/courses/#{@course.id}/assignments/#{@assignment.id}",
{ :controller => 'assignments_api', :action => 'show',
:format => 'json', :course_id => @course.id.to_s, :id => @assignment.id.to_s })
doc = Nokogiri::HTML::DocumentFragment.parse(json['description'])
expect(doc.at_css('img')['src']).to eq "http://www.example.com/courses/#{@course.id}/files/#{@attachment.id}/preview"
end
it "should prepend the hostname to all absolute-path links" do
@assignment = @course.assignments.create!(:title => "first assignment", :description => <<-HTML)
<p>
Hello, students.<br>
<img src='/equation_images/1234'>
<a href='/help'>click for teh help</a>
<a href='//example.com/quiz'>a quiz</a>
<a href='http://example.com/test1'>moar</a>
<a href='invalid url'>broke</a>
</p>
HTML
json = api_call(:get,
"/api/v1/courses/#{@course.id}/assignments/#{@assignment.id}",
{ :controller => 'assignments_api', :action => 'show',
:format => 'json', :course_id => @course.id.to_s, :id => @assignment.id.to_s })
doc = Nokogiri::HTML::DocumentFragment.parse(json['description'])
expect(doc.at_css('img')['src']).to eq "http://www.example.com/equation_images/1234"
expect(doc.css('a').map { |e| e['href'] }).to eq [
"http://www.example.com/help",
"//example.com/quiz",
"http://example.com/test1",
"invalid%20url",
]
end
it "should not choke on funny email addresses" do
@wiki_page = @course.wiki.wiki_pages.build(:title => "title")
@wiki_page.body = "<a href='mailto:djmankiewicz@homestarrunner,com'>e-nail</a>"
@wiki_page.workflow_state = 'active'
@wiki_page.save!
api_call(:get, "/api/v1/courses/#{@course.id}/pages/#{@wiki_page.url}",
{ :controller => 'wiki_pages_api', :action => 'show',
:format => 'json', :course_id => @course.id.to_s, :url => @wiki_page.url })
end
context "data api endpoints" do
context "course context" do
it "should process links to each type of object" do
@wiki_page = @course.wiki.wiki_pages.build(:title => "title")
@wiki_page.body = <<-HTML
<p>
<a href='/courses/#{@course.id}/assignments'>assignments index</a>
<a href='/courses/#{@course.id}/assignments/9~123'>assignment</a>
<a href='/courses/#{@course.id}/wiki'>wiki index</a>
<a href='/courses/#{@course.id}/wiki/test-wiki-page'>wiki page</a>
<a href='/courses/#{@course.id}/wiki/test-wiki-page-2?titleize=0'>wiki page</a>
<a href='/courses/#{@course.id}/pages'>wiki index</a>
<a href='/courses/#{@course.id}/pages/test-wiki-page'>wiki page</a>
<a href='/courses/#{@course.id}/pages/test-wiki-page-2?titleize=0'>wiki page</a>
<a href='/courses/#{@course.id}/discussion_topics'>discussion index</a>
<a href='/courses/#{@course.id}/discussion_topics/456'>discussion topic</a>
<a href='/courses/#{@course.id}/files'>files index</a>
<a href='/courses/#{@course.id}/files/789/download?verifier=lolcats'>files index</a>
<a href='/files/789/download?verifier=lolcats'>file</a>
<a href='/courses/#{@course.id}/quizzes'>quiz index</a>
<a href='/courses/#{@course.id}/quizzes/999'>quiz</a>
<a href='/courses/#{@course.id}/modules'>modules index</a>
<a href='/courses/#{@course.id}/modules/1024'>module</a>
<a href='/courses/#{@course.id}/external_tools/retrieve?url=http://lti-tool-provider.example.com/lti_tool'>LTI Launch</a>
</p>
HTML
@wiki_page.workflow_state = 'active'
@wiki_page.save!
json = api_call(:get, "/api/v1/courses/#{@course.id}/pages/#{@wiki_page.url}",
{ :controller => 'wiki_pages_api', :action => 'show',
:format => 'json', :course_id => @course.id.to_s, :url => @wiki_page.url })
doc = Nokogiri::HTML::DocumentFragment.parse(json['body'])
expect(doc.css('a').collect { |att| att['data-api-endpoint'] }).to eq [
"http://www.example.com/api/v1/courses/#{@course.id}/assignments",
"http://www.example.com/api/v1/courses/#{@course.id}/assignments/9~123",
"http://www.example.com/api/v1/courses/#{@course.id}/pages",
"http://www.example.com/api/v1/courses/#{@course.id}/pages/test-wiki-page",
"http://www.example.com/api/v1/courses/#{@course.id}/pages/test-wiki-page-2",
"http://www.example.com/api/v1/courses/#{@course.id}/pages",
"http://www.example.com/api/v1/courses/#{@course.id}/pages/test-wiki-page",
"http://www.example.com/api/v1/courses/#{@course.id}/pages/test-wiki-page-2",
"http://www.example.com/api/v1/courses/#{@course.id}/discussion_topics",
"http://www.example.com/api/v1/courses/#{@course.id}/discussion_topics/456",
"http://www.example.com/api/v1/courses/#{@course.id}/folders/root",
"http://www.example.com/api/v1/courses/#{@course.id}/files/789",
"http://www.example.com/api/v1/files/789",
"http://www.example.com/api/v1/courses/#{@course.id}/quizzes",
"http://www.example.com/api/v1/courses/#{@course.id}/quizzes/999",
"http://www.example.com/api/v1/courses/#{@course.id}/modules",
"http://www.example.com/api/v1/courses/#{@course.id}/modules/1024",
"http://www.example.com/api/v1/courses/#{@course.id}/external_tools/sessionless_launch?url=http%3A%2F%2Flti-tool-provider.example.com%2Flti_tool"
]
expect(doc.css('a').collect { |att| att['data-api-returntype'] }).to eq(
%w([Assignment] Assignment [Page] Page Page [Page] Page Page [Discussion] Discussion Folder File File [Quiz] Quiz [Module] Module SessionlessLaunchUrl)
)
end
end
context "group context" do
it "should process links to each type of object" do
group_with_user(:active_all => true)
@wiki_page = @group.wiki.wiki_pages.build(:title => "title")
@wiki_page.body = <<-HTML
<p>
<a href='/groups/#{@group.id}/wiki'>wiki index</a>
<a href='/groups/#{@group.id}/wiki/some-page'>wiki page</a>
<a href='/groups/#{@group.id}/pages'>wiki index</a>
<a href='/groups/#{@group.id}/pages/some-page'>wiki page</a>
<a href='/groups/#{@group.id}/discussion_topics'>discussion index</a>
<a href='/groups/#{@group.id}/discussion_topics/1~123'>discussion topic</a>
<a href='/groups/#{@group.id}/files'>files index</a>
<a href='/groups/#{@group.id}/files/789/preview'>file</a>
</p>
HTML
@wiki_page.workflow_state = 'active'
@wiki_page.save!
json = api_call(:get, "/api/v1/groups/#{@group.id}/pages/#{@wiki_page.url}",
{ :controller => 'wiki_pages_api', :action => 'show',
:format => 'json', :group_id => @group.id.to_s, :url => @wiki_page.url })
doc = Nokogiri::HTML::DocumentFragment.parse(json['body'])
expect(doc.css('a').collect { |att| att['data-api-endpoint'] }).to eq [
"http://www.example.com/api/v1/groups/#{@group.id}/pages",
"http://www.example.com/api/v1/groups/#{@group.id}/pages/some-page",
"http://www.example.com/api/v1/groups/#{@group.id}/pages",
"http://www.example.com/api/v1/groups/#{@group.id}/pages/some-page",
"http://www.example.com/api/v1/groups/#{@group.id}/discussion_topics",
"http://www.example.com/api/v1/groups/#{@group.id}/discussion_topics/1~123",
"http://www.example.com/api/v1/groups/#{@group.id}/folders/root",
"http://www.example.com/api/v1/groups/#{@group.id}/files/789"
]
expect(doc.css('a').collect{ |att| att['data-api-returntype'] }).to eq(
%w([Page] Page [Page] Page [Discussion] Discussion Folder File)
)
end
end
context "user context" do
it "should process links to each type of object" do
@topic = @course.discussion_topics.create!(:message => <<-HTML)
<a href='/users/#{@teacher.id}/files'>file index</a>
<a href='/users/#{@teacher.id}/files/789/preview'>file</a>
HTML
json = api_call(:get, "/api/v1/courses/#{@course.id}/discussion_topics/#{@topic.id}",
:controller => 'discussion_topics_api', :action => 'show', :format => 'json',
:course_id => @course.id.to_s, :topic_id => @topic.id.to_s)
doc = Nokogiri::HTML::DocumentFragment.parse(json['message'])
expect(doc.css('a').collect { |att| att['data-api-endpoint'] }).to eq [
"http://www.example.com/api/v1/users/#{@teacher.id}/folders/root",
"http://www.example.com/api/v1/users/#{@teacher.id}/files/789"
]
expect(doc.css('a').collect { |att| att['data-api-returntype'] }).to eq(
%w(Folder File)
)
end
end
end
context "process_incoming_html_content" do
class Tester
include Api
end
let(:tester) { Tester.new }
it "should add the expected href to instructure_inline_media_comment anchors" do
factory_with_protected_attributes(MediaObject, media_id: 'test2', media_type: 'audio')
html = tester.process_incoming_html_content(<<-HTML)
<a id='something-else' href='/blah'>no touchy</a>
<a class='instructure_inline_media_comment audio_comment'>no id</a>
<a id='media_comment_test1' class='instructure_inline_media_comment audio_comment'>with id</a>
<a id='media_comment_test2' class='instructure_inline_media_comment'>id, no type</a>
<a id='media_comment_test3' class='instructure_inline_media_comment'>id, no type, missing object</a>
HTML
doc = Nokogiri::HTML::DocumentFragment.parse(html)
anchors = doc.css('a')
expect(anchors[0]['id']).to eq 'something-else'
expect(anchors[0]['href']).to eq '/blah'
expect(anchors[1]['href']).to be_nil
expect(anchors[2]['href']).to eq '/media_objects/test1'
expect(anchors[2]['class']).to eq 'instructure_inline_media_comment audio_comment'
expect(anchors[3]['class']).to eq 'instructure_inline_media_comment audio_comment' # media_type added by code
expect(anchors[3]['href']).to eq '/media_objects/test2'
expect(anchors[4]['class']).to eq 'instructure_inline_media_comment' # media object not found, no type added
expect(anchors[4]['href']).to eq '/media_objects/test3'
end
it "should translate video and audio instructure_inline_media_comment tags" do
html = tester.process_incoming_html_content(<<-HTML)
<video src='/other'></video>
<video class='instructure_inline_media_comment' src='/some/redirect/url'>no media id</video>
<video class='instructure_inline_media_comment' src='/some/redirect/url' data-media_comment_id='test1'>with media id</video>
<audio class='instructure_inline_media_comment' src='/some/redirect/url' data-media_comment_id='test2'>with media id</video>
HTML
doc = Nokogiri::HTML::DocumentFragment.parse(html)
tags = doc.css('audio,video,a')
expect(tags[0].name).to eq 'video'
expect(tags[0]['src']).to eq '/other'
expect(tags[0]['class']).to be_nil
expect(tags[1].name).to eq 'video'
expect(tags[2].name).to eq 'a'
expect(tags[2]['class']).to eq 'instructure_inline_media_comment video_comment'
expect(tags[2]['href']).to eq '/media_objects/test1'
expect(tags[2]['id']).to eq 'media_comment_test1'
expect(tags[3].name).to eq 'a'
expect(tags[3]['class']).to eq 'instructure_inline_media_comment audio_comment'
expect(tags[3]['href']).to eq '/media_objects/test2'
expect(tags[3]['id']).to eq 'media_comment_test2'
end
context "with verified user-context file links" do
before do
user
attachment_model :context => @user
end
def confirm_url_stability(url)
link = %Q{<a href="#{url}">what</a>}
html = tester.process_incoming_html_content(link)
doc = Nokogiri::HTML::DocumentFragment.parse(html)
expect(doc.at_css('a')['href']).to eq url
end
it "ignores them when scoped to the file" do
url = "/files/#{@attachment.id}/download?verifier=#{@attachment.uuid}"
confirm_url_stability(url)
end
it "ignores them when scoped to the user" do
url = "/users/#{@user.id}/files/#{@attachment.id}/download?verifier=#{@attachment.uuid}"
confirm_url_stability(url)
end
end
context "with verified user-context file links" do
before do
user
attachment_model :context => @user
end
def confirm_url_stability(url)
link = %Q{<a href="#{url}">what</a>a>}
html = tester.process_incoming_html_content(link)
doc = Nokogiri::HTML::DocumentFragment.parse(html)
expect(doc.at_css('a')['href']).to eq url
end
it "ignores them when scoped to the file" do
url = "/files/#{@attachment.id}/download?verifier=#{@attachment.uuid}"
confirm_url_stability(url)
end
it "ignores them when scoped to the user" do
url = "/users/#{@user.id}/files/#{@attachment.id}/download?verifier=#{@attachment.uuid}"
confirm_url_stability(url)
end
it "ignores them when they include the host" do
url = "http://somedomain.instructure.com/files/#{@attachment.id}/download?verifier=#{@attachment.uuid}"
confirm_url_stability(url)
end
end
end
describe ".api_bulk_load_user_content_attachments" do
it "returns a hash of assignment_id => assignment" do
a1, a2, a3 = attachment_model, attachment_model, attachment_model
html1, html2 = <<-HTML1, <<-HTML2
<a href="/courses/#{@course.id}/files/#{a1.id}/download">uh...</a>
<img src="/courses/#{@course.id}/files/#{a2.id}/download">
HTML1
<a href="/courses/#{@course.id}/files/#{a3.id}/download">Hi</a>
HTML2
class ApiClass
include Api
end
expect(ApiClass.new.api_bulk_load_user_content_attachments(
[html1, html2],
@course
)).to eq({a1.id => a1, a2.id => a2, a3.id => a3})
end
end
describe "latex_to_mathml" do
it "returns mathml on success" do
valid_latex = '\frac{a}{b}'
expect(UserContent.latex_to_mathml(valid_latex)).to eql(%{<math xmlns="http://www.w3.org/1998/Math/MathML" display="inline"><mfrac><mrow><mi>a</mi></mrow><mrow><mi>b</mi></mrow></mfrac></math>})
end
it "returns empty string on parse error" do
invalid_latex = '\frac{a}{'
expect(UserContent.latex_to_mathml(invalid_latex)).to eql('')
end
end
describe "escape" do
describe "with equation images" do
context "valid latex" do
before do
@latex = '\frac{a}{b}'
@html = "<img class='equation_image' alt='#{@latex}' />"
end
it "retains the alt attribute" do
escaped = UserContent.escape(@html)
node = Nokogiri::HTML::DocumentFragment.parse(escaped).css("img").first
expect(node['alt']).to eql(@latex)
end
it "adds mathml in a span" do
escaped = UserContent.escape(@html)
node = Nokogiri::HTML::DocumentFragment.parse(escaped).css("img").first.next_sibling
expect(node.node_name).to eql("span")
expect(node.inner_html).to eql(Ritex::Parser.new.parse(@latex))
end
end
context "invalid latex" do
before do
@latex = '\frac{a}{' # incomplete
@html = "<img class='equation_image' alt='#{@latex}' />"
end
it "handles error gracefully" do
expect{ UserContent.escape(@html) }.not_to raise_error
end
it "retains the alt attribute" do
escaped = UserContent.escape(@html)
node = Nokogiri::HTML::DocumentFragment.parse(escaped).css("img").first
expect(node['alt']).to eql(@latex)
end
it "doesn't add mathml span" do
escaped = UserContent.escape(@html)
node = Nokogiri::HTML::DocumentFragment.parse(escaped).css("span").first
expect(node).to be_nil
end
end
end
end
end
| dgynn/canvas-lms | spec/apis/user_content_spec.rb | Ruby | agpl-3.0 | 26,172 |
#include "bench_framework.hpp"
#include <mapnik/image_util.hpp>
class test : public benchmark::test_case
{
mapnik::image_rgba8 im_;
public:
test(mapnik::parameters const& params)
: test_case(params),
im_(256,256) {}
bool validate() const
{
return true;
}
bool operator()() const
{
std::string out;
for (std::size_t i=0;i<iterations_;++i) {
out.clear();
out = mapnik::save_to_string(im_,"png8:m=h:z=1");
}
return true;
}
};
BENCHMARK(test,"encoding blank png")
| mapycz/mapnik | benchmark/test_png_encoding1.cpp | C++ | lgpl-2.1 | 570 |
/* -*- C++ -*- */
/************************************************************************
*
* Copyright(c) 1995~2006 Masaharu Goto (root-cint@cern.ch)
*
* For the licensing terms see the file COPYING
*
************************************************************************/
/*
*
* Copyright (c) 1994
* Hewlett-Packard Company
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Hewlett-Packard Company makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
*/
#ifndef FMULTIMAP_H
#define FMULTIMAP_H
#ifdef MULTIMAP_H
#undef MULTIMAP_H
#undef TREE_H
#define __MULTIMAP_WAS_DEFINED
#endif
#define Allocator far_allocator
#define multimap far_multimap
#define rb_tree far_rb_tree
#include <faralloc.h>
#include <multimap.h>
#undef MULTIMAP_H
#undef TREE_H
#ifdef __MULTIMAP_WAS_DEFINED
#define MULTIMAP_H
#define TREE_H
#undef __MULTIMAP_WAS_DEFINED
#endif
#undef Allocator
#undef multimap
#undef rb_tree
#endif
| krafczyk/root-5.34.09-ams | cint/cint/stl/fmultmap.h | C | lgpl-2.1 | 1,295 |
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* Copyright by the Board of Trustees of the University of Illinois. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the COPYING file, which can be found at the root of the source code *
* distribution tree, or in https://www.hdfgroup.org/licenses. *
* If you do not have access to either file, you may request a copy from *
* help@hdfgroup.org. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "H5Fmodule.h" /* This source code file is part of the H5F module */
/* Packages needed by this file... */
#include "H5private.h" /* Generic Functions */
#include "H5Eprivate.h" /* Error handling */
#include "H5Fpkg.h" /* File access */
/* PRIVATE PROTOTYPES */
/*-------------------------------------------------------------------------
* Function: H5F_fake_alloc
*
* Purpose: Allocate a "fake" file structure, for various routines to
* use for encoding/decoding data structures using internal API
* routines that need a file structure, but don't ultimately
* depend on having a "real" file.
*
* Return: Success: Pointer to 'faked up' file structure
* Failure: NULL
*
* Programmer: Quincey Koziol
* Oct 2, 2006
*
*-------------------------------------------------------------------------
*/
H5F_t *
H5F_fake_alloc(uint8_t sizeof_size)
{
H5F_t *f = NULL; /* Pointer to fake file struct */
H5F_t *ret_value = NULL; /* Return value */
FUNC_ENTER_NOAPI(NULL)
/* Allocate faked file struct */
if (NULL == (f = H5FL_CALLOC(H5F_t)))
HGOTO_ERROR(H5E_FILE, H5E_NOSPACE, NULL, "can't allocate top file structure")
if (NULL == (f->shared = H5FL_CALLOC(H5F_shared_t)))
HGOTO_ERROR(H5E_FILE, H5E_NOSPACE, NULL, "can't allocate shared file structure")
/* Only set fields necessary for clients */
if (sizeof_size == 0)
f->shared->sizeof_size = H5F_OBJ_SIZE_SIZE;
else
f->shared->sizeof_size = sizeof_size;
/* Set return value */
ret_value = f;
done:
if (!ret_value)
H5F_fake_free(f);
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5F_fake_alloc() */
/*-------------------------------------------------------------------------
* Function: H5F_fake_free
*
* Purpose: Free a "fake" file structure.
*
* Return: Success: non-negative
* Failure: negative
*
* Programmer: Quincey Koziol
* Oct 2, 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5F_fake_free(H5F_t *f)
{
FUNC_ENTER_NOAPI_NOINIT_NOERR
/* Free faked file struct */
if (f) {
/* Destroy shared file struct */
if (f->shared)
f->shared = H5FL_FREE(H5F_shared_t, f->shared);
f = H5FL_FREE(H5F_t, f);
} /* end if */
FUNC_LEAVE_NOAPI(SUCCEED)
} /* end H5F_fake_free() */
| su2code/SU2 | externals/cgns/hdf5/H5Ffake.c | C | lgpl-2.1 | 3,425 |
package dr.app.beauti.types;
/**
* @author Marc A. Suchard
*/
public enum HierarchicalModelType {
NORMAL_HPM,
LOGNORMAL_HPM;
public String toString() {
switch (this) {
case NORMAL_HPM:
return "Normal";
case LOGNORMAL_HPM:
return "Lognormal";
default:
return "";
}
}
}
| evolvedmicrobe/beast-mcmc | src/dr/app/beauti/types/HierarchicalModelType.java | Java | lgpl-2.1 | 406 |
/*
* httpconnect.h - HTTP "CONNECT" proxy
* Copyright (C) 2003 Justin Karneges
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef CS_HTTPCONNECT_H
#define CS_HTTPCONNECT_H
#include "bytestream.h"
// CS_NAMESPACE_BEGIN
class HttpConnect : public ByteStream
{
Q_OBJECT
public:
enum Error { ErrConnectionRefused = ErrCustom, ErrHostNotFound, ErrProxyConnect, ErrProxyNeg, ErrProxyAuth };
HttpConnect(QObject *parent=0);
~HttpConnect();
void setAuth(const QString &user, const QString &pass="");
void connectToHost(const QString &proxyHost, int proxyPort, const QString &host, int port);
// from ByteStream
void close();
qint64 bytesToWrite() const;
protected:
qint64 writeData(const char *data, qint64 maxSize);
signals:
void connected();
private slots:
void sock_connected();
void sock_connectionClosed();
void sock_delayedCloseFinished();
void sock_readyRead();
void sock_bytesWritten(qint64);
void sock_error(int);
private:
class Private;
Private *d;
void resetConnection(bool clear=false);
};
// CS_NAMESPACE_END
#endif
| harishnavnit/iris | src/irisnet/noncore/cutestuff/httpconnect.h | C | lgpl-2.1 | 1,762 |
using System;
namespace AutoTest.VM
{
class LaunchArguments
{
public Guid CorrelationId { get; private set; }
public int Port { get; private set; }
public string WatchPath { get; private set; }
public bool Debug { get; private set; }
public int OwnerPort { get; private set; }
public bool IsGlobal { get; private set; }
public int MasterProcessId { get; private set; }
public string ConfigPath { get; private set; }
public LaunchArguments(Guid correlationId, int port, string watchPath, string debug, int ownerPort, string runProfile, int masterProcessId, string configPath)
{
CorrelationId = correlationId;
Port = port;
WatchPath = watchPath;
Debug = (debug == "debug");
OwnerPort = ownerPort;
IsGlobal = (runProfile == "global");
MasterProcessId = masterProcessId;
ConfigPath = configPath;
}
}
}
| nahojd/ContinuousTests | src/AutoTest.VM/LaunchArguments.cs | C# | lgpl-2.1 | 999 |
Php Reports
===========
A reporting framework for managing and displaying nice looking, exportable reports from any data source, including SQL and MongoDB.
Major features include:
* Display a report from any data source that can output tabular data (SQL, MongoDB, PHP, etc.)
* Output reports in HTML, XML, CSV, JSON, or your own custom format
* Add customizable parameters to a report (e.g. start date and end date)
* Add graphs and charts with the Google Data Visualization API
* Supports multiple database environments (e.g. Production, Staging, and Dev)
* Fully extendable and customizable
For installation instructions and documentation, check out http://jdorn.github.io/php-reports/
If you have a question, post on the official forum - http://ost.io/@jdorn/php-reports
Basic Introduction
============
Reports are organized and grouped in directories. Each report is it's own file.
A report consists of headers containing meta-data (e.g. name and description)
and the actual report (SQL queries, javascript, or PHP code).
All reports return rows of data which are then displayed in a sortable/searchable HTML table.
Reports can be exported to a number of formats including CSV, XLS, JSON, and XML.
The Php Reports framework ties together all these different report types, output formats, and meta-data into
a consistent interface.
Example Reports
==============
Here's an example SQL report:
```sql
-- Products That Cost At Least $X
-- VARIABLE: {"name": "min_price"}
SELECT Name, Price FROM Products WHERE Price > "{{min_price}}"
```
The set of SQL comments at the top are the report headers. The first row is always the report name.
The `VARIABLE` header tells the report framework to prompt the user for a value before running the report. Once provided
it will be passed into the report body ("{{min_price}}" in this example) and executed.
Here's a MongoDB report:
```js
// List of All Foods
// MONGODATABASE: MyDatabase
// VARIABLE: {
// "name": "include_inactive",
// "display": "Include Inactive?",
// "type": "select",
// "options": ["yes","no"]
// }
var query = {'type': 'food'};
if(include_inactive == 'no') {
query.status = 'active';
}
var result = db.Products.find(query);
printjson(result);
```
As you can see, the structure is very similar. MongoDB reports use javascript style comments for the headers, but everything else remains the same.
The MONGODATABASE header, if specified, will populate the 'db' variable.
Here's a PHP Report:
```php
<?php
//List of Payment Charges
//This connects to the Stripe Payments api and shows a list of charges
//INCLUDE: /stripe.php
//VARIABLE: {"name": "count", "display": "Number to Display"}
if($count > 100 || $count < 1) throw new Exception("Count must be between 1 and 100");
$charges = Stripe_Charge::all(array("count" => $count));
$rows = array();
foreach($charges as $charge) {
$rows[] = array(
'Charge Id'=>$charge->id,
'Amount'=>number_format($charge->amount/100,2),
'Date'=>date('Y-m-d',$charge->created)
);
}
echo json_encode($rows);
?>
```
Again, the header format is very similar.
The INCLUDE header includes another report within the running one. Below is example content of /stripe.php:
```php
<?php
//Stripe PHP Included Report
//You can have headers here too; even nested INCLUDE headers!
//Some headers will even bubble up to the parent, such as the VARIABLE header
//include the Stripe API client
require_once('lib/Stripe/Stripe.php');
//set the Stripe api key
Stripe::setApiKey("123456");
?>
```
Hopefully, you can begin to see the power of Php Reports.
For full documentation and information on getting started, check out http://jdorn.github.io/php-reports/
| UnderDogg/php-reports | README.md | Markdown | lgpl-3.0 | 3,740 |
html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{ margin:0;padding:0;border:0;outline:0;font-size:100%;vertical-align:baseline;background:transparent}
.menu{ width:238px;position:fixed!important;_position:absolute;overflow:visible;display:block;z-index:10000;border-bottom:1px solid #ccc;font-family: 'Microsoft YaHei,宋体';_position:absolute;_left:expression(eval(document.documentElement.scrollLeft));_top:expression(eval(document.documentElement.scrollTop));zoom:1; -left:243px; top:93px; box-shadow:4px 2px 5px rgba(0, 0, 0, 0.2);}
.menu .title{ position:relative;font-weight:bold;font-family:Microsoft YaHei;font-size:13px;color:#fff;background-color:#a21c1d;height:30px;line-height:30px;padding-left:15px;padding-right:8px}
body,html{ background:#000; }
.top{ width:100%; height:93px; background:#B20000;}
.main{ width:930px; background:#FFF; height:2600px;margin:0 0 0 238px; padding-left:10px; }
.menu .items{ width:238px;overflow:hidden; position:relative; z-index:6;}
.top .middle{ width:1168px; height:100%; margin:0 auto;}
.top .middle .logo{ padding-top:50px;}
.wrap{ width:1178px; margin:0 auto; position:relative;}
.menu .items ul{ list-style:none}
a img{ border:none;}
.menu .items ul li{ display:block;position:relative;padding-left:10px;background:#fff;line-height:30px;cursor:pointer; float:left; width:100%;}
.menu .items h3{ padding-left:30px;font-weight:bold;font-family:Microsoft YaHei;font-size:12px}
.menu .items ul li.alt{ background:#f1f1f1}
.menu .items ul li.curr{ background:#6c5143;color:#fff;cursor:pointer;border-top:1px solid #6c5143;border-bottom:1px solid #6c5143}
.menu .items ul li p{ line-height:20px;font-size:12px;display:block}
.menu .items ul li p a{ color:#888;text-decoration:none;padding:0 2px;line-height:25px;height:25px;font-family: 'Microsoft YaHei,宋体';}
.menu .items ul li:hover { background:#88766E; color:#FFF}
.menu .items ul li:hover a {color:#FFF}
.menu .items ul li p a:hover{ text-decoration:underline;font-family: 'Microsoft YaHei,宋体';}
.menu .items ul li.curr p a{ color:#fff}
.menu .box{ background:repeat-y url('../images/bg_line_t.jpg') #fff;position:absolute;overflow:visible;min-width:500px;min-height:500px;_width:755px;_height:500px;border-left:1px solid #dfdfdf;border-top:1px solid #ccc;border-right:1px solid #ccc;border-bottom:1px solid #ccc; display:none; left:241px; top:0px; z-index:4;}
.menu .menuIcon{ position:absolute;display:block;width:5px;height:9px;top:40%;right:10px;background-position:-7px -480px;overflow:hidden}
.menu.btn_group{ position:absolute;display:block;width:45px;height:21px;top:4px;right:10px;background-position:-0px -492px;overflow:hidden}
.menu .btn_group.bleft{ background-position:-0px -492px}
.menu .btn_group.bright{ background-position:-0px -518px;}
.menu .btn_group .bleft{ margin:1px 0 1px 1px;float:left;display:block;height:19px;width:21px;cursor:pointer}
.menu .btn_group .bright{ margin:1px 1px 1px 0;float:right;display:block;height:19px;width:21px;cursor:pointer}
.menu .btn_group.bleft .bright{ cursor:default}
.menu .btn_group.bright .bleft{ cursor:default}
.menu .btn_group { background-position: 0 -492px;display: block;height: 21px;overflow: hidden;position: absolute;right: 10px;top: 4px;width: 45px;}
.menu .box .hide{ width:755px; height:500px;box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.2), 1px -3px 5px rgba(0, 0, 0, 0.2);display:none;}
.menu .items h3,.menu .menuIcon,.menu .btn_group{ background:url(../images/icon.png) no-repeat;}
.menu .list-item0 h3{ background-position:0 0}
.menu .list-item1 h3{ background-position:0 -30px}
.menu .list-item2 h3{ background-position:0 -60px}
.menu .list-item3 h3{ background-position:0 -90px}
.menu .list-item4 h3{ background-position:0 -120px}
.menu .list-item5 h3{ background-position:0 -150px}
.menu .list-item6 h3{ background-position:0 -180px}
.menu .list-item7 h3{ background-position:0 -210px}
.menu .list-item8 h3{ background-position:0 -240px}
.menu .list-item9 h3{ background-position:0 -270px}
.menu .list-item10 h3{ background-position:0 -300px}
.menu .list-item11 h3{ background-position:0 -330px}
.menu .list-item12 h3{ background-position:0 -360px}
.menu .list-item13 h3{ background-position:0 -390px}
.menu .list-item14 h3{ background-position:0 -420px}
.menu .list-item15 h3{ background-position:0 -450px} | moonsea/maosheji | web/resource/navMenu/css/style.css | CSS | lgpl-3.0 | 4,527 |
/*
* Copyright (C) 2004, 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "KURL.h"
#include <wtf/RetainPtr.h>
#include <CoreFoundation/CFURL.h>
using namespace std;
namespace WebCore {
typedef Vector<char, 512> CharBuffer;
CFURLRef createCFURLFromBuffer(const CharBuffer&);
KURL::KURL(CFURLRef url)
{
if (!url) {
invalidate();
return;
}
CFIndex bytesLength = CFURLGetBytes(url, 0, 0);
Vector<char, 512> buffer(bytesLength + 1);
char* bytes = &buffer[0];
CFURLGetBytes(url, reinterpret_cast<UInt8*>(bytes), bytesLength);
bytes[bytesLength] = '\0';
#if !USE(WTFURL)
parse(bytes);
#else
// FIXME: Add WTFURL Implementation.
UNUSED_PARAM(url);
invalidate();
#endif // USE(WTFURL)
}
CFURLRef createCFURLFromBuffer(const CharBuffer& buffer)
{
// NOTE: We use UTF-8 here since this encoding is used when computing strings when returning URL components
// (e.g calls to NSURL -path). However, this function is not tolerant of illegal UTF-8 sequences, which
// could either be a malformed string or bytes in a different encoding, like Shift-JIS, so we fall back
// onto using ISO Latin-1 in those cases.
CFURLRef result = CFURLCreateAbsoluteURLWithBytes(0, reinterpret_cast<const UInt8*>(buffer.data()), buffer.size(), kCFStringEncodingUTF8, 0, true);
if (!result)
result = CFURLCreateAbsoluteURLWithBytes(0, reinterpret_cast<const UInt8*>(buffer.data()), buffer.size(), kCFStringEncodingISOLatin1, 0, true);
return result;
}
#if !PLATFORM(MAC) && !(PLATFORM(QT) && USE(QTKIT))
CFURLRef KURL::createCFURL() const
{
#if !USE(WTFURL)
// FIXME: What should this return for invalid URLs?
// Currently it throws away the high bytes of the characters in the string in that case,
// which is clearly wrong.
CharBuffer buffer;
copyToBuffer(buffer);
return createCFURLFromBuffer(buffer);
#else // USE(WTFURL)
// FIXME: Add WTFURL Implementation.
return 0;
#endif
}
#endif
#if !USE(WTFURL) && !(PLATFORM(QT) && USE(QTKIT))
String KURL::fileSystemPath() const
{
RetainPtr<CFURLRef> cfURL(AdoptCF, createCFURL());
if (!cfURL)
return String();
#if PLATFORM(WIN)
CFURLPathStyle pathStyle = kCFURLWindowsPathStyle;
#else
CFURLPathStyle pathStyle = kCFURLPOSIXPathStyle;
#endif
return RetainPtr<CFStringRef>(AdoptCF, CFURLCopyFileSystemPath(cfURL.get(), pathStyle)).get();
}
#endif
}
| nawawi/wkhtmltopdf | webkit/Source/WebCore/platform/cf/KURLCFNet.cpp | C++ | lgpl-3.0 | 3,741 |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
HEADRequest,
sanitized_Request,
urlencode_postdata,
)
class GDCVaultIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?gdcvault\.com/play/(?P<id>\d+)/(?P<name>(\w|-)+)?'
_NETRC_MACHINE = 'gdcvault'
_TESTS = [
{
'url': 'http://www.gdcvault.com/play/1019721/Doki-Doki-Universe-Sweet-Simple',
'md5': '7ce8388f544c88b7ac11c7ab1b593704',
'info_dict': {
'id': '1019721',
'display_id': 'Doki-Doki-Universe-Sweet-Simple',
'ext': 'mp4',
'title': 'Doki-Doki Universe: Sweet, Simple and Genuine (GDC Next 10)'
}
},
{
'url': 'http://www.gdcvault.com/play/1015683/Embracing-the-Dark-Art-of',
'info_dict': {
'id': '1015683',
'display_id': 'Embracing-the-Dark-Art-of',
'ext': 'flv',
'title': 'Embracing the Dark Art of Mathematical Modeling in AI'
},
'params': {
'skip_download': True, # Requires rtmpdump
}
},
{
'url': 'http://www.gdcvault.com/play/1015301/Thexder-Meets-Windows-95-or',
'md5': 'a5eb77996ef82118afbbe8e48731b98e',
'info_dict': {
'id': '1015301',
'display_id': 'Thexder-Meets-Windows-95-or',
'ext': 'flv',
'title': 'Thexder Meets Windows 95, or Writing Great Games in the Windows 95 Environment',
},
'skip': 'Requires login',
},
{
'url': 'http://gdcvault.com/play/1020791/',
'only_matching': True,
},
{
# Hard-coded hostname
'url': 'http://gdcvault.com/play/1023460/Tenacious-Design-and-The-Interface',
'md5': 'a8efb6c31ed06ca8739294960b2dbabd',
'info_dict': {
'id': '1023460',
'ext': 'mp4',
'display_id': 'Tenacious-Design-and-The-Interface',
'title': 'Tenacious Design and The Interface of \'Destiny\'',
},
},
{
# Multiple audios
'url': 'http://www.gdcvault.com/play/1014631/Classic-Game-Postmortem-PAC',
'info_dict': {
'id': '1014631',
'ext': 'flv',
'title': 'How to Create a Good Game - From My Experience of Designing Pac-Man',
},
'params': {
'skip_download': True, # Requires rtmpdump
'format': 'jp', # The japanese audio
}
},
{
# gdc-player.html
'url': 'http://www.gdcvault.com/play/1435/An-American-engine-in-Tokyo',
'info_dict': {
'id': '1435',
'display_id': 'An-American-engine-in-Tokyo',
'ext': 'flv',
'title': 'An American Engine in Tokyo:/nThe collaboration of Epic Games and Square Enix/nFor THE LAST REMINANT',
},
'params': {
'skip_download': True, # Requires rtmpdump
},
},
]
def _login(self, webpage_url, display_id):
username, password = self._get_login_info()
if username is None or password is None:
self.report_warning('It looks like ' + webpage_url + ' requires a login. Try specifying a username and password and try again.')
return None
mobj = re.match(r'(?P<root_url>https?://.*?/).*', webpage_url)
login_url = mobj.group('root_url') + 'api/login.php'
logout_url = mobj.group('root_url') + 'logout'
login_form = {
'email': username,
'password': password,
}
request = sanitized_Request(login_url, urlencode_postdata(login_form))
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
self._download_webpage(request, display_id, 'Logging in')
start_page = self._download_webpage(webpage_url, display_id, 'Getting authenticated video page')
self._download_webpage(logout_url, display_id, 'Logging out')
return start_page
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
video_id = mobj.group('id')
display_id = mobj.group('name') or video_id
webpage_url = 'http://www.gdcvault.com/play/' + video_id
start_page = self._download_webpage(webpage_url, display_id)
direct_url = self._search_regex(
r's1\.addVariable\("file",\s*encodeURIComponent\("(/[^"]+)"\)\);',
start_page, 'url', default=None)
if direct_url:
title = self._html_search_regex(
r'<td><strong>Session Name</strong></td>\s*<td>(.*?)</td>',
start_page, 'title')
video_url = 'http://www.gdcvault.com' + direct_url
# resolve the url so that we can detect the correct extension
head = self._request_webpage(HEADRequest(video_url), video_id)
video_url = head.geturl()
return {
'id': video_id,
'display_id': display_id,
'url': video_url,
'title': title,
}
PLAYER_REGEX = r'<iframe src="(?P<xml_root>.+?)/(?:gdc-)?player.*?\.html.*?".*?</iframe>'
xml_root = self._html_search_regex(
PLAYER_REGEX, start_page, 'xml root', default=None)
if xml_root is None:
# Probably need to authenticate
login_res = self._login(webpage_url, display_id)
if login_res is None:
self.report_warning('Could not login.')
else:
start_page = login_res
# Grab the url from the authenticated page
xml_root = self._html_search_regex(
PLAYER_REGEX, start_page, 'xml root')
xml_name = self._html_search_regex(
r'<iframe src=".*?\?xml=(.+?\.xml).*?".*?</iframe>',
start_page, 'xml filename', default=None)
if xml_name is None:
# Fallback to the older format
xml_name = self._html_search_regex(
r'<iframe src=".*?\?xmlURL=xml/(?P<xml_file>.+?\.xml).*?".*?</iframe>',
start_page, 'xml filename')
return {
'_type': 'url_transparent',
'id': video_id,
'display_id': display_id,
'url': '%s/xml/%s' % (xml_root, xml_name),
'ie_key': 'DigitallySpeaking',
}
| stannynuytkens/youtube-dl | youtube_dl/extractor/gdcvault.py | Python | unlicense | 6,690 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.eagle.jobrunning.crawler;
public class JobContext {
public String jobId;
public String user;
public Long fetchedTime;
public JobContext() {
}
public JobContext(JobContext context) {
this.jobId = new String(context.jobId);
this.user = new String(context.user);
this.fetchedTime = new Long(context.fetchedTime);
}
public JobContext(String jobId, String user, Long fetchedTime) {
this.jobId = jobId;
this.user = user;
this.fetchedTime = fetchedTime;
}
@Override
public int hashCode() {
return jobId.hashCode() ;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof JobContext) {
JobContext context = (JobContext)obj;
if (this.jobId.equals(context.jobId)) {
return true;
}
}
return false;
}
}
| eBay/Eagle | eagle-core/eagle-data-process/eagle-storm-jobrunning-spout/src/main/java/org/apache/eagle/jobrunning/crawler/JobContext.java | Java | apache-2.0 | 1,589 |
// Code generated by protoc-gen-gogo.
// source: uuid.proto
// DO NOT EDIT!
package events
import proto "github.com/gogo/protobuf/proto"
import math "math"
// discarding unused import gogoproto "github.com/gogo/protobuf/gogoproto/gogo.pb"
import io "io"
import fmt "fmt"
import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = math.Inf
// / Type representing a 128-bit UUID.
//
// The bytes of the UUID should be packed in little-endian **byte** (not bit) order. For example, the UUID `f47ac10b-58cc-4372-a567-0e02b2c3d479` should be encoded as `UUID{ low: 0x7243cc580bc17af4, high: 0x79d4c3b2020e67a5 }`
type UUID struct {
Low *uint64 `protobuf:"varint,1,req,name=low" json:"low,omitempty"`
High *uint64 `protobuf:"varint,2,req,name=high" json:"high,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (m *UUID) Reset() { *m = UUID{} }
func (m *UUID) String() string { return proto.CompactTextString(m) }
func (*UUID) ProtoMessage() {}
func (m *UUID) GetLow() uint64 {
if m != nil && m.Low != nil {
return *m.Low
}
return 0
}
func (m *UUID) GetHigh() uint64 {
if m != nil && m.High != nil {
return *m.High
}
return 0
}
func init() {
}
func (m *UUID) Unmarshal(data []byte) error {
var hasFields [1]uint64
l := len(data)
iNdEx := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := data[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Low", wireType)
}
var v uint64
for shift := uint(0); ; shift += 7 {
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := data[iNdEx]
iNdEx++
v |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.Low = &v
hasFields[0] |= uint64(0x00000001)
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field High", wireType)
}
var v uint64
for shift := uint(0); ; shift += 7 {
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := data[iNdEx]
iNdEx++
v |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.High = &v
hasFields[0] |= uint64(0x00000002)
default:
var sizeOfWire int
for {
sizeOfWire++
wire >>= 7
if wire == 0 {
break
}
}
iNdEx -= sizeOfWire
skippy, err := skipUuid(data[iNdEx:])
if err != nil {
return err
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, data[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if hasFields[0]&uint64(0x00000001) == 0 {
return github_com_gogo_protobuf_proto.NewRequiredNotSetError("low")
}
if hasFields[0]&uint64(0x00000002) == 0 {
return github_com_gogo_protobuf_proto.NewRequiredNotSetError("high")
}
return nil
}
func skipUuid(data []byte) (n int, err error) {
l := len(data)
iNdEx := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := data[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for {
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if data[iNdEx-1] < 0x80 {
break
}
}
return iNdEx, nil
case 1:
iNdEx += 8
return iNdEx, nil
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := data[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
iNdEx += length
return iNdEx, nil
case 3:
for {
var wire uint64
var start int = iNdEx
for shift := uint(0); ; shift += 7 {
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := data[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
if wireType == 4 {
break
}
next, err := skipUuid(data[start:])
if err != nil {
return 0, err
}
iNdEx = start + next
}
return iNdEx, nil
case 4:
return iNdEx, nil
case 5:
iNdEx += 4
return iNdEx, nil
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
}
panic("unreachable")
}
func (m *UUID) Size() (n int) {
var l int
_ = l
if m.Low != nil {
n += 1 + sovUuid(uint64(*m.Low))
}
if m.High != nil {
n += 1 + sovUuid(uint64(*m.High))
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func sovUuid(x uint64) (n int) {
for {
n++
x >>= 7
if x == 0 {
break
}
}
return n
}
func sozUuid(x uint64) (n int) {
return sovUuid(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *UUID) Marshal() (data []byte, err error) {
size := m.Size()
data = make([]byte, size)
n, err := m.MarshalTo(data)
if err != nil {
return nil, err
}
return data[:n], nil
}
func (m *UUID) MarshalTo(data []byte) (n int, err error) {
var i int
_ = i
var l int
_ = l
if m.Low == nil {
return 0, github_com_gogo_protobuf_proto.NewRequiredNotSetError("low")
} else {
data[i] = 0x8
i++
i = encodeVarintUuid(data, i, uint64(*m.Low))
}
if m.High == nil {
return 0, github_com_gogo_protobuf_proto.NewRequiredNotSetError("high")
} else {
data[i] = 0x10
i++
i = encodeVarintUuid(data, i, uint64(*m.High))
}
if m.XXX_unrecognized != nil {
i += copy(data[i:], m.XXX_unrecognized)
}
return i, nil
}
func encodeFixed64Uuid(data []byte, offset int, v uint64) int {
data[offset] = uint8(v)
data[offset+1] = uint8(v >> 8)
data[offset+2] = uint8(v >> 16)
data[offset+3] = uint8(v >> 24)
data[offset+4] = uint8(v >> 32)
data[offset+5] = uint8(v >> 40)
data[offset+6] = uint8(v >> 48)
data[offset+7] = uint8(v >> 56)
return offset + 8
}
func encodeFixed32Uuid(data []byte, offset int, v uint32) int {
data[offset] = uint8(v)
data[offset+1] = uint8(v >> 8)
data[offset+2] = uint8(v >> 16)
data[offset+3] = uint8(v >> 24)
return offset + 4
}
func encodeVarintUuid(data []byte, offset int, v uint64) int {
for v >= 1<<7 {
data[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
data[offset] = uint8(v)
return offset + 1
}
| freeformz/sonde-go | events/uuid.pb.go | GO | apache-2.0 | 6,590 |
// Copyright 2016 CoreOS, 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.
package types
import (
"github.com/coreos/ignition/config/shared/errors"
"github.com/coreos/ignition/config/validate/report"
)
type Filesystem struct {
Name string `json:"name,omitempty"`
Mount *FilesystemMount `json:"mount,omitempty"`
Path *Path `json:"path,omitempty"`
}
type FilesystemMount struct {
Device Path `json:"device,omitempty"`
Format FilesystemFormat `json:"format,omitempty"`
Create *FilesystemCreate `json:"create,omitempty"`
}
type FilesystemCreate struct {
Force bool `json:"force,omitempty"`
Options MkfsOptions `json:"options,omitempty"`
}
func (f Filesystem) Validate() report.Report {
if f.Mount == nil && f.Path == nil {
return report.ReportFromError(errors.ErrFilesystemNoMountPath, report.EntryError)
}
if f.Mount != nil && f.Path != nil {
return report.ReportFromError(errors.ErrFilesystemMountAndPath, report.EntryError)
}
return report.Report{}
}
type FilesystemFormat string
func (f FilesystemFormat) Validate() report.Report {
switch f {
case "ext4", "btrfs", "xfs":
return report.Report{}
default:
return report.ReportFromError(errors.ErrFilesystemInvalidFormat, report.EntryError)
}
}
type MkfsOptions []string
| dm0-/mantle | vendor/github.com/coreos/ignition/config/v2_0/types/filesystem.go | GO | apache-2.0 | 1,814 |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(249)
var __weex_template__ = __webpack_require__(250)
var __weex_style__ = __webpack_require__(251)
var __weex_script__ = __webpack_require__(252)
__weex_define__('@weex-component/81fdd9b8b8bce1b304791aba10e15462', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
__weex_bootstrap__('@weex-component/81fdd9b8b8bce1b304791aba10e15462',undefined,undefined)
/***/ },
/***/ 244:
/***/ function(module, exports) {
module.exports = {
"type": "image",
"style": {
"width": function () {return this.width},
"height": function () {return this.height}
},
"attr": {
"src": function () {return this.src},
"imageQuality": function () {return this.quality}
},
"events": {
"click": "_clickHandler"
}
}
/***/ },
/***/ 245:
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
quality: 'normal',
width: 0,
height: 0,
src: '',
href: '',
spmc: 0,
spmd: 0
}},
methods: {
ready: function ready() {},
_clickHandler: function _clickHandler() {
this.$call('modal', 'toast', {
message: 'click',
duration: 1
});
}
}
};}
/* generated by weex-loader */
/***/ },
/***/ 246:
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(244)
var __weex_script__ = __webpack_require__(245)
__weex_define__('@weex-component/banner', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
})
/***/ },
/***/ 247:
/***/ function(module, exports) {
module.exports = {
"type": "container",
"children": [
{
"type": "container",
"shown": function () {return this.direction==='row'},
"style": {
"flexDirection": "row"
},
"children": [
{
"type": "container",
"repeat": function () {return this.ds},
"style": {
"width": function () {return this.width},
"height": function () {return this.height},
"marginLeft": function () {return this.space}
},
"children": [
{
"type": "banner",
"attr": {
"width": function () {return this.width},
"height": function () {return this.height},
"src": function () {return this.img},
"href": function () {return this.url}
}
}
]
}
]
},
{
"type": "container",
"shown": function () {return this.direction==='column'},
"children": [
{
"type": "container",
"repeat": function () {return this.ds},
"style": {
"width": function () {return this.width},
"height": function () {return this.height},
"marginTop": function () {return this.space}
},
"children": [
{
"type": "banner",
"attr": {
"width": function () {return this.width},
"height": function () {return this.height},
"src": function () {return this.img},
"href": function () {return this.url}
}
}
]
}
]
}
]
}
/***/ },
/***/ 248:
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
space: 0,
width: 0,
height: 0,
spmc: 0,
spmdprefix: '',
ds: []
}},
methods: {
ready: function ready() {
var self = this;
var ds = self.ds;
var length = ds.length;
for (var i = 0; i < length; i++) {
var item = ds[i];
item.index = i;
item.space = i % length === 0 ? 0 : self.space;
}
}
}
};}
/* generated by weex-loader */
/***/ },
/***/ 249:
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(246)
var __weex_template__ = __webpack_require__(247)
var __weex_script__ = __webpack_require__(248)
__weex_define__('@weex-component/banners', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
})
/***/ },
/***/ 250:
/***/ function(module, exports) {
module.exports = {
"type": "container",
"classList": [
"container"
],
"children": [
{
"type": "image",
"shown": function () {return this.ds.floorTitle},
"classList": [
"title"
],
"attr": {
"src": function () {return this.ds.floorTitle}
}
},
{
"type": "container",
"style": {
"marginLeft": 4,
"marginRight": 4
},
"children": [
{
"type": "banners",
"attr": {
"ds": function () {return this.bannerItems},
"direction": "column",
"width": function () {return this.NUMBER_742},
"height": function () {return this.NUMBER_230},
"space": function () {return this.NUMBER_4}
}
}
]
}
]
}
/***/ },
/***/ 251:
/***/ function(module, exports) {
module.exports = {
"title": {
"width": 750,
"height": 100
},
"container": {
"marginBottom": 4,
"backgroundColor": "#C0BABC"
}
}
/***/ },
/***/ 252:
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){"use strict";
module.exports = {
data: function () {return {
NUMBER_742: 742,
NUMBER_230: 230,
NUMBER_4: 4
}},
methods: {
ready: function ready() {
var self = this;
self._randomBrand();
},
_randomBrand: function _randomBrand() {
var self = this;
var bannerItems = self.ds.bannerItems;
bannerItems = bannerItems.sort(function () {
return Math.random() - 0.5;
});
self.bannerItems = bannerItems.slice(0, 8);
for (var i = 0; i < bannerItems.length; i++) {
var item = bannerItems[i];
if (i % 2 === 0) {
item.img = item.leftImg;
item.url = item.rightUrl;
} else {
item.img = item.rightImg;
item.url = item.rightUrl;
}
}
}
}
};}
/* generated by weex-loader */
/***/ }
/******/ }); | MrRaindrop/incubator-weex | android/playground/app/src/main/assets/showcase/new-fashion/brand.js | JavaScript | apache-2.0 | 8,757 |
/*
* Copyright 2012-present Facebook, 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.
*/
package com.facebook.buck.jvm.java;
import static com.facebook.buck.rules.BuildableProperties.Kind.PACKAGING;
import com.facebook.buck.io.DirectoryTraverser;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.rules.AbstractBuildRule;
import com.facebook.buck.rules.AddToRuleKey;
import com.facebook.buck.rules.BinaryBuildRule;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRules;
import com.facebook.buck.rules.BuildTargetSourcePath;
import com.facebook.buck.rules.BuildableContext;
import com.facebook.buck.rules.BuildableProperties;
import com.facebook.buck.rules.CommandTool;
import com.facebook.buck.rules.RuleKeyAppendable;
import com.facebook.buck.rules.RuleKeyBuilder;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePaths;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.facebook.buck.step.fs.MkdirAndSymlinkFileStep;
import com.facebook.buck.step.fs.MkdirStep;
import com.google.common.base.Preconditions;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.ImmutableSortedSet;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.annotation.Nullable;
@BuildsAnnotationProcessor
public class JavaBinary extends AbstractBuildRule
implements BinaryBuildRule, HasClasspathEntries, RuleKeyAppendable {
private static final BuildableProperties OUTPUT_TYPE = new BuildableProperties(PACKAGING);
@AddToRuleKey
@Nullable
private final String mainClass;
@AddToRuleKey
@Nullable
private final SourcePath manifestFile;
private final boolean mergeManifests;
@Nullable
private final Path metaInfDirectory;
@AddToRuleKey
private final ImmutableSet<String> blacklist;
private final DirectoryTraverser directoryTraverser;
private final ImmutableSetMultimap<JavaLibrary, Path> transitiveClasspathEntries;
public JavaBinary(
BuildRuleParams params,
SourcePathResolver resolver,
@Nullable String mainClass,
@Nullable SourcePath manifestFile,
boolean mergeManifests,
@Nullable Path metaInfDirectory,
ImmutableSet<String> blacklist,
DirectoryTraverser directoryTraverser,
ImmutableSetMultimap<JavaLibrary, Path> transitiveClasspathEntries) {
super(params, resolver);
this.mainClass = mainClass;
this.manifestFile = manifestFile;
this.mergeManifests = mergeManifests;
this.metaInfDirectory = metaInfDirectory;
this.blacklist = blacklist;
this.directoryTraverser = directoryTraverser;
this.transitiveClasspathEntries = transitiveClasspathEntries;
}
@Override
public BuildableProperties getProperties() {
return OUTPUT_TYPE;
}
@Override
public RuleKeyBuilder appendToRuleKey(RuleKeyBuilder builder) {
// Build a sorted set so that metaInfDirectory contents are listed in a canonical order.
ImmutableSortedSet.Builder<Path> paths = ImmutableSortedSet.naturalOrder();
BuildRules.addInputsToSortedSet(metaInfDirectory, paths, directoryTraverser);
return builder.setReflectively(
"metaInfDirectory",
FluentIterable.from(paths.build())
.transform(SourcePaths.toSourcePath(getProjectFilesystem())));
}
@Override
public ImmutableList<Step> getBuildSteps(
BuildContext context,
BuildableContext buildableContext) {
ImmutableList.Builder<Step> commands = ImmutableList.builder();
Path outputDirectory = getOutputDirectory();
Step mkdir = new MkdirStep(getProjectFilesystem(), outputDirectory);
commands.add(mkdir);
ImmutableSortedSet<Path> includePaths;
if (metaInfDirectory != null) {
Path stagingRoot = outputDirectory.resolve("meta_inf_staging");
Path stagingTarget = stagingRoot.resolve("META-INF");
MakeCleanDirectoryStep createStagingRoot = new MakeCleanDirectoryStep(
getProjectFilesystem(),
stagingRoot);
commands.add(createStagingRoot);
MkdirAndSymlinkFileStep link = new MkdirAndSymlinkFileStep(
getProjectFilesystem(),
metaInfDirectory,
stagingTarget);
commands.add(link);
includePaths = ImmutableSortedSet.<Path>naturalOrder()
.add(stagingRoot)
.addAll(getTransitiveClasspathEntries().values())
.build();
} else {
includePaths = ImmutableSortedSet.copyOf(getTransitiveClasspathEntries().values());
}
Path outputFile = getPathToOutput();
Path manifestPath = manifestFile == null ? null : getResolver().getAbsolutePath(manifestFile);
Step jar = new JarDirectoryStep(
getProjectFilesystem(),
outputFile,
includePaths,
mainClass,
manifestPath,
mergeManifests,
blacklist);
commands.add(jar);
buildableContext.recordArtifact(outputFile);
return commands.build();
}
@Override
public ImmutableSetMultimap<JavaLibrary, Path> getTransitiveClasspathEntries() {
return transitiveClasspathEntries;
}
@Override
public ImmutableSet<JavaLibrary> getTransitiveClasspathDeps() {
return transitiveClasspathEntries.keySet();
}
private Path getOutputDirectory() {
return BuildTargets.getGenPath(getBuildTarget(), "%s").getParent();
}
@Override
public Path getPathToOutput() {
return Paths.get(
String.format(
"%s/%s.jar",
getOutputDirectory(),
getBuildTarget().getShortNameAndFlavorPostfix()));
}
@Override
public Tool getExecutableCommand() {
Preconditions.checkState(
mainClass != null,
"Must specify a main class for %s in order to to run it.",
getBuildTarget());
return new CommandTool.Builder()
.addArg("java")
.addArg("-jar")
.addArg(new BuildTargetSourcePath(getBuildTarget()))
.build();
}
}
| mikekap/buck | src/com/facebook/buck/jvm/java/JavaBinary.java | Java | apache-2.0 | 6,767 |
<HTML><style type="text/css"> ul.inheritance {
margin:0;
padding:0;
}
ul.inheritance li {
display:inline;
list-style-type:none;
}
ul.inheritance li ul.inheritance {
margin-left:15px;
padding-left:15px;
padding-top:1px;
}
</style> <section class="detail" id="toLowerCase()">
<h3>toLowerCase</h3>
<div class="member-signature"><span class="modifiers">public</span> <span class="return-type"><a href="String.html"
title="class in java.lang">String</a></span> <span
class="element-name">toLowerCase</span>()
</div>
<div class="block">Converts all of the characters in this <code>String</code> to lower
case using the rules of the default locale. This is equivalent to calling
<code>toLowerCase(Locale.getDefault())</code>.
<p>
<b>Note:</b> This method is locale sensitive, and may produce unexpected
results if used for strings that are intended to be interpreted locale
independently.
Examples are programming language identifiers, protocol keys, and HTML
tags.
For instance, <code>"TITLE".toLowerCase()</code> in a Turkish locale
returns <code>"t\u0131tle"</code>, where '\u0131' is the
LATIN SMALL LETTER DOTLESS I character.
To obtain correct results for locale insensitive strings, use
<code>toLowerCase(Locale.ROOT)</code>.</p></div>
<dl class="notes">
<dt>Returns:</dt>
<dd>the <code>String</code>, converted to lowercase.</dd>
<dt>See Also:</dt>
<dd><a href="#toLowerCase(java.util.Locale)"><code>toLowerCase(Locale)</code></a></dd>
</dl>
</section>
</li>
<li>
</HTML> | siosio/intellij-community | java/java-tests/testData/codeInsight/externalJavadoc/String/16/expectedToLowerCase.html | HTML | apache-2.0 | 2,256 |
/* mbed Microcontroller Library
*******************************************************************************
* Copyright (c) 2018, STMicroelectronics
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************
*/
//==============================================================================
// Notes
//
// - The pins mentioned Px_y_ALTz are alternative possibilities which use other
// HW peripheral instances. You can use them the same way as any other "normal"
// pin (i.e. PwmOut pwm(PA_7_ALT0);). These pins are not displayed on the board
// pinout image on mbed.org.
//
// - The pins which are connected to other components present on the board have
// the comment "Connected to xxx". The pin function may not work properly in this
// case. These pins may not be displayed on the board pinout image on mbed.org.
// Please read the board reference manual and schematic for more information.
//
// - Warning: pins connected to the default STDIO_UART_TX and STDIO_UART_RX pins are commented
// See https://os.mbed.com/teams/ST/wiki/STDIO for more information.
//
//==============================================================================
#ifndef MBED_PERIPHERALPINMAPS_H
#define MBED_PERIPHERALPINMAPS_H
#include "PinNamesTypes.h"
#include <mstd_cstddef>
//*** ADC ***
//*** ADC ***
MSTD_CONSTEXPR_OBJ_11 PinMap PinMap_ADC[] = {
{PA_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // ADC1_IN1
{PA_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // ADC1_IN2
// {PA_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 3, 0)}, // ADC1_IN3 // Connected to STDIO_UART_TX
// {PA_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 4, 0)}, // ADC1_IN4 // Connected to STDIO_UART_RX
{PA_4, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // ADC2_IN1
// {PA_5, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // ADC2_IN2 // Connected to LD2 [Green Led]
{PA_6, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 3, 0)}, // ADC2_IN3
{PA_7, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 4, 0)}, // ADC2_IN4
{PB_0, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 12, 0)}, // ADC3_IN12
{PB_1, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // ADC3_IN1
{PB_2, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 12, 0)}, // ADC2_IN12
{PB_11, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 14, 0)}, // ADC1_IN14
{PB_11_ALT0, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 14, 0)}, // ADC2_IN14
{PB_12, ADC_4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 3, 0)}, // ADC4_IN3
{PB_13, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // ADC3_IN5
{PB_14, ADC_4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 4, 0)}, // ADC4_IN4
{PB_15, ADC_4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // ADC4_IN5
{PC_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC1_IN6
{PC_0_ALT0, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC2_IN6
{PC_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC1_IN7
{PC_1_ALT0, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC2_IN7
{PC_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC1_IN8
{PC_2_ALT0, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC2_IN8
{PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 9, 0)}, // ADC1_IN9
{PC_3_ALT0, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 9, 0)}, // ADC2_IN9
{PC_4, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // ADC2_IN5
{PC_5, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 11, 0)}, // ADC2_IN11
{NC, NC, 0}
};
MSTD_CONSTEXPR_OBJ_11 PinMap PinMap_ADC_Internal[] = {
{ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // ADC1_IN16
{ADC_VREF1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // ADC1_IN18
{ADC_VREF2, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // ADC2_IN18
{ADC_VREF3, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // ADC3_IN18
{ADC_VREF4, ADC_4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // ADC4_IN18
{ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // ADC1_IN17
{ADC_VOPAMP1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC1_IN15
{ADC_VOPAMP2, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // ADC2_IN17
{ADC_VOPAMP3, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // ADC3_IN17
{ADC_VOPAMP4, ADC_4, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // ADC4_IN17
{NC, NC, 0}
};
//*** DAC ***
MSTD_CONSTEXPR_OBJ_11 PinMap PinMap_DAC[] = {
{PA_4, DAC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // DAC1_OUT1
{PA_5, DAC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // DAC1_OUT2 // Connected to LD2 [Green Led]
{NC, NC, 0}
};
//*** I2C ***
MSTD_CONSTEXPR_OBJ_11 PinMap PinMap_I2C_SDA[] = {
{PA_10, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)},
{PA_14, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, // Connected to TCK
{PB_5, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF8_I2C3)},
{PB_7, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)},
{PB_9, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)},
{PC_9, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF3_I2C3)},
// {PF_0, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, // Connected to RCC_OSC_IN
{NC, NC, 0}
};
MSTD_CONSTEXPR_OBJ_11 PinMap PinMap_I2C_SCL[] = {
{PA_8, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF3_I2C3)},
{PA_9, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)},
{PA_15, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)},
{PB_6, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)},
{PB_8, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)},
// {PF_1, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, // Connected to RCC_OSC_OUT
{NC, NC, 0}
};
//*** PWM ***
// TIM2 cannot be used because already used by the us_ticker
MSTD_CONSTEXPR_OBJ_11 PinMap PinMap_PWM[] = {
// {PA_0, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1
// {PA_1, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2
{PA_1, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM15, 1, 1)}, // TIM15_CH1N
// {PA_2, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 // Connected to STDIO_UART_TX
// {PA_2, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM15, 1, 0)}, // TIM15_CH1 // Connected to STDIO_UART_TX
// {PA_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 // Connected to STDIO_UART_RX
// {PA_3, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM15, 2, 0)}, // TIM15_CH2 // Connected to STDIO_UART_RX
{PA_4, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2
// {PA_5, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1 // Connected to LD2 [Green Led]
{PA_6, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1
{PA_6_ALT0, PWM_16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM16, 1, 0)}, // TIM16_CH1
{PA_7, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_TIM1, 1, 1)}, // TIM1_CH1N
{PA_7_ALT0, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2
{PA_7_ALT1, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM8, 1, 1)}, // TIM8_CH1N
{PA_7_ALT2, PWM_17, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM17, 1, 0)}, // TIM17_CH1
{PA_8, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_TIM1, 1, 0)}, // TIM1_CH1
{PA_9, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_TIM1, 2, 0)}, // TIM1_CH2
// {PA_9, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_TIM2, 3, 0)}, // TIM2_CH3
{PA_10, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_TIM1, 3, 0)}, // TIM1_CH3
// {PA_10, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_TIM2, 4, 0)}, // TIM2_CH4
{PA_11, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_TIM1, 1, 1)}, // TIM1_CH1N
{PA_11_ALT0, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF11_TIM1, 4, 0)}, // TIM1_CH4
{PA_11_ALT1, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_TIM4, 1, 0)}, // TIM4_CH1
{PA_12, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_TIM1, 2, 1)}, // TIM1_CH2N
{PA_12_ALT0, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_TIM4, 2, 0)}, // TIM4_CH2
{PA_12_ALT1, PWM_16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM16, 1, 0)}, // TIM16_CH1
{PA_13, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_TIM4, 3, 0)}, // TIM4_CH3 // Connected to TMS
{PA_13_ALT0, PWM_16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM16, 1, 1)}, // TIM16_CH1N // Connected to TMS
{PA_14, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_TIM8, 2, 0)}, // TIM8_CH2 // Connected to TCK
// {PA_15, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1
{PA_15, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM8, 1, 0)}, // TIM8_CH1
{PB_0, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_TIM1, 2, 1)}, // TIM1_CH2N
{PB_0_ALT0, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 3, 0)}, // TIM3_CH3
{PB_0_ALT1, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM8, 2, 1)}, // TIM8_CH2N
{PB_1, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_TIM1, 3, 1)}, // TIM1_CH3N
{PB_1_ALT0, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 4, 0)}, // TIM3_CH4
{PB_1_ALT1, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM8, 3, 1)}, // TIM8_CH3N
// {PB_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2 // Connected to SWO
{PB_3, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM8, 1, 1)}, // TIM8_CH1N // Connected to SWO
{PB_4, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1
{PB_4_ALT0, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM8, 2, 1)}, // TIM8_CH2N
{PB_4_ALT1, PWM_16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM16, 1, 0)}, // TIM16_CH1
{PB_5, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2
{PB_5_ALT0, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 3, 1)}, // TIM8_CH3N
{PB_5_ALT1, PWM_17, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_TIM17, 1, 0)}, // TIM17_CH1
{PB_6, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 1, 0)}, // TIM4_CH1
{PB_6_ALT0, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_TIM8, 1, 0)}, // TIM8_CH1
{PB_6_ALT1, PWM_16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM16, 1, 1)}, // TIM16_CH1N
{PB_7, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_TIM3, 4, 0)}, // TIM3_CH4
{PB_7_ALT0, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 2, 0)}, // TIM4_CH2
{PB_7_ALT1, PWM_17, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM17, 1, 1)}, // TIM17_CH1N
{PB_8, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 3, 0)}, // TIM4_CH3
{PB_8_ALT0, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_TIM8, 2, 0)}, // TIM8_CH2
{PB_8_ALT1, PWM_16, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM16, 1, 0)}, // TIM16_CH1
{PB_9, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 4, 0)}, // TIM4_CH4
{PB_9_ALT0, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF10_TIM8, 3, 0)}, // TIM8_CH3
{PB_9_ALT1, PWM_17, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM17, 1, 0)}, // TIM17_CH1
// {PB_10, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3
// {PB_11, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4
{PB_13, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_TIM1, 1, 1)}, // TIM1_CH1N
{PB_14, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_TIM1, 2, 1)}, // TIM1_CH2N
{PB_14_ALT0, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM15, 1, 0)}, // TIM15_CH1
{PB_15, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM1, 3, 1)}, // TIM1_CH3N
{PB_15_ALT0, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM15, 1, 1)}, // TIM15_CH1N
{PB_15_ALT1, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM15, 2, 0)}, // TIM15_CH2
{PC_0, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM1, 1, 0)}, // TIM1_CH1
{PC_1, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM1, 2, 0)}, // TIM1_CH2
{PC_2, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM1, 3, 0)}, // TIM1_CH3
{PC_3, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM1, 4, 0)}, // TIM1_CH4
{PC_6, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1
{PC_6_ALT0, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM8, 1, 0)}, // TIM8_CH1
{PC_7, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2
{PC_7_ALT0, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM8, 2, 0)}, // TIM8_CH2
{PC_8, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 3, 0)}, // TIM3_CH3
{PC_8_ALT0, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM8, 3, 0)}, // TIM8_CH3
{PC_9, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 4, 0)}, // TIM3_CH4
{PC_9_ALT0, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM8, 4, 0)}, // TIM8_CH4
{PC_10, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM8, 1, 1)}, // TIM8_CH1N
{PC_11, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM8, 2, 1)}, // TIM8_CH2N
{PC_12, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM8, 3, 1)}, // TIM8_CH3N
{PC_13, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM1, 1, 1)}, // TIM1_CH1N // Connected to B1 [Blue PushButton]
// {PF_0, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_TIM1, 3, 1)}, // TIM1_CH3N // Connected to RCC_OSC_IN
{NC, NC, 0}
};
//*** SERIAL ***
MSTD_CONSTEXPR_OBJ_11 PinMap PinMap_UART_TX[] = {
{PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, // Connected to STDIO_UART_TX
{PA_9, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
{PA_14, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, // Connected to TCK
{PB_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, // Connected to SWO
{PB_6, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
{PB_9, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PB_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PC_4, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
{PC_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PC_10_ALT0, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_UART4)},
{PC_12, UART_5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_UART5)},
{NC, NC, 0}
};
MSTD_CONSTEXPR_OBJ_11 PinMap PinMap_UART_RX[] = {
{PA_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, // Connected to STDIO_UART_RX
{PA_10, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
{PA_15, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)},
{PB_4, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)},
{PB_7, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
{PB_8, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PB_11, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PC_5, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
{PC_11, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{PC_11_ALT0, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_UART4)},
{PD_2, UART_5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_UART5)},
{NC, NC, 0}
};
MSTD_CONSTEXPR_OBJ_11 PinMap PinMap_UART_RTS[] = {
{PA_1, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)},
{PA_12, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
{PB_14, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{NC, NC, 0}
};
MSTD_CONSTEXPR_OBJ_11 PinMap PinMap_UART_CTS[] = {
{PA_0, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)},
{PA_11, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)},
{PA_13, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, // Connected to TMS
{PB_13, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)},
{NC, NC, 0}
};
//*** SPI ***
MSTD_CONSTEXPR_OBJ_11 PinMap PinMap_SPI_MOSI[] = {
{PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)},
{PA_11, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)},
{PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)},
{PB_5_ALT0, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)},
{PB_15, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)},
{PC_12, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)},
{NC, NC, 0}
};
MSTD_CONSTEXPR_OBJ_11 PinMap PinMap_SPI_MISO[] = {
{PA_6, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)},
{PA_10, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)},
{PB_4, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)},
{PB_4_ALT0, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)},
{PB_14, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)},
{PC_11, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)},
{NC, NC, 0}
};
MSTD_CONSTEXPR_OBJ_11 PinMap PinMap_SPI_SCLK[] = {
{PA_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, // Connected to LD2 [Green Led]
{PB_3, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, // Connected to SWO
{PB_3_ALT0, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, // Connected to SWO
{PB_13, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)},
{PC_10, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)},
// {PF_1, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, // Connected to RCC_OSC_OUT
{NC, NC, 0}
};
MSTD_CONSTEXPR_OBJ_11 PinMap PinMap_SPI_SSEL[] = {
{PA_4, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)},
{PA_4_ALT0, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)},
{PA_15, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)},
{PA_15_ALT0, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)},
{PB_12, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)},
// {PF_0, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, // Connected to RCC_OSC_IN
{NC, NC, 0}
};
//*** CAN ***
MSTD_CONSTEXPR_OBJ_11 PinMap PinMap_CAN_RD[] = {
{PA_11, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN)},
{PB_8, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN)},
{NC, NC, 0}
};
MSTD_CONSTEXPR_OBJ_11 PinMap PinMap_CAN_TD[] = {
{PA_12, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN)},
{PB_9, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN)},
{NC, NC, 0}
};
//*** USBDEVICE ***
MSTD_CONSTEXPR_OBJ_11 PinMap PinMap_USB_FS[] = {
{PA_11, USB_FS, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, GPIO_AF_NONE)}, // USB_DM
{PA_12, USB_FS, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, GPIO_AF_NONE)}, // USB_DP
{NC, NC, 0}
};
#define PINMAP_ANALOGIN PinMap_ADC
#define PINMAP_ANALOGIN_INTERNAL PinMap_ADC_Internal
#define PINMAP_ANALOGOUT PinMap_DAC
#define PINMAP_I2C_SDA PinMap_I2C_SDA
#define PINMAP_I2C_SCL PinMap_I2C_SCL
#define PINMAP_UART_TX PinMap_UART_TX
#define PINMAP_UART_RX PinMap_UART_RX
#define PINMAP_UART_CTS PinMap_UART_CTS
#define PINMAP_UART_RTS PinMap_UART_RTS
#define PINMAP_SPI_SCLK PinMap_SPI_SCLK
#define PINMAP_SPI_MOSI PinMap_SPI_MOSI
#define PINMAP_SPI_MISO PinMap_SPI_MISO
#define PINMAP_SPI_SSEL PinMap_SPI_SSEL
#define PINMAP_PWM PinMap_PWM
#define PINMAP_CAN_RD PinMap_CAN_RD
#define PINMAP_CAN_TD PinMap_CAN_TD
#endif | mbedmicro/mbed | targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xE/TARGET_NUCLEO_F303RE/PeripheralPinMaps.h | C | apache-2.0 | 24,186 |
#!/usr/bin/python2
# Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project authors may
# be found in the AUTHORS file in the root of the source tree.
# To run this script please copy "out/<build_name>//pyproto/webrtc/modules/
# audio_coding/audio_network_adaptor/debug_dump_pb2.py" to this folder.
# The you can run this script with:
# "python parse_ana_dump.py -m uplink_bandwidth_bps -f dump_file.dat"
# You can add as may metrics or decisions to the plot as you like.
# form more information call:
# "python parse_ana_dump.py --help"
import struct
from optparse import OptionParser
import matplotlib.pyplot as plt
import debug_dump_pb2
def GetNextMessageSize(file_to_parse):
data = file_to_parse.read(4)
if data == '':
return 0
return struct.unpack('<I', data)[0]
def GetNextMessageFromFile(file_to_parse):
message_size = GetNextMessageSize(file_to_parse)
if message_size == 0:
return None
try:
event = debug_dump_pb2.Event()
event.ParseFromString(file_to_parse.read(message_size))
except IOError:
print 'Invalid message in file'
return None
return event
def InitMetrics():
metrics = {}
event = debug_dump_pb2.Event()
for metric in event.network_metrics.DESCRIPTOR.fields:
metrics[metric.name] = {'time': [], 'value': []}
return metrics
def InitDecisions():
decisions = {}
event = debug_dump_pb2.Event()
for decision in event.encoder_runtime_config.DESCRIPTOR.fields:
decisions[decision.name] = {'time': [], 'value': []}
return decisions
def ParseAnaDump(dump_file_to_parse):
with open(dump_file_to_parse, 'rb') as file_to_parse:
metrics = InitMetrics()
decisions = InitDecisions()
first_time_stamp = None
while True:
event = GetNextMessageFromFile(file_to_parse)
if event == None:
break
if first_time_stamp == None:
first_time_stamp = event.timestamp
if event.type == debug_dump_pb2.Event.ENCODER_RUNTIME_CONFIG:
for decision in event.encoder_runtime_config.DESCRIPTOR.fields:
if event.encoder_runtime_config.HasField(decision.name):
decisions[decision.name]['time'].append(event.timestamp -
first_time_stamp)
decisions[decision.name]['value'].append(
getattr(event.encoder_runtime_config, decision.name))
if event.type == debug_dump_pb2.Event.NETWORK_METRICS:
for metric in event.network_metrics.DESCRIPTOR.fields:
if event.network_metrics.HasField(metric.name):
metrics[metric.name]['time'].append(event.timestamp -
first_time_stamp)
metrics[metric.name]['value'].append(
getattr(event.network_metrics, metric.name))
return (metrics, decisions)
def main():
parser = OptionParser()
parser.add_option(
"-f", "--dump_file", dest="dump_file_to_parse", help="dump file to parse")
parser.add_option(
'-m',
'--metric_plot',
default=[],
type=str,
help='metric key (name of the metric) to plot',
dest='metric_keys',
action='append')
parser.add_option(
'-d',
'--decision_plot',
default=[],
type=str,
help='decision key (name of the decision) to plot',
dest='decision_keys',
action='append')
options = parser.parse_args()[0]
if options.dump_file_to_parse == None:
print "No dump file to parse is set.\n"
parser.print_help()
exit()
(metrics, decisions) = ParseAnaDump(options.dump_file_to_parse)
metric_keys = options.metric_keys
decision_keys = options.decision_keys
plot_count = len(metric_keys) + len(decision_keys)
if plot_count == 0:
print "You have to set at least one metric or decision to plot.\n"
parser.print_help()
exit()
plots = []
if plot_count == 1:
f, mp_plot = plt.subplots()
plots.append(mp_plot)
else:
f, mp_plots = plt.subplots(plot_count, sharex=True)
plots.extend(mp_plots.tolist())
for key in metric_keys:
plot = plots.pop()
plot.grid(True)
plot.set_title(key + " (metric)")
plot.plot(metrics[key]['time'], metrics[key]['value'])
for key in decision_keys:
plot = plots.pop()
plot.grid(True)
plot.set_title(key + " (decision)")
plot.plot(decisions[key]['time'], decisions[key]['value'])
f.subplots_adjust(hspace=0.3)
plt.show()
if __name__ == "__main__":
main()
| wangcy6/storm_app | frame/c++/webrtc-master/modules/audio_coding/audio_network_adaptor/parse_ana_dump.py | Python | apache-2.0 | 4,718 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gobblin.runtime.commit;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import gobblin.commit.CommitSequence;
import gobblin.commit.FsRenameCommitStep;
import gobblin.configuration.ConfigurationKeys;
import gobblin.configuration.State;
import gobblin.runtime.JobState.DatasetState;
/**
* Tests for {@link CommitSequence}.
*
* @author Ziyang Liu
*/
@Test(groups = { "gobblin.runtime.commit" })
public class CommitSequenceTest {
private static final String ROOT_DIR = "commit-sequence-test";
private FileSystem fs;
private CommitSequence sequence;
@BeforeClass
public void setUp() throws IOException {
this.fs = FileSystem.getLocal(new Configuration());
this.fs.delete(new Path(ROOT_DIR), true);
Path storeRootDir = new Path(ROOT_DIR, "store");
Path dir1 = new Path(ROOT_DIR, "dir1");
Path dir2 = new Path(ROOT_DIR, "dir2");
this.fs.mkdirs(dir1);
this.fs.mkdirs(dir2);
Path src1 = new Path(dir1, "file1");
Path src2 = new Path(dir2, "file2");
Path dst1 = new Path(dir2, "file1");
Path dst2 = new Path(dir1, "file2");
this.fs.createNewFile(src1);
this.fs.createNewFile(src2);
DatasetState ds = new DatasetState("job-name", "job-id");
ds.setDatasetUrn("urn");
ds.setNoJobFailure();
State state = new State();
state.setProp(ConfigurationKeys.STATE_STORE_ROOT_DIR_KEY, storeRootDir.toString());
this.sequence = new CommitSequence.Builder().withJobName("testjob").withDatasetUrn("testurn")
.beginStep(FsRenameCommitStep.Builder.class).from(src1).to(dst1).withProps(state).endStep()
.beginStep(FsRenameCommitStep.Builder.class).from(src2).to(dst2).withProps(state).endStep()
.beginStep(DatasetStateCommitStep.Builder.class).withDatasetUrn("urn").withDatasetState(ds).withProps(state)
.endStep().build();
}
@AfterClass
public void tearDown() throws IOException {
this.fs.delete(new Path(ROOT_DIR), true);
}
@Test
public void testExecute() throws IOException {
this.sequence.execute();
Assert.assertTrue(this.fs.exists(new Path(ROOT_DIR, "dir1/file2")));
Assert.assertTrue(this.fs.exists(new Path(ROOT_DIR, "dir2/file1")));
Assert.assertTrue(this.fs.exists(new Path(ROOT_DIR, "store/job-name/urn-job-id.jst")));
Assert.assertTrue(this.fs.exists(new Path(ROOT_DIR, "store/job-name/urn-current.jst")));
}
}
| ydai1124/gobblin-1 | gobblin-runtime/src/test/java/gobblin/runtime/commit/CommitSequenceTest.java | Java | apache-2.0 | 3,431 |
"""Support for Verisure Smartplugs."""
import logging
from time import monotonic
from homeassistant.components.switch import SwitchEntity
from . import CONF_SMARTPLUGS, HUB as hub
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Verisure switch platform."""
if not int(hub.config.get(CONF_SMARTPLUGS, 1)):
return False
hub.update_overview()
switches = []
switches.extend(
[
VerisureSmartplug(device_label)
for device_label in hub.get("$.smartPlugs[*].deviceLabel")
]
)
add_entities(switches)
class VerisureSmartplug(SwitchEntity):
"""Representation of a Verisure smartplug."""
def __init__(self, device_id):
"""Initialize the Verisure device."""
self._device_label = device_id
self._change_timestamp = 0
self._state = False
@property
def name(self):
"""Return the name or location of the smartplug."""
return hub.get_first(
"$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label
)
@property
def is_on(self):
"""Return true if on."""
if monotonic() - self._change_timestamp < 10:
return self._state
self._state = (
hub.get_first(
"$.smartPlugs[?(@.deviceLabel == '%s')].currentState",
self._device_label,
)
== "ON"
)
return self._state
@property
def available(self):
"""Return True if entity is available."""
return (
hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label)
is not None
)
def turn_on(self, **kwargs):
"""Set smartplug status on."""
hub.session.set_smartplug_state(self._device_label, True)
self._state = True
self._change_timestamp = monotonic()
def turn_off(self, **kwargs):
"""Set smartplug status off."""
hub.session.set_smartplug_state(self._device_label, False)
self._state = False
self._change_timestamp = monotonic()
# pylint: disable=no-self-use
def update(self):
"""Get the latest date of the smartplug."""
hub.update_overview()
| nkgilley/home-assistant | homeassistant/components/verisure/switch.py | Python | apache-2.0 | 2,311 |
/*
* Copyright 2015 JBoss, by Red Hat, 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.
*/
package org.uberfire.ext.wires.bayesian.network.client.factory;
import com.ait.lienzo.client.core.shape.Rectangle;
import com.ait.lienzo.client.core.shape.Shape;
import com.ait.lienzo.client.core.shape.Text;
import com.ait.lienzo.shared.core.types.Color;
import org.uberfire.ext.wires.core.client.util.ShapesUtils;
public class BaseFactory {
private static final String defaultFillColor = ShapesUtils.RGB_FILL_SHAPE;
private static final String defaultBorderColor = ShapesUtils.RGB_STROKE_SHAPE;
protected void setAttributes( final Shape<?> shape,
final String fillColor,
final double x,
final double y,
final String borderColor ) {
String fill = ( fillColor == null ) ? defaultFillColor : fillColor;
String border = ( borderColor == null ) ? defaultBorderColor : borderColor;
shape.setX( x ).setY( y ).setStrokeColor( border ).setStrokeWidth( ShapesUtils.RGB_STROKE_WIDTH_SHAPE ).setFillColor( fill ).setDraggable( false );
}
protected Rectangle drawComponent( final String color,
final int positionX,
final int positionY,
final int width,
final int height,
String borderColor,
double radius ) {
if ( borderColor == null ) {
borderColor = Color.rgbToBrowserHexColor( 0, 0, 0 );
}
Rectangle component = new Rectangle( width,
height );
setAttributes( component,
color,
positionX,
positionY,
borderColor );
component.setCornerRadius( radius );
return component;
}
protected Text drawText( final String description,
final int fontSize,
final int positionX,
final int positionY ) {
return new Text( description,
"Times",
fontSize ).setX( positionX ).setY( positionY );
}
}
| dgutierr/uberfire-extensions | uberfire-wires/uberfire-wires-bayesian-network/uberfire-wires-bayesian-network-client/src/main/java/org/uberfire/ext/wires/bayesian/network/client/factory/BaseFactory.java | Java | apache-2.0 | 2,954 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.template.impl;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupActionProvider;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementAction;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.Project;
import com.intellij.util.Consumer;
import com.intellij.util.PlatformIcons;
/**
* @author peter
*/
public class LiveTemplateLookupActionProvider implements LookupActionProvider {
@Override
public void fillActions(LookupElement element, final Lookup lookup, Consumer<LookupElementAction> consumer) {
if (element instanceof LiveTemplateLookupElementImpl) {
final TemplateImpl template = ((LiveTemplateLookupElementImpl)element).getTemplate();
final TemplateImpl templateFromSettings = TemplateSettings.getInstance().getTemplate(template.getKey(), template.getGroupName());
if (templateFromSettings != null) {
consumer.consume(new LookupElementAction(PlatformIcons.EDIT, CodeInsightBundle.message("action.text.edit.live.template.settings")) {
@Override
public Result performLookupAction() {
final Project project = lookup.getProject();
ApplicationManager.getApplication().invokeLater(() -> {
if (project.isDisposed()) return;
final LiveTemplatesConfigurable configurable = new LiveTemplatesConfigurable();
ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> configurable.getTemplateListPanel().editTemplate(template));
});
return Result.HIDE_LOOKUP;
}
});
consumer.consume(new LookupElementAction(AllIcons.Actions.Cancel, CodeInsightBundle.message("action.text.disable.live.template", template.getKey())) {
@Override
public Result performLookupAction() {
ApplicationManager.getApplication().invokeLater(() -> templateFromSettings.setDeactivated(true));
return Result.HIDE_LOOKUP;
}
});
}
}
}
}
| siosio/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateLookupActionProvider.java | Java | apache-2.0 | 2,424 |
using System;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Robotics.Mobile.Core.Bluetooth.LE;
using Xamarin.Forms.Platform.Android;
namespace HeadLights.Android
{
[Activity (Label = "HeadLights.Android.Android", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : AndroidActivity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
Xamarin.Forms.Forms.Init (this, bundle);
//TODO: need adapter
//SetPage (App.GetMainPage ());
}
}
}
| venkatarajasekhar/Monkey.Robotics | Evolve Hacks/4_AddHeadlights/Headlights/HeadLights.Mobile.Android/MainActivity.cs | C# | apache-2.0 | 676 |
// +build linux freebsd
package daemon
import (
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"time"
"github.com/docker/docker/container"
"github.com/docker/docker/daemon/links"
"github.com/docker/docker/pkg/idtools"
"github.com/docker/docker/pkg/mount"
"github.com/docker/docker/pkg/stringid"
"github.com/docker/docker/runconfig"
"github.com/docker/libnetwork"
"github.com/opencontainers/selinux/go-selinux/label"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
)
func (daemon *Daemon) setupLinkedContainers(container *container.Container) ([]string, error) {
var env []string
children := daemon.children(container)
bridgeSettings := container.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
if bridgeSettings == nil || bridgeSettings.EndpointSettings == nil {
return nil, nil
}
for linkAlias, child := range children {
if !child.IsRunning() {
return nil, fmt.Errorf("Cannot link to a non running container: %s AS %s", child.Name, linkAlias)
}
childBridgeSettings := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
if childBridgeSettings == nil || childBridgeSettings.EndpointSettings == nil {
return nil, fmt.Errorf("container %s not attached to default bridge network", child.ID)
}
link := links.NewLink(
bridgeSettings.IPAddress,
childBridgeSettings.IPAddress,
linkAlias,
child.Config.Env,
child.Config.ExposedPorts,
)
env = append(env, link.ToEnv()...)
}
return env, nil
}
func (daemon *Daemon) getIpcContainer(id string) (*container.Container, error) {
errMsg := "can't join IPC of container " + id
// Check the container exists
container, err := daemon.GetContainer(id)
if err != nil {
return nil, errors.Wrap(err, errMsg)
}
// Check the container is running and not restarting
if err := daemon.checkContainer(container, containerIsRunning, containerIsNotRestarting); err != nil {
return nil, errors.Wrap(err, errMsg)
}
// Check the container ipc is shareable
if st, err := os.Stat(container.ShmPath); err != nil || !st.IsDir() {
if err == nil || os.IsNotExist(err) {
return nil, errors.New(errMsg + ": non-shareable IPC")
}
// stat() failed?
return nil, errors.Wrap(err, errMsg+": unexpected error from stat "+container.ShmPath)
}
return container, nil
}
func (daemon *Daemon) getPidContainer(container *container.Container) (*container.Container, error) {
containerID := container.HostConfig.PidMode.Container()
container, err := daemon.GetContainer(containerID)
if err != nil {
return nil, errors.Wrapf(err, "cannot join PID of a non running container: %s", container.ID)
}
return container, daemon.checkContainer(container, containerIsRunning, containerIsNotRestarting)
}
func containerIsRunning(c *container.Container) error {
if !c.IsRunning() {
return stateConflictError{errors.Errorf("container %s is not running", c.ID)}
}
return nil
}
func containerIsNotRestarting(c *container.Container) error {
if c.IsRestarting() {
return errContainerIsRestarting(c.ID)
}
return nil
}
func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
ipcMode := c.HostConfig.IpcMode
switch {
case ipcMode.IsContainer():
ic, err := daemon.getIpcContainer(ipcMode.Container())
if err != nil {
return err
}
c.ShmPath = ic.ShmPath
case ipcMode.IsHost():
if _, err := os.Stat("/dev/shm"); err != nil {
return fmt.Errorf("/dev/shm is not mounted, but must be for --ipc=host")
}
c.ShmPath = "/dev/shm"
case ipcMode.IsPrivate(), ipcMode.IsNone():
// c.ShmPath will/should not be used, so make it empty.
// Container's /dev/shm mount comes from OCI spec.
c.ShmPath = ""
case ipcMode.IsEmpty():
// A container was created by an older version of the daemon.
// The default behavior used to be what is now called "shareable".
fallthrough
case ipcMode.IsShareable():
rootIDs := daemon.idMappings.RootPair()
if !c.HasMountFor("/dev/shm") {
shmPath, err := c.ShmResourcePath()
if err != nil {
return err
}
if err := idtools.MkdirAllAndChown(shmPath, 0700, rootIDs); err != nil {
return err
}
shmproperty := "mode=1777,size=" + strconv.FormatInt(c.HostConfig.ShmSize, 10)
if err := unix.Mount("shm", shmPath, "tmpfs", uintptr(unix.MS_NOEXEC|unix.MS_NOSUID|unix.MS_NODEV), label.FormatMountLabel(shmproperty, c.GetMountLabel())); err != nil {
return fmt.Errorf("mounting shm tmpfs: %s", err)
}
if err := os.Chown(shmPath, rootIDs.UID, rootIDs.GID); err != nil {
return err
}
c.ShmPath = shmPath
}
default:
return fmt.Errorf("invalid IPC mode: %v", ipcMode)
}
return nil
}
func (daemon *Daemon) setupSecretDir(c *container.Container) (setupErr error) {
if len(c.SecretReferences) == 0 {
return nil
}
localMountPath := c.SecretMountPath()
logrus.Debugf("secrets: setting up secret dir: %s", localMountPath)
// retrieve possible remapped range start for root UID, GID
rootIDs := daemon.idMappings.RootPair()
// create tmpfs
if err := idtools.MkdirAllAndChown(localMountPath, 0700, rootIDs); err != nil {
return errors.Wrap(err, "error creating secret local mount path")
}
defer func() {
if setupErr != nil {
// cleanup
_ = detachMounted(localMountPath)
if err := os.RemoveAll(localMountPath); err != nil {
logrus.Errorf("error cleaning up secret mount: %s", err)
}
}
}()
tmpfsOwnership := fmt.Sprintf("uid=%d,gid=%d", rootIDs.UID, rootIDs.GID)
if err := mount.Mount("tmpfs", localMountPath, "tmpfs", "nodev,nosuid,noexec,"+tmpfsOwnership); err != nil {
return errors.Wrap(err, "unable to setup secret mount")
}
if c.DependencyStore == nil {
return fmt.Errorf("secret store is not initialized")
}
for _, s := range c.SecretReferences {
// TODO (ehazlett): use type switch when more are supported
if s.File == nil {
logrus.Error("secret target type is not a file target")
continue
}
// secrets are created in the SecretMountPath on the host, at a
// single level
fPath := c.SecretFilePath(*s)
if err := idtools.MkdirAllAndChown(filepath.Dir(fPath), 0700, rootIDs); err != nil {
return errors.Wrap(err, "error creating secret mount path")
}
logrus.WithFields(logrus.Fields{
"name": s.File.Name,
"path": fPath,
}).Debug("injecting secret")
secret, err := c.DependencyStore.Secrets().Get(s.SecretID)
if err != nil {
return errors.Wrap(err, "unable to get secret from secret store")
}
if err := ioutil.WriteFile(fPath, secret.Spec.Data, s.File.Mode); err != nil {
return errors.Wrap(err, "error injecting secret")
}
uid, err := strconv.Atoi(s.File.UID)
if err != nil {
return err
}
gid, err := strconv.Atoi(s.File.GID)
if err != nil {
return err
}
if err := os.Chown(fPath, rootIDs.UID+uid, rootIDs.GID+gid); err != nil {
return errors.Wrap(err, "error setting ownership for secret")
}
}
label.Relabel(localMountPath, c.MountLabel, false)
// remount secrets ro
if err := mount.Mount("tmpfs", localMountPath, "tmpfs", "remount,ro,"+tmpfsOwnership); err != nil {
return errors.Wrap(err, "unable to remount secret dir as readonly")
}
return nil
}
func (daemon *Daemon) setupConfigDir(c *container.Container) (setupErr error) {
if len(c.ConfigReferences) == 0 {
return nil
}
localPath := c.ConfigsDirPath()
logrus.Debugf("configs: setting up config dir: %s", localPath)
// retrieve possible remapped range start for root UID, GID
rootIDs := daemon.idMappings.RootPair()
// create tmpfs
if err := idtools.MkdirAllAndChown(localPath, 0700, rootIDs); err != nil {
return errors.Wrap(err, "error creating config dir")
}
defer func() {
if setupErr != nil {
if err := os.RemoveAll(localPath); err != nil {
logrus.Errorf("error cleaning up config dir: %s", err)
}
}
}()
if c.DependencyStore == nil {
return fmt.Errorf("config store is not initialized")
}
for _, configRef := range c.ConfigReferences {
// TODO (ehazlett): use type switch when more are supported
if configRef.File == nil {
logrus.Error("config target type is not a file target")
continue
}
fPath := c.ConfigFilePath(*configRef)
log := logrus.WithFields(logrus.Fields{"name": configRef.File.Name, "path": fPath})
if err := idtools.MkdirAllAndChown(filepath.Dir(fPath), 0700, rootIDs); err != nil {
return errors.Wrap(err, "error creating config path")
}
log.Debug("injecting config")
config, err := c.DependencyStore.Configs().Get(configRef.ConfigID)
if err != nil {
return errors.Wrap(err, "unable to get config from config store")
}
if err := ioutil.WriteFile(fPath, config.Spec.Data, configRef.File.Mode); err != nil {
return errors.Wrap(err, "error injecting config")
}
uid, err := strconv.Atoi(configRef.File.UID)
if err != nil {
return err
}
gid, err := strconv.Atoi(configRef.File.GID)
if err != nil {
return err
}
if err := os.Chown(fPath, rootIDs.UID+uid, rootIDs.GID+gid); err != nil {
return errors.Wrap(err, "error setting ownership for config")
}
label.Relabel(fPath, c.MountLabel, false)
}
return nil
}
func killProcessDirectly(cntr *container.Container) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Block until the container to stops or timeout.
status := <-cntr.Wait(ctx, container.WaitConditionNotRunning)
if status.Err() != nil {
// Ensure that we don't kill ourselves
if pid := cntr.GetPID(); pid != 0 {
logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(cntr.ID))
if err := unix.Kill(pid, 9); err != nil {
if err != unix.ESRCH {
return err
}
e := errNoSuchProcess{pid, 9}
logrus.Debug(e)
return e
}
}
}
return nil
}
func detachMounted(path string) error {
return unix.Unmount(path, unix.MNT_DETACH)
}
func isLinkable(child *container.Container) bool {
// A container is linkable only if it belongs to the default network
_, ok := child.NetworkSettings.Networks[runconfig.DefaultDaemonNetworkMode().NetworkName()]
return ok
}
func enableIPOnPredefinedNetwork() bool {
return false
}
func (daemon *Daemon) isNetworkHotPluggable() bool {
return true
}
func setupPathsAndSandboxOptions(container *container.Container, sboxOptions *[]libnetwork.SandboxOption) error {
var err error
container.HostsPath, err = container.GetRootResourcePath("hosts")
if err != nil {
return err
}
*sboxOptions = append(*sboxOptions, libnetwork.OptionHostsPath(container.HostsPath))
container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf")
if err != nil {
return err
}
*sboxOptions = append(*sboxOptions, libnetwork.OptionResolvConfPath(container.ResolvConfPath))
return nil
}
func (daemon *Daemon) initializeNetworkingPaths(container *container.Container, nc *container.Container) error {
container.HostnamePath = nc.HostnamePath
container.HostsPath = nc.HostsPath
container.ResolvConfPath = nc.ResolvConfPath
return nil
}
| raja-sami-10p/moby | daemon/container_operations_unix.go | GO | apache-2.0 | 11,070 |
/*
* Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#import "../AmazonServiceRequest.h"
#import "ElasticLoadBalancingRequest.h"
#import "ElasticLoadBalancingDescribeInstanceHealthRequest.h"
#import "ElasticLoadBalancingInstance.h"
/**
* Describe Instance Health Request Marshaller
*/
@interface ElasticLoadBalancingDescribeInstanceHealthRequestMarshaller:NSObject {
}
+(AmazonServiceRequest *)createRequest:(ElasticLoadBalancingDescribeInstanceHealthRequest *)describeInstanceHealthRequest;
@end
| abovelabs/aws-ios-sdk | src/include/ElasticLoadBalancing/ElasticLoadBalancingDescribeInstanceHealthRequestMarshaller.h | C | apache-2.0 | 1,040 |
// This file was automatically generated. Do not modify.
'use strict';
goog.provide('Blockly.Msg.az');
goog.require('Blockly.Msg');
Blockly.Msg.ADD_COMMENT = "Şərh əlavə et";
Blockly.Msg.CHANGE_VALUE_TITLE = "Qiyməti dəyiş:";
Blockly.Msg.CHAT = "Chat with your collaborator by typing in this box!"; // untranslated
Blockly.Msg.COLLAPSE_ALL = "Blokları yığ";
Blockly.Msg.COLLAPSE_BLOCK = "Bloku yığ";
Blockly.Msg.COLOUR_BLEND_COLOUR1 = "rəng 1";
Blockly.Msg.COLOUR_BLEND_COLOUR2 = "rəng 2";
Blockly.Msg.COLOUR_BLEND_HELPURL = "http://meyerweb.com/eric/tools/color-blend/";
Blockly.Msg.COLOUR_BLEND_RATIO = "nisbət";
Blockly.Msg.COLOUR_BLEND_TITLE = "qarışdır";
Blockly.Msg.COLOUR_BLEND_TOOLTIP = "İki rəngi verilmiş nisbətdə (0,0 - 1,0) qarışdırır.";
Blockly.Msg.COLOUR_PICKER_HELPURL = "https://en.wikipedia.org/wiki/Color"; // untranslated
Blockly.Msg.COLOUR_PICKER_TOOLTIP = "Palitradan bir rəng seçin.";
Blockly.Msg.COLOUR_RANDOM_HELPURL = "http://randomcolour.com"; // untranslated
Blockly.Msg.COLOUR_RANDOM_TITLE = "təsadüfi rəng";
Blockly.Msg.COLOUR_RANDOM_TOOLTIP = "Təsadüfi bir rəng seçin.";
Blockly.Msg.COLOUR_RGB_BLUE = "mavi";
Blockly.Msg.COLOUR_RGB_GREEN = "yaşıl";
Blockly.Msg.COLOUR_RGB_HELPURL = "http://www.december.com/html/spec/colorper.html";
Blockly.Msg.COLOUR_RGB_RED = "qırmızı";
Blockly.Msg.COLOUR_RGB_TITLE = "rəngin komponentləri:";
Blockly.Msg.COLOUR_RGB_TOOLTIP = "Qırmızı, yaşıl və mavinin göstərilən miqdarı ilə bir rəng düzəlt. Bütün qiymətlər 0 ilə 100 arasında olmalıdır.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL = "https://code.google.com/p/blockly/wiki/Loops#Loop_Termination_Blocks";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = "dövrdən çıx";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = "dövrün növbəti addımından davam et";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = "Cari dövrdən çıx.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = "Bu dövrün qalanını ötür və növbəti addımla davam et.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING = "Xəbərdarlıq: Bu blok ancaq dövr daxilində istifadə oluna bilər.";
Blockly.Msg.CONTROLS_FOREACH_HELPURL = "https://code.google.com/p/blockly/wiki/Loops#for_each";
Blockly.Msg.CONTROLS_FOREACH_INPUT_INLIST = "siyahıda";
Blockly.Msg.CONTROLS_FOREACH_INPUT_INLIST_TAIL = ""; // untranslated
Blockly.Msg.CONTROLS_FOREACH_INPUT_ITEM = "hər element üçün";
Blockly.Msg.CONTROLS_FOREACH_TOOLTIP = "Siyahıdakı hər element üçün \"%1\" dəyişənini elementə mənimsət və bundan sonra bəzi əmrləri yerinə yetir.";
Blockly.Msg.CONTROLS_FOR_HELPURL = "https://code.google.com/p/blockly/wiki/Loops#count_with";
Blockly.Msg.CONTROLS_FOR_INPUT_FROM_TO_BY = "%1 ilə başlayıb, %2 qiymətinə kimi %3 qədər dəyiş";
Blockly.Msg.CONTROLS_FOR_INPUT_WITH = "say:";
Blockly.Msg.CONTROLS_FOR_TOOLTIP = "%1 dəyişəni başlanğıc ədəddən son ədədə qədər göstərilən aralıqla qiymətlər aldıqca göstərilən blokları yerinə yetir.";
Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = "\"Əgər\" blokuna bir şərt əlavə et.";
Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = "\"Əgər\" blokuna qalan bütün halları əhatə edəb son bir şərt əlavə et.";
Blockly.Msg.CONTROLS_IF_HELPURL = "http://code.google.com/p/blockly/wiki/If_Then";
Blockly.Msg.CONTROLS_IF_IF_TOOLTIP = "Bu \"əgər\" blokunu dəyişdirmək üçün bölümlərin yenisini əlavə et, sil və ya yerini dəyiş.";
Blockly.Msg.CONTROLS_IF_MSG_ELSE = "əks halda";
Blockly.Msg.CONTROLS_IF_MSG_ELSEIF = "əks halda əgər";
Blockly.Msg.CONTROLS_IF_MSG_IF = "əgər";
Blockly.Msg.CONTROLS_IF_TOOLTIP_1 = "Əgər qiymət doğrudursa, onda bəzi əmrləri yerinə yetir.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_2 = "Əgər qiymət doğrudursa, onda birinci əmrlər blokunu yerinə yetir. Əks halda isə ikinci əmrlər blokunu yerinə yetir.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_3 = "Əgər birinci qiymət doğrudursa, onda birinci əmrlər blokunu yerinə yetir. Əks halda əgər ikinci qiymət doğrudursa, onda ikinci əmrlər blokunu yerinə yetir.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_4 = "Əgər birinci qiymət doğrudursa, onda birinci əmrlər blokunu yerinə yetir. Əks halda əgər ikinci qiymət doğrudursa, onda ikinci əmrlər blokunu yerinə yetir. Əgər qiymətlərdən heç biri doğru deyilsə, onda axırıncı əmrlər blokunu yerinə yetir.";
Blockly.Msg.CONTROLS_REPEAT_HELPURL = "https://en.wikipedia.org/wiki/For_loop"; // untranslated
Blockly.Msg.CONTROLS_REPEAT_INPUT_DO = "icra et";
Blockly.Msg.CONTROLS_REPEAT_TITLE = "%1 dəfə təkrar et";
Blockly.Msg.CONTROLS_REPEAT_TITLE_REPEAT = "təkrar et";
Blockly.Msg.CONTROLS_REPEAT_TITLE_TIMES = "dəfə";
Blockly.Msg.CONTROLS_REPEAT_TOOLTIP = "Bəzi əmrləri bir neçə dəfə yerinə yetir.";
Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL = "http://code.google.com/p/blockly/wiki/Repeat";
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = "təkrar et, ta ki";
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE = "təkrar et, hələ ki";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = "Hələ ki, qiymət \"yalan\"dır, bəzi əmrləri yerinə yetir.";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = "Hələ ki, qiymət \"doğru\"dur, bəzi əmrləri yerinə yetir.";
Blockly.Msg.DELETE_BLOCK = "Bloku sil";
Blockly.Msg.DELETE_X_BLOCKS = "%1 bloku sil";
Blockly.Msg.DISABLE_BLOCK = "Bloku söndür";
Blockly.Msg.DUPLICATE_BLOCK = "Dublikat";
Blockly.Msg.ENABLE_BLOCK = "Bloku aktivləşdir";
Blockly.Msg.EXPAND_ALL = "Blokları aç";
Blockly.Msg.EXPAND_BLOCK = "Bloku aç";
Blockly.Msg.EXTERNAL_INPUTS = "Xarici girişlər";
Blockly.Msg.HELP = "Kömək";
Blockly.Msg.INLINE_INPUTS = "Sətiriçi girişlər";
Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL = "https://en.wikipedia.org/wiki/Linked_list#Empty_lists"; // untranslated
Blockly.Msg.LISTS_CREATE_EMPTY_TITLE = "boş siyahı düzəlt";
Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP = "Heç bir verilən qeyd olunmamış, uzunluğu 0 olan bir siyahı verir";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = "siyahı";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP = "Bu siyahı blokunu yenidən konfigurasiya etmək üçün bölmələri əlavə edin, silin və ya yerlərini dəyişin.";
Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH = "bunlardan siyahı düzəlt";
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP = "Siyahıya element əlavə edin.";
Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP = "İstənilən ölçülü siyahı yaradın.";
Blockly.Msg.LISTS_GET_INDEX_FIRST = "birinci";
Blockly.Msg.LISTS_GET_INDEX_FROM_END = "axırdan # nömrəli";
Blockly.Msg.LISTS_GET_INDEX_FROM_START = "#";
Blockly.Msg.LISTS_GET_INDEX_GET = "götür";
Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE = "götür və sil";
Blockly.Msg.LISTS_GET_INDEX_LAST = "axırıncı";
Blockly.Msg.LISTS_GET_INDEX_RANDOM = "təsadüfi";
Blockly.Msg.LISTS_GET_INDEX_REMOVE = "yığışdır";
Blockly.Msg.LISTS_GET_INDEX_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST = "Siyahının ilk elementini qaytarır.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_END = "Siyahıdan təyin olunmuş indeksli elementi qaytarır. #1 son elementdir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_START = "Siyahıdan təyin olunmuş indeksli elementi qaytarır. #1 ilk elementdir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST = "Siyahının son elementini qaytarır.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = "Siyahıdan hər hansı təsadüfi elementi qaytarır.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = "Siyahıdan ilk elementi silir və qaytarır.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_END = "Siyahıdan təyin olunmuş indeksli elementi silir və qaytarır. #1 son elementdir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_START = "Siyahıdan təyin olunmuş indeksli elementi silir və qaytarır. #1 ilk elementdir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = "Siyahıdan son elementi silir və qaytarır.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = "Siyahıdan təsadufi elementi silir və qaytarır.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = "Siyahıdan ilk elementi silir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_END = "Siyahıdan təyin olunmuş indeksli elementi silir. #1 son elementdir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_START = "Siyahıdan təyin olunmuş indeksli elementi silir. #1 ilk elementdir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = "Siyahıdan son elementi silir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = "Siyahıdan təsadüfi bir elementi silir.";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END = "sondan # nömrəliyə";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START = "# nömrəliyə";
Blockly.Msg.LISTS_GET_SUBLIST_END_LAST = "Sonuncuya";
Blockly.Msg.LISTS_GET_SUBLIST_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#Getting_a_sublist";
Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST = "Birincidən alt-siyahını alın";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END = "# sonuncudan alt-siyahını alın";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START = "# - dən alt-siyahını alın";
Blockly.Msg.LISTS_GET_SUBLIST_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP = "Siyahının təyin olunmuş hissəsinin surətini yaradın.";
Blockly.Msg.LISTS_INDEX_OF_FIRST = "Element ilə ilk rastlaşma indeksini müəyyən edin";
Blockly.Msg.LISTS_INDEX_OF_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#Getting_Items_from_a_List";
Blockly.Msg.LISTS_INDEX_OF_LAST = "Element ilə son rastlaşma indeksini müəyyən edin";
Blockly.Msg.LISTS_INDEX_OF_TOOLTIP = "Siyahıda element ilə ilk/son rastlaşma indeksini qaytarır. Əgər tekst siyahıda tapılmazsa, 0 qaytarılır.";
Blockly.Msg.LISTS_INLIST = "siyahıda";
Blockly.Msg.LISTS_IS_EMPTY_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#is_empty";
Blockly.Msg.LISTS_IS_EMPTY_TITLE = "%1 boşdur";
Blockly.Msg.LISTS_LENGTH_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#length_of";
Blockly.Msg.LISTS_LENGTH_TITLE = "%1 siyahısının uzunluğu";
Blockly.Msg.LISTS_LENGTH_TOOLTIP = "Siyahının uzunluğunu verir.";
Blockly.Msg.LISTS_REPEAT_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#create_list_with";
Blockly.Msg.LISTS_REPEAT_TITLE = "%1 elementinin %2 dəfə təkrarlandığı siyahı düzəlt";
Blockly.Msg.LISTS_REPEAT_TOOLTIP = "Təyin olunmuş elementin/qiymətin təyin olunmuş sayda təkrarlandığı siyahını yaradır.";
Blockly.Msg.LISTS_SET_INDEX_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#in_list_..._set";
Blockly.Msg.LISTS_SET_INDEX_INPUT_TO = "Kimi";
Blockly.Msg.LISTS_SET_INDEX_INSERT = "daxil et";
Blockly.Msg.LISTS_SET_INDEX_SET = "təyin et";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST = "Elementi siyahının əvvəlinə daxil edir.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_END = "Elementi siyahıda göstərilən yerə daxil edir. #1 axırıncı elementdir.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_START = "Elementi siyahıda göstərilən yerə daxil edir. #1 birinci elementdir.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST = "Elementi siyahının sonuna artırır.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM = "Elementi siyahıda təsadüfi seçilmiş bir yerə atır.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST = "Siyahıda birinci elementi təyin edir.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_END = "Siyahının göstərilən yerdəki elementini təyin edir. #1 axırıncı elementdir.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_START = "Siyahının göstərilən yerdəki elementini təyin edir. #1 birinci elementdir.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST = "Siyahının sonuncu elementini təyin edir.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM = "Siyahının təsadüfi seçilmiş bir elementini təyin edir.";
Blockly.Msg.LISTS_TOOLTIP = "Siyahı boşdursa \"doğru\" cavabını qaytarır.";
Blockly.Msg.LOGIC_BOOLEAN_FALSE = "yalan";
Blockly.Msg.LOGIC_BOOLEAN_HELPURL = "http://code.google.com/p/blockly/wiki/True_False";
Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP = "\"doğru\" və ya \"yalan\" cavanını qaytarır.";
Blockly.Msg.LOGIC_BOOLEAN_TRUE = "doğru";
Blockly.Msg.LOGIC_COMPARE_HELPURL = "https://en.wikipedia.org/wiki/Inequality_(mathematics)"; // untranslated
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ = "Girişlər bir birinə bərabərdirsə \"doğru\" cavabını qaytarır.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT = "Birinci giriş ikincidən böyükdürsə \"doğru\" cavabını qaytarır.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE = "Birinci giriş ikincidən böyük və ya bərarbərdirsə \"doğru\" cavabını qaytarır.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT = "Birinci giriş ikincidən kiçikdirsə \"doğru\" cavabını qaytarır.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE = "Birinci giriş ikincidən kiçik və ya bərarbərdirsə \"doğru\" cavabını qaytarır.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ = "Girişlər bərabər deyillərsə \"doğru\" cavabını qaytarır.";
Blockly.Msg.LOGIC_NEGATE_HELPURL = "http://code.google.com/p/blockly/wiki/Not";
Blockly.Msg.LOGIC_NEGATE_TITLE = "%1 deyil";
Blockly.Msg.LOGIC_NEGATE_TOOLTIP = "Giriş \"yalan\"-dursa \"doğru\" cavabını qaytarır. Giriş \"doğru\"-dursa \"yalan\" cavabını qaytarır.";
Blockly.Msg.LOGIC_NULL = "boş";
Blockly.Msg.LOGIC_NULL_HELPURL = "https://en.wikipedia.org/wiki/Nullable_type"; // untranslated
Blockly.Msg.LOGIC_NULL_TOOLTIP = "Boş cavab qaytarır.";
Blockly.Msg.LOGIC_OPERATION_AND = "və";
Blockly.Msg.LOGIC_OPERATION_HELPURL = "http://code.google.com/p/blockly/wiki/And_Or";
Blockly.Msg.LOGIC_OPERATION_OR = "və ya";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND = "Hər iki giriş \"doğru\"-dursa \"doğru\" cavabını qaytarır.";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR = "Girişlərdən heç olmasa biri \"doğru\"-dursa \"doğru\" cavabını qaytarır.";
Blockly.Msg.LOGIC_TERNARY_CONDITION = "test";
Blockly.Msg.LOGIC_TERNARY_HELPURL = "https://en.wikipedia.org/wiki/%3F:"; // untranslated
Blockly.Msg.LOGIC_TERNARY_IF_FALSE = "əgər yalandırsa";
Blockly.Msg.LOGIC_TERNARY_IF_TRUE = "əgər doğrudursa";
Blockly.Msg.LOGIC_TERNARY_TOOLTIP = "'Yoxla' əmrindəki şərtə nəzər yetirin. Əgər şərt \"doğru\"-dursa \"əgər doğru\", əks halda isə \"əgər yalan\" cavabını qaytarır.";
Blockly.Msg.MATH_ADDITION_SYMBOL = "+";
Blockly.Msg.MATH_ARITHMETIC_HELPURL = "https://az.wikipedia.org/wiki/Hesab";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = "İki ədədin cəmini qaytarır.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = "İki ədədin nisbətini qaytarır.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS = "İki ədədin fərqini qaytarır.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = "İki ədədin hasilini verir.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER = "Birinci ədədin ikinci ədəd dərəcəsindən qüvvətini qaytarır.";
Blockly.Msg.MATH_CHANGE_HELPURL = "https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter"; // untranslated
Blockly.Msg.MATH_CHANGE_INPUT_BY = "buna:";
Blockly.Msg.MATH_CHANGE_TITLE_CHANGE = "dəyiş:";
Blockly.Msg.MATH_CHANGE_TOOLTIP = "'%1' dəyişəninin üzərinə bir ədəd artır.";
Blockly.Msg.MATH_CONSTANT_HELPURL = "https://en.wikipedia.org/wiki/Mathematical_constant"; // untranslated
Blockly.Msg.MATH_CONSTANT_TOOLTIP = "Ümumi sabitlərdən birini qaytarır π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), və ya ∞ (sonsuzluq).";
Blockly.Msg.MATH_CONSTRAIN_HELPURL = "https://en.wikipedia.org/wiki/Clamping_%28graphics%29"; // untranslated
Blockly.Msg.MATH_CONSTRAIN_TITLE = "%1 üçün ən aşağı %2, ən yuxarı %3 olmağı tələb et";
Blockly.Msg.MATH_CONSTRAIN_TOOLTIP = "Bir ədədin verilmiş iki ədəd arasında olmasını tələb edir (sərhədlər də daxil olmaqla).";
Blockly.Msg.MATH_DIVISION_SYMBOL = "÷";
Blockly.Msg.MATH_IS_DIVISIBLE_BY = "bölünür";
Blockly.Msg.MATH_IS_EVEN = "cütdür";
Blockly.Msg.MATH_IS_NEGATIVE = "mənfidir";
Blockly.Msg.MATH_IS_ODD = "təkdir";
Blockly.Msg.MATH_IS_POSITIVE = "müsətdir";
Blockly.Msg.MATH_IS_PRIME = "sadədir";
Blockly.Msg.MATH_IS_TOOLTIP = "Bir ədədin cüt, tək, sadə, tam, müsbət, mənfi olmasını və ya müəyyən bir ədədə bölünməsini yoxlayır. \"Doğru\" və ya \"yalan\" qiymətini qaytarır.";
Blockly.Msg.MATH_IS_WHOLE = "tamdır";
Blockly.Msg.MATH_MODULO_HELPURL = "https://en.wikipedia.org/wiki/Modulo_operation"; // untranslated
Blockly.Msg.MATH_MODULO_TITLE = "%1 ÷ %2 bölməsinin qalığı";
Blockly.Msg.MATH_MODULO_TOOLTIP = "İki ədədin nisbətindən alınan qalığı qaytarır.";
Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = "×";
Blockly.Msg.MATH_NUMBER_HELPURL = "https://en.wikipedia.org/wiki/Number"; // untranslated
Blockly.Msg.MATH_NUMBER_TOOLTIP = "Ədəd.";
Blockly.Msg.MATH_ONLIST_HELPURL = ""; // untranslated
Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE = "siyahının ədədi ortası";
Blockly.Msg.MATH_ONLIST_OPERATOR_MAX = "siyahının maksimumu";
Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN = "siyahının medianı";
Blockly.Msg.MATH_ONLIST_OPERATOR_MIN = "siyahının minimumu";
Blockly.Msg.MATH_ONLIST_OPERATOR_MODE = "Siyahı modları( Ən çox rastlaşılan elementləri)";
Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM = "siyahıdan təsadüfi seçilmiş bir element";
Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV = "Siyahının standart deviasiyası";
Blockly.Msg.MATH_ONLIST_OPERATOR_SUM = "Siyahının cəmi";
Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE = "Siyahıdaki ədədlərin ədədi ortasını qaytarır.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX = "Siyahıdaki ən böyük elementi qaytarır.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN = "Siyahının median elementini qaytarır.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN = "Siyahıdaki ən kiçik ədədi qaytarır.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE = "Siyahıdaki ən çox rastlanan element(lər)dən ibarət siyahı qaytarır.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM = "Siyahıdan təsadüfi bir element qaytarır.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV = "Siyahının standart deviasiyasını qaytarır.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM = "Siyahıdakı bütün ədədlərin cəmini qaytarır.";
Blockly.Msg.MATH_POWER_SYMBOL = "^";
Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation"; // untranslated
Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM = "təsadüfi kəsr";
Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP = "0.0 (daxil olmaqla) və 1.0 (daxil olmamaqla) ədədlərinin arasından təsadüfi bir kəsr ədəd qaytarır.";
Blockly.Msg.MATH_RANDOM_INT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation"; // untranslated
Blockly.Msg.MATH_RANDOM_INT_TITLE = "%1 ilə %2 arasından təsadüfi tam ədəd";
Blockly.Msg.MATH_RANDOM_INT_TOOLTIP = "Verilmiş iki ədəd arasından (ədədrlər də daxil olmaqla) təsadüfi bir tam ədəd qaytarır.";
Blockly.Msg.MATH_ROUND_HELPURL = "https://en.wikipedia.org/wiki/Rounding"; // untranslated
Blockly.Msg.MATH_ROUND_OPERATOR_ROUND = "yuvarlaqlaşdır";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN = "aşağı yuvarlaqlaşdır";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP = "yuxarı yuvarlaqlaşdır";
Blockly.Msg.MATH_ROUND_TOOLTIP = "Ədədi aşağı və ya yuxari yuvarlaqşdır.";
Blockly.Msg.MATH_SINGLE_HELPURL = "https://en.wikipedia.org/wiki/Square_root"; // untranslated
Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE = "modul";
Blockly.Msg.MATH_SINGLE_OP_ROOT = "kvadrat kök";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS = "Ədədin modulunu qaytarır.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP = "e sabitinin verilmiş ədədə qüvvətini qaytarır.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LN = "Ədədin natural loqarifmini tapır.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10 = "Ədədin 10-cu dərəcədən loqarifmini tapır.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG = "Ədədin əksini qaytarır.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10 = "10-un verilmiş ədədə qüvvətini qaytarır.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT = "Ədədin kvadrat kökünü qaytarır.";
Blockly.Msg.MATH_SUBTRACTION_SYMBOL = "-";
Blockly.Msg.MATH_TRIG_ACOS = "arccos";
Blockly.Msg.MATH_TRIG_ASIN = "arcsin";
Blockly.Msg.MATH_TRIG_ATAN = "arctan";
Blockly.Msg.MATH_TRIG_COS = "cos";
Blockly.Msg.MATH_TRIG_HELPURL = "https://en.wikipedia.org/wiki/Trigonometric_functions"; // untranslated
Blockly.Msg.MATH_TRIG_SIN = "sin";
Blockly.Msg.MATH_TRIG_TAN = "tg";
Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS = "Ədədin arccosinusunu qaytarır.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN = "Ədədin arcsinusunu qaytarır.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN = "Ədədin arctanqensini qaytarır.";
Blockly.Msg.MATH_TRIG_TOOLTIP_COS = "Dərəcənin kosinusunu qaytarır (radianın yox).";
Blockly.Msg.MATH_TRIG_TOOLTIP_SIN = "Dərəcənin sinusunu qaytar (radianın yox).";
Blockly.Msg.MATH_TRIG_TOOLTIP_TAN = "Dərəcənin tangensini qaytar (radianın yox).";
Blockly.Msg.NEW_VARIABLE = "Yeni dəyişən...";
Blockly.Msg.NEW_VARIABLE_TITLE = "Yeni dəyişənin adı:";
Blockly.Msg.ORDINAL_NUMBER_SUFFIX = ""; // untranslated
Blockly.Msg.PROCEDURES_BEFORE_PARAMS = "ilə:";
Blockly.Msg.PROCEDURES_CALLNORETURN_CALL = ""; // untranslated
Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP = "Yaradılmış '%1' funksiyasını çalışdır.";
Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP = "Yaradılmış '%1' funksiyasını çalışdır və nəticəni istifadə et.";
Blockly.Msg.PROCEDURES_CREATE_DO = "'%1' yarat";
Blockly.Msg.PROCEDURES_DEFNORETURN_DO = ""; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE = "hansısa əməliyyat";
Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE = "icra et:";
Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP = "Nəticəsi olmayan funksiya yaradır.";
Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_DEFRETURN_RETURN = "qaytar";
Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP = "Nəticəsi olan funksiya yaradır.";
Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING = "Xəbərdarlıq: Bu funksiyanın təkrar olunmuş parametrləri var.";
Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF = "Funksiyanın təyinatını vurğula";
Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP = "Əgər bir dəyər \"doğru\"-dursa onda ikinci dəyəri qaytar.";
Blockly.Msg.PROCEDURES_IFRETURN_WARNING = "Xəbərdarlıq: Bu blok ancaq bir funksiyanın təyinatı daxilində işlədilə bilər.";
Blockly.Msg.PROCEDURES_MUTATORARG_TITLE = "Giriş adı:";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE = "girişlər";
Blockly.Msg.REMOVE_COMMENT = "Şərhi sil";
Blockly.Msg.RENAME_VARIABLE = "Dəyişənin adını dəyiş...";
Blockly.Msg.RENAME_VARIABLE_TITLE = "Bütün '%1' dəyişənlərinin adını buna dəyiş:";
Blockly.Msg.TEXT_APPEND_APPENDTEXT = "bu mətni əlavə et:";
Blockly.Msg.TEXT_APPEND_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_modification";
Blockly.Msg.TEXT_APPEND_TO = "bu mətnin sonuna:";
Blockly.Msg.TEXT_APPEND_TOOLTIP = "'%1' dəyişəninin sonuna nəsə əlavə et.";
Blockly.Msg.TEXT_CHANGECASE_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Adjusting_text_case";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE = "kiçik hərflərlə";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE = "Baş Hərflərlə";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE = "BÖYÜK HƏRFLƏRLƏ";
Blockly.Msg.TEXT_CHANGECASE_TOOLTIP = "Mətndə hərflərin böyük-kiçikliyini dəyiş.";
Blockly.Msg.TEXT_CHARAT_FIRST = "birinci hərfi götür";
Blockly.Msg.TEXT_CHARAT_FROM_END = "axırdan bu nömrəli hərfi götür";
Blockly.Msg.TEXT_CHARAT_FROM_START = "bu nömrəli hərfi götür";
Blockly.Msg.TEXT_CHARAT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Extracting_text";
Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT = "növbəti mətndə";
Blockly.Msg.TEXT_CHARAT_LAST = "axırıncı hərfi götür";
Blockly.Msg.TEXT_CHARAT_RANDOM = "təsadüfi hərf götür";
Blockly.Msg.TEXT_CHARAT_TAIL = ""; // untranslated
Blockly.Msg.TEXT_CHARAT_TOOLTIP = "Göstərilən mövqedəki hərfi qaytarır.";
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP = "Mətnə bir element əlavə et.";
Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN = "birləşdir";
Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP = "Bu mətn blokunu yenidən konfigurasiya etmək üçün bölmələri əlavə edin, silin və ya yerlərini dəyişin.";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END = "axırdan bu nömrəli hərfə qədər";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START = "bu nömrəli hərfə qədər";
Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST = "son hərfə qədər";
Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL = "http://code.google.com/p/blockly/wiki/Text#Extracting_a_region_of_text";
Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT = "mətndə";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST = "Mətnin surətini ilk hərfdən";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END = "Mətnin surətini sondan bu nömrəli # hərfdən";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START = "Mətnin surətini bu nömrəli hərfdən";
Blockly.Msg.TEXT_GET_SUBSTRING_TAIL = ""; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP = "Mətnin təyin olunmuş hissəsini qaytarır.";
Blockly.Msg.TEXT_INDEXOF_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Finding_text";
Blockly.Msg.TEXT_INDEXOF_INPUT_INTEXT = "mətndə";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST = "Bu mətn ilə ilk rastlaşmanı tap:";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST = "Bu mətn ilə son rastlaşmanı tap:";
Blockly.Msg.TEXT_INDEXOF_TAIL = ""; // untranslated
Blockly.Msg.TEXT_INDEXOF_TOOLTIP = "Birinci mətnin ikinci mətndə ilk/son rastlaşma indeksini qaytarır. Əgər rastlaşma baş verməzsə, 0 qaytarır.";
Blockly.Msg.TEXT_ISEMPTY_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Checking_for_empty_text";
Blockly.Msg.TEXT_ISEMPTY_TITLE = "%1 boşdur";
Blockly.Msg.TEXT_ISEMPTY_TOOLTIP = "Verilmiş mətn boşdursa, doğru qiymətini qaytarır.";
Blockly.Msg.TEXT_JOIN_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_creation";
Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH = "Verilmişlərlə mətn yarat";
Blockly.Msg.TEXT_JOIN_TOOLTIP = "İxtiyari sayda elementlərinin birləşməsi ilə mətn parçası yarat.";
Blockly.Msg.TEXT_LENGTH_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_modification";
Blockly.Msg.TEXT_LENGTH_TITLE = "%1 - ın uzunluğu";
Blockly.Msg.TEXT_LENGTH_TOOLTIP = "Verilmiş mətndəki hərflərin(sözlər arası boşluqlar sayılmaqla) sayını qaytarır.";
Blockly.Msg.TEXT_PRINT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Printing_text";
Blockly.Msg.TEXT_PRINT_TITLE = "%1 - i çap elə";
Blockly.Msg.TEXT_PRINT_TOOLTIP = "Təyin olunmuş mətn, ədəd və ya hər hansı bir başqa elementi çap elə.";
Blockly.Msg.TEXT_PROMPT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Getting_input_from_the_user";
Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER = "İstifadəçiyə ədəd daxil etməsi üçün sorğu/tələb göndərin.";
Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT = "İstifadəçiyə mətn daxil etməsi üçün sorğu/tələb göndərin.";
Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER = "İstifadəçiyə ədəd daxil etməsi üçün sorğunu/tələbi ismarıc kimi göndərin";
Blockly.Msg.TEXT_PROMPT_TYPE_TEXT = "İstifadəçiyə mətn daxil etməsi üçün sorğunu/tələbi ismarıc ilə göndərin";
Blockly.Msg.TEXT_TEXT_HELPURL = "https://en.wikipedia.org/wiki/String_(computer_science)"; // untranslated
Blockly.Msg.TEXT_TEXT_TOOLTIP = "Mətndəki hərf, söz və ya sətir.";
Blockly.Msg.TEXT_TRIM_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Trimming_%28removing%29_spaces";
Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH = "Boşluqları hər iki tərəfdən pozun";
Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT = "Boşluqlari yalnız sol tərəfdən pozun";
Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT = "Boşluqları yalnız sağ tərəfdən pozun";
Blockly.Msg.TEXT_TRIM_TOOLTIP = "Mətnin hər iki və ya yalnız bir tərəfdən olan boşluqları pozulmuş surətini qaytarın.";
Blockly.Msg.VARIABLES_DEFAULT_NAME = "element";
Blockly.Msg.VARIABLES_GET_CREATE_SET = "'%1 - i təyin et' - i yarat";
Blockly.Msg.VARIABLES_GET_HELPURL = "http://code.google.com/p/blockly/wiki/Variables#Get";
Blockly.Msg.VARIABLES_GET_TAIL = ""; // untranslated
Blockly.Msg.VARIABLES_GET_TITLE = ""; // untranslated
Blockly.Msg.VARIABLES_GET_TOOLTIP = "Bu dəyişənin qiymətini qaytarır.";
Blockly.Msg.VARIABLES_SET_CREATE_GET = "'%1 - i götür' - ü yarat";
Blockly.Msg.VARIABLES_SET_HELPURL = "http://code.google.com/p/blockly/wiki/Variables#Set";
Blockly.Msg.VARIABLES_SET_TAIL = "- i bu qiymət ilə təyin et:";
Blockly.Msg.VARIABLES_SET_TITLE = "set"; // untranslated
Blockly.Msg.VARIABLES_SET_TOOLTIP = "Bu dəyişəni daxil edilmiş qiymətə bərabər edir.";
Blockly.Msg.PROCEDURES_DEFRETURN_TITLE = Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE;
Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE = Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE;
Blockly.Msg.VARIABLES_SET_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.MATH_CHANGE_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.VARIABLES_GET_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.PROCEDURES_DEFRETURN_DO = Blockly.Msg.PROCEDURES_DEFNORETURN_DO;
Blockly.Msg.LISTS_GET_INDEX_HELPURL = Blockly.Msg.LISTS_INDEX_OF_HELPURL;
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.CONTROLS_IF_MSG_THEN = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.PROCEDURES_CALLRETURN_CALL = Blockly.Msg.PROCEDURES_CALLNORETURN_CALL;
Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.CONTROLS_FOR_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_FOREACH_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_IF_TITLE_IF = Blockly.Msg.CONTROLS_IF_MSG_IF;
Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF = Blockly.Msg.CONTROLS_IF_MSG_ELSEIF;
Blockly.Msg.TEXT_APPEND_VARIABLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE = Blockly.Msg.CONTROLS_IF_MSG_ELSE; | drk123/buildafaq | third_party/msg/js/az.js | JavaScript | apache-2.0 | 31,031 |
// +build dfssh
package dockerfile2llb
import (
"github.com/moby/buildkit/client/llb"
"github.com/moby/buildkit/frontend/dockerfile/instructions"
"github.com/pkg/errors"
)
func dispatchSSH(m *instructions.Mount) (llb.RunOption, error) {
if m.Source != "" {
return nil, errors.Errorf("ssh does not support source")
}
opts := []llb.SSHOption{llb.SSHID(m.CacheID)}
if m.Target != "" {
// TODO(AkihiroSuda): support specifying permission bits
opts = append(opts, llb.SSHSocketTarget(m.Target))
}
if !m.Required {
opts = append(opts, llb.SSHOptional)
}
return llb.AddSSHSocket(opts...), nil
}
| laijs/moby | vendor/github.com/moby/buildkit/frontend/dockerfile/dockerfile2llb/convert_ssh.go | GO | apache-2.0 | 613 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.connect.file;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.common.config.ConfigDef.Importance;
import org.apache.kafka.common.config.ConfigDef.Type;
import org.apache.kafka.common.utils.AppInfoParser;
import org.apache.kafka.connect.connector.Task;
import org.apache.kafka.connect.sink.SinkConnector;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Very simple connector that works with the console. This connector supports both source and
* sink modes via its 'mode' setting.
*/
public class FileStreamSinkConnector extends SinkConnector {
public static final String FILE_CONFIG = "file";
private static final ConfigDef CONFIG_DEF = new ConfigDef()
.define(FILE_CONFIG, Type.STRING, Importance.HIGH, "Destination filename.");
private String filename;
@Override
public String version() {
return AppInfoParser.getVersion();
}
@Override
public void start(Map<String, String> props) {
filename = props.get(FILE_CONFIG);
}
@Override
public Class<? extends Task> taskClass() {
return FileStreamSinkTask.class;
}
@Override
public List<Map<String, String>> taskConfigs(int maxTasks) {
ArrayList<Map<String, String>> configs = new ArrayList<>();
for (int i = 0; i < maxTasks; i++) {
Map<String, String> config = new HashMap<>();
if (filename != null)
config.put(FILE_CONFIG, filename);
configs.add(config);
}
return configs;
}
@Override
public void stop() {
// Nothing to do since FileStreamSinkConnector has no background monitoring.
}
@Override
public ConfigDef config() {
return CONFIG_DEF;
}
}
| wangcy6/storm_app | frame/kafka-0.11.0/kafka-0.11.0.1-src/connect/file/src/main/java/org/apache/kafka/connect/file/FileStreamSinkConnector.java | Java | apache-2.0 | 2,629 |
package org.python.util.install.driver;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import org.python.util.install.ChildProcess;
import org.python.util.install.FileHelper;
public class NormalVerifier implements Verifier {
protected static final String AUTOTEST_PY = "autotest.py";
private static final String BIN = "bin";
private static final String JYTHON_UP = "jython up and running!";
private static final String JYTHON = "jython";
private static final String VERIFYING = "verifying";
private File _targetDir;
public void setTargetDir(File targetDir) {
_targetDir = targetDir;
}
public File getTargetDir() {
return _targetDir;
}
public void verify() throws DriverException {
createTestScriptFile(); // create the test .py script
// verify the most simple start of jython works
verifyStart(getSimpleCommand());
}
/**
* Will be overridden in subclass StandaloneVerifier
*
* @return the command array to start jython with
* @throws DriverException
* if there was a problem getting the target directory path
*/
protected String[] getSimpleCommand() throws DriverException {
return new String[] {
Paths.get(BIN).resolve(JYTHON).toString(),
_targetDir.toPath().resolve(AUTOTEST_PY).toString() };
}
/**
* @return The directory where to create the shell script test command in.
*
* @throws DriverException
*/
protected final File getShellScriptTestCommandDir() throws DriverException {
return _targetDir.toPath().resolve(BIN).toFile();
}
/**
* Internal method verifying a jython-starting command by capturing the output
*
* @param command
*
* @throws DriverException
*/
private void verifyStart(String[] command) throws DriverException {
ChildProcess p = new ChildProcess(command);
p.setDebug(true);
p.setCWD(_targetDir.toPath());
System.err.println("Verify start: command=" + Arrays.toString(command) + ", cwd=" + p.getCWD());
int exitValue = p.run();
// if (exitValue != 0) {
// throw new DriverException("start of jython failed\n"
// + "command: " + Arrays.toString(command)
// + "\ncwd: " + p.getCWD()
// + "\nexit value: " + exitValue
// + "\nstdout: " + p.getStdout()
// + "\nstderr: " + p.getStderr());
// }
verifyError(p.getStderr());
verifyOutput(p.getStdout());
}
/**
* Will be overridden in subclass StandaloneVerifier
*
* @return <code>true</code> if the jython start shell script should be verified (using
* different options)
*/
protected boolean doShellScriptTests() {
return true;
}
private void verifyError(List<String> stderr) throws DriverException {
for (String line : stderr) {
if (isExpectedError(line)) {
feedback(line);
} else {
throw new DriverException(stderr.toString());
}
}
}
private boolean isExpectedError(String line) {
boolean expected = false;
if (line.startsWith("*sys-package-mgr*")) {
expected = true;
}
return expected;
}
private void verifyOutput(List<String> stdout) throws DriverException {
boolean started = false;
for (String line : stdout) {
if (isExpectedOutput(line)) {
feedback(line);
if (line.startsWith(JYTHON_UP)) {
started = true;
}
} else {
throw new DriverException(stdout.toString());
}
}
if (!started) {
throw new DriverException("start of jython failed:\n" + stdout.toString());
}
}
private boolean isExpectedOutput(String line) {
boolean expected = false;
if (line.startsWith("[ChildProcess]") || line.startsWith(VERIFYING)) {
expected = true;
} else if (line.startsWith(JYTHON_UP)) {
expected = true;
}
return expected;
}
private String getTestScript() {
StringBuilder b = new StringBuilder(80);
b.append("import sys\n");
b.append("import os\n");
b.append("print '");
b.append(JYTHON_UP);
b.append("'\n");
return b.toString();
}
private void createTestScriptFile() throws DriverException {
File file = new File(getTargetDir(), AUTOTEST_PY);
try {
FileHelper.write(file, getTestScript());
} catch (IOException ioe) {
throw new DriverException(ioe);
}
}
private void feedback(String line) {
System.out.println("feedback " + line);
}
}
| alvin319/CarnotKE | jyhton/installer/src/java/org/python/util/install/driver/NormalVerifier.java | Java | apache-2.0 | 5,129 |
# Copyright 2013 IBM Corporation
# All Rights Reserved.
#
# 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.
from tempest.api.compute import base
from tempest import test
class HypervisorAdminTestJSON(base.BaseV2ComputeAdminTest):
"""Tests Hypervisors API that require admin privileges"""
@classmethod
def setup_clients(cls):
super(HypervisorAdminTestJSON, cls).setup_clients()
cls.client = cls.os_adm.hypervisor_client
def _list_hypervisors(self):
# List of hypervisors
hypers = self.client.list_hypervisors()['hypervisors']
return hypers
def assertHypervisors(self, hypers):
self.assertTrue(len(hypers) > 0, "No hypervisors found: %s" % hypers)
@test.idempotent_id('7f0ceacd-c64d-4e96-b8ee-d02943142cc5')
def test_get_hypervisor_list(self):
# List of hypervisor and available hypervisors hostname
hypers = self._list_hypervisors()
self.assertHypervisors(hypers)
@test.idempotent_id('1e7fdac2-b672-4ad1-97a4-bad0e3030118')
def test_get_hypervisor_list_details(self):
# Display the details of the all hypervisor
hypers = self.client.list_hypervisors(detail=True)['hypervisors']
self.assertHypervisors(hypers)
@test.idempotent_id('94ff9eae-a183-428e-9cdb-79fde71211cc')
def test_get_hypervisor_show_details(self):
# Display the details of the specified hypervisor
hypers = self._list_hypervisors()
self.assertHypervisors(hypers)
details = self.client.show_hypervisor(hypers[0]['id'])['hypervisor']
self.assertTrue(len(details) > 0)
self.assertEqual(details['hypervisor_hostname'],
hypers[0]['hypervisor_hostname'])
@test.idempotent_id('e81bba3f-6215-4e39-a286-d52d2f906862')
def test_get_hypervisor_show_servers(self):
# Show instances about the specific hypervisors
hypers = self._list_hypervisors()
self.assertHypervisors(hypers)
hostname = hypers[0]['hypervisor_hostname']
hypervisors = (self.client.list_servers_on_hypervisor(hostname)
['hypervisors'])
self.assertTrue(len(hypervisors) > 0)
@test.idempotent_id('797e4f28-b6e0-454d-a548-80cc77c00816')
def test_get_hypervisor_stats(self):
# Verify the stats of the all hypervisor
stats = (self.client.show_hypervisor_statistics()
['hypervisor_statistics'])
self.assertTrue(len(stats) > 0)
@test.idempotent_id('91a50d7d-1c2b-4f24-b55a-a1fe20efca70')
def test_get_hypervisor_uptime(self):
# Verify that GET shows the specified hypervisor uptime
hypers = self._list_hypervisors()
# Ironic will register each baremetal node as a 'hypervisor',
# so the hypervisor list can contain many hypervisors of type
# 'ironic'. If they are ALL ironic, skip this test since ironic
# doesn't support hypervisor uptime. Otherwise, remove them
# from the list of hypervisors to test.
ironic_only = True
hypers_without_ironic = []
for hyper in hypers:
details = (self.client.show_hypervisor(hypers[0]['id'])
['hypervisor'])
if details['hypervisor_type'] != 'ironic':
hypers_without_ironic.append(hyper)
ironic_only = False
if ironic_only:
raise self.skipException(
"Ironic does not support hypervisor uptime")
has_valid_uptime = False
for hyper in hypers_without_ironic:
# because hypervisors might be disabled, this loops looking
# for any good hit.
try:
uptime = (self.client.show_hypervisor_uptime(hyper['id'])
['hypervisor'])
if len(uptime) > 0:
has_valid_uptime = True
break
except Exception:
pass
self.assertTrue(
has_valid_uptime,
"None of the hypervisors had a valid uptime: %s" % hypers)
@test.idempotent_id('d7e1805b-3b14-4a3b-b6fd-50ec6d9f361f')
def test_search_hypervisor(self):
hypers = self._list_hypervisors()
self.assertHypervisors(hypers)
hypers = self.client.search_hypervisor(
hypers[0]['hypervisor_hostname'])['hypervisors']
self.assertHypervisors(hypers)
| zsoltdudas/lis-tempest | tempest/api/compute/admin/test_hypervisor.py | Python | apache-2.0 | 4,953 |
# Deploy a First Micro Stack App
The second hack is meant to get you familiar with the architecture of apps built with the Monkey.Robotics Micro Stack framework.
## Steps
1. Read the [Getting Started with the Micro Stack Framework Overview](../../Getting%20Started/Micro_Stack) to get an idea of how the architecture of the Micro Stack Framework works.
2. Build and Deploy the [ButtonPush](ButtonPush.zip) app. The ButtonPush app illustrates the Reactive architecture by linking the Netduino’s onboard button to the onboard LED, so that when you push the button, the LED lights up. It’s a very simple application but illustrates how powerful the Micro Stack is.
| venkatarajasekhar/Monkey.Robotics | Evolve Hacks/3_DeployMicroStackApp/readme.md | Markdown | apache-2.0 | 671 |
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class LocalRewriter
Public Overrides Function VisitSyncLockStatement(node As BoundSyncLockStatement) As BoundNode
Dim statements = ArrayBuilder(Of BoundStatement).GetInstance
Dim syntaxNode = DirectCast(node.Syntax, SyncLockBlockSyntax)
' rewrite the lock expression.
Dim visitedLockExpression = VisitExpressionNode(node.LockExpression)
Dim objectType = GetSpecialType(SpecialType.System_Object)
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Dim conversionKind = Conversions.ClassifyConversion(visitedLockExpression.Type, objectType, useSiteDiagnostics).Key
_diagnostics.Add(node, useSiteDiagnostics)
' when passing this boundlocal to Monitor.Enter and Monitor.Exit we need to pass a local of type object, because the parameter
' are of type object. We also do not want to have this conversion being shown in the semantic model, which is why we add it
' during rewriting. Because only reference types are allowed for synclock, this is always guaranteed to succeed.
' This also unboxes a type parameter, so that the same object is passed to both methods.
If Not Conversions.IsIdentityConversion(conversionKind) Then
Dim integerOverflow As Boolean
Dim constantResult = Conversions.TryFoldConstantConversion(
visitedLockExpression,
objectType,
integerOverflow)
visitedLockExpression = TransformRewrittenConversion(New BoundConversion(node.LockExpression.Syntax,
visitedLockExpression,
conversionKind,
False,
False,
constantResult,
objectType))
End If
' create a new temp local for the lock object
Dim tempLockObjectLocal As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, objectType, SynthesizedLocalKind.Lock, syntaxNode.SyncLockStatement)
Dim boundLockObjectLocal = New BoundLocal(syntaxNode,
tempLockObjectLocal,
objectType)
Dim instrument As Boolean = Me.Instrument(node)
If instrument Then
' create a sequence point that contains the whole SyncLock statement as the first reachable sequence point
' of the SyncLock statement.
Dim prologue = _instrumenterOpt.CreateSyncLockStatementPrologue(node)
If prologue IsNot Nothing Then
statements.Add(prologue)
End If
End If
' assign the lock expression / object to it to avoid changes to it
Dim tempLockObjectAssignment As BoundStatement = New BoundAssignmentOperator(syntaxNode,
boundLockObjectLocal,
visitedLockExpression,
suppressObjectClone:=True,
type:=objectType).ToStatement
boundLockObjectLocal = boundLockObjectLocal.MakeRValue()
If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then
tempLockObjectAssignment = RegisterUnstructuredExceptionHandlingResumeTarget(syntaxNode, tempLockObjectAssignment, canThrow:=True)
End If
Dim saveState As UnstructuredExceptionHandlingContext = LeaveUnstructuredExceptionHandlingContext(node)
If instrument Then
tempLockObjectAssignment = _instrumenterOpt.InstrumentSyncLockObjectCapture(node, tempLockObjectAssignment)
End If
statements.Add(tempLockObjectAssignment)
' If the type of the lock object is System.Object we need to call the vb runtime helper
' Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType to ensure no value type is
' used. Note that we are checking type on original bound node for LockExpression because rewritten node will
' always have System.Object as its type due to conversion added above.
' If helper not available on this platform (/vbruntime*), don't call this helper and do not report errors.
Dim checkForSyncLockOnValueTypeMethod As MethodSymbol = Nothing
If node.LockExpression.Type.IsObjectType() AndAlso
TryGetWellknownMember(checkForSyncLockOnValueTypeMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType, syntaxNode, isOptional:=True) Then
Dim boundHelperCall = New BoundCall(syntaxNode,
checkForSyncLockOnValueTypeMethod,
Nothing,
Nothing,
ImmutableArray.Create(Of BoundExpression)(boundLockObjectLocal),
Nothing,
checkForSyncLockOnValueTypeMethod.ReturnType,
suppressObjectClone:=True)
Dim boundHelperCallStatement = boundHelperCall.ToStatement
boundHelperCallStatement.SetWasCompilerGenerated() ' used to not create sequence points
statements.Add(boundHelperCallStatement)
End If
Dim locals As ImmutableArray(Of LocalSymbol)
Dim boundLockTakenLocal As BoundLocal = Nothing
Dim tempLockTakenAssignment As BoundStatement = Nothing
Dim tryStatements As ImmutableArray(Of BoundStatement)
Dim boundMonitorEnterCallStatement As BoundStatement = GenerateMonitorEnter(node.LockExpression.Syntax, boundLockObjectLocal, boundLockTakenLocal, tempLockTakenAssignment)
' the new Monitor.Enter call will be inside the try block, the old is outside
If boundLockTakenLocal IsNot Nothing Then
locals = ImmutableArray.Create(Of LocalSymbol)(tempLockObjectLocal, boundLockTakenLocal.LocalSymbol)
statements.Add(tempLockTakenAssignment)
tryStatements = ImmutableArray.Create(Of BoundStatement)(boundMonitorEnterCallStatement,
DirectCast(Visit(node.Body), BoundBlock))
Else
locals = ImmutableArray.Create(tempLockObjectLocal)
statements.Add(boundMonitorEnterCallStatement)
tryStatements = ImmutableArray.Create(Of BoundStatement)(DirectCast(Visit(node.Body), BoundBlock))
End If
' rewrite the SyncLock body
Dim tryBody As BoundBlock = New BoundBlock(syntaxNode,
Nothing,
ImmutableArray(Of LocalSymbol).Empty,
tryStatements)
Dim statementInFinally As BoundStatement = GenerateMonitorExit(syntaxNode, boundLockObjectLocal, boundLockTakenLocal)
Dim finallyBody As BoundBlock = New BoundBlock(syntaxNode,
Nothing,
ImmutableArray(Of LocalSymbol).Empty,
ImmutableArray.Create(Of BoundStatement)(statementInFinally))
If instrument Then
' Add a sequence point to highlight the "End SyncLock" syntax in case the body has thrown an exception
finallyBody = DirectCast(Concat(finallyBody, _instrumenterOpt.CreateSyncLockExitDueToExceptionEpilogue(node)), BoundBlock)
End If
Dim rewrittenSyncLock = RewriteTryStatement(syntaxNode, tryBody, ImmutableArray(Of BoundCatchBlock).Empty, finallyBody, Nothing)
statements.Add(rewrittenSyncLock)
If instrument Then
' Add a sequence point to highlight the "End SyncLock" syntax in case the body has been complete executed and
' exited normally
Dim epilogue = _instrumenterOpt.CreateSyncLockExitNormallyEpilogue(node)
If epilogue IsNot Nothing Then
statements.Add(epilogue)
End If
End If
RestoreUnstructuredExceptionHandlingContext(node, saveState)
Return New BoundBlock(syntaxNode,
Nothing,
locals,
statements.ToImmutableAndFree)
End Function
Private Function GenerateMonitorEnter(
syntaxNode As SyntaxNode,
boundLockObject As BoundExpression,
<Out> ByRef boundLockTakenLocal As BoundLocal,
<Out> ByRef boundLockTakenInitialization As BoundStatement
) As BoundStatement
boundLockTakenLocal = Nothing
boundLockTakenInitialization = Nothing
Dim parameters As ImmutableArray(Of BoundExpression)
' Figure out what Enter method to call from Monitor.
' In case the "new" Monitor.Enter(Object, ByRef Boolean) method is found, use that one,
' otherwise fall back to the Monitor.Enter() method.
Dim enterMethod As MethodSymbol = Nothing
If TryGetWellknownMember(enterMethod, WellKnownMember.System_Threading_Monitor__Enter2, syntaxNode, isOptional:=True) Then
' create local for the lockTaken boolean and initialize it with "False"
Dim tempLockTaken As LocalSymbol
If syntaxNode.Parent.Kind = SyntaxKind.SyncLockStatement Then
tempLockTaken = New SynthesizedLocal(Me._currentMethodOrLambda, enterMethod.Parameters(1).Type, SynthesizedLocalKind.LockTaken, DirectCast(syntaxNode.Parent, SyncLockStatementSyntax))
Else
tempLockTaken = New SynthesizedLocal(Me._currentMethodOrLambda, enterMethod.Parameters(1).Type, SynthesizedLocalKind.LoweringTemp)
End If
Debug.Assert(tempLockTaken.Type.IsBooleanType())
boundLockTakenLocal = New BoundLocal(syntaxNode, tempLockTaken, tempLockTaken.Type)
boundLockTakenInitialization = New BoundAssignmentOperator(syntaxNode,
boundLockTakenLocal,
New BoundLiteral(syntaxNode, ConstantValue.False, boundLockTakenLocal.Type),
suppressObjectClone:=True,
type:=boundLockTakenLocal.Type).ToStatement
boundLockTakenInitialization.SetWasCompilerGenerated() ' used to not create sequence points
parameters = ImmutableArray.Create(Of BoundExpression)(boundLockObject, boundLockTakenLocal)
boundLockTakenLocal = boundLockTakenLocal.MakeRValue()
Else
TryGetWellknownMember(enterMethod, WellKnownMember.System_Threading_Monitor__Enter, syntaxNode)
parameters = ImmutableArray.Create(Of BoundExpression)(boundLockObject)
End If
If enterMethod IsNot Nothing Then
' create a call to void Enter(object)
Dim boundMonitorEnterCall As BoundExpression
boundMonitorEnterCall = New BoundCall(syntaxNode,
enterMethod,
Nothing,
Nothing,
parameters,
Nothing,
enterMethod.ReturnType,
suppressObjectClone:=True)
Dim boundMonitorEnterCallStatement = boundMonitorEnterCall.ToStatement
boundMonitorEnterCallStatement.SetWasCompilerGenerated() ' used to not create sequence points
Return boundMonitorEnterCallStatement
End If
Return New BoundBadExpression(syntaxNode, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, parameters, ErrorTypeSymbol.UnknownResultType, hasErrors:=True).ToStatement()
End Function
Private Function GenerateMonitorExit(
syntaxNode As SyntaxNode,
boundLockObject As BoundExpression,
boundLockTakenLocal As BoundLocal
) As BoundStatement
Dim statementInFinally As BoundStatement
Dim boundMonitorExitCall As BoundExpression
Dim exitMethod As MethodSymbol = Nothing
If TryGetWellknownMember(exitMethod, WellKnownMember.System_Threading_Monitor__Exit, syntaxNode) Then
' create a call to void Monitor.Exit(object)
boundMonitorExitCall = New BoundCall(syntaxNode,
exitMethod,
Nothing,
Nothing,
ImmutableArray.Create(Of BoundExpression)(boundLockObject),
Nothing,
exitMethod.ReturnType,
suppressObjectClone:=True)
Else
boundMonitorExitCall = New BoundBadExpression(syntaxNode, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(boundLockObject), ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
End If
Dim boundMonitorExitCallStatement = boundMonitorExitCall.ToStatement
boundMonitorExitCallStatement.SetWasCompilerGenerated() ' used to not create sequence points
If boundLockTakenLocal IsNot Nothing Then
Debug.Assert(boundLockTakenLocal.Type.IsBooleanType())
' if the "new" enter method is used we need to check the temporary boolean to see if the lock was really taken.
' (maybe there was an exception after try and before the enter call).
Dim boundCondition = New BoundBinaryOperator(syntaxNode,
BinaryOperatorKind.Equals,
boundLockTakenLocal,
New BoundLiteral(syntaxNode, ConstantValue.True, boundLockTakenLocal.Type),
False,
boundLockTakenLocal.Type)
statementInFinally = RewriteIfStatement(syntaxNode, boundCondition, boundMonitorExitCallStatement, Nothing, instrumentationTargetOpt:=Nothing)
Else
statementInFinally = boundMonitorExitCallStatement
End If
Return statementInFinally
End Function
End Class
End Namespace
| yeaicc/roslyn | src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_SyncLock.vb | Visual Basic | apache-2.0 | 16,832 |
/*****************************************************************************
* *
* OpenNI 1.x Alpha *
* Copyright (C) 2012 PrimeSense Ltd. *
* *
* This file is part of OpenNI. *
* *
* 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. *
* *
*****************************************************************************/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace OpenNI
{
public static class Log
{
public static readonly string MASK_ALL = "ALL";
public static void Init()
{
int status = SafeNativeMethods.xnLogInitSystem();
WrapperUtils.ThrowOnError(status);
}
public static void InitFromXmlFile(string xmlFile)
{
int status = SafeNativeMethods.xnLogInitFromXmlFile(xmlFile);
WrapperUtils.ThrowOnError(status);
}
public static void Close()
{
int status = SafeNativeMethods.xnLogClose();
WrapperUtils.ThrowOnError(status);
}
public static void SetMaskState(string maskName, bool on)
{
int status = SafeNativeMethods.xnLogSetMaskState(maskName, on);
WrapperUtils.ThrowOnError(status);
}
public static void SetSeverityFilter(LogSeverity severity)
{
int status = SafeNativeMethods.xnLogSetSeverityFilter(severity);
WrapperUtils.ThrowOnError(status);
}
public static void SetConsoleOutput(bool on)
{
int status = SafeNativeMethods.xnLogSetConsoleOutput(on);
WrapperUtils.ThrowOnError(status);
}
public static void SetFileOutput(bool on)
{
int status = SafeNativeMethods.xnLogSetFileOutput(on);
WrapperUtils.ThrowOnError(status);
}
public static void SetOutputFolder(string folder)
{
int status = SafeNativeMethods.xnLogSetOutputFolder(folder);
WrapperUtils.ThrowOnError(status);
}
}
} | rxl194/OpenNI | Wrappers/OpenNI.net/Log.cs | C# | apache-2.0 | 3,080 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.