code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
/**
* Copyright 2009-2010 Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Common styles
*/
body {
background-color: white;
color: black;
font-size: 14pt;
}
body:hover {
color: white;
}
navigationBar {
background-color: #778CA8;
}
toolbar {
background-color: #6D84A2;
}
searchbar {
background-color: #C8C8C8;
}
/**
* Tables
*/
table {
background-color: none;
}
groupedTable {
background-color: groupTableViewBackgroundColor;
}
searchTable {
background-color: #EBEBEB;
}
searchTableSeparator {
background-color: #D9D9D9;
}
/**
* Table Items
*/
.tableItemLink {
color: #576B95;
}
.tableItemTimestamp {
color: #2470D8;
}
/* More button, generally used at the bottom of a table. */
.moreButton {
color: #2470D8;
}
/**
* Table Headers
*/
.tableHeader {
color: #576B95;
text-shadow: 0px 1px 0px transparent;
}
/**
* Photo Captions
*/
.photoCaption {
color: white;
text-shadow: 0px 1px 0px rgba(0, 0, 0, 0.9);
}
/**
* Drag Refresh Headers
*/
.dragRefreshHeaderLastUpdated {
font-size: 12pt;
}
.dragRefreshHeaderStatusFont {
font-size: 13pt;
font-weight: bold;
}
.dragRefreshHeader {
background-color: #E2E7ED;
color: #576C89;
text-shadow: 0px 1px 0px #E6E6E6;
}
| brunow/TTPostControllerExample | three20/src/extThree20CSSStyle/Resources/extThree20CSSStyle.bundle/stylesheets/default.css | CSS | mit | 1,766 |
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\ApiBundle\Command;
/** @experimental */
interface ChannelCodeAwareInterface extends CommandAwareDataTransformerInterface
{
public function getChannelCode(): ?string;
public function setChannelCode(?string $channelCode): void;
}
| loic425/Sylius | src/Sylius/Bundle/ApiBundle/Command/ChannelCodeAwareInterface.php | PHP | mit | 508 |
/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved.
*
* The information contained herein is property of Nordic Semiconductor ASA.
* Terms and conditions of usage are described in detail in NORDIC
* SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT.
*
* Licensees are granted free, non-transferable use of the information. NO
* WARRANTY of ANY KIND is provided. This heading must NOT be removed from
* the file.
*
*/
#ifndef BLE_CONN_H__
#define BLE_CONN_H__
/**
* @addtogroup ser_codecs Serialization codecs
* @ingroup ble_sdk_lib_serialization
*/
/**
* @addtogroup ser_conn_s120_codecs Connectivity s120 codecs
* @ingroup ser_codecs
*/
/**@file
*
* @defgroup ble_conn Connectivity command request decoders and command response encoders
* @{
* @ingroup ser_conn_s120_codecs
*
* @brief Connectivity command request decoders and command response encoders.
*/
#include "ble.h"
/**@brief Decodes @ref sd_ble_tx_buffer_count_get command request.
*
* @sa @ref nrf51_tx_buffer_count_get_encoding for packet format,
* @ref ble_tx_buffer_count_get_rsp_enc for response encoding.
*
* @param[in] p_buf Pointer to beginning of command request packet.
* @param[in] packet_len Length (in bytes) of response packet.
* @param[out] pp_count Pointer to pointer to location for count.
*
* @retval NRF_SUCCESS Decoding success.
* @retval NRF_ERROR_NULL Decoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Decoding failure. Incorrect buffer length.
* @retval NRF_ERROR_INVALID_PARAM Decoding failure. Invalid operation type.
*/
uint32_t ble_tx_buffer_count_get_req_dec(uint8_t const * const p_buf,
uint16_t packet_len,
uint8_t * * const pp_count);
/**@brief Encodes @ref sd_ble_tx_buffer_count_get command response.
*
* @sa @ref nrf51_tx_buffer_count_get_encoding for packet format.
* @ref ble_tx_buffer_count_get_req_dec for request decoding.
*
* @param[in] return_code Return code indicating if command was successful or not.
* @param[out] p_buf Pointer to buffer where encoded data command response will be
* returned.
* @param[in,out] p_buf_len \c in: size of \p p_buf buffer.
* \c out: Length of encoded command response packet.
* @param[in] p_count Pointer to count value.
*
* @retval NRF_SUCCESS Encoding success.
* @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Encoding failure. Incorrect buffer length.
*/
uint32_t ble_tx_buffer_count_get_rsp_enc(uint32_t return_code,
uint8_t * const p_buf,
uint32_t * const p_buf_len,
uint8_t const * const p_count);
/**@brief Event encoding dispatcher.
*
* The event encoding dispatcher will route the event packet to the correct encoder which in turn
* encodes the contents of the event and updates the \p p_buf buffer.
*
* @param[in] p_event Pointer to the \ref ble_evt_t buffer that shall be encoded.
* @param[in] event_len Size (in bytes) of \p p_event buffer.
* @param[out] p_buf Pointer to the beginning of a buffer for encoded event packet.
* @param[in,out] p_buf_len \c in: Size (in bytes) of \p p_buf buffer.
* \c out: Length of encoded contents in \p p_buf.
*
* @retval NRF_SUCCESS Encoding success.
* @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Encoding failure. Incorrect buffer length.
* @retval NRF_ERROR_NOT_SUPPORTED Event encoder is not implemented.
*/
uint32_t ble_event_enc(ble_evt_t const * const p_event,
uint32_t event_len,
uint8_t * const p_buf,
uint32_t * const p_buf_len);
/**@brief Decodes @ref sd_ble_version_get command request.
*
* @sa @ref nrf51_version_get_encoding for packet format,
* @ref ble_version_get_rsp_enc for response encoding.
*
* @param[in] p_buf Pointer to beginning of command request packet.
* @param[in] packet_len Length (in bytes) of response packet.
* @param[out] pp_version Pointer to pointer to @ref ble_version_t address.
*
* @retval NRF_SUCCESS Decoding success.
* @retval NRF_ERROR_NULL Decoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Decoding failure. Incorrect buffer length.
* @retval NRF_ERROR_INVALID_PARAM Decoding failure. Invalid operation type.
*/
uint32_t ble_version_get_req_dec(uint8_t const * const p_buf,
uint16_t packet_len,
ble_version_t * * const pp_version);
/**@brief Encodes @ref sd_ble_version_get command response.
*
* @sa @ref nrf51_version_get_encoding for packet format.
* @ref ble_version_get_req_dec for request decoding.
*
* @param[in] return_code Return code indicating if command was successful or not.
* @param[out] p_buf Pointer to buffer where encoded data command response will be
* returned.
* @param[in,out] p_buf_len \c in: size of \p p_buf buffer.
* \c out: Length of encoded command response packet.
* @param[in] p_version Pointer to @ref ble_version_t address.
*
* @retval NRF_SUCCESS Encoding success.
* @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Encoding failure. Incorrect buffer length.
*/
uint32_t ble_version_get_rsp_enc(uint32_t return_code,
uint8_t * const p_buf,
uint32_t * const p_buf_len,
ble_version_t const * const p_version);
/**@brief Decodes @ref sd_ble_opt_get command request.
*
* @sa @ref nrf51_opt_get_encoding for packet format,
* @ref ble_opt_get_rsp_enc for response encoding.
*
* @param[in] p_buf Pointer to beginning of command request packet.
* @param[in] packet_len Length (in bytes) of response packet.
* @param[out] p_opt_id Pointer to pointer to @ref ble_version_t address.
* @param[out] pp_opt Pointer to pointer to @ref ble_opt_t address.
*
* @retval NRF_SUCCESS Decoding success.
* @retval NRF_ERROR_NULL Decoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Decoding failure. Incorrect buffer length.
* @retval NRF_ERROR_INVALID_PARAM Decoding failure. Invalid operation type.
*/
uint32_t ble_opt_get_req_dec(uint8_t const * const p_buf,
uint16_t packet_len,
uint32_t * const p_opt_id,
ble_opt_t **const pp_opt );
/**@brief Encodes @ref sd_ble_opt_get command response.
*
* @sa @ref nrf51_opt_get_encoding for packet format.
* @ref ble_opt_get_req_dec for request decoding.
*
* @param[in] return_code Return code indicating if command was successful or not.
* @param[out] p_buf Pointer to buffer where encoded data command response will be
* returned.
* @param[in,out] p_buf_len \c in: size of \p p_buf buffer.
* \c out: Length of encoded command response packet.
* @param[in] opt_id identifies type of ble_opt_t union
* @param[in] p_opt Pointer to @ref ble_opt_t union.
*
* @retval NRF_SUCCESS Encoding success.
* @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Encoding failure. Incorrect buffer length.
*/
uint32_t ble_opt_get_rsp_enc(uint32_t return_code,
uint8_t * const p_buf,
uint32_t * const p_buf_len,
uint32_t opt_id,
ble_opt_t const * const p_opt);
/**@brief Decodes @ref sd_ble_opt_set command request.
*
* @sa @ref nrf51_opt_set_encoding for packet format,
* @ref ble_opt_set_rsp_enc for response encoding.
*
* @param[in] p_buf Pointer to beginning of command request packet.
* @param[in] packet_len Length (in bytes) of response packet.
* @param[out] p_opt_id Pointer to @ref ble_opt_t union type identifier.
* @param[out] pp_opt Pointer to pointer to @ref ble_opt_t union.
*
* @retval NRF_SUCCESS Decoding success.
* @retval NRF_ERROR_NULL Decoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Decoding failure. Incorrect buffer length.
* @retval NRF_ERROR_INVALID_PARAM Decoding failure. Invalid operation type.
*/
uint32_t ble_opt_set_req_dec(uint8_t const * const p_buf,
uint16_t packet_len,
uint32_t * const p_opt_id,
ble_opt_t **const pp_opt );
/**@brief Encodes @ref sd_ble_opt_set command response.
*
* @sa @ref nrf51_opt_set_encoding for packet format.
* @ref ble_opt_set_req_dec for request decoding.
*
* @param[in] return_code Return code indicating if command was successful or not.
* @param[out] p_buf Pointer to buffer where encoded data command response will be
* returned.
* @param[in,out] p_buf_len \c in: size of \p p_buf buffer.
* \c out: Length of encoded command response packet.
*
* @retval NRF_SUCCESS Encoding success.
* @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Encoding failure. Incorrect buffer length.
*/
uint32_t ble_opt_set_rsp_enc(uint32_t return_code,
uint8_t * const p_buf,
uint32_t * const p_buf_len);
/**@brief Decodes @ref sd_ble_uuid_encode command request.
*
* @sa @ref nrf51_uuid_encode_encoding for packet format,
* @ref ble_uuid_encode_rsp_enc for response encoding.
*
* @param[in] p_buf Pointer to beginning of command request packet.
* @param[in] packet_len Length (in bytes) of response packet.
* @param[out] pp_uuid Pointer to pointer to @ref ble_uuid_t structure.
* @param[out] pp_uuid_le_len Pointer to pointer to the length of encoded UUID.
* @param[out] pp_uuid_le Pointer to pointer to buffer where encoded UUID will be stored.
*
* @retval NRF_SUCCESS Decoding success.
* @retval NRF_ERROR_NULL Decoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Decoding failure. Incorrect buffer length.
* @retval NRF_ERROR_INVALID_PARAM Decoding failure. Invalid operation type.
*/
uint32_t ble_uuid_encode_req_dec(uint8_t const * const p_buf,
uint16_t packet_len,
ble_uuid_t * * const pp_uuid,
uint8_t * * const pp_uuid_le_len,
uint8_t * * const pp_uuid_le);
/**@brief Encodes @ref sd_ble_uuid_encode command response.
*
* @sa @ref nrf51_uuid_encode_encoding for packet format.
* @ref ble_uuid_encode_req_dec for request decoding.
*
* @param[in] return_code Return code indicating if command was successful or not.
* @param[out] p_buf Pointer to buffer where encoded data command response will be
* returned.
* @param[in,out] p_buf_len \c in: size of \p p_buf buffer.
* \c out: Length of encoded command response packet.
* @param[in] uuid_le_len Length of the encoded UUID.
* @param[in] p_uuid_le Pointer to the buffer with encoded UUID.
*
* @retval NRF_SUCCESS Encoding success.
* @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Encoding failure. Incorrect buffer length.
*/
uint32_t ble_uuid_encode_rsp_enc(uint32_t return_code,
uint8_t * const p_buf,
uint32_t * const p_buf_len,
uint8_t uuid_le_len,
uint8_t const * const p_uuid_le);
/**@brief Decodes @ref sd_ble_uuid_decode command request.
*
* @sa @ref nrf51_uuid_decode_encoding for packet format,
* @ref ble_uuid_decode_rsp_enc for response encoding.
*
* @param[in] p_buf Pointer to beginning of command request packet.
* @param[in] buf_len Length (in bytes) of response packet.
* @param[out] p_uuid_le_len Pointer to the length of encoded UUID.
* @param[out] pp_uuid_le Pointer to pointer to buffer where encoded UUID will be stored.
* @param[out] pp_uuid Pointer to pointer to @ref ble_uuid_t structure.
* \c It will be set to NULL if p_uuid is not present in the packet.
*
* @retval NRF_SUCCESS Decoding success.
* @retval NRF_ERROR_NULL Decoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Decoding failure. Incorrect buffer length.
*/
uint32_t ble_uuid_decode_req_dec(uint8_t const * const p_buf,
uint32_t const buf_len,
uint8_t * p_uuid_le_len,
uint8_t * * const pp_uuid_le,
ble_uuid_t * * const pp_uuid);
/**@brief Encodes @ref sd_ble_uuid_decode command response.
*
* @sa @ref nrf51_uuid_decode_encoding for packet format.
* @ref ble_uuid_decode_req_dec for request decoding.
*
* @param[in] return_code Return code indicating if command was successful or not.
* @param[out] p_buf Pointer to buffer where encoded data command response will be
* returned.
* @param[in,out] p_buf_len \c in: size of \p p_buf buffer.
* \c out: Length of encoded command response packet.
* @param[in] p_uuid Pointer to the buffer with encoded UUID.
*
* @retval NRF_SUCCESS Encoding success.
* @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Encoding failure. Incorrect buffer length.
*/
uint32_t ble_uuid_decode_rsp_enc(uint32_t return_code,
uint8_t * const p_buf,
uint32_t * const p_buf_len,
ble_uuid_t const * const p_uuid);
/**@brief Decodes @ref sd_ble_uuid_vs_add command request.
*
* @sa @ref nrf51_uuid_vs_add_encoding for packet format,
* @ref ble_uuid_vs_add_rsp_enc for response encoding.
*
* @param[in] p_buf Pointer to beginning of command request packet.
* @param[in] buf_len Length (in bytes) of response packet.
* @param[out] pp_uuid Pointer to pointer to UUID.
* \c It will be set to NULL if p_uuid is not present in the packet.
* @param[out] pp_uuid_type Pointer to pointer to UUID type.
* \c It will be set to NULL if p_uuid_type is not present in the packet.
*
* @retval NRF_SUCCESS Decoding success.
* @retval NRF_ERROR_NULL Decoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Decoding failure. Incorrect buffer length.
*/
uint32_t ble_uuid_vs_add_req_dec(uint8_t const * const p_buf,
uint16_t buf_len,
ble_uuid128_t * * const pp_uuid,
uint8_t * * const pp_uuid_type);
/**@brief Encodes @ref sd_ble_uuid_vs_add command response.
*
* @sa @ref nrf51_uuid_vs_add_encoding for packet format.
* @ref ble_uuid_vs_add_req_dec for request decoding.
*
* @param[in] return_code Return code indicating if command was successful or not.
* @param[out] p_buf Pointer to buffer where encoded data command response will be
* returned.
* @param[in,out] p_buf_len \c in: size of \p p_buf buffer.
* \c out: Length of encoded command response packet.
* @param[in] p_uuid_type Pointer to the UUID type.
*
* @retval NRF_SUCCESS Encoding success.
* @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Encoding failure. Incorrect buffer length.
*/
uint32_t ble_uuid_vs_add_rsp_enc(uint32_t return_code,
uint8_t * const p_buf,
uint32_t * const p_buf_len,
uint8_t const * const p_uuid_type);
/**@brief Decodes @ref sd_ble_enable command request.
*
* @sa @ref nrf51_enable_encoding for packet format,
* @ref ble_enable_rsp_enc for response encoding.
*
* @param[in] p_buf Pointer to beginning of command request packet.
* @param[in] packet_len Length (in bytes) of response packet.
* @param[out] pp_ble_enable_params Pointer to pointer to ble_enable_params_t.
* \c It will be set to NULL if p_ble_enable_params is not present in the packet.
*
* @retval NRF_SUCCESS Decoding success.
* @retval NRF_ERROR_NULL Decoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Decoding failure. Incorrect buffer length.
*/
uint32_t ble_enable_req_dec(uint8_t const * const p_buf,
uint32_t packet_len,
ble_enable_params_t * * const pp_ble_enable_params);
/**@brief Encodes @ref sd_ble_enable command response.
*
* @sa @ref nrf51_enable_encoding for packet format.
* @ref ble_enable_req_dec for request decoding.
*
* @param[in] return_code Return code indicating if command was successful or not.
* @param[out] p_buf Pointer to buffer where encoded data command response will be
* returned.
* @param[in,out] p_buf_len \c in: size of \p p_buf buffer.
* \c out: Length of encoded command response packet.
*
* @retval NRF_SUCCESS Encoding success.
* @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Encoding failure. Incorrect buffer length.
*/
uint32_t ble_enable_rsp_enc(uint32_t return_code,
uint8_t * const p_buf,
uint32_t * const p_buf_len);
/**@brief Pre-decodes opt_id of @ref ble_opt_t for middleware.
*
* @param[out] p_buf Pointer to buffer where encoded data command response will be
* returned.
* @param[in,out] packet_len \c in: size of \p p_buf buffer.
* \c out: Length of encoded command response packet.
* @param[in,out] p_opt_id Pointer to opt_id which identifies type of @ref ble_opt_t union.
*
* @retval NRF_SUCCESS Encoding success.
* @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Encoding failure. Incorrect buffer length.
*/
uint32_t ble_opt_id_pre_dec(uint8_t const * const p_buf,
uint16_t packet_len,
uint32_t * const p_opt_id);
/**@brief Decodes @ref sd_ble_user_mem_reply command request.
*
* @sa @ref nrf51_user_mem_reply_encoding for packet format,
* @ref ble_user_mem_reply_rsp_enc for response encoding.
*
* @param[in] p_buf Pointer to beginning of command request packet.
* @param[in] packet_len Length (in bytes) of response packet.
* @param[in] p_conn_handle Pointer to Connection Handle.
* @param[in,out] pp_block Pointer to pointer to ble_user_mem_block_t.
* \c It will be set to NULL if p_block is not present in the packet.
*
* @retval NRF_SUCCESS Decoding success.
* @retval NRF_ERROR_NULL Decoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Decoding failure. Incorrect buffer length.
*/
uint32_t ble_user_mem_reply_req_dec(uint8_t const * const p_buf,
uint32_t packet_len,
uint16_t * const p_conn_handle,
ble_user_mem_block_t * * const pp_block);
/**@brief Encodes @ref sd_ble_user_mem_reply command response.
*
* @sa @ref nrf51_user_mem_reply_encoding for packet format.
* @ref ble_user_mem_reply_req_dec for request decoding.
*
* @param[in] return_code Return code indicating if command was successful or not.
* @param[out] p_buf Pointer to buffer where encoded data command response will be
* returned.
* @param[in,out] p_buf_len \c in: size of \p p_buf buffer.
* \c out: Length of encoded command response packet.
*
* @retval NRF_SUCCESS Encoding success.
* @retval NRF_ERROR_NULL Encoding failure. NULL pointer supplied.
* @retval NRF_ERROR_INVALID_LENGTH Encoding failure. Incorrect buffer length.
*/
uint32_t ble_user_mem_reply_rsp_enc(uint32_t return_code,
uint8_t * const p_buf,
uint32_t * const p_buf_len);
/** @} */
#endif
| lab11/nrf5x-base | sdk/nrf51_sdk_9.0.0/components/serialization/connectivity/codecs/s120/serializers/ble_conn.h | C | mit | 22,979 |
/**
* @file
* lwIP network interface abstraction
*
* @defgroup netif Network interface (NETIF)
* @ingroup callbackstyle_api
*
* @defgroup netif_ip4 IPv4 address handling
* @ingroup netif
*
* @defgroup netif_ip6 IPv6 address handling
* @ingroup netif
*
* @defgroup netif_cd Client data handling
* Store data (void*) on a netif for application usage.
* @see @ref LWIP_NUM_NETIF_CLIENT_DATA
* @ingroup netif
*/
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*/
#include "lwip/opt.h"
#include <string.h>
#include "lwip/def.h"
#include "lwip/ip_addr.h"
#include "lwip/ip6_addr.h"
#include "lwip/netif.h"
#include "lwip/priv/tcp_priv.h"
#include "lwip/udp.h"
#include "lwip/raw.h"
#include "lwip/snmp.h"
#include "lwip/igmp.h"
#include "lwip/etharp.h"
#include "lwip/stats.h"
#include "lwip/sys.h"
#include "lwip/ip.h"
#if ENABLE_LOOPBACK
#if LWIP_NETIF_LOOPBACK_MULTITHREADING
#include "lwip/tcpip.h"
#endif /* LWIP_NETIF_LOOPBACK_MULTITHREADING */
#endif /* ENABLE_LOOPBACK */
#include "netif/ethernet.h"
#if LWIP_AUTOIP
#include "lwip/autoip.h"
#endif /* LWIP_AUTOIP */
#if LWIP_DHCP
#include "lwip/dhcp.h"
#endif /* LWIP_DHCP */
#if LWIP_IPV6_DHCP6
#include "lwip/dhcp6.h"
#endif /* LWIP_IPV6_DHCP6 */
#if LWIP_IPV6_MLD
#include "lwip/mld6.h"
#endif /* LWIP_IPV6_MLD */
#if LWIP_IPV6
#include "lwip/nd6.h"
#endif
#if LWIP_NETIF_STATUS_CALLBACK
#define NETIF_STATUS_CALLBACK(n) do{ if (n->status_callback) { (n->status_callback)(n); }}while(0)
#else
#define NETIF_STATUS_CALLBACK(n)
#endif /* LWIP_NETIF_STATUS_CALLBACK */
#if LWIP_NETIF_LINK_CALLBACK
#define NETIF_LINK_CALLBACK(n) do{ if (n->link_callback) { (n->link_callback)(n); }}while(0)
#else
#define NETIF_LINK_CALLBACK(n)
#endif /* LWIP_NETIF_LINK_CALLBACK */
struct netif *netif_list;
struct netif *netif_default;
static u8_t netif_num;
#if LWIP_NUM_NETIF_CLIENT_DATA > 0
static u8_t netif_client_id;
#endif
#define NETIF_REPORT_TYPE_IPV4 0x01
#define NETIF_REPORT_TYPE_IPV6 0x02
static void netif_issue_reports(struct netif* netif, u8_t report_type);
#if LWIP_IPV6
static err_t netif_null_output_ip6(struct netif *netif, struct pbuf *p, const ip6_addr_t *ipaddr);
#endif /* LWIP_IPV6 */
#if LWIP_HAVE_LOOPIF
#if LWIP_IPV4
static err_t netif_loop_output_ipv4(struct netif *netif, struct pbuf *p, const ip4_addr_t* addr);
#endif
#if LWIP_IPV6
static err_t netif_loop_output_ipv6(struct netif *netif, struct pbuf *p, const ip6_addr_t* addr);
#endif
static struct netif loop_netif;
/**
* Initialize a lwip network interface structure for a loopback interface
*
* @param netif the lwip network interface structure for this loopif
* @return ERR_OK if the loopif is initialized
* ERR_MEM if private data couldn't be allocated
*/
static err_t
netif_loopif_init(struct netif *netif)
{
/* initialize the snmp variables and counters inside the struct netif
* ifSpeed: no assumption can be made!
*/
MIB2_INIT_NETIF(netif, snmp_ifType_softwareLoopback, 0);
netif->name[0] = 'l';
netif->name[1] = 'o';
#if LWIP_IPV4
netif->output = netif_loop_output_ipv4;
#endif
#if LWIP_IPV6
netif->output_ip6 = netif_loop_output_ipv6;
#endif
#if LWIP_LOOPIF_MULTICAST
netif->flags |= NETIF_FLAG_IGMP;
#endif
return ERR_OK;
}
#endif /* LWIP_HAVE_LOOPIF */
void
netif_init(void)
{
#if LWIP_HAVE_LOOPIF
#if LWIP_IPV4
#define LOOPIF_ADDRINIT &loop_ipaddr, &loop_netmask, &loop_gw,
ip4_addr_t loop_ipaddr, loop_netmask, loop_gw;
IP4_ADDR(&loop_gw, 127,0,0,1);
IP4_ADDR(&loop_ipaddr, 127,0,0,1);
IP4_ADDR(&loop_netmask, 255,0,0,0);
#else /* LWIP_IPV4 */
#define LOOPIF_ADDRINIT
#endif /* LWIP_IPV4 */
#if NO_SYS
netif_add(&loop_netif, LOOPIF_ADDRINIT NULL, netif_loopif_init, ip_input);
#else /* NO_SYS */
netif_add(&loop_netif, LOOPIF_ADDRINIT NULL, netif_loopif_init, tcpip_input);
#endif /* NO_SYS */
#if LWIP_IPV6
IP_ADDR6(loop_netif.ip6_addr, 0, 0, 0, PP_HTONL(0x00000001UL));
loop_netif.ip6_addr_state[0] = IP6_ADDR_VALID;
#endif /* LWIP_IPV6 */
netif_set_link_up(&loop_netif);
netif_set_up(&loop_netif);
#endif /* LWIP_HAVE_LOOPIF */
}
/**
* @ingroup lwip_nosys
* Forwards a received packet for input processing with
* ethernet_input() or ip_input() depending on netif flags.
* Don't call directly, pass to netif_add() and call
* netif->input().
* Only works if the netif driver correctly sets
* NETIF_FLAG_ETHARP and/or NETIF_FLAG_ETHERNET flag!
*/
err_t
netif_input(struct pbuf *p, struct netif *inp)
{
#if LWIP_ETHERNET
if (inp->flags & (NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET)) {
return ethernet_input(p, inp);
} else
#endif /* LWIP_ETHERNET */
return ip_input(p, inp);
}
/**
* @ingroup netif
* Add a network interface to the list of lwIP netifs.
*
* @param netif a pre-allocated netif structure
* @param ipaddr IP address for the new netif
* @param netmask network mask for the new netif
* @param gw default gateway IP address for the new netif
* @param state opaque data passed to the new netif
* @param init callback function that initializes the interface
* @param input callback function that is called to pass
* ingress packets up in the protocol layer stack.\n
* It is recommended to use a function that passes the input directly
* to the stack (netif_input(), NO_SYS=1 mode) or via sending a
* message to TCPIP thread (tcpip_input(), NO_SYS=0 mode).\n
* These functions use netif flags NETIF_FLAG_ETHARP and NETIF_FLAG_ETHERNET
* to decide whether to forward to ethernet_input() or ip_input().
* In other words, the functions only work when the netif
* driver is implemented correctly!\n
* Most members of struct netif should be be initialized by the
* netif init function = netif driver (init parameter of this function).\n
* IPv6: Don't forget to call netif_create_ip6_linklocal_address() after
* setting the MAC address in struct netif.hwaddr
* (IPv6 requires a link-local address).
*
* @return netif, or NULL if failed.
*/
struct netif *
netif_add(struct netif *netif,
#if LWIP_IPV4
const ip4_addr_t *ipaddr, const ip4_addr_t *netmask, const ip4_addr_t *gw,
#endif /* LWIP_IPV4 */
void *state, netif_init_fn init, netif_input_fn input)
{
#if LWIP_IPV6
s8_t i;
#endif
LWIP_ASSERT("No init function given", init != NULL);
/* reset new interface configuration state */
#if LWIP_IPV4
ip_addr_set_zero_ip4(&netif->ip_addr);
ip_addr_set_zero_ip4(&netif->netmask);
ip_addr_set_zero_ip4(&netif->gw);
#endif /* LWIP_IPV4 */
#if LWIP_IPV6
for (i = 0; i < LWIP_IPV6_NUM_ADDRESSES; i++) {
ip_addr_set_zero_ip6(&netif->ip6_addr[i]);
netif->ip6_addr_state[i] = IP6_ADDR_INVALID;
}
netif->output_ip6 = netif_null_output_ip6;
#endif /* LWIP_IPV6 */
NETIF_SET_CHECKSUM_CTRL(netif, NETIF_CHECKSUM_ENABLE_ALL);
netif->flags = 0;
#ifdef netif_get_client_data
memset(netif->client_data, 0, sizeof(netif->client_data));
#endif /* LWIP_NUM_NETIF_CLIENT_DATA */
#if LWIP_IPV6_AUTOCONFIG
/* IPv6 address autoconfiguration not enabled by default */
netif->ip6_autoconfig_enabled = 0;
#endif /* LWIP_IPV6_AUTOCONFIG */
#if LWIP_IPV6_SEND_ROUTER_SOLICIT
netif->rs_count = LWIP_ND6_MAX_MULTICAST_SOLICIT;
#endif /* LWIP_IPV6_SEND_ROUTER_SOLICIT */
#if LWIP_NETIF_STATUS_CALLBACK
netif->status_callback = NULL;
#endif /* LWIP_NETIF_STATUS_CALLBACK */
#if LWIP_NETIF_LINK_CALLBACK
netif->link_callback = NULL;
#endif /* LWIP_NETIF_LINK_CALLBACK */
#if LWIP_IGMP
netif->igmp_mac_filter = NULL;
#endif /* LWIP_IGMP */
#if LWIP_IPV6 && LWIP_IPV6_MLD
netif->mld_mac_filter = NULL;
#endif /* LWIP_IPV6 && LWIP_IPV6_MLD */
#if ENABLE_LOOPBACK
netif->loop_first = NULL;
netif->loop_last = NULL;
#endif /* ENABLE_LOOPBACK */
/* remember netif specific state information data */
netif->state = state;
netif->num = netif_num++;
netif->input = input;
NETIF_SET_HWADDRHINT(netif, NULL);
#if ENABLE_LOOPBACK && LWIP_LOOPBACK_MAX_PBUFS
netif->loop_cnt_current = 0;
#endif /* ENABLE_LOOPBACK && LWIP_LOOPBACK_MAX_PBUFS */
#if LWIP_IPV4
netif_set_addr(netif, ipaddr, netmask, gw);
#endif /* LWIP_IPV4 */
/* call user specified initialization function for netif */
if (init(netif) != ERR_OK) {
return NULL;
}
/* add this netif to the list */
netif->next = netif_list;
netif_list = netif;
mib2_netif_added(netif);
#if LWIP_IGMP
/* start IGMP processing */
if (netif->flags & NETIF_FLAG_IGMP) {
igmp_start(netif);
}
#endif /* LWIP_IGMP */
LWIP_DEBUGF(NETIF_DEBUG, ("netif: added interface %c%c IP",
netif->name[0], netif->name[1]));
#if LWIP_IPV4
LWIP_DEBUGF(NETIF_DEBUG, (" addr "));
ip4_addr_debug_print(NETIF_DEBUG, ipaddr);
LWIP_DEBUGF(NETIF_DEBUG, (" netmask "));
ip4_addr_debug_print(NETIF_DEBUG, netmask);
LWIP_DEBUGF(NETIF_DEBUG, (" gw "));
ip4_addr_debug_print(NETIF_DEBUG, gw);
#endif /* LWIP_IPV4 */
LWIP_DEBUGF(NETIF_DEBUG, ("\n"));
return netif;
}
#if LWIP_IPV4
/**
* @ingroup netif_ip4
* Change IP address configuration for a network interface (including netmask
* and default gateway).
*
* @param netif the network interface to change
* @param ipaddr the new IP address
* @param netmask the new netmask
* @param gw the new default gateway
*/
void
netif_set_addr(struct netif *netif, const ip4_addr_t *ipaddr, const ip4_addr_t *netmask,
const ip4_addr_t *gw)
{
if (ip4_addr_isany(ipaddr)) {
/* when removing an address, we have to remove it *before* changing netmask/gw
to ensure that tcp RST segment can be sent correctly */
netif_set_ipaddr(netif, ipaddr);
netif_set_netmask(netif, netmask);
netif_set_gw(netif, gw);
} else {
netif_set_netmask(netif, netmask);
netif_set_gw(netif, gw);
/* set ipaddr last to ensure netmask/gw have been set when status callback is called */
netif_set_ipaddr(netif, ipaddr);
}
}
#endif /* LWIP_IPV4*/
/**
* @ingroup netif
* Remove a network interface from the list of lwIP netifs.
*
* @param netif the network interface to remove
*/
void
netif_remove(struct netif *netif)
{
#if LWIP_IPV6
int i;
#endif
if (netif == NULL) {
return;
}
#if LWIP_IPV4
if (!ip4_addr_isany_val(*netif_ip4_addr(netif))) {
#if LWIP_TCP
tcp_netif_ip_addr_changed(netif_ip_addr4(netif), NULL);
#endif /* LWIP_TCP */
#if LWIP_UDP
udp_netif_ip_addr_changed(netif_ip_addr4(netif), NULL);
#endif /* LWIP_UDP */
#if LWIP_RAW
raw_netif_ip_addr_changed(netif_ip_addr4(netif), NULL);
#endif /* LWIP_RAW */
}
#if LWIP_IGMP
/* stop IGMP processing */
if (netif->flags & NETIF_FLAG_IGMP) {
igmp_stop(netif);
}
#endif /* LWIP_IGMP */
#endif /* LWIP_IPV4*/
#if LWIP_IPV6
for (i = 0; i < LWIP_IPV6_NUM_ADDRESSES; i++) {
if (ip6_addr_isvalid(netif_ip6_addr_state(netif, i))) {
#if LWIP_TCP
tcp_netif_ip_addr_changed(netif_ip_addr6(netif, i), NULL);
#endif /* LWIP_TCP */
#if LWIP_UDP
udp_netif_ip_addr_changed(netif_ip_addr6(netif, i), NULL);
#endif /* LWIP_UDP */
#if LWIP_RAW
raw_netif_ip_addr_changed(netif_ip_addr6(netif, i), NULL);
#endif /* LWIP_RAW */
}
}
#if LWIP_IPV6_MLD
/* stop MLD processing */
mld6_stop(netif);
#endif /* LWIP_IPV6_MLD */
#endif /* LWIP_IPV6 */
if (netif_is_up(netif)) {
/* set netif down before removing (call callback function) */
netif_set_down(netif);
}
mib2_remove_ip4(netif);
/* this netif is default? */
if (netif_default == netif) {
/* reset default netif */
netif_set_default(NULL);
}
/* is it the first netif? */
if (netif_list == netif) {
netif_list = netif->next;
} else {
/* look for netif further down the list */
struct netif * tmp_netif;
for (tmp_netif = netif_list; tmp_netif != NULL; tmp_netif = tmp_netif->next) {
if (tmp_netif->next == netif) {
tmp_netif->next = netif->next;
break;
}
}
if (tmp_netif == NULL) {
return; /* netif is not on the list */
}
}
mib2_netif_removed(netif);
#if LWIP_NETIF_REMOVE_CALLBACK
if (netif->remove_callback) {
netif->remove_callback(netif);
}
#endif /* LWIP_NETIF_REMOVE_CALLBACK */
LWIP_DEBUGF( NETIF_DEBUG, ("netif_remove: removed netif\n") );
}
/**
* @ingroup netif
* Find a network interface by searching for its name
*
* @param name the name of the netif (like netif->name) plus concatenated number
* in ascii representation (e.g. 'en0')
*/
struct netif *
netif_find(const char *name)
{
struct netif *netif;
u8_t num;
if (name == NULL) {
return NULL;
}
num = name[2] - '0';
for (netif = netif_list; netif != NULL; netif = netif->next) {
if (num == netif->num &&
name[0] == netif->name[0] &&
name[1] == netif->name[1]) {
LWIP_DEBUGF(NETIF_DEBUG, ("netif_find: found %c%c\n", name[0], name[1]));
return netif;
}
}
LWIP_DEBUGF(NETIF_DEBUG, ("netif_find: didn't find %c%c\n", name[0], name[1]));
return NULL;
}
#if LWIP_IPV4
/**
* @ingroup netif_ip4
* Change the IP address of a network interface
*
* @param netif the network interface to change
* @param ipaddr the new IP address
*
* @note call netif_set_addr() if you also want to change netmask and
* default gateway
*/
void
netif_set_ipaddr(struct netif *netif, const ip4_addr_t *ipaddr)
{
ip_addr_t new_addr;
*ip_2_ip4(&new_addr) = (ipaddr ? *ipaddr : *IP4_ADDR_ANY4);
IP_SET_TYPE_VAL(new_addr, IPADDR_TYPE_V4);
/* address is actually being changed? */
if (ip4_addr_cmp(ip_2_ip4(&new_addr), netif_ip4_addr(netif)) == 0) {
LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_STATE, ("netif_set_ipaddr: netif address being changed\n"));
#if LWIP_TCP
tcp_netif_ip_addr_changed(netif_ip_addr4(netif), &new_addr);
#endif /* LWIP_TCP */
#if LWIP_UDP
udp_netif_ip_addr_changed(netif_ip_addr4(netif), &new_addr);
#endif /* LWIP_UDP */
#if LWIP_RAW
raw_netif_ip_addr_changed(netif_ip_addr4(netif), &new_addr);
#endif /* LWIP_RAW */
mib2_remove_ip4(netif);
mib2_remove_route_ip4(0, netif);
/* set new IP address to netif */
ip4_addr_set(ip_2_ip4(&netif->ip_addr), ipaddr);
IP_SET_TYPE_VAL(netif->ip_addr, IPADDR_TYPE_V4);
mib2_add_ip4(netif);
mib2_add_route_ip4(0, netif);
netif_issue_reports(netif, NETIF_REPORT_TYPE_IPV4);
NETIF_STATUS_CALLBACK(netif);
}
LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("netif: IP address of interface %c%c set to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n",
netif->name[0], netif->name[1],
ip4_addr1_16(netif_ip4_addr(netif)),
ip4_addr2_16(netif_ip4_addr(netif)),
ip4_addr3_16(netif_ip4_addr(netif)),
ip4_addr4_16(netif_ip4_addr(netif))));
}
/**
* @ingroup netif_ip4
* Change the default gateway for a network interface
*
* @param netif the network interface to change
* @param gw the new default gateway
*
* @note call netif_set_addr() if you also want to change ip address and netmask
*/
void
netif_set_gw(struct netif *netif, const ip4_addr_t *gw)
{
ip4_addr_set(ip_2_ip4(&netif->gw), gw);
IP_SET_TYPE_VAL(netif->gw, IPADDR_TYPE_V4);
LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("netif: GW address of interface %c%c set to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n",
netif->name[0], netif->name[1],
ip4_addr1_16(netif_ip4_gw(netif)),
ip4_addr2_16(netif_ip4_gw(netif)),
ip4_addr3_16(netif_ip4_gw(netif)),
ip4_addr4_16(netif_ip4_gw(netif))));
}
/**
* @ingroup netif_ip4
* Change the netmask of a network interface
*
* @param netif the network interface to change
* @param netmask the new netmask
*
* @note call netif_set_addr() if you also want to change ip address and
* default gateway
*/
void
netif_set_netmask(struct netif *netif, const ip4_addr_t *netmask)
{
mib2_remove_route_ip4(0, netif);
/* set new netmask to netif */
ip4_addr_set(ip_2_ip4(&netif->netmask), netmask);
IP_SET_TYPE_VAL(netif->netmask, IPADDR_TYPE_V4);
mib2_add_route_ip4(0, netif);
LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("netif: netmask of interface %c%c set to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n",
netif->name[0], netif->name[1],
ip4_addr1_16(netif_ip4_netmask(netif)),
ip4_addr2_16(netif_ip4_netmask(netif)),
ip4_addr3_16(netif_ip4_netmask(netif)),
ip4_addr4_16(netif_ip4_netmask(netif))));
}
#endif /* LWIP_IPV4 */
/**
* @ingroup netif
* Set a network interface as the default network interface
* (used to output all packets for which no specific route is found)
*
* @param netif the default network interface
*/
void
netif_set_default(struct netif *netif)
{
if (netif == NULL) {
/* remove default route */
mib2_remove_route_ip4(1, netif);
} else {
/* install default route */
mib2_add_route_ip4(1, netif);
}
netif_default = netif;
LWIP_DEBUGF(NETIF_DEBUG, ("netif: setting default interface %c%c\n",
netif ? netif->name[0] : '\'', netif ? netif->name[1] : '\''));
}
/**
* @ingroup netif
* Bring an interface up, available for processing
* traffic.
*/
void
netif_set_up(struct netif *netif)
{
if (!(netif->flags & NETIF_FLAG_UP)) {
netif->flags |= NETIF_FLAG_UP;
MIB2_COPY_SYSUPTIME_TO(&netif->ts);
NETIF_STATUS_CALLBACK(netif);
if (netif->flags & NETIF_FLAG_LINK_UP) {
netif_issue_reports(netif, NETIF_REPORT_TYPE_IPV4|NETIF_REPORT_TYPE_IPV6);
}
}
}
/** Send ARP/IGMP/MLD/RS events, e.g. on link-up/netif-up or addr-change
*/
static void
netif_issue_reports(struct netif* netif, u8_t report_type)
{
#if LWIP_IPV4
if ((report_type & NETIF_REPORT_TYPE_IPV4) &&
!ip4_addr_isany_val(*netif_ip4_addr(netif))) {
#if LWIP_ARP
/* For Ethernet network interfaces, we would like to send a "gratuitous ARP" */
if (netif->flags & (NETIF_FLAG_ETHARP)) {
etharp_gratuitous(netif);
}
#endif /* LWIP_ARP */
#if LWIP_IGMP
/* resend IGMP memberships */
if (netif->flags & NETIF_FLAG_IGMP) {
igmp_report_groups(netif);
}
#endif /* LWIP_IGMP */
}
#endif /* LWIP_IPV4 */
#if LWIP_IPV6
if (report_type & NETIF_REPORT_TYPE_IPV6) {
#if LWIP_IPV6_MLD
/* send mld memberships */
mld6_report_groups(netif);
#endif /* LWIP_IPV6_MLD */
#if LWIP_IPV6_SEND_ROUTER_SOLICIT
/* Send Router Solicitation messages. */
netif->rs_count = LWIP_ND6_MAX_MULTICAST_SOLICIT;
#endif /* LWIP_IPV6_SEND_ROUTER_SOLICIT */
}
#endif /* LWIP_IPV6 */
}
/**
* @ingroup netif
* Bring an interface down, disabling any traffic processing.
*/
void
netif_set_down(struct netif *netif)
{
if (netif->flags & NETIF_FLAG_UP) {
netif->flags &= ~NETIF_FLAG_UP;
MIB2_COPY_SYSUPTIME_TO(&netif->ts);
#if LWIP_IPV4 && LWIP_ARP
if (netif->flags & NETIF_FLAG_ETHARP) {
etharp_cleanup_netif(netif);
}
#endif /* LWIP_IPV4 && LWIP_ARP */
#if LWIP_IPV6
nd6_cleanup_netif(netif);
#endif /* LWIP_IPV6 */
NETIF_STATUS_CALLBACK(netif);
}
}
#if LWIP_NETIF_STATUS_CALLBACK
/**
* @ingroup netif
* Set callback to be called when interface is brought up/down or address is changed while up
*/
void
netif_set_status_callback(struct netif *netif, netif_status_callback_fn status_callback)
{
if (netif) {
netif->status_callback = status_callback;
}
}
#endif /* LWIP_NETIF_STATUS_CALLBACK */
#if LWIP_NETIF_REMOVE_CALLBACK
/**
* @ingroup netif
* Set callback to be called when the interface has been removed
*/
void
netif_set_remove_callback(struct netif *netif, netif_status_callback_fn remove_callback)
{
if (netif) {
netif->remove_callback = remove_callback;
}
}
#endif /* LWIP_NETIF_REMOVE_CALLBACK */
/**
* @ingroup netif
* Called by a driver when its link goes up
*/
void
netif_set_link_up(struct netif *netif)
{
if (!(netif->flags & NETIF_FLAG_LINK_UP)) {
netif->flags |= NETIF_FLAG_LINK_UP;
#if LWIP_DHCP
dhcp_network_changed(netif);
#endif /* LWIP_DHCP */
#if LWIP_AUTOIP
autoip_network_changed(netif);
#endif /* LWIP_AUTOIP */
if (netif->flags & NETIF_FLAG_UP) {
netif_issue_reports(netif, NETIF_REPORT_TYPE_IPV4|NETIF_REPORT_TYPE_IPV6);
}
NETIF_LINK_CALLBACK(netif);
}
}
/**
* @ingroup netif
* Called by a driver when its link goes down
*/
void
netif_set_link_down(struct netif *netif )
{
if (netif->flags & NETIF_FLAG_LINK_UP) {
netif->flags &= ~NETIF_FLAG_LINK_UP;
NETIF_LINK_CALLBACK(netif);
}
}
#if LWIP_NETIF_LINK_CALLBACK
/**
* @ingroup netif
* Set callback to be called when link is brought up/down
*/
void
netif_set_link_callback(struct netif *netif, netif_status_callback_fn link_callback)
{
if (netif) {
netif->link_callback = link_callback;
}
}
#endif /* LWIP_NETIF_LINK_CALLBACK */
#if ENABLE_LOOPBACK
/**
* @ingroup netif
* Send an IP packet to be received on the same netif (loopif-like).
* The pbuf is simply copied and handed back to netif->input.
* In multithreaded mode, this is done directly since netif->input must put
* the packet on a queue.
* In callback mode, the packet is put on an internal queue and is fed to
* netif->input by netif_poll().
*
* @param netif the lwip network interface structure
* @param p the (IP) packet to 'send'
* @return ERR_OK if the packet has been sent
* ERR_MEM if the pbuf used to copy the packet couldn't be allocated
*/
err_t
netif_loop_output(struct netif *netif, struct pbuf *p)
{
struct pbuf *r;
err_t err;
struct pbuf *last;
#if LWIP_LOOPBACK_MAX_PBUFS
u16_t clen = 0;
#endif /* LWIP_LOOPBACK_MAX_PBUFS */
/* If we have a loopif, SNMP counters are adjusted for it,
* if not they are adjusted for 'netif'. */
#if MIB2_STATS
#if LWIP_HAVE_LOOPIF
struct netif *stats_if = &loop_netif;
#else /* LWIP_HAVE_LOOPIF */
struct netif *stats_if = netif;
#endif /* LWIP_HAVE_LOOPIF */
#endif /* MIB2_STATS */
SYS_ARCH_DECL_PROTECT(lev);
/* Allocate a new pbuf */
r = pbuf_alloc(PBUF_LINK, p->tot_len, PBUF_RAM);
if (r == NULL) {
LINK_STATS_INC(link.memerr);
LINK_STATS_INC(link.drop);
MIB2_STATS_NETIF_INC(stats_if, ifoutdiscards);
return ERR_MEM;
}
#if LWIP_LOOPBACK_MAX_PBUFS
clen = pbuf_clen(r);
/* check for overflow or too many pbuf on queue */
if (((netif->loop_cnt_current + clen) < netif->loop_cnt_current) ||
((netif->loop_cnt_current + clen) > LWIP_LOOPBACK_MAX_PBUFS)) {
pbuf_free(r);
LINK_STATS_INC(link.memerr);
LINK_STATS_INC(link.drop);
MIB2_STATS_NETIF_INC(stats_if, ifoutdiscards);
return ERR_MEM;
}
netif->loop_cnt_current += clen;
#endif /* LWIP_LOOPBACK_MAX_PBUFS */
/* Copy the whole pbuf queue p into the single pbuf r */
if ((err = pbuf_copy(r, p)) != ERR_OK) {
pbuf_free(r);
LINK_STATS_INC(link.memerr);
LINK_STATS_INC(link.drop);
MIB2_STATS_NETIF_INC(stats_if, ifoutdiscards);
return err;
}
/* Put the packet on a linked list which gets emptied through calling
netif_poll(). */
/* let last point to the last pbuf in chain r */
for (last = r; last->next != NULL; last = last->next);
SYS_ARCH_PROTECT(lev);
if (netif->loop_first != NULL) {
LWIP_ASSERT("if first != NULL, last must also be != NULL", netif->loop_last != NULL);
netif->loop_last->next = r;
netif->loop_last = last;
} else {
netif->loop_first = r;
netif->loop_last = last;
}
SYS_ARCH_UNPROTECT(lev);
LINK_STATS_INC(link.xmit);
MIB2_STATS_NETIF_ADD(stats_if, ifoutoctets, p->tot_len);
MIB2_STATS_NETIF_INC(stats_if, ifoutucastpkts);
#if LWIP_NETIF_LOOPBACK_MULTITHREADING
/* For multithreading environment, schedule a call to netif_poll */
tcpip_callback_with_block((tcpip_callback_fn)netif_poll, netif, 0);
#endif /* LWIP_NETIF_LOOPBACK_MULTITHREADING */
return ERR_OK;
}
#if LWIP_HAVE_LOOPIF
#if LWIP_IPV4
static err_t
netif_loop_output_ipv4(struct netif *netif, struct pbuf *p, const ip4_addr_t* addr)
{
LWIP_UNUSED_ARG(addr);
return netif_loop_output(netif, p);
}
#endif /* LWIP_IPV4 */
#if LWIP_IPV6
static err_t
netif_loop_output_ipv6(struct netif *netif, struct pbuf *p, const ip6_addr_t* addr)
{
LWIP_UNUSED_ARG(addr);
return netif_loop_output(netif, p);
}
#endif /* LWIP_IPV6 */
#endif /* LWIP_HAVE_LOOPIF */
/**
* Call netif_poll() in the main loop of your application. This is to prevent
* reentering non-reentrant functions like tcp_input(). Packets passed to
* netif_loop_output() are put on a list that is passed to netif->input() by
* netif_poll().
*/
void
netif_poll(struct netif *netif)
{
struct pbuf *in;
/* If we have a loopif, SNMP counters are adjusted for it,
* if not they are adjusted for 'netif'. */
#if MIB2_STATS
#if LWIP_HAVE_LOOPIF
struct netif *stats_if = &loop_netif;
#else /* LWIP_HAVE_LOOPIF */
struct netif *stats_if = netif;
#endif /* LWIP_HAVE_LOOPIF */
#endif /* MIB2_STATS */
SYS_ARCH_DECL_PROTECT(lev);
do {
/* Get a packet from the list. With SYS_LIGHTWEIGHT_PROT=1, this is protected */
SYS_ARCH_PROTECT(lev);
in = netif->loop_first;
if (in != NULL) {
struct pbuf *in_end = in;
#if LWIP_LOOPBACK_MAX_PBUFS
u8_t clen = 1;
#endif /* LWIP_LOOPBACK_MAX_PBUFS */
while (in_end->len != in_end->tot_len) {
LWIP_ASSERT("bogus pbuf: len != tot_len but next == NULL!", in_end->next != NULL);
in_end = in_end->next;
#if LWIP_LOOPBACK_MAX_PBUFS
clen++;
#endif /* LWIP_LOOPBACK_MAX_PBUFS */
}
#if LWIP_LOOPBACK_MAX_PBUFS
/* adjust the number of pbufs on queue */
LWIP_ASSERT("netif->loop_cnt_current underflow",
((netif->loop_cnt_current - clen) < netif->loop_cnt_current));
netif->loop_cnt_current -= clen;
#endif /* LWIP_LOOPBACK_MAX_PBUFS */
/* 'in_end' now points to the last pbuf from 'in' */
if (in_end == netif->loop_last) {
/* this was the last pbuf in the list */
netif->loop_first = netif->loop_last = NULL;
} else {
/* pop the pbuf off the list */
netif->loop_first = in_end->next;
LWIP_ASSERT("should not be null since first != last!", netif->loop_first != NULL);
}
/* De-queue the pbuf from its successors on the 'loop_' list. */
in_end->next = NULL;
}
SYS_ARCH_UNPROTECT(lev);
if (in != NULL) {
LINK_STATS_INC(link.recv);
MIB2_STATS_NETIF_ADD(stats_if, ifinoctets, in->tot_len);
MIB2_STATS_NETIF_INC(stats_if, ifinucastpkts);
/* loopback packets are always IP packets! */
if (ip_input(in, netif) != ERR_OK) {
pbuf_free(in);
}
/* Don't reference the packet any more! */
in = NULL;
}
/* go on while there is a packet on the list */
} while (netif->loop_first != NULL);
}
#if !LWIP_NETIF_LOOPBACK_MULTITHREADING
/**
* Calls netif_poll() for every netif on the netif_list.
*/
void
netif_poll_all(void)
{
struct netif *netif = netif_list;
/* loop through netifs */
while (netif != NULL) {
netif_poll(netif);
/* proceed to next network interface */
netif = netif->next;
}
}
#endif /* !LWIP_NETIF_LOOPBACK_MULTITHREADING */
#endif /* ENABLE_LOOPBACK */
#if LWIP_NUM_NETIF_CLIENT_DATA > 0
/**
* @ingroup netif_cd
* Allocate an index to store data in client_data member of struct netif.
* Returned value is an index in mentioned array.
* @see LWIP_NUM_NETIF_CLIENT_DATA
*/
u8_t
netif_alloc_client_data_id(void)
{
u8_t result = netif_client_id;
netif_client_id++;
LWIP_ASSERT("Increase LWIP_NUM_NETIF_CLIENT_DATA in lwipopts.h", result < LWIP_NUM_NETIF_CLIENT_DATA);
return result + LWIP_NETIF_CLIENT_DATA_INDEX_MAX;
}
#endif
#if LWIP_IPV6
/**
* @ingroup netif_ip6
* Change an IPv6 address of a network interface
*
* @param netif the network interface to change
* @param addr_idx index of the IPv6 address
* @param addr6 the new IPv6 address
*
* @note call netif_ip6_addr_set_state() to set the address valid/temptative
*/
void
netif_ip6_addr_set(struct netif *netif, s8_t addr_idx, const ip6_addr_t *addr6)
{
LWIP_ASSERT("addr6 != NULL", addr6 != NULL);
netif_ip6_addr_set_parts(netif, addr_idx, addr6->addr[0], addr6->addr[1],
addr6->addr[2], addr6->addr[3]);
}
/*
* Change an IPv6 address of a network interface (internal version taking 4 * u32_t)
*
* @param netif the network interface to change
* @param addr_idx index of the IPv6 address
* @param i0 word0 of the new IPv6 address
* @param i1 word1 of the new IPv6 address
* @param i2 word2 of the new IPv6 address
* @param i3 word3 of the new IPv6 address
*/
void
netif_ip6_addr_set_parts(struct netif *netif, s8_t addr_idx, u32_t i0, u32_t i1, u32_t i2, u32_t i3)
{
const ip6_addr_t *old_addr;
LWIP_ASSERT("netif != NULL", netif != NULL);
LWIP_ASSERT("invalid index", addr_idx < LWIP_IPV6_NUM_ADDRESSES);
old_addr = netif_ip6_addr(netif, addr_idx);
/* address is actually being changed? */
if ((old_addr->addr[0] != i0) || (old_addr->addr[1] != i1) ||
(old_addr->addr[2] != i2) || (old_addr->addr[3] != i3)) {
LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_STATE, ("netif_ip6_addr_set: netif address being changed\n"));
if (netif_ip6_addr_state(netif, addr_idx) & IP6_ADDR_VALID) {
#if LWIP_TCP || LWIP_UDP
ip_addr_t new_ipaddr;
IP_ADDR6(&new_ipaddr, i0, i1, i2, i3);
#endif /* LWIP_TCP || LWIP_UDP */
#if LWIP_TCP
tcp_netif_ip_addr_changed(netif_ip_addr6(netif, addr_idx), &new_ipaddr);
#endif /* LWIP_TCP */
#if LWIP_UDP
udp_netif_ip_addr_changed(netif_ip_addr6(netif, addr_idx), &new_ipaddr);
#endif /* LWIP_UDP */
#if LWIP_RAW
raw_netif_ip_addr_changed(netif_ip_addr6(netif, addr_idx), &new_ipaddr);
#endif /* LWIP_RAW */
}
/* @todo: remove/readd mib2 ip6 entries? */
IP6_ADDR(ip_2_ip6(&(netif->ip6_addr[addr_idx])), i0, i1, i2, i3);
IP_SET_TYPE_VAL(netif->ip6_addr[addr_idx], IPADDR_TYPE_V6);
if (netif_ip6_addr_state(netif, addr_idx) & IP6_ADDR_VALID) {
netif_issue_reports(netif, NETIF_REPORT_TYPE_IPV6);
NETIF_STATUS_CALLBACK(netif);
}
}
LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("netif: IPv6 address %d of interface %c%c set to %s/0x%"X8_F"\n",
addr_idx, netif->name[0], netif->name[1], ip6addr_ntoa(netif_ip6_addr(netif, addr_idx)),
netif_ip6_addr_state(netif, addr_idx)));
}
/**
* @ingroup netif_ip6
* Change the state of an IPv6 address of a network interface
* (INVALID, TEMPTATIVE, PREFERRED, DEPRECATED, where TEMPTATIVE
* includes the number of checks done, see ip6_addr.h)
*
* @param netif the network interface to change
* @param addr_idx index of the IPv6 address
* @param state the new IPv6 address state
*/
void
netif_ip6_addr_set_state(struct netif* netif, s8_t addr_idx, u8_t state)
{
u8_t old_state;
LWIP_ASSERT("netif != NULL", netif != NULL);
LWIP_ASSERT("invalid index", addr_idx < LWIP_IPV6_NUM_ADDRESSES);
old_state = netif_ip6_addr_state(netif, addr_idx);
/* state is actually being changed? */
if (old_state != state) {
u8_t old_valid = old_state & IP6_ADDR_VALID;
u8_t new_valid = state & IP6_ADDR_VALID;
LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_STATE, ("netif_ip6_addr_set_state: netif address state being changed\n"));
if (old_valid && !new_valid) {
/* address about to be removed by setting invalid */
#if LWIP_TCP
tcp_netif_ip_addr_changed(netif_ip_addr6(netif, addr_idx), NULL);
#endif /* LWIP_TCP */
#if LWIP_UDP
udp_netif_ip_addr_changed(netif_ip_addr6(netif, addr_idx), NULL);
#endif /* LWIP_UDP */
#if LWIP_RAW
raw_netif_ip_addr_changed(netif_ip_addr6(netif, addr_idx), NULL);
#endif /* LWIP_RAW */
/* @todo: remove mib2 ip6 entries? */
}
netif->ip6_addr_state[addr_idx] = state;
if (!old_valid && new_valid) {
/* address added by setting valid */
/* @todo: add mib2 ip6 entries? */
netif_issue_reports(netif, NETIF_REPORT_TYPE_IPV6);
}
if ((old_state & IP6_ADDR_PREFERRED) != (state & IP6_ADDR_PREFERRED)) {
/* address state has changed (valid flag changed or switched between
preferred and deprecated) -> call the callback function */
NETIF_STATUS_CALLBACK(netif);
}
}
LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("netif: IPv6 address %d of interface %c%c set to %s/0x%"X8_F"\n",
addr_idx, netif->name[0], netif->name[1], ip6addr_ntoa(netif_ip6_addr(netif, addr_idx)),
netif_ip6_addr_state(netif, addr_idx)));
}
/**
* Checks if a specific address is assigned to the netif and returns its
* index.
*
* @param netif the netif to check
* @param ip6addr the IPv6 address to find
* @return >= 0: address found, this is its index
* -1: address not found on this netif
*/
s8_t
netif_get_ip6_addr_match(struct netif *netif, const ip6_addr_t *ip6addr)
{
s8_t i;
for (i = 0; i < LWIP_IPV6_NUM_ADDRESSES; i++) {
if (!ip6_addr_isinvalid(netif_ip6_addr_state(netif, i)) &&
ip6_addr_cmp(netif_ip6_addr(netif, i), ip6addr)) {
return i;
}
}
return -1;
}
/**
* @ingroup netif_ip6
* Create a link-local IPv6 address on a netif (stored in slot 0)
*
* @param netif the netif to create the address on
* @param from_mac_48bit if != 0, assume hwadr is a 48-bit MAC address (std conversion)
* if == 0, use hwaddr directly as interface ID
*/
void
netif_create_ip6_linklocal_address(struct netif *netif, u8_t from_mac_48bit)
{
u8_t i, addr_index;
/* Link-local prefix. */
ip_2_ip6(&netif->ip6_addr[0])->addr[0] = PP_HTONL(0xfe800000ul);
ip_2_ip6(&netif->ip6_addr[0])->addr[1] = 0;
/* Generate interface ID. */
if (from_mac_48bit) {
/* Assume hwaddr is a 48-bit IEEE 802 MAC. Convert to EUI-64 address. Complement Group bit. */
ip_2_ip6(&netif->ip6_addr[0])->addr[2] = lwip_htonl((((u32_t)(netif->hwaddr[0] ^ 0x02)) << 24) |
((u32_t)(netif->hwaddr[1]) << 16) |
((u32_t)(netif->hwaddr[2]) << 8) |
(0xff));
ip_2_ip6(&netif->ip6_addr[0])->addr[3] = lwip_htonl((0xfeul << 24) |
((u32_t)(netif->hwaddr[3]) << 16) |
((u32_t)(netif->hwaddr[4]) << 8) |
(netif->hwaddr[5]));
} else {
/* Use hwaddr directly as interface ID. */
ip_2_ip6(&netif->ip6_addr[0])->addr[2] = 0;
ip_2_ip6(&netif->ip6_addr[0])->addr[3] = 0;
addr_index = 3;
for (i = 0; (i < 8) && (i < netif->hwaddr_len); i++) {
if (i == 4) {
addr_index--;
}
ip_2_ip6(&netif->ip6_addr[0])->addr[addr_index] |= ((u32_t)(netif->hwaddr[netif->hwaddr_len - i - 1])) << (8 * (i & 0x03));
}
}
/* Set address state. */
#if LWIP_IPV6_DUP_DETECT_ATTEMPTS
/* Will perform duplicate address detection (DAD). */
netif->ip6_addr_state[0] = IP6_ADDR_TENTATIVE;
#else
/* Consider address valid. */
netif->ip6_addr_state[0] = IP6_ADDR_PREFERRED;
#endif /* LWIP_IPV6_AUTOCONFIG */
}
/**
* @ingroup netif_ip6
* This function allows for the easy addition of a new IPv6 address to an interface.
* It takes care of finding an empty slot and then sets the address tentative
* (to make sure that all the subsequent processing happens).
*
* @param netif netif to add the address on
* @param ip6addr address to add
* @param chosen_idx if != NULL, the chosen IPv6 address index will be stored here
*/
err_t
netif_add_ip6_address(struct netif *netif, const ip6_addr_t *ip6addr, s8_t *chosen_idx)
{
s8_t i;
i = netif_get_ip6_addr_match(netif, ip6addr);
if (i >= 0) {
/* Address already added */
if (chosen_idx != NULL) {
*chosen_idx = i;
}
return ERR_OK;
}
/* Find a free slot -- musn't be the first one (reserved for link local) */
for (i = 1; i < LWIP_IPV6_NUM_ADDRESSES; i++) {
if (!ip6_addr_isvalid(netif->ip6_addr_state[i])) {
ip_addr_copy_from_ip6(netif->ip6_addr[i], *ip6addr);
netif_ip6_addr_set_state(netif, i, IP6_ADDR_TENTATIVE);
if (chosen_idx != NULL) {
*chosen_idx = i;
}
return ERR_OK;
}
}
if (chosen_idx != NULL) {
*chosen_idx = -1;
}
return ERR_VAL;
}
/** Dummy IPv6 output function for netifs not supporting IPv6
*/
static err_t
netif_null_output_ip6(struct netif *netif, struct pbuf *p, const ip6_addr_t *ipaddr)
{
LWIP_UNUSED_ARG(netif);
LWIP_UNUSED_ARG(p);
LWIP_UNUSED_ARG(ipaddr);
return ERR_IF;
}
#endif /* LWIP_IPV6 */
| chinesebear/rtt-net | rtt-2.1/components/net/lwip-2.0.0/src/core/netif.c | C | mit | 37,448 |
/*
Copyright 2005-2014 Intel Corporation. All Rights Reserved.
This file is part of Threading Building Blocks. Threading Building Blocks 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. Threading Building Blocks 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 Threading Building Blocks; if not, write to the
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
As a special exception, you may use this file as part of a free software library without
restriction. Specifically, if other files instantiate templates or use macros or inline
functions from this file, or you compile this file and link it with other files to produce
an executable, this file does not by itself cause the resulting executable to be covered
by the GNU General Public License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU General Public License.
*/
#define NOMINMAX
#include "harness_defs.h"
#include "tbb/concurrent_queue.h"
#include "tbb/tick_count.h"
#include "harness.h"
#include "harness_allocator.h"
#include <vector>
static tbb::atomic<long> FooConstructed;
static tbb::atomic<long> FooDestroyed;
enum state_t{
LIVE=0x1234,
DEAD=0xDEAD
};
class Foo {
state_t state;
public:
int thread_id;
int serial;
Foo() : state(LIVE), thread_id(0), serial(0) {
++FooConstructed;
}
Foo( const Foo& item ) : state(LIVE) {
ASSERT( item.state==LIVE, NULL );
++FooConstructed;
thread_id = item.thread_id;
serial = item.serial;
}
~Foo() {
ASSERT( state==LIVE, NULL );
++FooDestroyed;
state=DEAD;
thread_id=DEAD;
serial=DEAD;
}
void operator=( const Foo& item ) {
ASSERT( item.state==LIVE, NULL );
ASSERT( state==LIVE, NULL );
thread_id = item.thread_id;
serial = item.serial;
}
bool is_const() {return false;}
bool is_const() const {return true;}
static void clear_counters() { FooConstructed = 0; FooDestroyed = 0; }
static long get_n_constructed() { return FooConstructed; }
static long get_n_destroyed() { return FooDestroyed; }
};
// problem size
static const int N = 50000; // # of bytes
#if TBB_USE_EXCEPTIONS
//! Exception for concurrent_queue
class Foo_exception : public std::bad_alloc {
public:
virtual const char *what() const throw() { return "out of Foo limit"; }
virtual ~Foo_exception() throw() {}
};
static tbb::atomic<long> FooExConstructed;
static tbb::atomic<long> FooExDestroyed;
static tbb::atomic<long> serial_source;
static long MaxFooCount = 0;
static const long Threshold = 400;
class FooEx {
state_t state;
public:
int serial;
FooEx() : state(LIVE) {
++FooExConstructed;
serial = serial_source++;
}
FooEx( const FooEx& item ) : state(LIVE) {
ASSERT( item.state == LIVE, NULL );
++FooExConstructed;
if( MaxFooCount && (FooExConstructed-FooExDestroyed) >= MaxFooCount ) // in push()
throw Foo_exception();
serial = item.serial;
}
~FooEx() {
ASSERT( state==LIVE, NULL );
++FooExDestroyed;
state=DEAD;
serial=DEAD;
}
void operator=( FooEx& item ) {
ASSERT( item.state==LIVE, NULL );
ASSERT( state==LIVE, NULL );
serial = item.serial;
if( MaxFooCount==2*Threshold && (FooExConstructed-FooExDestroyed) <= MaxFooCount/4 ) // in pop()
throw Foo_exception();
}
#if __TBB_CPP11_RVALUE_REF_PRESENT
void operator=( FooEx&& item ) {
operator=( item );
item.serial = 0;
}
#endif /* __TBB_CPP11_RVALUE_REF_PRESENT */
} ;
#endif /* TBB_USE_EXCEPTIONS */
const size_t MAXTHREAD = 256;
static int Sum[MAXTHREAD];
//! Count of various pop operations
/** [0] = pop_if_present that failed
[1] = pop_if_present that succeeded
[2] = pop */
static tbb::atomic<long> PopKind[3];
const int M = 10000;
#if __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT && __TBB_CPP11_RVALUE_REF_PRESENT
const size_t push_selector_variants = 3;
#elif __TBB_CPP11_RVALUE_REF_PRESENT
const size_t push_selector_variants = 2;
#else
const size_t push_selector_variants = 1;
#endif
template<typename CQ, typename ValueType, typename CounterType>
void push( CQ& q, ValueType v, CounterType i ) {
switch( i % push_selector_variants ) {
case 0: q.push( v ); break;
#if __TBB_CPP11_RVALUE_REF_PRESENT
case 1: q.push( std::move(v) ); break;
#if __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT
case 2: q.emplace( v ); break;
#endif
#endif
default: ASSERT( false, NULL ); break;
}
}
template<typename CQ,typename T>
struct Body: NoAssign {
CQ* queue;
const int nthread;
Body( int nthread_ ) : nthread(nthread_) {}
void operator()( int thread_id ) const {
long pop_kind[3] = {0,0,0};
int serial[MAXTHREAD+1];
memset( serial, 0, nthread*sizeof(int) );
ASSERT( thread_id<nthread, NULL );
long sum = 0;
for( long j=0; j<M; ++j ) {
T f;
f.thread_id = DEAD;
f.serial = DEAD;
bool prepopped = false;
if( j&1 ) {
prepopped = queue->try_pop( f );
++pop_kind[prepopped];
}
T g;
g.thread_id = thread_id;
g.serial = j+1;
push( *queue, g, j );
if( !prepopped ) {
while( !(queue)->try_pop(f) ) __TBB_Yield();
++pop_kind[2];
}
ASSERT( f.thread_id<=nthread, NULL );
ASSERT( f.thread_id==nthread || serial[f.thread_id]<f.serial, "partial order violation" );
serial[f.thread_id] = f.serial;
sum += f.serial-1;
}
Sum[thread_id] = sum;
for( int k=0; k<3; ++k )
PopKind[k] += pop_kind[k];
}
};
// Define wrapper classes to test tbb::concurrent_queue<T>
template<typename T, typename A = tbb::cache_aligned_allocator<T> >
class ConcQWithSizeWrapper : public tbb::concurrent_queue<T, A> {
public:
ConcQWithSizeWrapper() {}
ConcQWithSizeWrapper( const ConcQWithSizeWrapper& q ) : tbb::concurrent_queue<T, A>( q ) {}
ConcQWithSizeWrapper(const A& a) : tbb::concurrent_queue<T, A>( a ) {}
#if __TBB_CPP11_RVALUE_REF_PRESENT
ConcQWithSizeWrapper(ConcQWithSizeWrapper&& q) : tbb::concurrent_queue<T>( std::move(q) ) {}
ConcQWithSizeWrapper(ConcQWithSizeWrapper&& q, const A& a)
: tbb::concurrent_queue<T, A>( std::move(q), a ) { }
#endif /* __TBB_CPP11_RVALUE_REF_PRESENT */
template<typename InputIterator>
ConcQWithSizeWrapper( InputIterator begin, InputIterator end, const A& a = A())
: tbb::concurrent_queue<T, A>(begin,end,a) {}
size_t size() const { return this->unsafe_size(); }
};
template<typename T>
class ConcQPushPopWrapper : public tbb::concurrent_queue<T> {
public:
ConcQPushPopWrapper() : my_capacity( size_t(-1)/(sizeof(void*)+sizeof(T)) ) {}
size_t size() const { return this->unsafe_size(); }
void set_capacity( const ptrdiff_t n ) { my_capacity = n; }
bool try_push( const T& source ) { return this->push( source ); }
bool try_pop( T& dest ) { return this->tbb::concurrent_queue<T>::try_pop( dest ); }
size_t my_capacity;
};
template<typename T>
class ConcQWithCapacity : public tbb::concurrent_queue<T> {
public:
ConcQWithCapacity() : my_capacity( size_t(-1)/(sizeof(void*)+sizeof(T)) ) {}
size_t size() const { return this->unsafe_size(); }
size_t capacity() const { return my_capacity; }
void set_capacity( const int n ) { my_capacity = n; }
bool try_push( const T& source ) { this->push( source ); return (size_t)source.serial<my_capacity; }
bool try_pop( T& dest ) { this->tbb::concurrent_queue<T>::try_pop( dest ); return (size_t)dest.serial<my_capacity; }
size_t my_capacity;
};
template <typename Queue>
void AssertEquality(Queue &q, const std::vector<typename Queue::value_type> &vec) {
ASSERT(q.size() == typename Queue::size_type(vec.size()), NULL);
ASSERT(std::equal(q.unsafe_begin(), q.unsafe_end(), vec.begin(), Harness::IsEqual()), NULL);
}
template <typename Queue>
void AssertEmptiness(Queue &q) {
ASSERT(q.empty(), NULL);
ASSERT(!q.size(), NULL);
typename Queue::value_type elem;
ASSERT(!q.try_pop(elem), NULL);
}
enum push_t { push_op, try_push_op };
template<push_t push_op>
struct pusher {
#if __TBB_CPP11_RVALUE_REF_PRESENT
template<typename CQ, typename VType>
static bool push( CQ& queue, VType&& val ) {
queue.push( std::forward<VType>( val ) );
return true;
}
#else
template<typename CQ, typename VType>
static bool push( CQ& queue, const VType& val ) {
queue.push( val );
return true;
}
#endif /* __TBB_CPP11_RVALUE_REF_PRESENT */
};
template<>
struct pusher< try_push_op > {
#if __TBB_CPP11_RVALUE_REF_PRESENT
template<typename CQ, typename VType>
static bool push( CQ& queue, VType&& val ) {
return queue.try_push( std::forward<VType>( val ) );
}
#else
template<typename CQ, typename VType>
static bool push( CQ& queue, const VType& val ) {
return queue.try_push( val );
}
#endif /* __TBB_CPP11_RVALUE_REF_PRESENT */
};
enum pop_t { pop_op, try_pop_op };
template<pop_t pop_op>
struct popper {
#if __TBB_CPP11_RVALUE_REF_PRESENT
template<typename CQ, typename VType>
static bool pop( CQ& queue, VType&& val ) {
if( queue.empty() ) return false;
queue.pop( std::forward<VType>( val ) );
return true;
}
#else
template<typename CQ, typename VType>
static bool pop( CQ& queue, VType& val ) {
if( queue.empty() ) return false;
queue.pop( val );
return true;
}
#endif /* __TBB_CPP11_RVALUE_REF_PRESENT */
};
template<>
struct popper< try_pop_op > {
#if __TBB_CPP11_RVALUE_REF_PRESENT
template<typename CQ, typename VType>
static bool pop( CQ& queue, VType&& val ) {
return queue.try_pop( std::forward<VType>( val ) );
}
#else
template<typename CQ, typename VType>
static bool pop( CQ& queue, VType& val ) {
return queue.try_pop( val );
}
#endif /* __TBB_CPP11_RVALUE_REF_PRESENT */
};
template <push_t push_op, typename Queue>
void FillTest(Queue &q, const std::vector<typename Queue::value_type> &vec) {
for (typename std::vector<typename Queue::value_type>::const_iterator it = vec.begin(); it != vec.end(); ++it)
ASSERT(pusher<push_op>::push(q, *it), NULL);
AssertEquality(q, vec);
}
template <pop_t pop_op, typename Queue>
void EmptyTest(Queue &q, const std::vector<typename Queue::value_type> &vec) {
typedef typename Queue::value_type value_type;
value_type elem;
typename std::vector<value_type>::const_iterator it = vec.begin();
while (popper<pop_op>::pop(q, elem)) {
ASSERT(Harness::IsEqual()(elem, *it), NULL);
++it;
}
ASSERT(it == vec.end(), NULL);
AssertEmptiness(q);
}
template <typename T, typename A>
void bounded_queue_specific_test(tbb::concurrent_queue<T, A> &, const std::vector<T> &) { /* do nothing */ }
template <typename T, typename A>
void bounded_queue_specific_test(tbb::concurrent_bounded_queue<T, A> &q, const std::vector<T> &vec) {
typedef typename tbb::concurrent_bounded_queue<T, A>::size_type size_type;
FillTest<try_push_op>(q, vec);
tbb::concurrent_bounded_queue<T, A> q2 = q;
EmptyTest<pop_op>(q, vec);
// capacity
q2.set_capacity(size_type(vec.size()));
ASSERT(q2.capacity() == size_type(vec.size()), NULL);
ASSERT(q2.size() == size_type(vec.size()), NULL);
ASSERT(!q2.try_push(vec[0]), NULL);
#if TBB_USE_EXCEPTIONS
q.abort();
#endif
}
template<typename CQ, typename T>
void TestPushPop( size_t prefill, ptrdiff_t capacity, int nthread ) {
ASSERT( nthread>0, "nthread must be positive" );
ptrdiff_t signed_prefill = ptrdiff_t(prefill);
if( signed_prefill+1>=capacity )
return;
bool success = false;
for( int k=0; k<3; ++k )
PopKind[k] = 0;
for( int trial=0; !success; ++trial ) {
T::clear_counters();
Body<CQ,T> body(nthread);
CQ queue;
queue.set_capacity( capacity );
body.queue = &queue;
for( size_t i=0; i<prefill; ++i ) {
T f;
f.thread_id = nthread;
f.serial = 1+int(i);
push(queue, f, i);
ASSERT( unsigned(queue.size())==i+1, NULL );
ASSERT( !queue.empty(), NULL );
}
tbb::tick_count t0 = tbb::tick_count::now();
NativeParallelFor( nthread, body );
tbb::tick_count t1 = tbb::tick_count::now();
double timing = (t1-t0).seconds();
REMARK("prefill=%d capacity=%d threads=%d time = %g = %g nsec/operation\n", int(prefill), int(capacity), nthread, timing, timing/(2*M*nthread)*1.E9);
int sum = 0;
for( int k=0; k<nthread; ++k )
sum += Sum[k];
int expected = int(nthread*((M-1)*M/2) + ((prefill-1)*prefill)/2);
for( int i=int(prefill); --i>=0; ) {
ASSERT( !queue.empty(), NULL );
T f;
bool result = queue.try_pop(f);
ASSERT( result, NULL );
ASSERT( int(queue.size())==i, NULL );
sum += f.serial-1;
}
ASSERT( queue.empty(), "The queue should be empty" );
ASSERT( queue.size()==0, "The queue should have zero size" );
if( sum!=expected )
REPORT("sum=%d expected=%d\n",sum,expected);
ASSERT( T::get_n_constructed()==T::get_n_destroyed(), NULL );
// TODO: checks by counting allocators
success = true;
if( nthread>1 && prefill==0 ) {
// Check that pop_if_present got sufficient exercise
for( int k=0; k<2; ++k ) {
#if (_WIN32||_WIN64)
// The TBB library on Windows seems to have a tough time generating
// the desired interleavings for pop_if_present, so the code tries longer, and settles
// for fewer desired interleavings.
const int max_trial = 100;
const int min_requirement = 20;
#else
const int min_requirement = 100;
const int max_trial = 20;
#endif /* _WIN32||_WIN64 */
if( PopKind[k]<min_requirement ) {
if( trial>=max_trial ) {
if( Verbose )
REPORT("Warning: %d threads had only %ld pop_if_present operations %s after %d trials (expected at least %d). "
"This problem may merely be unlucky scheduling. "
"Investigate only if it happens repeatedly.\n",
nthread, long(PopKind[k]), k==0?"failed":"succeeded", max_trial, min_requirement);
else
REPORT("Warning: the number of %s pop_if_present operations is less than expected for %d threads. Investigate if it happens repeatedly.\n",
k==0?"failed":"succeeded", nthread );
} else {
success = false;
}
}
}
}
}
}
class Bar {
state_t state;
public:
static size_t construction_num, destruction_num;
ptrdiff_t my_id;
Bar() : state(LIVE), my_id(-1) {}
Bar(size_t _i) : state(LIVE), my_id(_i) { construction_num++; }
Bar( const Bar& a_bar ) : state(LIVE) {
ASSERT( a_bar.state==LIVE, NULL );
my_id = a_bar.my_id;
construction_num++;
}
~Bar() {
ASSERT( state==LIVE, NULL );
state = DEAD;
my_id = DEAD;
destruction_num++;
}
void operator=( const Bar& a_bar ) {
ASSERT( a_bar.state==LIVE, NULL );
ASSERT( state==LIVE, NULL );
my_id = a_bar.my_id;
}
friend bool operator==(const Bar& bar1, const Bar& bar2 ) ;
} ;
size_t Bar::construction_num = 0;
size_t Bar::destruction_num = 0;
bool operator==(const Bar& bar1, const Bar& bar2) {
ASSERT( bar1.state==LIVE, NULL );
ASSERT( bar2.state==LIVE, NULL );
return bar1.my_id == bar2.my_id;
}
class BarIterator
{
Bar* bar_ptr;
BarIterator(Bar* bp_) : bar_ptr(bp_) {}
public:
~BarIterator() {}
BarIterator& operator=( const BarIterator& other ) {
bar_ptr = other.bar_ptr;
return *this;
}
Bar& operator*() const {
return *bar_ptr;
}
BarIterator& operator++() {
++bar_ptr;
return *this;
}
Bar* operator++(int) {
Bar* result = &operator*();
operator++();
return result;
}
friend bool operator==(const BarIterator& bia, const BarIterator& bib) ;
friend bool operator!=(const BarIterator& bia, const BarIterator& bib) ;
template<typename CQ, typename T, typename TIter, typename CQ_EX, typename T_EX>
friend void TestConstructors ();
} ;
bool operator==(const BarIterator& bia, const BarIterator& bib) {
return bia.bar_ptr==bib.bar_ptr;
}
bool operator!=(const BarIterator& bia, const BarIterator& bib) {
return bia.bar_ptr!=bib.bar_ptr;
}
#if TBB_USE_EXCEPTIONS
class Bar_exception : public std::bad_alloc {
public:
virtual const char *what() const throw() { return "making the entry invalid"; }
virtual ~Bar_exception() throw() {}
};
class BarEx {
static int count;
public:
state_t state;
typedef enum {
PREPARATION,
COPY_CONSTRUCT
} mode_t;
static mode_t mode;
ptrdiff_t my_id;
ptrdiff_t my_tilda_id;
static int button;
BarEx() : state(LIVE), my_id(-1), my_tilda_id(-1) {}
BarEx(size_t _i) : state(LIVE), my_id(_i), my_tilda_id(my_id^(-1)) {}
BarEx( const BarEx& a_bar ) : state(LIVE) {
ASSERT( a_bar.state==LIVE, NULL );
my_id = a_bar.my_id;
if( mode==PREPARATION )
if( !( ++count % 100 ) )
throw Bar_exception();
my_tilda_id = a_bar.my_tilda_id;
}
~BarEx() {
ASSERT( state==LIVE, NULL );
state = DEAD;
my_id = DEAD;
}
static void set_mode( mode_t m ) { mode = m; }
void operator=( const BarEx& a_bar ) {
ASSERT( a_bar.state==LIVE, NULL );
ASSERT( state==LIVE, NULL );
my_id = a_bar.my_id;
my_tilda_id = a_bar.my_tilda_id;
}
friend bool operator==(const BarEx& bar1, const BarEx& bar2 ) ;
} ;
int BarEx::count = 0;
BarEx::mode_t BarEx::mode = BarEx::PREPARATION;
bool operator==(const BarEx& bar1, const BarEx& bar2) {
ASSERT( bar1.state==LIVE, NULL );
ASSERT( bar2.state==LIVE, NULL );
ASSERT( (bar1.my_id ^ bar1.my_tilda_id) == -1, NULL );
ASSERT( (bar2.my_id ^ bar2.my_tilda_id) == -1, NULL );
return bar1.my_id==bar2.my_id && bar1.my_tilda_id==bar2.my_tilda_id;
}
#endif /* TBB_USE_EXCEPTIONS */
template<typename CQ, typename T, typename TIter, typename CQ_EX, typename T_EX>
void TestConstructors ()
{
CQ src_queue;
typename CQ::const_iterator dqb;
typename CQ::const_iterator dqe;
typename CQ::const_iterator iter;
for( size_t size=0; size<1001; ++size ) {
for( size_t i=0; i<size; ++i )
src_queue.push(T(i+(i^size)));
typename CQ::const_iterator sqb( src_queue.unsafe_begin() );
typename CQ::const_iterator sqe( src_queue.unsafe_end() );
CQ dst_queue(sqb, sqe);
ASSERT(src_queue.size()==dst_queue.size(), "different size");
src_queue.clear();
}
T bar_array[1001];
for( size_t size=0; size<1001; ++size ) {
for( size_t i=0; i<size; ++i )
bar_array[i] = T(i+(i^size));
const TIter sab(bar_array+0);
const TIter sae(bar_array+size);
CQ dst_queue2(sab, sae);
ASSERT( size==unsigned(dst_queue2.size()), NULL );
ASSERT( sab==TIter(bar_array+0), NULL );
ASSERT( sae==TIter(bar_array+size), NULL );
dqb = dst_queue2.unsafe_begin();
dqe = dst_queue2.unsafe_end();
TIter v_iter(sab);
for( ; dqb != dqe; ++dqb, ++v_iter )
ASSERT( *dqb == *v_iter, "unexpected element" );
ASSERT( v_iter==sae, "different size?" );
}
src_queue.clear();
CQ dst_queue3( src_queue );
ASSERT( src_queue.size()==dst_queue3.size(), NULL );
ASSERT( 0==dst_queue3.size(), NULL );
int k=0;
for( size_t i=0; i<1001; ++i ) {
T tmp_bar;
src_queue.push(T(++k));
src_queue.push(T(++k));
src_queue.try_pop(tmp_bar);
CQ dst_queue4( src_queue );
ASSERT( src_queue.size()==dst_queue4.size(), NULL );
dqb = dst_queue4.unsafe_begin();
dqe = dst_queue4.unsafe_end();
iter = src_queue.unsafe_begin();
for( ; dqb != dqe; ++dqb, ++iter )
ASSERT( *dqb == *iter, "unexpected element" );
ASSERT( iter==src_queue.unsafe_end(), "different size?" );
}
CQ dst_queue5( src_queue );
ASSERT( src_queue.size()==dst_queue5.size(), NULL );
dqb = dst_queue5.unsafe_begin();
dqe = dst_queue5.unsafe_end();
iter = src_queue.unsafe_begin();
for( ; dqb != dqe; ++dqb, ++iter )
ASSERT( *dqb == *iter, "unexpected element" );
for( size_t i=0; i<100; ++i) {
T tmp_bar;
src_queue.push(T(i+1000));
src_queue.push(T(i+1000));
src_queue.try_pop(tmp_bar);
dst_queue5.push(T(i+1000));
dst_queue5.push(T(i+1000));
dst_queue5.try_pop(tmp_bar);
}
ASSERT( src_queue.size()==dst_queue5.size(), NULL );
dqb = dst_queue5.unsafe_begin();
dqe = dst_queue5.unsafe_end();
iter = src_queue.unsafe_begin();
for( ; dqb != dqe; ++dqb, ++iter )
ASSERT( *dqb == *iter, "unexpected element" );
ASSERT( iter==src_queue.unsafe_end(), "different size?" );
#if __TBB_THROW_ACROSS_MODULE_BOUNDARY_BROKEN || __TBB_PLACEMENT_NEW_EXCEPTION_SAFETY_BROKEN
REPORT("Known issue: part of the constructor test is skipped.\n");
#elif TBB_USE_EXCEPTIONS
k = 0;
typename CQ_EX::size_type n_elements=0;
CQ_EX src_queue_ex;
for( size_t size=0; size<1001; ++size ) {
T_EX tmp_bar_ex;
typename CQ_EX::size_type n_successful_pushes=0;
T_EX::set_mode( T_EX::PREPARATION );
try {
src_queue_ex.push(T_EX(k+(k^size)));
++n_successful_pushes;
} catch (...) {
}
++k;
try {
src_queue_ex.push(T_EX(k+(k^size)));
++n_successful_pushes;
} catch (...) {
}
++k;
src_queue_ex.try_pop(tmp_bar_ex);
n_elements += (n_successful_pushes - 1);
ASSERT( src_queue_ex.size()==n_elements, NULL);
T_EX::set_mode( T_EX::COPY_CONSTRUCT );
CQ_EX dst_queue_ex( src_queue_ex );
ASSERT( src_queue_ex.size()==dst_queue_ex.size(), NULL );
typename CQ_EX::const_iterator dqb_ex = dst_queue_ex.unsafe_begin();
typename CQ_EX::const_iterator dqe_ex = dst_queue_ex.unsafe_end();
typename CQ_EX::const_iterator iter_ex = src_queue_ex.unsafe_begin();
for( ; dqb_ex != dqe_ex; ++dqb_ex, ++iter_ex )
ASSERT( *dqb_ex == *iter_ex, "unexpected element" );
ASSERT( iter_ex==src_queue_ex.unsafe_end(), "different size?" );
}
#endif /* TBB_USE_EXCEPTIONS */
#if __TBB_CPP11_RVALUE_REF_PRESENT
// Testing work of move constructors
src_queue.clear();
typedef typename CQ::size_type qsize_t;
for( qsize_t size = 0; size < 1001; ++size ) {
for( qsize_t i = 0; i < size; ++i )
src_queue.push( T(i + (i ^ size)) );
std::vector<const T*> locations(size);
typename CQ::const_iterator qit = src_queue.unsafe_begin();
for( qsize_t i = 0; i < size; ++i, ++qit )
locations[i] = &(*qit);
qsize_t size_of_queue = src_queue.size();
CQ dst_queue( std::move(src_queue) );
ASSERT( src_queue.empty() && src_queue.size() == 0, "not working move constructor?" );
ASSERT( size == size_of_queue && size_of_queue == dst_queue.size(),
"not working move constructor?" );
qit = dst_queue.unsafe_begin();
for( qsize_t i = 0; i < size; ++i, ++qit )
ASSERT( locations[i] == &(*qit), "there was data movement during move constructor" );
for( qsize_t i = 0; i < size; ++i ) {
T test(i + (i ^ size));
T popped;
bool pop_result = dst_queue.try_pop( popped );
ASSERT( pop_result, NULL );
ASSERT( test == popped, NULL );
}
}
#endif /* __TBB_CPP11_RVALUE_REF_PRESENT */
}
#if __TBB_CPP11_RVALUE_REF_PRESENT
template<class T>
class allocator: public tbb::cache_aligned_allocator<T> {
public:
size_t m_unique_id;
allocator() : m_unique_id( 0 ) {}
allocator(size_t unique_id) { m_unique_id = unique_id; }
template<typename U>
allocator(const allocator<U>& a) throw() { m_unique_id = a.m_unique_id; }
template<typename U>
struct rebind { typedef allocator<U> other; };
friend bool operator==(const allocator& lhs, const allocator& rhs) {
return lhs.m_unique_id == rhs.m_unique_id;
}
};
// Checks operability of the queue the data was moved from
template<typename T, typename CQ>
void TestQueueOperabilityAfterDataMove( CQ& queue ) {
const size_t size = 10;
std::vector<T> v(size);
for( size_t i = 0; i < size; ++i ) v[i] = T( i * i + i );
FillTest<push_op>(queue, v);
EmptyTest<try_pop_op>(queue, v);
bounded_queue_specific_test(queue, v);
}
template<class CQ, class T>
void TestMoveConstructors() {
T::construction_num = T::destruction_num = 0;
CQ src_queue( allocator<T>(0) );
const size_t size = 10;
for( size_t i = 0; i < size; ++i )
src_queue.push( T(i + (i ^ size)) );
ASSERT( T::construction_num == 2 * size, NULL );
ASSERT( T::destruction_num == size, NULL );
const T* locations[size];
typename CQ::const_iterator qit = src_queue.unsafe_begin();
for( size_t i = 0; i < size; ++i, ++qit )
locations[i] = &(*qit);
// Ensuring allocation operation takes place during move when allocators are different
CQ dst_queue( std::move(src_queue), allocator<T>(1) );
ASSERT( T::construction_num == 2 * size + size, NULL );
ASSERT( T::destruction_num == 2 * size + size, NULL );
TestQueueOperabilityAfterDataMove<T>( src_queue );
qit = dst_queue.unsafe_begin();
for( size_t i = 0; i < size; ++i, ++qit ) {
ASSERT( locations[i] != &(*qit), "item was not moved" );
locations[i] = &(*qit);
}
T::construction_num = T::destruction_num = 0;
// Ensuring there is no allocation operation during move with equal allocators
CQ dst_queue2( std::move(dst_queue), allocator<T>(1) );
ASSERT( T::construction_num == 0, NULL );
ASSERT( T::destruction_num == 0, NULL );
TestQueueOperabilityAfterDataMove<T>( dst_queue );
qit = dst_queue2.unsafe_begin();
for( size_t i = 0; i < size; ++i, ++qit ) {
ASSERT( locations[i] == &(*qit), "item was moved" );
}
for( size_t i = 0; i < size; ++i) {
T test(i + (i ^ size));
T popped;
bool pop_result = dst_queue2.try_pop( popped );
ASSERT( pop_result, NULL );
ASSERT( test == popped, NULL );
}
ASSERT( dst_queue2.empty(), NULL );
ASSERT( dst_queue2.size() == 0, NULL );
}
void TestMoveConstruction() {
REMARK("Testing move constructors with specified allocators...");
TestMoveConstructors< ConcQWithSizeWrapper< Bar, allocator<Bar> >, Bar >();
TestMoveConstructors< tbb::concurrent_bounded_queue< Bar, allocator<Bar> >, Bar >();
REMARK(" work\n");
}
#endif /* __TBB_CPP11_RVALUE_REF_PRESENT */
template<typename Iterator1, typename Iterator2>
void TestIteratorAux( Iterator1 i, Iterator2 j, int size ) {
// Now test iteration
Iterator1 old_i;
for( int k=0; k<size; ++k ) {
ASSERT( i!=j, NULL );
ASSERT( !(i==j), NULL );
Foo f;
if( k&1 ) {
// Test pre-increment
f = *old_i++;
// Test assignment
i = old_i;
} else {
// Test post-increment
f=*i++;
if( k<size-1 ) {
// Test "->"
ASSERT( k+2==i->serial, NULL );
}
// Test assignment
old_i = i;
}
ASSERT( k+1==f.serial, NULL );
}
ASSERT( !(i!=j), NULL );
ASSERT( i==j, NULL );
}
template<typename Iterator1, typename Iterator2>
void TestIteratorAssignment( Iterator2 j ) {
Iterator1 i(j);
ASSERT( i==j, NULL );
ASSERT( !(i!=j), NULL );
Iterator1 k;
k = j;
ASSERT( k==j, NULL );
ASSERT( !(k!=j), NULL );
}
template<typename Iterator, typename T>
void TestIteratorTraits() {
AssertSameType( static_cast<typename Iterator::difference_type*>(0), static_cast<ptrdiff_t*>(0) );
AssertSameType( static_cast<typename Iterator::value_type*>(0), static_cast<T*>(0) );
AssertSameType( static_cast<typename Iterator::pointer*>(0), static_cast<T**>(0) );
AssertSameType( static_cast<typename Iterator::iterator_category*>(0), static_cast<std::forward_iterator_tag*>(0) );
T x;
typename Iterator::reference xr = x;
typename Iterator::pointer xp = &x;
ASSERT( &xr==xp, NULL );
}
//! Test the iterators for concurrent_queue
template<typename CQ>
void TestIterator() {
CQ queue;
const CQ& const_queue = queue;
for( int j=0; j<500; ++j ) {
TestIteratorAux( queue.unsafe_begin() , queue.unsafe_end() , j );
TestIteratorAux( const_queue.unsafe_begin(), const_queue.unsafe_end(), j );
TestIteratorAux( const_queue.unsafe_begin(), queue.unsafe_end() , j );
TestIteratorAux( queue.unsafe_begin() , const_queue.unsafe_end(), j );
Foo f;
f.serial = j+1;
queue.push(f);
}
TestIteratorAssignment<typename CQ::const_iterator>( const_queue.unsafe_begin() );
TestIteratorAssignment<typename CQ::const_iterator>( queue.unsafe_begin() );
TestIteratorAssignment<typename CQ::iterator>( queue.unsafe_begin() );
TestIteratorTraits<typename CQ::const_iterator, const Foo>();
TestIteratorTraits<typename CQ::iterator, Foo>();
}
template<typename CQ>
void TestConcurrentQueueType() {
AssertSameType( typename CQ::value_type(), Foo() );
Foo f;
const Foo g;
typename CQ::reference r = f;
ASSERT( &r==&f, NULL );
ASSERT( !r.is_const(), NULL );
typename CQ::const_reference cr = g;
ASSERT( &cr==&g, NULL );
ASSERT( cr.is_const(), NULL );
}
template<typename CQ, typename T>
void TestEmptyQueue() {
const CQ queue;
ASSERT( queue.size()==0, NULL );
ASSERT( queue.capacity()>0, NULL );
ASSERT( size_t(queue.capacity())>=size_t(-1)/(sizeof(void*)+sizeof(T)), NULL );
}
template<typename CQ,typename T>
void TestFullQueue() {
for( int n=0; n<10; ++n ) {
T::clear_counters();
CQ queue;
queue.set_capacity(n);
for( int i=0; i<=n; ++i ) {
T f;
f.serial = i;
bool result = queue.try_push( f );
ASSERT( result==(i<n), NULL );
}
for( int i=0; i<=n; ++i ) {
T f;
bool result = queue.try_pop( f );
ASSERT( result==(i<n), NULL );
ASSERT( !result || f.serial==i, NULL );
}
ASSERT( T::get_n_constructed()==T::get_n_destroyed(), NULL );
}
}
template<typename CQ>
void TestClear() {
FooConstructed = 0;
FooDestroyed = 0;
const unsigned int n=5;
CQ queue;
const int q_capacity=10;
queue.set_capacity(q_capacity);
for( size_t i=0; i<n; ++i ) {
Foo f;
f.serial = int(i);
queue.push( f );
}
ASSERT( unsigned(queue.size())==n, NULL );
queue.clear();
ASSERT( queue.size()==0, NULL );
for( size_t i=0; i<n; ++i ) {
Foo f;
f.serial = int(i);
queue.push( f );
}
ASSERT( unsigned(queue.size())==n, NULL );
queue.clear();
ASSERT( queue.size()==0, NULL );
for( size_t i=0; i<n; ++i ) {
Foo f;
f.serial = int(i);
queue.push( f );
}
ASSERT( unsigned(queue.size())==n, NULL );
}
template<typename T>
struct TestNegativeQueueBody: NoAssign {
tbb::concurrent_bounded_queue<T>& queue;
const int nthread;
TestNegativeQueueBody( tbb::concurrent_bounded_queue<T>& q, int n ) : queue(q), nthread(n) {}
void operator()( int k ) const {
if( k==0 ) {
int number_of_pops = nthread-1;
// Wait for all pops to pend.
while( queue.size()>-number_of_pops ) {
__TBB_Yield();
}
for( int i=0; ; ++i ) {
ASSERT( queue.size()==i-number_of_pops, NULL );
ASSERT( queue.empty()==(queue.size()<=0), NULL );
if( i==number_of_pops ) break;
// Satisfy another pop
queue.push( T() );
}
} else {
// Pop item from queue
T item;
queue.pop(item);
}
}
};
//! Test a queue with a negative size.
template<typename T>
void TestNegativeQueue( int nthread ) {
tbb::concurrent_bounded_queue<T> queue;
NativeParallelFor( nthread, TestNegativeQueueBody<T>(queue,nthread) );
}
#if TBB_USE_EXCEPTIONS
template<typename CQ,typename A1,typename A2,typename T>
void TestExceptionBody() {
enum methods {
m_push = 0,
m_pop
};
REMARK("Testing exception safety\n");
MaxFooCount = 5;
// verify 'clear()' on exception; queue's destructor calls its clear()
// Do test on queues of two different types at the same time to
// catch problem with incorrect sharing between templates.
{
CQ queue0;
tbb::concurrent_queue<int,A1> queue1;
for( int i=0; i<2; ++i ) {
bool caught = false;
try {
A2::init_counters();
A2::set_limits(N/2);
for( int k=0; k<N; k++ ) {
if( i==0 )
push(queue0, T(), i);
else
queue1.push( k );
}
} catch (...) {
caught = true;
}
ASSERT( caught, "call to push should have thrown exception" );
}
}
REMARK("... queue destruction test passed\n");
try {
int n_pushed=0, n_popped=0;
for(int t = 0; t <= 1; t++)// exception type -- 0 : from allocator(), 1 : from Foo's constructor
{
CQ queue_test;
for( int m=m_push; m<=m_pop; m++ ) {
// concurrent_queue internally rebinds the allocator to one with 'char'
A2::init_counters();
if(t) MaxFooCount = MaxFooCount + 400;
else A2::set_limits(N/2);
try {
switch(m) {
case m_push:
for( int k=0; k<N; k++ ) {
push( queue_test, T(), k );
n_pushed++;
}
break;
case m_pop:
n_popped=0;
for( int k=0; k<n_pushed; k++ ) {
T elt;
queue_test.try_pop( elt );
n_popped++;
}
n_pushed = 0;
A2::set_limits();
break;
}
if( !t && m==m_push ) ASSERT(false, "should throw an exception");
} catch ( Foo_exception & ) {
switch(m) {
case m_push: {
ASSERT( ptrdiff_t(queue_test.size())==n_pushed, "incorrect queue size" );
long tc = MaxFooCount;
MaxFooCount = 0;
for( int k=0; k<(int)tc; k++ ) {
push( queue_test, T(), k );
n_pushed++;
}
MaxFooCount = tc;
}
break;
case m_pop:
MaxFooCount = 0; // disable exception
n_pushed -= (n_popped+1); // including one that threw an exception
ASSERT( n_pushed>=0, "n_pushed cannot be less than 0" );
for( int k=0; k<1000; k++ ) {
push( queue_test, T(), k );
n_pushed++;
}
ASSERT( !queue_test.empty(), "queue must not be empty" );
ASSERT( ptrdiff_t(queue_test.size())==n_pushed, "queue size must be equal to n pushed" );
for( int k=0; k<n_pushed; k++ ) {
T elt;
queue_test.try_pop( elt );
}
ASSERT( queue_test.empty(), "queue must be empty" );
ASSERT( queue_test.size()==0, "queue must be empty" );
break;
}
} catch ( std::bad_alloc & ) {
A2::set_limits(); // disable exception from allocator
size_t size = queue_test.size();
switch(m) {
case m_push:
ASSERT( size>0, "incorrect queue size");
break;
case m_pop:
if( !t ) ASSERT( false, "should not throw an exceptin" );
break;
}
}
REMARK("... for t=%d and m=%d, exception test passed\n", t, m);
}
}
} catch(...) {
ASSERT(false, "unexpected exception");
}
}
#endif /* TBB_USE_EXCEPTIONS */
void TestExceptions() {
#if __TBB_THROW_ACROSS_MODULE_BOUNDARY_BROKEN
REPORT("Known issue: exception safety test is skipped.\n");
#elif TBB_USE_EXCEPTIONS
typedef static_counting_allocator<std::allocator<FooEx>, size_t> allocator_t;
typedef static_counting_allocator<std::allocator<char>, size_t> allocator_char_t;
TestExceptionBody<ConcQWithSizeWrapper<FooEx, allocator_t>,allocator_t,allocator_char_t,FooEx>();
TestExceptionBody<tbb::concurrent_bounded_queue<FooEx, allocator_t>,allocator_t,allocator_char_t,FooEx>();
#endif /* TBB_USE_EXCEPTIONS */
}
template<typename CQ, typename T>
struct TestQueueElements: NoAssign {
CQ& queue;
const int nthread;
TestQueueElements( CQ& q, int n ) : queue(q), nthread(n) {}
void operator()( int k ) const {
for( int i=0; i<1000; ++i ) {
if( (i&0x1)==0 ) {
ASSERT( T(k)<T(nthread), NULL );
queue.push( T(k) );
} else {
// Pop item from queue
T item = 0;
queue.try_pop(item);
ASSERT( item<=T(nthread), NULL );
}
}
}
};
//! Test concurrent queue with primitive data type
template<typename CQ, typename T>
void TestPrimitiveTypes( int nthread, T exemplar )
{
CQ queue;
for( int i=0; i<100; ++i )
queue.push( exemplar );
NativeParallelFor( nthread, TestQueueElements<CQ,T>(queue,nthread) );
}
#include "harness_m128.h"
#if HAVE_m128 || HAVE_m256
//! Test concurrent queue with vector types
/** Type Queue should be a queue of ClassWithSSE/ClassWithAVX. */
template<typename ClassWithVectorType, typename Queue>
void TestVectorTypes() {
Queue q1;
for( int i=0; i<100; ++i ) {
// VC8 does not properly align a temporary value; to work around, use explicit variable
ClassWithVectorType bar(i);
q1.push(bar);
}
// Copy the queue
Queue q2 = q1;
// Check that elements of the copy are correct
typename Queue::const_iterator ci = q2.unsafe_begin();
for( int i=0; i<100; ++i ) {
ClassWithVectorType foo = *ci;
ClassWithVectorType bar(i);
ASSERT( *ci==bar, NULL );
++ci;
}
for( int i=0; i<101; ++i ) {
ClassWithVectorType tmp;
bool b = q1.try_pop( tmp );
ASSERT( b==(i<100), NULL );
ClassWithVectorType bar(i);
ASSERT( !b || tmp==bar, NULL );
}
}
#endif /* HAVE_m128 || HAVE_m256 */
void TestEmptiness()
{
REMARK(" Test Emptiness\n");
TestEmptyQueue<ConcQWithCapacity<char>, char>();
TestEmptyQueue<ConcQWithCapacity<Foo>, Foo>();
TestEmptyQueue<tbb::concurrent_bounded_queue<char>, char>();
TestEmptyQueue<tbb::concurrent_bounded_queue<Foo>, Foo>();
}
void TestFullness()
{
REMARK(" Test Fullness\n");
TestFullQueue<ConcQWithCapacity<Foo>,Foo>();
TestFullQueue<tbb::concurrent_bounded_queue<Foo>,Foo>();
}
void TestClearWorks()
{
REMARK(" Test concurrent_queue::clear() works\n");
TestClear<ConcQWithCapacity<Foo> >();
TestClear<tbb::concurrent_bounded_queue<Foo> >();
}
void TestQueueTypeDeclaration()
{
REMARK(" Test concurrent_queue's types work\n");
TestConcurrentQueueType<tbb::concurrent_queue<Foo> >();
TestConcurrentQueueType<tbb::concurrent_bounded_queue<Foo> >();
}
void TestQueueIteratorWorks()
{
REMARK(" Test concurrent_queue's iterators work\n");
TestIterator<tbb::concurrent_queue<Foo> >();
TestIterator<tbb::concurrent_bounded_queue<Foo> >();
}
#if TBB_USE_EXCEPTIONS
#define BAR_EX BarEx
#else
#define BAR_EX Empty /* passed as template arg but should not be used */
#endif
class Empty;
void TestQueueConstructors()
{
REMARK(" Test concurrent_queue's constructors work\n");
TestConstructors<ConcQWithSizeWrapper<Bar>,Bar,BarIterator,ConcQWithSizeWrapper<BAR_EX>,BAR_EX>();
TestConstructors<tbb::concurrent_bounded_queue<Bar>,Bar,BarIterator,tbb::concurrent_bounded_queue<BAR_EX>,BAR_EX>();
}
void TestQueueWorksWithPrimitiveTypes()
{
REMARK(" Test concurrent_queue works with primitive types\n");
TestPrimitiveTypes<tbb::concurrent_queue<char>, char>( MaxThread, (char)1 );
TestPrimitiveTypes<tbb::concurrent_queue<int>, int>( MaxThread, (int)-12 );
TestPrimitiveTypes<tbb::concurrent_queue<float>, float>( MaxThread, (float)-1.2f );
TestPrimitiveTypes<tbb::concurrent_queue<double>, double>( MaxThread, (double)-4.3 );
TestPrimitiveTypes<tbb::concurrent_bounded_queue<char>, char>( MaxThread, (char)1 );
TestPrimitiveTypes<tbb::concurrent_bounded_queue<int>, int>( MaxThread, (int)-12 );
TestPrimitiveTypes<tbb::concurrent_bounded_queue<float>, float>( MaxThread, (float)-1.2f );
TestPrimitiveTypes<tbb::concurrent_bounded_queue<double>, double>( MaxThread, (double)-4.3 );
}
void TestQueueWorksWithSSE()
{
REMARK(" Test concurrent_queue works with SSE data\n");
#if HAVE_m128
TestVectorTypes<ClassWithSSE, tbb::concurrent_queue<ClassWithSSE> >();
TestVectorTypes<ClassWithSSE, tbb::concurrent_bounded_queue<ClassWithSSE> >();
#endif /* HAVE_m128 */
#if HAVE_m256
if( have_AVX() ) {
TestVectorTypes<ClassWithAVX, tbb::concurrent_queue<ClassWithAVX> >();
TestVectorTypes<ClassWithAVX, tbb::concurrent_bounded_queue<ClassWithAVX> >();
}
#endif /* HAVE_m256 */
}
void TestConcurrentPushPop()
{
REMARK(" Test concurrent_queue's concurrent push and pop\n");
for( int nthread=MinThread; nthread<=MaxThread; ++nthread ) {
REMARK(" Testing with %d thread(s)\n", nthread );
TestNegativeQueue<Foo>(nthread);
for( size_t prefill=0; prefill<64; prefill+=(1+prefill/3) ) {
TestPushPop<ConcQPushPopWrapper<Foo>,Foo>(prefill,ptrdiff_t(-1),nthread);
TestPushPop<ConcQPushPopWrapper<Foo>,Foo>(prefill,ptrdiff_t(1),nthread);
TestPushPop<ConcQPushPopWrapper<Foo>,Foo>(prefill,ptrdiff_t(2),nthread);
TestPushPop<ConcQPushPopWrapper<Foo>,Foo>(prefill,ptrdiff_t(10),nthread);
TestPushPop<ConcQPushPopWrapper<Foo>,Foo>(prefill,ptrdiff_t(100),nthread);
}
for( size_t prefill=0; prefill<64; prefill+=(1+prefill/3) ) {
TestPushPop<tbb::concurrent_bounded_queue<Foo>,Foo>(prefill,ptrdiff_t(-1),nthread);
TestPushPop<tbb::concurrent_bounded_queue<Foo>,Foo>(prefill,ptrdiff_t(1),nthread);
TestPushPop<tbb::concurrent_bounded_queue<Foo>,Foo>(prefill,ptrdiff_t(2),nthread);
TestPushPop<tbb::concurrent_bounded_queue<Foo>,Foo>(prefill,ptrdiff_t(10),nthread);
TestPushPop<tbb::concurrent_bounded_queue<Foo>,Foo>(prefill,ptrdiff_t(100),nthread);
}
}
}
#if TBB_USE_EXCEPTIONS
tbb::atomic<size_t> num_pushed;
tbb::atomic<size_t> num_popped;
tbb::atomic<size_t> failed_pushes;
tbb::atomic<size_t> failed_pops;
class SimplePushBody {
tbb::concurrent_bounded_queue<int>* q;
int max;
public:
SimplePushBody(tbb::concurrent_bounded_queue<int>* _q, int hi_thr) : q(_q), max(hi_thr) {}
void operator()(int thread_id) const {
if (thread_id == max) {
Harness::Sleep(50);
q->abort();
return;
}
try {
q->push(42);
++num_pushed;
} catch ( tbb::user_abort& ) {
++failed_pushes;
}
}
};
class SimplePopBody {
tbb::concurrent_bounded_queue<int>* q;
int max;
public:
SimplePopBody(tbb::concurrent_bounded_queue<int>* _q, int hi_thr) : q(_q), max(hi_thr) {}
void operator()(int thread_id) const {
int e;
if (thread_id == max) {
Harness::Sleep(50);
q->abort();
return;
}
try {
q->pop(e);
++num_popped;
} catch ( tbb::user_abort& ) {
++failed_pops;
}
}
};
#endif /* TBB_USE_EXCEPTIONS */
void TestAbort() {
#if TBB_USE_EXCEPTIONS
for (int nthreads=MinThread; nthreads<=MaxThread; ++nthreads) {
REMARK("Testing Abort on %d thread(s).\n", nthreads);
REMARK("...testing pushing to zero-sized queue\n");
tbb::concurrent_bounded_queue<int> iq1;
iq1.set_capacity(0);
for (int i=0; i<10; ++i) {
num_pushed = num_popped = failed_pushes = failed_pops = 0;
SimplePushBody my_push_body1(&iq1, nthreads);
NativeParallelFor( nthreads+1, my_push_body1 );
ASSERT(num_pushed == 0, "no elements should have been pushed to zero-sized queue");
ASSERT((int)failed_pushes == nthreads, "All threads should have failed to push an element to zero-sized queue");
}
REMARK("...testing pushing to small-sized queue\n");
tbb::concurrent_bounded_queue<int> iq2;
iq2.set_capacity(2);
for (int i=0; i<10; ++i) {
num_pushed = num_popped = failed_pushes = failed_pops = 0;
SimplePushBody my_push_body2(&iq2, nthreads);
NativeParallelFor( nthreads+1, my_push_body2 );
ASSERT(num_pushed <= 2, "at most 2 elements should have been pushed to queue of size 2");
if (nthreads >= 2)
ASSERT((int)failed_pushes == nthreads-2, "nthreads-2 threads should have failed to push an element to queue of size 2");
int e;
while (iq2.try_pop(e)) ;
}
REMARK("...testing popping from small-sized queue\n");
tbb::concurrent_bounded_queue<int> iq3;
iq3.set_capacity(2);
for (int i=0; i<10; ++i) {
num_pushed = num_popped = failed_pushes = failed_pops = 0;
iq3.push(42);
iq3.push(42);
SimplePopBody my_pop_body(&iq3, nthreads);
NativeParallelFor( nthreads+1, my_pop_body);
ASSERT(num_popped <= 2, "at most 2 elements should have been popped from queue of size 2");
if (nthreads >= 2)
ASSERT((int)failed_pops == nthreads-2, "nthreads-2 threads should have failed to pop an element from queue of size 2");
else {
int e;
iq3.pop(e);
}
}
REMARK("...testing pushing and popping from small-sized queue\n");
tbb::concurrent_bounded_queue<int> iq4;
int cap = nthreads/2;
if (!cap) cap=1;
iq4.set_capacity(cap);
for (int i=0; i<10; ++i) {
num_pushed = num_popped = failed_pushes = failed_pops = 0;
SimplePushBody my_push_body2(&iq4, nthreads);
NativeParallelFor( nthreads+1, my_push_body2 );
ASSERT((int)num_pushed <= cap, "at most cap elements should have been pushed to queue of size cap");
if (nthreads >= cap)
ASSERT((int)failed_pushes == nthreads-cap, "nthreads-cap threads should have failed to push an element to queue of size cap");
SimplePopBody my_pop_body(&iq4, nthreads);
NativeParallelFor( nthreads+1, my_pop_body);
ASSERT((int)num_popped <= cap, "at most cap elements should have been popped from queue of size cap");
if (nthreads >= cap)
ASSERT((int)failed_pops == nthreads-cap, "nthreads-cap threads should have failed to pop an element from queue of size cap");
else {
int e;
while (iq4.try_pop(e)) ;
}
}
}
#endif
}
#if __TBB_CPP11_RVALUE_REF_PRESENT
struct MoveOperationTracker {
static size_t copy_constructor_called_times;
static size_t move_constructor_called_times;
static size_t copy_assignment_called_times;
static size_t move_assignment_called_times;
MoveOperationTracker() {}
MoveOperationTracker(const MoveOperationTracker&) {
++copy_constructor_called_times;
}
MoveOperationTracker(MoveOperationTracker&&) {
++move_constructor_called_times;
}
MoveOperationTracker& operator=(MoveOperationTracker const&) {
++copy_assignment_called_times;
return *this;
}
MoveOperationTracker& operator=(MoveOperationTracker&&) {
++move_assignment_called_times;
return *this;
}
};
size_t MoveOperationTracker::copy_constructor_called_times = 0;
size_t MoveOperationTracker::move_constructor_called_times = 0;
size_t MoveOperationTracker::copy_assignment_called_times = 0;
size_t MoveOperationTracker::move_assignment_called_times = 0;
template <class CQ, push_t push_op, pop_t pop_op>
void TestMoveSupport() {
size_t &mcct = MoveOperationTracker::move_constructor_called_times;
size_t &ccct = MoveOperationTracker::copy_constructor_called_times;
size_t &cact = MoveOperationTracker::copy_assignment_called_times;
size_t &mact = MoveOperationTracker::move_assignment_called_times;
mcct = ccct = cact = mact = 0;
CQ q;
ASSERT(mcct == 0, "Value must be zero-initialized");
ASSERT(ccct == 0, "Value must be zero-initialized");
ASSERT(pusher<push_op>::push( q, MoveOperationTracker() ), NULL);
ASSERT(mcct == 1, "Not working push(T&&) or try_push(T&&)?");
ASSERT(ccct == 0, "Copying of arg occurred during push(T&&) or try_push(T&&)");
MoveOperationTracker ob;
ASSERT(pusher<push_op>::push( q, std::move(ob) ), NULL);
ASSERT(mcct == 2, "Not working push(T&&) or try_push(T&&)?");
ASSERT(ccct == 0, "Copying of arg occurred during push(T&&) or try_push(T&&)");
ASSERT(cact == 0, "Copy assignment called during push(T&&) or try_push(T&&)");
ASSERT(mact == 0, "Move assignment called during push(T&&) or try_push(T&&)");
bool result = popper<pop_op>::pop( q, ob );
ASSERT(result, NULL);
ASSERT(cact == 0, "Copy assignment called during try_pop(T&&)");
ASSERT(mact == 1, "Move assignment was not called during try_pop(T&&)");
}
void TestMoveSupportInPushPop() {
REMARK("Testing Move Support in Push/Pop...");
TestMoveSupport< tbb::concurrent_queue<MoveOperationTracker>, push_op, try_pop_op >();
TestMoveSupport< tbb::concurrent_bounded_queue<MoveOperationTracker>, push_op, pop_op >();
TestMoveSupport< tbb::concurrent_bounded_queue<MoveOperationTracker>, try_push_op, try_pop_op >();
REMARK(" works.\n");
}
#if __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT
class NonTrivialConstructorType {
public:
NonTrivialConstructorType( int a = 0 ) : m_a( a ), m_str( "" ) {}
NonTrivialConstructorType( const std::string& str ) : m_a( 0 ), m_str( str ) {}
NonTrivialConstructorType( int a, const std::string& str ) : m_a( a ), m_str( str ) {}
int get_a() const { return m_a; }
std::string get_str() const { return m_str; }
private:
int m_a;
std::string m_str;
};
enum emplace_t { emplace_op, try_emplace_op };
template< emplace_t emplace_op >
struct emplacer {
template< typename CQ, typename... Args>
static void emplace( CQ& queue, Args&&... val ) { queue.emplace( std::forward<Args>( val )... ); }
};
template<>
struct emplacer< try_emplace_op > {
template<typename CQ, typename... Args>
static void emplace( CQ& queue, Args&&... val ) {
bool result = queue.try_emplace( std::forward<Args>( val )... );
ASSERT( result, "try_emplace error\n" );
}
};
template<typename CQ, emplace_t emplace_op>
void TestEmplaceInQueue() {
CQ cq;
std::string test_str = "I'm being emplaced!";
{
emplacer<emplace_op>::emplace( cq, 5 );
ASSERT( cq.size() == 1, NULL );
NonTrivialConstructorType popped( -1 );
bool result = cq.try_pop( popped );
ASSERT( result, NULL );
ASSERT( popped.get_a() == 5, NULL );
ASSERT( popped.get_str() == std::string( "" ), NULL );
}
ASSERT( cq.empty(), NULL );
{
NonTrivialConstructorType popped( -1 );
emplacer<emplace_op>::emplace( cq, std::string(test_str) );
bool result = cq.try_pop( popped );
ASSERT( result, NULL );
ASSERT( popped.get_a() == 0, NULL );
ASSERT( popped.get_str() == test_str, NULL );
}
ASSERT( cq.empty(), NULL );
{
NonTrivialConstructorType popped( -1, "" );
emplacer<emplace_op>::emplace( cq, 5, std::string(test_str) );
bool result = cq.try_pop( popped );
ASSERT( result, NULL );
ASSERT( popped.get_a() == 5, NULL );
ASSERT( popped.get_str() == test_str, NULL );
}
}
void TestEmplace() {
REMARK("Testing support for 'emplace' method...");
TestEmplaceInQueue< ConcQWithSizeWrapper<NonTrivialConstructorType>, emplace_op >();
TestEmplaceInQueue< tbb::concurrent_bounded_queue<NonTrivialConstructorType>, emplace_op >();
TestEmplaceInQueue< tbb::concurrent_bounded_queue<NonTrivialConstructorType>, try_emplace_op >();
REMARK(" works.\n");
}
#endif /* __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT */
#endif /* __TBB_CPP11_RVALUE_REF_PRESENT */
template <typename Queue>
void Examine(Queue q, const std::vector<typename Queue::value_type> &vec) {
typedef typename Queue::value_type value_type;
AssertEquality(q, vec);
const Queue cq = q;
AssertEquality(cq, vec);
q.clear();
AssertEmptiness(q);
FillTest<push_op>(q, vec);
EmptyTest<try_pop_op>(q, vec);
bounded_queue_specific_test(q, vec);
typename Queue::allocator_type a = q.get_allocator();
value_type *ptr = a.allocate(1);
ASSERT(ptr, NULL);
a.deallocate(ptr, 1);
}
template <typename Queue, typename QueueDebugAlloc>
void TypeTester(const std::vector<typename Queue::value_type> &vec) {
typedef typename std::vector<typename Queue::value_type>::const_iterator iterator;
ASSERT(vec.size() >= 5, "Array should have at least 5 elements");
// Construct an empty queue.
Queue q1;
for (iterator it = vec.begin(); it != vec.end(); ++it) q1.push(*it);
Examine(q1, vec);
// Copying constructor.
Queue q3(q1);
Examine(q3, vec);
// Construct with non-default allocator.
QueueDebugAlloc q4;
for (iterator it = vec.begin(); it != vec.end(); ++it) q4.push(*it);
Examine(q4, vec);
// Copying constructor with the same allocator type.
QueueDebugAlloc q5(q4);
Examine(q5, vec);
// Construction with given allocator instance.
typename QueueDebugAlloc::allocator_type a;
QueueDebugAlloc q6(a);
for (iterator it = vec.begin(); it != vec.end(); ++it) q6.push(*it);
Examine(q6, vec);
// Construction with copying iteration range and given allocator instance.
QueueDebugAlloc q7(q1.unsafe_begin(), q1.unsafe_end(), a);
Examine<QueueDebugAlloc>(q7, vec);
}
template <typename value_type>
void TestTypes(const std::vector<value_type> &vec) {
TypeTester< ConcQWithSizeWrapper<value_type>, ConcQWithSizeWrapper<value_type, debug_allocator<value_type> > >(vec);
TypeTester< tbb::concurrent_bounded_queue<value_type>, tbb::concurrent_bounded_queue<value_type, debug_allocator<value_type> > >(vec);
}
void TestTypes() {
const int NUMBER = 10;
std::vector<int> arrInt;
for (int i = 0; i < NUMBER; ++i) arrInt.push_back(i);
std::vector< tbb::atomic<int> > arrTbb;
for (int i = 0; i < NUMBER; ++i) {
tbb::atomic<int> a;
a = i;
arrTbb.push_back(a);
}
TestTypes(arrInt);
TestTypes(arrTbb);
#if __TBB_CPP11_SMART_POINTERS_PRESENT
std::vector< std::shared_ptr<int> > arrShr;
for (int i = 0; i < NUMBER; ++i) arrShr.push_back(std::make_shared<int>(i));
std::vector< std::weak_ptr<int> > arrWk;
std::copy(arrShr.begin(), arrShr.end(), std::back_inserter(arrWk));
TestTypes(arrShr);
TestTypes(arrWk);
#else
REPORT("Known issue: C++11 smart pointer tests are skipped.\n");
#endif /* __TBB_CXX11_TYPES_PRESENT */
}
int TestMain () {
TestEmptiness();
TestFullness();
TestClearWorks();
TestQueueTypeDeclaration();
TestQueueIteratorWorks();
TestQueueConstructors();
TestQueueWorksWithPrimitiveTypes();
TestQueueWorksWithSSE();
// Test concurrent operations
TestConcurrentPushPop();
TestExceptions();
TestAbort();
#if __TBB_CPP11_RVALUE_REF_PRESENT
TestMoveSupportInPushPop();
TestMoveConstruction();
#if __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT
TestEmplace();
#endif /* __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT */
#endif /* __TBB_CPP11_RVALUE_REF_PRESENT */
TestTypes();
return Harness::Done;
}
| rutgers-apl/TaskProf | tprof-tbb-lib/src/test/test_concurrent_queue.cpp | C++ | mit | 59,098 |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.CosmosDB.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// The access keys for the given database account.
/// </summary>
public partial class DatabaseAccountListKeysResult : DatabaseAccountListReadOnlyKeysResult
{
/// <summary>
/// Initializes a new instance of the DatabaseAccountListKeysResult
/// class.
/// </summary>
public DatabaseAccountListKeysResult()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the DatabaseAccountListKeysResult
/// class.
/// </summary>
/// <param name="primaryReadonlyMasterKey">Base 64 encoded value of the
/// primary read-only key.</param>
/// <param name="secondaryReadonlyMasterKey">Base 64 encoded value of
/// the secondary read-only key.</param>
/// <param name="primaryMasterKey">Base 64 encoded value of the primary
/// read-write key.</param>
/// <param name="secondaryMasterKey">Base 64 encoded value of the
/// secondary read-write key.</param>
public DatabaseAccountListKeysResult(string primaryReadonlyMasterKey = default(string), string secondaryReadonlyMasterKey = default(string), string primaryMasterKey = default(string), string secondaryMasterKey = default(string))
: base(primaryReadonlyMasterKey, secondaryReadonlyMasterKey)
{
PrimaryMasterKey = primaryMasterKey;
SecondaryMasterKey = secondaryMasterKey;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets base 64 encoded value of the primary read-write key.
/// </summary>
[JsonProperty(PropertyName = "primaryMasterKey")]
public string PrimaryMasterKey { get; private set; }
/// <summary>
/// Gets base 64 encoded value of the secondary read-write key.
/// </summary>
[JsonProperty(PropertyName = "secondaryMasterKey")]
public string SecondaryMasterKey { get; private set; }
}
}
| ayeletshpigelman/azure-sdk-for-net | sdk/cosmosdb/Microsoft.Azure.Management.CosmosDB/src/Generated/Models/DatabaseAccountListKeysResult.cs | C# | mit | 2,628 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Paul Sokolovsky
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <assert.h>
#include <string.h>
#include "py/nlr.h"
#include "py/runtime.h"
#if MICROPY_PY_UHASHLIB
#include "crypto-algorithms/sha256.h"
#if MICROPY_PY_UHASHLIB_SHA1
#include "lib/axtls/crypto/crypto.h"
#endif
typedef struct _mp_obj_hash_t {
mp_obj_base_t base;
char state[0];
} mp_obj_hash_t;
STATIC mp_obj_t hash_update(mp_obj_t self_in, mp_obj_t arg);
STATIC mp_obj_t hash_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
mp_arg_check_num(n_args, n_kw, 0, 1, false);
mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(CRYAL_SHA256_CTX));
o->base.type = type;
sha256_init((CRYAL_SHA256_CTX*)o->state);
if (n_args == 1) {
hash_update(MP_OBJ_FROM_PTR(o), args[0]);
}
return MP_OBJ_FROM_PTR(o);
}
#if MICROPY_PY_UHASHLIB_SHA1
STATIC mp_obj_t sha1_update(mp_obj_t self_in, mp_obj_t arg);
STATIC mp_obj_t sha1_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
mp_arg_check_num(n_args, n_kw, 0, 1, false);
mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(SHA1_CTX));
o->base.type = type;
SHA1_Init((SHA1_CTX*)o->state);
if (n_args == 1) {
sha1_update(MP_OBJ_FROM_PTR(o), args[0]);
}
return MP_OBJ_FROM_PTR(o);
}
#endif
STATIC mp_obj_t hash_update(mp_obj_t self_in, mp_obj_t arg) {
mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ);
sha256_update((CRYAL_SHA256_CTX*)self->state, bufinfo.buf, bufinfo.len);
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(hash_update_obj, hash_update);
#if MICROPY_PY_UHASHLIB_SHA1
STATIC mp_obj_t sha1_update(mp_obj_t self_in, mp_obj_t arg) {
mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ);
SHA1_Update((SHA1_CTX*)self->state, bufinfo.buf, bufinfo.len);
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(sha1_update_obj, sha1_update);
#endif
STATIC mp_obj_t hash_digest(mp_obj_t self_in) {
mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
vstr_t vstr;
vstr_init_len(&vstr, SHA256_BLOCK_SIZE);
sha256_final((CRYAL_SHA256_CTX*)self->state, (byte*)vstr.buf);
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
}
MP_DEFINE_CONST_FUN_OBJ_1(hash_digest_obj, hash_digest);
#if MICROPY_PY_UHASHLIB_SHA1
STATIC mp_obj_t sha1_digest(mp_obj_t self_in) {
mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
vstr_t vstr;
vstr_init_len(&vstr, SHA1_SIZE);
SHA1_Final((byte*)vstr.buf, (SHA1_CTX*)self->state);
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
}
MP_DEFINE_CONST_FUN_OBJ_1(sha1_digest_obj, sha1_digest);
#endif
STATIC const mp_rom_map_elem_t hash_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_update), MP_ROM_PTR(&hash_update_obj) },
{ MP_ROM_QSTR(MP_QSTR_digest), MP_ROM_PTR(&hash_digest_obj) },
};
STATIC MP_DEFINE_CONST_DICT(hash_locals_dict, hash_locals_dict_table);
STATIC const mp_obj_type_t sha256_type = {
{ &mp_type_type },
.name = MP_QSTR_sha256,
.make_new = hash_make_new,
.locals_dict = (void*)&hash_locals_dict,
};
#if MICROPY_PY_UHASHLIB_SHA1
STATIC const mp_rom_map_elem_t sha1_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_update), MP_ROM_PTR(&sha1_update_obj) },
{ MP_ROM_QSTR(MP_QSTR_digest), MP_ROM_PTR(&sha1_digest_obj) },
};
STATIC MP_DEFINE_CONST_DICT(sha1_locals_dict, sha1_locals_dict_table);
STATIC const mp_obj_type_t sha1_type = {
{ &mp_type_type },
.name = MP_QSTR_sha1,
.make_new = sha1_make_new,
.locals_dict = (void*)&sha1_locals_dict,
};
#endif
STATIC const mp_rom_map_elem_t mp_module_hashlib_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uhashlib) },
{ MP_ROM_QSTR(MP_QSTR_sha256), MP_ROM_PTR(&sha256_type) },
#if MICROPY_PY_UHASHLIB_SHA1
{ MP_ROM_QSTR(MP_QSTR_sha1), MP_ROM_PTR(&sha1_type) },
#endif
};
STATIC MP_DEFINE_CONST_DICT(mp_module_hashlib_globals, mp_module_hashlib_globals_table);
const mp_obj_module_t mp_module_uhashlib = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_hashlib_globals,
};
#include "crypto-algorithms/sha256.c"
#endif //MICROPY_PY_UHASHLIB
| ignorabimus/micropython-c-api | micropython/extmod/moduhashlib.c | C | mit | 5,524 |
//
// NSString+XHLaunchAd.h
// XHLaunchAdExample
//
// Created by zhuxiaohui on 2016/6/26.
// Copyright © 2016年 it7090.com. All rights reserved.
// 代码地址:https://github.com/CoderZhuXH/XHLaunchAd
#import <Foundation/Foundation.h>
@interface NSString (XHLaunchAd)
@property(nonatomic,assign,readonly)BOOL xh_isURLString;
@property(nonatomic,copy,readonly,nonnull)NSString *xh_videoName;
@property(nonatomic,copy,readonly,nonnull)NSString *xh_md5String;
-(BOOL)xh_containsSubString:(nonnull NSString *)subString;
@end
| zc150815/ired6-1.0.0 | ired6 1.0.0/ired6/Classes/Others/Tools/XHLaunchAd/NSString+XHLaunchAd.h | C | mit | 537 |
package net
import (
"io"
)
const (
bufferSize = 4 * 1024
)
// ReaderToChan dumps all content from a given reader to a chan by constantly reading it until EOF.
func ReaderToChan(stream chan<- []byte, reader io.Reader) error {
for {
buffer := make([]byte, bufferSize)
nBytes, err := reader.Read(buffer)
if nBytes > 0 {
stream <- buffer[:nBytes]
}
if err != nil {
return err
}
}
}
// ChanToWriter dumps all content from a given chan to a writer until the chan is closed.
func ChanToWriter(writer io.Writer, stream <-chan []byte) error {
for buffer := range stream {
_, err := writer.Write(buffer)
if err != nil {
return err
}
}
return nil
}
| larryeee/v2ray-core | common/net/transport.go | GO | mit | 677 |
{{<div}}
{{$div}}
{{>template}}
{{/div}}
{{/div}} | xuvw/GRMustache | src/tests/Public/v7.0/Suites/spullara:mustache.java/GRMustacheJavaSuites/partialsubpartial.html | HTML | mit | 49 |
using System;
using System.Collections.Generic;
namespace Orleans.Providers.Streams.Common
{
/// <summary>
/// Object pool that roughly ensures only a specified number of the objects are allowed to be allocated.
/// When more objects are allocated then is specified, previously allocated objects will be signaled to be purged in order.
/// When objects are signaled, they should be returned to the pool. How this is done is an implementation
/// detail of the object.
/// </summary>
/// <typeparam name="T"></typeparam>
public class FixedSizeObjectPool<T> : ObjectPool<T>
where T : PooledResource<T>
{
private const int MinObjectCount = 3; // 1MB
/// <summary>
/// Queue of objects that have been allocated and are currently in use.
/// Tracking these is necessary for keeping a fixed size. These are used to reclaim allocated resources
/// by signaling purges which should eventually return the resource to the pool.
/// Protected for test reasons
/// </summary>
protected readonly Queue<T> usedObjects = new Queue<T>();
private readonly object locker = new object();
private readonly int maxObjectCount;
/// <summary>
/// Manages a memory pool of poolSize blocks.
/// Whenever we've allocated more blocks than the poolSize, we signal the oldest allocated block to purge
/// itself and return to the pool.
/// </summary>
/// <param name="poolSize"></param>
/// <param name="factoryFunc"></param>
public FixedSizeObjectPool(int poolSize, Func<T> factoryFunc)
: base(factoryFunc, poolSize)
{
if (poolSize < MinObjectCount)
{
throw new ArgumentOutOfRangeException("poolSize", "Minimum object count is " + MinObjectCount);
}
maxObjectCount = poolSize;
}
/// <summary>
/// Allocates a resource from the pool.
/// </summary>
/// <returns></returns>
public override T Allocate()
{
T obj;
lock (locker)
{
// if we've used all we are allowed, signal object it has been purged and should be returned to the pool
if (usedObjects.Count >= maxObjectCount)
{
usedObjects.Dequeue().SignalPurge();
}
obj = base.Allocate();
// track used objects
usedObjects.Enqueue(obj);
}
return obj;
}
/// <summary>
/// Returns a resource to the pool to be reused
/// </summary>
/// <param name="resource"></param>
public override void Free(T resource)
{
lock (locker)
{
base.Free(resource);
}
}
}
}
| shlomiw/orleans | src/OrleansProviders/Streams/Common/PooledCache/FixedSizeObjectPool.cs | C# | mit | 2,936 |
'use strict';
var BigNumber = require('../../type/BigNumber');
var Range = require('../../type/Range');
var Index = require('../../type/Index');
var isNumber = require('../../util/number').isNumber;
/**
* Attach a transform function to math.index
* Adds a property transform containing the transform function.
*
* This transform creates a one-based index instead of a zero-based index
* @param {Object} math
*/
module.exports = function (math) {
var transform = function () {
var args = [];
for (var i = 0, ii = arguments.length; i < ii; i++) {
var arg = arguments[i];
// change from one-based to zero based, and convert BigNumber to number
if (arg instanceof Range) {
arg.start--;
arg.end -= (arg.step > 0 ? 0 : 2);
}
else if (isNumber(arg)) {
arg--;
}
else if (arg instanceof BigNumber) {
arg = arg.toNumber() - 1;
}
else {
throw new TypeError('Ranges must be a Number or Range');
}
args[i] = arg;
}
var res = new Index();
Index.apply(res, args);
return res;
};
math.index.transform = transform;
return transform;
};
| MonoHearted/Flowerbless | node_modules/mathjs/lib/expression/transform/index.transform.js | JavaScript | mit | 1,170 |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Security.Models
{
using Newtonsoft.Json;
using System.Linq;
public partial class IoTSecuritySolutionAnalyticsModelPropertiesDevicesMetricsItem
{
/// <summary>
/// Initializes a new instance of the
/// IoTSecuritySolutionAnalyticsModelPropertiesDevicesMetricsItem
/// class.
/// </summary>
public IoTSecuritySolutionAnalyticsModelPropertiesDevicesMetricsItem()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the
/// IoTSecuritySolutionAnalyticsModelPropertiesDevicesMetricsItem
/// class.
/// </summary>
/// <param name="date">Aggregation of IoT Security solution device
/// alert metrics by date.</param>
/// <param name="devicesMetrics">Device alert count by
/// severity.</param>
public IoTSecuritySolutionAnalyticsModelPropertiesDevicesMetricsItem(System.DateTime? date = default(System.DateTime?), IoTSeverityMetrics devicesMetrics = default(IoTSeverityMetrics))
{
Date = date;
DevicesMetrics = devicesMetrics;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets aggregation of IoT Security solution device alert
/// metrics by date.
/// </summary>
[JsonProperty(PropertyName = "date")]
public System.DateTime? Date { get; set; }
/// <summary>
/// Gets or sets device alert count by severity.
/// </summary>
[JsonProperty(PropertyName = "devicesMetrics")]
public IoTSeverityMetrics DevicesMetrics { get; set; }
}
}
| jackmagic313/azure-sdk-for-net | sdk/securitycenter/Microsoft.Azure.Management.SecurityCenter/src/Generated/Models/IoTSecuritySolutionAnalyticsModelPropertiesDevicesMetricsItem.cs | C# | mit | 2,216 |
package com.greenlemonmobile.app.ebook.books.imagezoom.graphics;
import android.graphics.Bitmap;
/**
* Base interface used in the {@link ImageViewTouchBase} view
* @author alessandro
*
*/
public interface IBitmapDrawable {
Bitmap getBitmap();
}
| yy1300326388/iBooks | src/com/greenlemonmobile/app/ebook/books/imagezoom/graphics/IBitmapDrawable.java | Java | mit | 253 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DocStrap Module: ink/collector</title>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">
<link type="text/css" rel="stylesheet" href="styles/site.united.css">
</head>
<body>
<div class="container-fluid">
<div class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<a class="brand" href="index.html">DocStrap</a>
<ul class="nav">
<li class="dropdown">
<a href="modules.list.html" class="dropdown-toggle" data-toggle="dropdown">Modules<b
class="caret"></b></a>
<ul class="dropdown-menu ">
<li>
<a href="module-base.html">base</a>
</li>
<li>
<a href="chains_.html">base/chains</a>
</li>
<li>
<a href="binder.html">documents/binder</a>
</li>
<li>
<a href="model_.html">documents/model</a>
</li>
<li>
<a href="probe.html">documents/probe</a>
</li>
<li>
<a href="schema_.html">documents/schema</a>
</li>
<li>
<a href="collector.html">ink/collector</a>
</li>
<li>
<a href="bussable_.html">mixins/bussable</a>
</li>
<li>
<a href="signalable_.html">mixins/signalable</a>
</li>
<li>
<a href="format.html">strings/format</a>
</li>
<li>
<a href="logger.html">utils/logger</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b
class="caret"></b></a>
<ul class="dropdown-menu ">
<li>
<a href="base.html">base</a>
</li>
<li>
<a href="chains.html">base/chains</a>
</li>
<li>
<a href="model.html">documents/model</a>
</li>
<li>
<a href="probe.queryOperators.html">documents/probe.queryOperators</a>
</li>
<li>
<a href="probe.updateOperators.html">documents/probe.updateOperators</a>
</li>
<li>
<a href="collector-ACollector.html">ink/collector~ACollector</a>
</li>
<li>
<a href="collector-CollectorBase_.html">ink/collector~CollectorBase</a>
</li>
<li>
<a href="collector-OCollector.html">ink/collector~OCollector</a>
</li>
<li>
<a href="signalable-Signal.html">mixins/signalable~Signal</a>
</li>
<li>
<a href="logger.Logger.html">utils/logger.Logger</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="mixins.list.html" class="dropdown-toggle" data-toggle="dropdown">Mixins<b
class="caret"></b></a>
<ul class="dropdown-menu ">
<li>
<a href="schema.html">documents/schema</a>
</li>
<li>
<a href="bussable.html">mixins/bussable</a>
</li>
<li>
<a href="signalable.html">mixins/signalable</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="tutorials.list.html" class="dropdown-toggle" data-toggle="dropdown">Tutorials<b
class="caret"></b></a>
<ul class="dropdown-menu ">
<li>
<a href="tutorial-Teeth.html">Brush Teeth</a>
</li>
<li>
<a href="tutorial-Car.html">Drive Car</a>
</li>
<li>
<a href="tutorial-Test.html">Fence Test</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="global.html" class="dropdown-toggle" data-toggle="dropdown">Global<b
class="caret"></b></a>
<ul class="dropdown-menu ">
<li>
<a href="global.html#utils/logger">utils/logger</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="row-fluid">
<div class="span8">
<div id="main">
<h1 class="page-title">Module: ink/collector</h1>
<section>
<header>
<h2>
ink/collector
</h2>
</header>
<article>
<div class="container-overview">
<div class="description"><p>An object and array collector</p></div>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-2">line 2</a>
</li>
</ul>
</dd>
</dl>
</div>
<h3 class="subsection-title">Classes</h3>
<dl>
<dt><a href="collector-ACollector.html">ACollector</a></dt>
<dd></dd>
<dt><a href="collector-CollectorBase_.html">CollectorBase</a></dt>
<dd></dd>
<dt><a href="collector-OCollector.html">OCollector</a></dt>
<dd></dd>
</dl>
<h3 class="subsection-title">Members</h3>
<dl>
<dt class="name" id="difference">
<h4><span class="type-signature"></span>difference<span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Creates an array of array elements not present in the other arrays using strict equality for comparisons, i.e. ===.</p>
</div>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-278">line 278</a>
</li>
</ul>
</dd>
</dl>
</dd>
<dt class="name" id="head">
<h4><span class="type-signature"></span>head<span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Gets the first n values of the array</p>
</div>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-290">line 290</a>
</li>
</ul>
</dd>
</dl>
</dd>
<dt class="name" id="heap">
<h4><span class="type-signature"></span>heap<span class="type-signature"> :object|array</span></h4>
</dt>
<dd>
<div class="description">
<p>The collection that being managed</p>
</div>
<h5>Type:</h5>
<ul>
<li>
<span class="param-type">object</span>
|
<span class="param-type">array</span>
</li>
</ul>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-26">line 26</a>
</li>
</ul>
</dd>
</dl>
</dd>
<dt class="name" id="tail">
<h4><span class="type-signature"></span>tail<span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>This method gets all but the first values of array</p>
</div>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-284">line 284</a>
</li>
</ul>
</dd>
</dl>
</dd>
</dl>
<h3 class="subsection-title">Methods</h3>
<dl>
<dt>
<h4 class="name" id="collect"><span class="type-signature"><static> </span>collect<span class="signature">(obj)</span><span class="type-signature"> → {ACollector|OCollector}</span></h4>
</dt>
<dd>
<div class="description">
<p>Collect an object</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>obj</code></td>
<td class="type">
<span class="param-type">array</span>
|
<span class="param-type">object</span>
</td>
<td class="description last"><p>What to collect</p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-363">line 363</a>
</li>
</ul>
</dd>
</dl>
<h5>Returns:</h5>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">ACollector</span>
|
<span class="param-type">OCollector</span>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="add"><span class="type-signature"><inner> </span>add<span class="signature">(item)</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Adds to the top of the collection</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>item</code></td>
<td class="type">
<span class="param-type">*</span>
</td>
<td class="description last"><p>The item to add to the collection. Only one item at a time can be added</p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-296">line 296</a>
</li>
</ul>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="add"><span class="type-signature"><inner> </span>add<span class="signature">(key, item)</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Adds an item to the collection</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>key</code></td>
<td class="type">
<span class="param-type">*</span>
</td>
<td class="description last"><p>The key to use for the item being added.</p></td>
</tr>
<tr>
<td class="name"><code>item</code></td>
<td class="type">
<span class="param-type">*</span>
</td>
<td class="description last"><p>The item to add to the collection. The item is not iterated so that you could add bundled items to the collection</p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-56">line 56</a>
</li>
</ul>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="append"><span class="type-signature"><inner> </span>append<span class="signature">(item)</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Add to the bottom of the list</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>item</code></td>
<td class="type">
<span class="param-type">*</span>
</td>
<td class="description last"><p>The item to add to the collection. Only one item at a time can be added</p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-303">line 303</a>
</li>
</ul>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="at"><span class="type-signature"><inner> </span>at<span class="signature">(args)</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Creates an array of elements from the specified indexes, or keys, of the collection. Indexes may be specified as
individual arguments or as arrays of indexes</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>args</code></td>
<td class="type">
<span class="param-type">indexes</span>
</td>
<td class="description last"><p>The indexes to use</p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-324">line 324</a>
</li>
</ul>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="compact"><span class="type-signature"><inner> </span>compact<span class="signature">()</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Modifies the collection with all falsey values of array removed. The values false, null, 0, "", undefined and NaN are all falsey.</p>
</div>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-316">line 316</a>
</li>
</ul>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="countBy"><span class="type-signature"><inner> </span>countBy<span class="signature">(<span class="optional">query</span>, iterator, <span class="optional">thisobj</span>)</span><span class="type-signature"> → {object}</span></h4>
</dt>
<dd>
<div class="description">
<p>Creates an object composed of keys returned from running each element
of the collection through the given callback. The corresponding value of each key
is the number of times the key was returned by the callback.</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Argument</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>query</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>A query to evaluate. If you pass in a query, only the items that match the query
are iterated over.</p></td>
</tr>
<tr>
<td class="name"><code>iterator</code></td>
<td class="type">
<span class="param-type">function</span>
</td>
<td class="attributes">
</td>
<td class="description last"></td>
</tr>
<tr>
<td class="name"><code>thisobj</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>The value of <code>this</code></p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-138">line 138</a>
</li>
</ul>
</dd>
</dl>
<h5>Returns:</h5>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">object</span>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="destroy"><span class="type-signature"><inner> </span>destroy<span class="signature">()</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Destructor called when the object is destroyed.</p>
</div>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-241">line 241</a>
</li>
</ul>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="each"><span class="type-signature"><inner> </span>each<span class="signature">(<span class="optional">query</span>, iterator, <span class="optional">thisobj</span>)</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Iterate over each item in the collection, or a subset that matches a query. This supports two signatures:
<code>.each(query, function)</code> and <code>.each(function)</code>. If you pass in a query, only the items that match the query
are iterated over.</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Argument</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>query</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>A query to evaluate</p></td>
</tr>
<tr>
<td class="name"><code>iterator</code></td>
<td class="type">
<span class="param-type">function</span>
</td>
<td class="attributes">
</td>
<td class="description last"><p>Function to execute against each item in the collection</p></td>
</tr>
<tr>
<td class="name"><code>thisobj</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>The value of <code>this</code></p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-67">line 67</a>
</li>
</ul>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="flatten"><span class="type-signature"><inner> </span>flatten<span class="signature">(<span class="optional">query</span>, iterator,, <span class="optional">thisobj</span>)</span><span class="type-signature"> → {number}</span></h4>
</dt>
<dd>
<div class="description">
<p>Flattens a nested array (the nesting can be to any depth). If isShallow is truthy, array will only be flattened a single level.
If callback is passed, each element of array is passed through a callback before flattening.</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Argument</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>query</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>A query to evaluate . If you pass in a query, only the items that match the query
are iterated over.</p></td>
</tr>
<tr>
<td class="name"><code>iterator,</code></td>
<td class="type">
<span class="param-type">function</span>
</td>
<td class="attributes">
</td>
<td class="description last"></td>
</tr>
<tr>
<td class="name"><code>thisobj</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>The value of <code>this</code></p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-338">line 338</a>
</li>
</ul>
</dd>
</dl>
<h5>Returns:</h5>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">number</span>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="groupBy"><span class="type-signature"><inner> </span>groupBy<span class="signature">(<span class="optional">query</span>, iterator, <span class="optional">thisobj</span>)</span><span class="type-signature"> → {object}</span></h4>
</dt>
<dd>
<div class="description">
<p>Creates an object composed of keys returned from running each element of the collection through the callback.
The corresponding value of each key is an array of elements passed to callback that returned the key.
The callback is invoked with three arguments: (value, index|key, collection).</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Argument</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>query</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>A query to evaluate . If you pass in a query, only the items that match the query
are iterated over.</p></td>
</tr>
<tr>
<td class="name"><code>iterator</code></td>
<td class="type">
<span class="param-type">function</span>
</td>
<td class="attributes">
</td>
<td class="description last"></td>
</tr>
<tr>
<td class="name"><code>thisobj</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>The value of <code>this</code></p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-157">line 157</a>
</li>
</ul>
</dd>
</dl>
<h5>Returns:</h5>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">object</span>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="index"><span class="type-signature"><inner> </span>index<span class="signature">(key)</span><span class="type-signature"> → {*}</span></h4>
</dt>
<dd>
<div class="description">
<p>Gets an items by its index</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>key</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>The index to get</p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-352">line 352</a>
</li>
</ul>
</dd>
</dl>
<h5>Returns:</h5>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">*</span>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="key"><span class="type-signature"><inner> </span>key<span class="signature">(key)</span><span class="type-signature"> → {*}</span></h4>
</dt>
<dd>
<div class="description">
<p>Get a record by key</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>key</code></td>
<td class="type">
<span class="param-type">*</span>
</td>
<td class="description last"><p>The key of the record to get</p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-257">line 257</a>
</li>
</ul>
</dd>
</dl>
<h5>Returns:</h5>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">*</span>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="map"><span class="type-signature"><inner> </span>map<span class="signature">(<span class="optional">query</span>, iterator, <span class="optional">thisobj</span>)</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Maps the contents to an array by iterating over it and transforming it. You supply the iterator. Supports two signatures:
<code>.map(query, function)</code> and <code>.map(function)</code>. If you pass in a query, only the items that match the query
are iterated over.</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Argument</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>query</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>A query to evaluate</p></td>
</tr>
<tr>
<td class="name"><code>iterator</code></td>
<td class="type">
<span class="param-type">function</span>
</td>
<td class="attributes">
</td>
<td class="description last"><p>Function to execute against each item in the collection</p></td>
</tr>
<tr>
<td class="name"><code>thisobj</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>The value of <code>this</code></p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-99">line 99</a>
</li>
</ul>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="max"><span class="type-signature"><inner> </span>max<span class="signature">(<span class="optional">query</span>, iterator, <span class="optional">thisobj</span>)</span><span class="type-signature"> → {number}</span></h4>
</dt>
<dd>
<div class="description">
<p>Retrieves the maximum value of an array. If callback is passed,
it will be executed for each value in the array to generate the criterion by which the value is ranked.</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Argument</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>query</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>A query to evaluate . If you pass in a query, only the items that match the query
are iterated over.</p></td>
</tr>
<tr>
<td class="name"><code>iterator</code></td>
<td class="type">
<span class="param-type">function</span>
</td>
<td class="attributes">
</td>
<td class="description last"></td>
</tr>
<tr>
<td class="name"><code>thisobj</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>The value of <code>this</code></p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-211">line 211</a>
</li>
</ul>
</dd>
</dl>
<h5>Returns:</h5>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">number</span>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="min"><span class="type-signature"><inner> </span>min<span class="signature">(<span class="optional">query</span>, iterator, <span class="optional">thisobj</span>)</span><span class="type-signature"> → {number}</span></h4>
</dt>
<dd>
<div class="description">
<p>Retrieves the minimum value of an array. If callback is passed,
it will be executed for each value in the array to generate the criterion by which the value is ranked.</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Argument</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>query</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>A query to evaluate . If you pass in a query, only the items that match the query
are iterated over.</p></td>
</tr>
<tr>
<td class="name"><code>iterator</code></td>
<td class="type">
<span class="param-type">function</span>
</td>
<td class="attributes">
</td>
<td class="description last"></td>
</tr>
<tr>
<td class="name"><code>thisobj</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>The value of <code>this</code></p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-229">line 229</a>
</li>
</ul>
</dd>
</dl>
<h5>Returns:</h5>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">number</span>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="pluck"><span class="type-signature"><inner> </span>pluck<span class="signature">(<span class="optional">query</span>, property)</span><span class="type-signature"> → {*}</span></h4>
</dt>
<dd>
<div class="description">
<p>Reduce the collection to a single value. Supports two signatures:
<code>.pluck(query, function)</code> and <code>.pluck(function)</code></p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Argument</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>query</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>The query to evaluate. If you pass in a query, only the items that match the query
are iterated over.</p></td>
</tr>
<tr>
<td class="name"><code>property</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="attributes">
</td>
<td class="description last"><p>The property that will be 'plucked' from the contents of the collection</p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-174">line 174</a>
</li>
</ul>
</dd>
</dl>
<h5>Returns:</h5>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">*</span>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="push"><span class="type-signature"><inner> </span>push<span class="signature">(item)</span><span class="type-signature"></span></h4>
</dt>
<dd>
<div class="description">
<p>Add an item to the top of the list. This is identical to <code>add</code>, but is provided for stack semantics</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>item</code></td>
<td class="type">
<span class="param-type">*</span>
</td>
<td class="description last"><p>The item to add to the collection. Only one item at a time can be added</p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-310">line 310</a>
</li>
</ul>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="reduce"><span class="type-signature"><inner> </span>reduce<span class="signature">(<span class="optional">query</span>, iterator, <span class="optional">accumulator</span>, <span class="optional">thisobj</span>)</span><span class="type-signature"> → {*}</span></h4>
</dt>
<dd>
<div class="description">
<p>Reduces a collection to a value which is the accumulated result of running each element in the collection through the
callback, where each successive callback execution consumes the return value of the previous execution. If accumulator
is not passed, the first element of the collection will be used as the initial accumulator value.
are iterated over.</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Argument</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>query</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>A query to evaluate</p></td>
</tr>
<tr>
<td class="name"><code>iterator</code></td>
<td class="type">
<span class="param-type">function</span>
</td>
<td class="attributes">
</td>
<td class="description last"><p>The function that will be executed in each item in the collection</p></td>
</tr>
<tr>
<td class="name"><code>accumulator</code></td>
<td class="type">
<span class="param-type">*</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>Initial value of the accumulator.</p></td>
</tr>
<tr>
<td class="name"><code>thisobj</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>The value of <code>this</code></p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-119">line 119</a>
</li>
</ul>
</dd>
</dl>
<h5>Returns:</h5>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">*</span>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="sortBy"><span class="type-signature"><inner> </span>sortBy<span class="signature">(<span class="optional">query</span>, iterator, <span class="optional">thisobj</span>)</span><span class="type-signature"> → {array}</span></h4>
</dt>
<dd>
<div class="description">
<p>Returns a sorted copy of the collection.</p>
</div>
<h5>Parameters:</h5>
<table class="params table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Argument</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>query</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>The query to evaluate. If you pass in a query, only the items that match the query
are iterated over.</p></td>
</tr>
<tr>
<td class="name"><code>iterator</code></td>
<td class="type">
<span class="param-type">function</span>
</td>
<td class="attributes">
</td>
<td class="description last"></td>
</tr>
<tr>
<td class="name"><code>thisobj</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="attributes">
<optional><br>
</td>
<td class="description last"><p>The value of <code>this</code></p></td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-193">line 193</a>
</li>
</ul>
</dd>
</dl>
<h5>Returns:</h5>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">array</span>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="toArray"><span class="type-signature"><inner> </span>toArray<span class="signature">()</span><span class="type-signature"> → {array}</span></h4>
</dt>
<dd>
<div class="description">
<p>Returns the collection as an array. If it is already an array, it just returns that.</p>
</div>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-80">line 80</a>
</li>
</ul>
</dd>
</dl>
<h5>Returns:</h5>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">array</span>
</dd>
</dl>
</dd>
<dt>
<h4 class="name" id="toJSON"><span class="type-signature"><inner> </span>toJSON<span class="signature">()</span><span class="type-signature"> → {object}</span></h4>
</dt>
<dd>
<div class="description">
<p>Supports conversion to a JSON string or for passing over the wire</p>
</div>
<dl class="details">
<dt class="tag-source">Source:</dt>
<dd class="tag-source">
<ul class="dummy">
<li>
<a href="collector.js.html">documents/collector.js</a>,
<a href="collector.js.html#sunlight-1-line-88">line 88</a>
</li>
</ul>
</dd>
</dl>
<h5>Returns:</h5>
<ul>
<li>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">object</span>
</dd>
</dl>
</li>
<li>
<dl>
<dt>
Type
</dt>
<dd>
<span class="param-type">Object</span>
|
<span class="param-type">array</span>
</dd>
</dl>
</li>
</ul>
</dd>
</dl>
</article>
</section>
</div>
<div class="clearfix"></div>
<footer>
<span class="copyright">
DocStrap Copyright © 2012-2013 The contributors to the JSDoc3 and DocStrap projects.
</span>
<br />
<span class="jsdoc-message">
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.3.0-alpha5</a>
on Mon Jul 7th 2014 using the <a
href="https://github.com/terryweiss/docstrap">DocStrap template</a>.
</span>
</footer>
</div>
<div class="span3">
<div id="toc"></div>
</div>
<br clear="both">
</div>
</div>
<!--<script src="scripts/sunlight.js"></script>-->
<script src="scripts/docstrap.lib.js"></script>
<script src="scripts/bootstrap-dropdown.js"></script>
<script src="scripts/toc.js"></script>
<script>
$( function () {
$( "[id*='$']" ).each( function () {
var $this = $( this );
$this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) );
} );
$( "#toc" ).toc( {
anchorName : function ( i, heading, prefix ) {
return $( heading ).attr( "id" ) || ( prefix + i );
},
selectors : "h1,h2,h3,h4",
showAndHide : false,
scrollTo : "100px"
} );
$( "#toc>ul" ).addClass( "nav nav-pills nav-stacked" );
$( "#main span[id^='toc']" ).addClass( "toc-shim" );
$( '.dropdown-toggle' ).dropdown();
// $( ".tutorial-section pre, .readme-section pre" ).addClass( "sunlight-highlight-javascript" ).addClass( "linenums" );
$( ".tutorial-section pre, .readme-section pre" ).each( function () {
var $this = $( this );
var example = $this.find( "code" );
exampleText = example.html();
var lang = /{@lang (.*?)}/.exec( exampleText );
if ( lang && lang[1] ) {
exampleText = exampleText.replace( lang[0], "" );
example.html( exampleText );
lang = lang[1];
} else {
lang = "javascript";
}
if ( lang ) {
$this
.addClass( "sunlight-highlight-" + lang )
.addClass( "linenums" )
.html( example.html() );
}
} );
Sunlight.highlightAll( {
lineNumbers : true,
showMenu : true,
enableDoclinks : true
} );
} );
</script>
<!--Navigation and Symbol Display-->
<!--Google Analytics-->
</body>
</html> | guoguogis/ng-nice | npminstall/ink-docstrap/themes/united/collector.html | HTML | mit | 55,447 |
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#ifndef OPENCV_CORE_ALLOCATOR_STATS_HPP
#define OPENCV_CORE_ALLOCATOR_STATS_HPP
#include "../cvdef.h"
namespace cv { namespace utils {
class AllocatorStatisticsInterface
{
protected:
AllocatorStatisticsInterface() {}
virtual ~AllocatorStatisticsInterface() {}
public:
virtual uint64_t getCurrentUsage() const = 0;
virtual uint64_t getTotalUsage() const = 0;
virtual uint64_t getNumberOfAllocations() const = 0;
virtual uint64_t getPeakUsage() const = 0;
/** set peak usage = current usage */
virtual void resetPeakUsage() = 0;
};
}} // namespace
#endif // OPENCV_CORE_ALLOCATOR_STATS_HPP
| HuTianQi/QQ | app/src/main/cpp/third_part/opencv/include/opencv2/core/utils/allocator_stats.hpp | C++ | mit | 821 |
define("ace/snippets/typescript",["require","exports","module"],function(e,t,n){"use strict";t.snippetText="",t.scope="typescript"});
(function() {
window.require(["ace/snippets/typescript"], function(m) {
if (typeof module == "object") {
module.exports = m;
}
});
})();
| holtkamp/cdnjs | ajax/libs/ace/1.3.2/snippets/typescript.js | JavaScript | mit | 431 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
package fixtures.azurespecials.implementation;
import com.microsoft.azure.AzureClient;
import com.microsoft.azure.AzureServiceClient;
import com.microsoft.azure.RestClient;
import com.microsoft.rest.credentials.ServiceClientCredentials;
import fixtures.azurespecials.ApiVersionDefaults;
import fixtures.azurespecials.ApiVersionLocals;
import fixtures.azurespecials.AutoRestAzureSpecialParametersTestClient;
import fixtures.azurespecials.Headers;
import fixtures.azurespecials.Odatas;
import fixtures.azurespecials.SkipUrlEncodings;
import fixtures.azurespecials.SubscriptionInCredentials;
import fixtures.azurespecials.SubscriptionInMethods;
import fixtures.azurespecials.XMsClientRequestIds;
/**
* Initializes a new instance of the AutoRestAzureSpecialParametersTestClientImpl class.
*/
public final class AutoRestAzureSpecialParametersTestClientImpl extends AzureServiceClient implements AutoRestAzureSpecialParametersTestClient {
/** the {@link AzureClient} used for long running operations. */
private AzureClient azureClient;
/**
* Gets the {@link AzureClient} used for long running operations.
* @return the azure client;
*/
public AzureClient getAzureClient() {
return this.azureClient;
}
/** The subscription id, which appears in the path, always modeled in credentials. The value is always '1234-5678-9012-3456'. */
private String subscriptionId;
/**
* Gets The subscription id, which appears in the path, always modeled in credentials. The value is always '1234-5678-9012-3456'.
*
* @return the subscriptionId value.
*/
public String subscriptionId() {
return this.subscriptionId;
}
/**
* Sets The subscription id, which appears in the path, always modeled in credentials. The value is always '1234-5678-9012-3456'.
*
* @param subscriptionId the subscriptionId value.
* @return the service client itself
*/
public AutoRestAzureSpecialParametersTestClientImpl withSubscriptionId(String subscriptionId) {
this.subscriptionId = subscriptionId;
return this;
}
/** The api version, which appears in the query, the value is always '2015-07-01-preview'. */
private String apiVersion;
/**
* Gets The api version, which appears in the query, the value is always '2015-07-01-preview'.
*
* @return the apiVersion value.
*/
public String apiVersion() {
return this.apiVersion;
}
/** Gets or sets the preferred language for the response. */
private String acceptLanguage;
/**
* Gets Gets or sets the preferred language for the response.
*
* @return the acceptLanguage value.
*/
public String acceptLanguage() {
return this.acceptLanguage;
}
/**
* Sets Gets or sets the preferred language for the response.
*
* @param acceptLanguage the acceptLanguage value.
* @return the service client itself
*/
public AutoRestAzureSpecialParametersTestClientImpl withAcceptLanguage(String acceptLanguage) {
this.acceptLanguage = acceptLanguage;
return this;
}
/** Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. */
private int longRunningOperationRetryTimeout;
/**
* Gets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30.
*
* @return the longRunningOperationRetryTimeout value.
*/
public int longRunningOperationRetryTimeout() {
return this.longRunningOperationRetryTimeout;
}
/**
* Sets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30.
*
* @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value.
* @return the service client itself
*/
public AutoRestAzureSpecialParametersTestClientImpl withLongRunningOperationRetryTimeout(int longRunningOperationRetryTimeout) {
this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout;
return this;
}
/** When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */
private boolean generateClientRequestId;
/**
* Gets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true.
*
* @return the generateClientRequestId value.
*/
public boolean generateClientRequestId() {
return this.generateClientRequestId;
}
/**
* Sets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true.
*
* @param generateClientRequestId the generateClientRequestId value.
* @return the service client itself
*/
public AutoRestAzureSpecialParametersTestClientImpl withGenerateClientRequestId(boolean generateClientRequestId) {
this.generateClientRequestId = generateClientRequestId;
return this;
}
/**
* The XMsClientRequestIds object to access its operations.
*/
private XMsClientRequestIds xMsClientRequestIds;
/**
* Gets the XMsClientRequestIds object to access its operations.
* @return the XMsClientRequestIds object.
*/
public XMsClientRequestIds xMsClientRequestIds() {
return this.xMsClientRequestIds;
}
/**
* The SubscriptionInCredentials object to access its operations.
*/
private SubscriptionInCredentials subscriptionInCredentials;
/**
* Gets the SubscriptionInCredentials object to access its operations.
* @return the SubscriptionInCredentials object.
*/
public SubscriptionInCredentials subscriptionInCredentials() {
return this.subscriptionInCredentials;
}
/**
* The SubscriptionInMethods object to access its operations.
*/
private SubscriptionInMethods subscriptionInMethods;
/**
* Gets the SubscriptionInMethods object to access its operations.
* @return the SubscriptionInMethods object.
*/
public SubscriptionInMethods subscriptionInMethods() {
return this.subscriptionInMethods;
}
/**
* The ApiVersionDefaults object to access its operations.
*/
private ApiVersionDefaults apiVersionDefaults;
/**
* Gets the ApiVersionDefaults object to access its operations.
* @return the ApiVersionDefaults object.
*/
public ApiVersionDefaults apiVersionDefaults() {
return this.apiVersionDefaults;
}
/**
* The ApiVersionLocals object to access its operations.
*/
private ApiVersionLocals apiVersionLocals;
/**
* Gets the ApiVersionLocals object to access its operations.
* @return the ApiVersionLocals object.
*/
public ApiVersionLocals apiVersionLocals() {
return this.apiVersionLocals;
}
/**
* The SkipUrlEncodings object to access its operations.
*/
private SkipUrlEncodings skipUrlEncodings;
/**
* Gets the SkipUrlEncodings object to access its operations.
* @return the SkipUrlEncodings object.
*/
public SkipUrlEncodings skipUrlEncodings() {
return this.skipUrlEncodings;
}
/**
* The Odatas object to access its operations.
*/
private Odatas odatas;
/**
* Gets the Odatas object to access its operations.
* @return the Odatas object.
*/
public Odatas odatas() {
return this.odatas;
}
/**
* The Headers object to access its operations.
*/
private Headers headers;
/**
* Gets the Headers object to access its operations.
* @return the Headers object.
*/
public Headers headers() {
return this.headers;
}
/**
* Initializes an instance of AutoRestAzureSpecialParametersTestClient client.
*
* @param credentials the management credentials for Azure
*/
public AutoRestAzureSpecialParametersTestClientImpl(ServiceClientCredentials credentials) {
this("http://localhost", credentials);
}
/**
* Initializes an instance of AutoRestAzureSpecialParametersTestClient client.
*
* @param baseUrl the base URL of the host
* @param credentials the management credentials for Azure
*/
public AutoRestAzureSpecialParametersTestClientImpl(String baseUrl, ServiceClientCredentials credentials) {
this(new RestClient.Builder()
.withBaseUrl(baseUrl)
.withCredentials(credentials)
.build());
}
/**
* Initializes an instance of AutoRestAzureSpecialParametersTestClient client.
*
* @param restClient the REST client to connect to Azure.
*/
public AutoRestAzureSpecialParametersTestClientImpl(RestClient restClient) {
super(restClient);
initialize();
}
protected void initialize() {
this.apiVersion = "2015-07-01-preview";
this.acceptLanguage = "en-US";
this.longRunningOperationRetryTimeout = 30;
this.generateClientRequestId = true;
this.xMsClientRequestIds = new XMsClientRequestIdsImpl(restClient().retrofit(), this);
this.subscriptionInCredentials = new SubscriptionInCredentialsImpl(restClient().retrofit(), this);
this.subscriptionInMethods = new SubscriptionInMethodsImpl(restClient().retrofit(), this);
this.apiVersionDefaults = new ApiVersionDefaultsImpl(restClient().retrofit(), this);
this.apiVersionLocals = new ApiVersionLocalsImpl(restClient().retrofit(), this);
this.skipUrlEncodings = new SkipUrlEncodingsImpl(restClient().retrofit(), this);
this.odatas = new OdatasImpl(restClient().retrofit(), this);
this.headers = new HeadersImpl(restClient().retrofit(), this);
this.azureClient = new AzureClient(this);
}
/**
* Gets the User-Agent header for the client.
*
* @return the user agent string.
*/
@Override
public String userAgent() {
return String.format("Azure-SDK-For-Java/%s (%s)",
getClass().getPackage().getImplementationVersion(),
"AutoRestAzureSpecialParametersTestClient, 2015-07-01-preview");
}
}
| yaqiyang/autorest | src/generator/AutoRest.Java.Azure.Tests/src/main/java/fixtures/azurespecials/implementation/AutoRestAzureSpecialParametersTestClientImpl.java | Java | mit | 10,599 |
package org.jabref.benchmarks;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import org.jabref.Globals;
import org.jabref.logic.exporter.BibtexDatabaseWriter;
import org.jabref.logic.exporter.SavePreferences;
import org.jabref.logic.exporter.StringSaveSession;
import org.jabref.logic.formatter.bibtexfields.HtmlToLatexFormatter;
import org.jabref.logic.importer.ParseException;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.importer.fileformat.BibtexParser;
import org.jabref.logic.layout.format.HTMLChars;
import org.jabref.logic.layout.format.LatexToUnicodeFormatter;
import org.jabref.logic.search.SearchQuery;
import org.jabref.model.Defaults;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.database.BibDatabaseModeDetection;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.groups.GroupHierarchyType;
import org.jabref.model.groups.KeywordGroup;
import org.jabref.model.groups.WordKeywordGroup;
import org.jabref.model.metadata.MetaData;
import org.jabref.preferences.JabRefPreferences;
import org.openjdk.jmh.Main;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.RunnerException;
@State(Scope.Thread)
public class Benchmarks {
private String bibtexString;
private final BibDatabase database = new BibDatabase();
private String latexConversionString;
private String htmlConversionString;
@Setup
public void init() throws Exception {
Globals.prefs = JabRefPreferences.getInstance();
Random randomizer = new Random();
for (int i = 0; i < 1000; i++) {
BibEntry entry = new BibEntry();
entry.setCiteKey("id" + i);
entry.setField("title", "This is my title " + i);
entry.setField("author", "Firstname Lastname and FirstnameA LastnameA and FirstnameB LastnameB" + i);
entry.setField("journal", "Journal Title " + i);
entry.setField("keyword", "testkeyword");
entry.setField("year", "1" + i);
entry.setField("rnd", "2" + randomizer.nextInt());
database.insertEntry(entry);
}
BibtexDatabaseWriter<StringSaveSession> databaseWriter = new BibtexDatabaseWriter<>(StringSaveSession::new);
StringSaveSession saveSession = databaseWriter.savePartOfDatabase(
new BibDatabaseContext(database, new MetaData(), new Defaults()), database.getEntries(),
new SavePreferences());
bibtexString = saveSession.getStringValue();
latexConversionString = "{A} \\textbf{bold} approach {\\it to} ${{\\Sigma}}{\\Delta}$ modulator \\textsuperscript{2} \\$";
htmlConversionString = "<b>Österreich</b> – & characters ⪢ <i>italic</i>";
}
@Benchmark
public ParserResult parse() throws IOException {
BibtexParser parser = new BibtexParser(Globals.prefs.getImportFormatPreferences());
return parser.parse(new StringReader(bibtexString));
}
@Benchmark
public String write() throws Exception {
BibtexDatabaseWriter<StringSaveSession> databaseWriter = new BibtexDatabaseWriter<>(StringSaveSession::new);
StringSaveSession saveSession = databaseWriter.savePartOfDatabase(
new BibDatabaseContext(database, new MetaData(), new Defaults()), database.getEntries(),
new SavePreferences());
return saveSession.getStringValue();
}
@Benchmark
public List<BibEntry> search() {
// FIXME: Reuse SearchWorker here
SearchQuery searchQuery = new SearchQuery("Journal Title 500", false, false);
return database.getEntries().stream().filter(searchQuery::isMatch).collect(Collectors.toList());
}
@Benchmark
public List<BibEntry> parallelSearch() {
// FIXME: Reuse SearchWorker here
SearchQuery searchQuery = new SearchQuery("Journal Title 500", false, false);
return database.getEntries().parallelStream().filter(searchQuery::isMatch).collect(Collectors.toList());
}
@Benchmark
public BibDatabaseMode inferBibDatabaseMode() {
return BibDatabaseModeDetection.inferMode(database);
}
@Benchmark
public String latexToUnicodeConversion() {
LatexToUnicodeFormatter f = new LatexToUnicodeFormatter();
return f.format(latexConversionString);
}
@Benchmark
public String latexToHTMLConversion() {
HTMLChars f = new HTMLChars();
return f.format(latexConversionString);
}
@Benchmark
public String htmlToLatexConversion() {
HtmlToLatexFormatter f = new HtmlToLatexFormatter();
return f.format(htmlConversionString);
}
@Benchmark
public boolean keywordGroupContains() throws ParseException {
KeywordGroup group = new WordKeywordGroup("testGroup", GroupHierarchyType.INDEPENDENT, "keyword", "testkeyword", false, ',', false);
return group.containsAll(database.getEntries());
}
public static void main(String[] args) throws IOException, RunnerException {
Main.main(args);
}
}
| shitikanth/jabref | src/jmh/java/org/jabref/benchmarks/Benchmarks.java | Java | mit | 5,418 |
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Order\Model;
use Doctrine\Common\Collections\Collection;
use Sylius\Component\Resource\Model\SoftDeletableInterface;
use Sylius\Component\Resource\Model\TimestampableInterface;
use Sylius\Component\Sequence\Model\SequenceSubjectInterface;
/**
* Order interface.
*
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface OrderInterface extends AdjustableInterface, TimestampableInterface, SoftDeletableInterface, SequenceSubjectInterface
{
const STATE_CART = 'cart';
const STATE_CART_LOCKED = 'cart_locked';
const STATE_PENDING = 'pending';
const STATE_CONFIRMED = 'confirmed';
const STATE_SHIPPED = 'shipped';
const STATE_ABANDONED = 'abandoned';
const STATE_CANCELLED = 'cancelled';
const STATE_RETURNED = 'returned';
/**
* Has the order been completed by user and can be handled.
*
* @return Boolean
*/
public function isCompleted();
/**
* Mark the order as completed.
*/
public function complete();
/**
* Return completion date.
*
* @return \DateTime
*/
public function getCompletedAt();
/**
* Set completion time.
*
* @param null|\DateTime $completedAt
*/
public function setCompletedAt(\DateTime $completedAt = null);
/**
* Get order items.
*
* @return Collection|OrderItemInterface[] An array or collection of OrderItemInterface
*/
public function getItems();
/**
* Set items.
*
* @param Collection|OrderItemInterface[] $items
*/
public function setItems(Collection $items);
/**
* Returns number of order items.
*
* @return integer
*/
public function countItems();
/**
* Adds item to order.
*
* @param OrderItemInterface $item
*/
public function addItem(OrderItemInterface $item);
/**
* Remove item from order.
*
* @param OrderItemInterface $item
*/
public function removeItem(OrderItemInterface $item);
/**
* Has item in order?
*
* @param OrderItemInterface $item
*
* @return Boolean
*/
public function hasItem(OrderItemInterface $item);
/**
* Get items total.
*
* @return integer
*/
public function getItemsTotal();
/**
* Calculate items total based on the items
* unit prices and quantities.
*/
public function calculateItemsTotal();
/**
* Get order total.
*
* @return integer
*/
public function getTotal();
/**
* Set total.
*
* @param integer $total
*/
public function setTotal($total);
/**
* Calculate total.
* Items total + Adjustments total.
*/
public function calculateTotal();
/**
* Alias of {@link countItems()}.
*
* @deprecated To be removed in 1.0. Use {@link countItems()} instead.
*/
public function getTotalItems();
/**
* Returns total quantity of items in cart.
*
* @return integer
*/
public function getTotalQuantity();
/**
* Checks whether the cart is empty or not.
*
* @return Boolean
*/
public function isEmpty();
/**
* Clears all items in cart.
*/
public function clearItems();
/**
* Get order state.
*
* @return string
*/
public function getState();
/**
* Set order state.
*
* @param string $state
*/
public function setState($state);
}
| gonzalovilaseca/Sylius | src/Sylius/Component/Order/Model/OrderInterface.php | PHP | mit | 3,770 |
<?php
/*
* This file is part of the Assetic package, an OpenSky project.
*
* (c) 2010-2013 OpenSky Project Inc
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Assetic\Test\Filter;
use Assetic\Asset\FileAsset;
use Assetic\Filter\UglifyJs2Filter;
use Symfony\Component\Process\ProcessBuilder;
/**
* @group integration
*/
class UglifyJs2FilterTest extends FilterTestCase
{
private $asset;
private $filter;
protected function setUp()
{
$uglifyjsBin = $this->findExecutable('uglifyjs', 'UGLIFYJS2_BIN');
$nodeBin = $this->findExecutable('node', 'NODE_BIN');
if (!$uglifyjsBin) {
$this->markTestSkipped('Unable to find `uglifyjs` executable.');
}
// verify uglifyjs version
$pb = new ProcessBuilder($nodeBin ? array($nodeBin, $uglifyjsBin) : array($uglifyjsBin));
$pb->add('--version');
if (isset($_SERVER['NODE_PATH'])) {
$pb->setEnv('NODE_PATH', $_SERVER['NODE_PATH']);
}
if (0 !== $pb->getProcess()->run()) {
$this->markTestSkipped('Incorrect version of UglifyJs');
}
$this->asset = new FileAsset(__DIR__.'/fixtures/uglifyjs/script.js');
$this->asset->load();
$this->filter = new UglifyJs2Filter($uglifyjsBin, $nodeBin);
}
protected function tearDown()
{
$this->asset = null;
$this->filter = null;
}
public function testUglify()
{
$this->filter->filterDump($this->asset);
$this->assertContains('function', $this->asset->getContent());
$this->assertNotContains('/**', $this->asset->getContent());
}
public function testCompress()
{
$this->filter->setCompress(true);
$this->filter->filterDump($this->asset);
$this->assertContains('var var2', $this->asset->getContent());
$this->assertNotContains('var var1', $this->asset->getContent());
}
public function testMangle()
{
$this->filter->setMangle(true);
$this->filter->filterDump($this->asset);
$this->assertContains('new Array(1,2,3,4)', $this->asset->getContent());
$this->assertNotContains('var var2', $this->asset->getContent());
}
public function testCompressAndMangle()
{
$this->filter->setCompress(true);
$this->filter->setMangle(true);
$this->filter->filterDump($this->asset);
$this->assertNotContains('var var1', $this->asset->getContent());
$this->assertNotContains('var var2', $this->asset->getContent());
$this->assertContains('new Array(1,2,3,4)', $this->asset->getContent());
}
public function testBeautify()
{
$this->filter->setBeautify(true);
$this->filter->filterDump($this->asset);
$this->assertContains(' foo', $this->asset->getContent());
$this->assertNotContains('/**', $this->asset->getContent());
}
}
| githubsvn/local.tyhv | vendor/kriswallsmith/assetic/tests/Assetic/Test/Filter/UglifyJs2FilterTest.php | PHP | mit | 3,014 |
<?php
namespace PayPal\Common;
class PPReflectionUtil {
/**
* @var array|ReflectionMethod[]
*/
private static $propertiesRefl = array();
/**
* @var array|string[]
*/
private static $propertiesType = array();
/**
*
* @param string $class
* @param string $propertyName
*/
public static function getPropertyClass($class, $propertyName) {
if (($annotations = self::propertyAnnotations($class, $propertyName)) && isset($annotations['return'])) {
// if (substr($annotations['param'], -2) === '[]') {
// $param = substr($annotations['param'], 0, -2);
// }
$param = $annotations['return'];
}
if(isset($param)) {
$anno = explode(' ', $param);
return $anno[0];
} else {
return 'string';
}
}
/**
* @param string $class
* @param string $propertyName
* @throws RuntimeException
* @return string
*/
public static function propertyAnnotations($class, $propertyName)
{
$class = is_object($class) ? get_class($class) : $class;
if (!class_exists('ReflectionProperty')) {
throw new \RuntimeException("Property type of " . $class . "::{$propertyName} cannot be resolved");
}
if ($annotations =& self::$propertiesType[$class][$propertyName]) {
return $annotations;
}
if (!($refl =& self::$propertiesRefl[$class][$propertyName])) {
$getter = method_exists($class, "get" . ucfirst($propertyName)) ? "get". ucfirst($propertyName)
: "get". preg_replace("/([_-\s]?([a-z0-9]+))/e", "ucwords('\\2')", $propertyName);
$refl = new \ReflectionMethod($class, $getter);
self::$propertiesRefl[$class][$propertyName] = $refl;
}
// todo: smarter regexp
if (!preg_match_all('~\@([^\s@\(]+)[\t ]*(?:\(?([^\n@]+)\)?)?~i', $refl->getDocComment(), $annots, PREG_PATTERN_ORDER)) {
return NULL;
}
foreach ($annots[1] as $i => $annot) {
$annotations[strtolower($annot)] = empty($annots[2][$i]) ? TRUE : rtrim($annots[2][$i], " \t\n\r)");
}
return $annotations;
}
} | dip712204123/kidskula | vendor/paypal/sdk-core-php/lib/PayPal/Common/PPReflectionUtil.php | PHP | mit | 1,972 |
// #docplaster
// #docregion
import { Component } from '@angular/core';
import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser';
@Component({
selector: 'app-bypass-security',
templateUrl: './bypass-security.component.html',
})
export class BypassSecurityComponent {
dangerousUrl: string;
trustedUrl: SafeUrl;
dangerousVideoUrl!: string;
videoUrl!: SafeResourceUrl;
// #docregion trust-url
constructor(private sanitizer: DomSanitizer) {
// javascript: URLs are dangerous if attacker controlled.
// Angular sanitizes them in data binding, but you can
// explicitly tell Angular to trust this value:
this.dangerousUrl = 'javascript:alert("Hi there")';
this.trustedUrl = sanitizer.bypassSecurityTrustUrl(this.dangerousUrl);
// #enddocregion trust-url
this.updateVideoUrl('PUBnlbjZFAI');
}
// #docregion trust-video-url
updateVideoUrl(id: string) {
// Appending an ID to a YouTube URL is safe.
// Always make sure to construct SafeValue objects as
// close as possible to the input data so
// that it's easier to check if the value is safe.
this.dangerousVideoUrl = 'https://www.youtube.com/embed/' + id;
this.videoUrl =
this.sanitizer.bypassSecurityTrustResourceUrl(this.dangerousVideoUrl);
}
// #enddocregion trust-video-url
}
| ocombe/angular | aio/content/examples/security/src/app/bypass-security.component.ts | TypeScript | mit | 1,340 |
% ----------------------------------------------------------------------
% System: ECLiPSe Constraint Logic Programming System
% Version: $Id: heaps.pl,v 1.1 2008/06/30 17:43:46 jschimpf Exp $
%
% Copyright: This library has been adapted from code from the Edinburgh
% DEC-10 Prolog Library, whose copyright notice says:
%
% These files are all in the "public domain" so you can
% use them freely, copy them, incorporate them into
% programs of your own and so forth without payment.
% The work of producing them in the first place and of
% organising them as detailed here has been funded over
% the years at Edinburgh University mainly by the
% Science and Engineering Research Council. Their
% dissemination has been encouraged by the Alvey Special
% Interest Group: Artificial Intelligence. We would
% appreciate it if you were to acknowledge these bodies
% when you use or re-distribute any of these files.
% ----------------------------------------------------------------------
% File : HEAPS.PL
% Author : R.A.O'Keefe
% Updated: 29 November 1983
% Purpose: Implement heaps in Prolog.
:- module(heaps). % ECLiPSe header
:- export
add_to_heap/4,
get_from_heap/4,
heap_size/2,
heap_to_list/2,
list_to_heap/2,
min_of_heap/3,
min_of_heap/5.
:- comment(summary, "Implement heaps in Prolog").
:- comment(author, "R.A.O'Keefe").
:- comment(copyright, 'This file is in the public domain').
:- comment(date, "29 November 1983").
:- comment(desc, html("<P>
A heap is a labelled binary tree where the key of each node is less
than or equal to the keys of its sons. The point of a heap is that
we can keep on adding new elements to the heap and we can keep on
taking out the minimum element. If there are N elements total, the
total time is O(NlgN). If you know all the elements in advance, you
are better off doing a merge-sort, but this file is for when you
want to do say a best-first search, and have no idea when you start
how many elements there will be, let alone what they are.
</P><P>
A heap is represented as a triple t(N, Free, Tree) where N is the
number of elements in the tree, Free is a list of integers which
specifies unused positions in the tree, and Tree is a tree made of
<PRE>
t terms for empty subtrees and
t(Key,Datum,Lson,Rson) terms for the rest
</PRE>
The nodes of the tree are notionally numbered like this:
<PRE>
1
2 3
4 6 5 7
8 12 10 14 9 13 11 15
.. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
</PRE>
The idea is that if the maximum number of elements that have been in
the heap so far is M, and the tree currently has K elements, the tree
is some subtreee of the tree of this form having exactly M elements,
and the Free list is a list of K-M integers saying which of the
positions in the M-element tree are currently unoccupied. This free
list is needed to ensure that the cost of passing N elements through
the heap is O(NlgM) instead of O(NlgN). For M say 100 and N say 10^4
this means a factor of two. The cost of the free list is slight.
The storage cost of a heap in a copying Prolog (which Dec-10 Prolog is
not) is 2K+3M words.
</P>
")).
:- comment(add_to_heap/4, [
summary:"inserts the new Key-Datum pair into the heap",
template:"add_to_heap(+OldHeap, +Key, +Datum, -NewHeap)",
desc:html("
inserts the new Key-Datum pair into the heap. The insertion is
not stable, that is, if you insert several pairs with the same
Key it is not defined which of them will come out first, and it
is possible for any of them to come out first depending on the
history of the heap. If you need a stable heap, you could add
a counter to the heap and include the counter at the time of
insertion in the key. If the free list is empty, the tree will
be grown, otherwise one of the empty slots will be re-used. (I
use imperative programming language, but the heap code is as
pure as the trees code, you can create any number of variants
starting from the same heap, and they will share what common
structure they can without interfering with each other.)
")]).
add_to_heap(t(M,[],OldTree), Key, Datum, t(N,[],NewTree)) :- !,
N is M+1,
add_to_heap(N, Key, Datum, OldTree, NewTree).
add_to_heap(t(M,[H|T],OldTree), Key, Datum, t(N,T,NewTree)) :-
N is M+1,
add_to_heap(H, Key, Datum, OldTree, NewTree).
add_to_heap(1, Key, Datum, _, t(Key,Datum,t,t)) :- !.
add_to_heap(N, Key, Datum, t(K1,D1,L1,R1), t(K2,D2,L2,R2)) :-
E is N mod 2,
M is N // 2,
sort2(Key, Datum, K1, D1, K2, D2, K3, D3),
add_to_heap(E, M, K3, D3, L1, R1, L2, R2).
add_to_heap(0, N, Key, Datum, L1, R, L2, R) :- !,
add_to_heap(N, Key, Datum, L1, L2).
add_to_heap(1, N, Key, Datum, L, R1, L, R2) :- !,
add_to_heap(N, Key, Datum, R1, R2).
sort2(Key1, Datum1, Key2, Datum2, Key1, Datum1, Key2, Datum2) :-
Key1 @< Key2,
!.
sort2(Key1, Datum1, Key2, Datum2, Key2, Datum2, Key1, Datum1).
:- comment(get_from_heap/4, [
summary:"returns the Key-Datum pair in OldHeap with the smallest Key",
template:"get_from_heap(+OldHeap, ?Key, ?Datum, -NewHeap)",
desc:html("
returns the Key-Datum pair in OldHeap with the smallest Key, and
also a New Heap which is the Old Heap with that pair deleted.
The easy part is picking off the smallest element. The hard part
is repairing the heap structure. repair_heap/4 takes a pair of
heaps and returns a new heap built from their elements, and the
position number of the gap in the new tree. Note that repair_heap
is *not* tail-recursive.
")]).
get_from_heap(t(N,Free,t(Key,Datum,L,R)), Key, Datum, t(M,[Hole|Free],Tree)) :-
M is N-1,
repair_heap(L, R, Tree, Hole).
repair_heap(t(K1,D1,L1,R1), t(K2,D2,L2,R2), t(K2,D2,t(K1,D1,L1,R1),R3), N) :-
K2 @< K1,
!,
repair_heap(L2, R2, R3, M),
N is 2*M+1.
repair_heap(t(K1,D1,L1,R1), t(K2,D2,L2,R2), t(K1,D1,L3,t(K2,D2,L2,R2)), N) :- !,
repair_heap(L1, R1, L3, M),
N is 2*M.
repair_heap(t(K1,D1,L1,R1), t, t(K1,D1,L3,t), N) :- !,
repair_heap(L1, R1, L3, M),
N is 2*M.
repair_heap(t, t(K2,D2,L2,R2), t(K2,D2,t,R3), N) :- !,
repair_heap(L2, R2, R3, M),
N is 2*M+1.
repair_heap(t, t, t, 1) :- !.
:- comment(heap_size/2, [
summary:"reports the number of elements currently in the heap",
template:"heap_size(+Heap, ?Size)"]).
heap_size(t(Size,_,_), Size).
:- comment(heap_to_list/2, [
summary:"returns the current set of Key-Datum pairs in the Heap as a List.",
template:"heap_to_list(+Heap, -List)",
desc:html("
returns the current set of Key-Datum pairs in the Heap as a
List, sorted into ascending order of Keys. This is included
simply because I think every data structure foo ought to have
a foo_to_list and list_to_foo relation (where, of course, it
makes sense!) so that conversion between arbitrary data
structures is as easy as possible. This predicate is basically
just a merge sort, where we can exploit the fact that the tops
of the subtrees are smaller than their descendants.
")]).
heap_to_list(t(_,_,Tree), List) :-
heap_tree_to_list(Tree, List).
heap_tree_to_list(t, []) :- !.
heap_tree_to_list(t(Key,Datum,Lson,Rson), [Key-Datum|Merged]) :-
heap_tree_to_list(Lson, Llist),
heap_tree_to_list(Rson, Rlist),
heap_tree_to_list(Llist, Rlist, Merged).
heap_tree_to_list([H1|T1], [H2|T2], [H2|T3]) :-
H2 @< H1,
!,
heap_tree_to_list([H1|T1], T2, T3).
heap_tree_to_list([H1|T1], T2, [H1|T3]) :- !,
heap_tree_to_list(T1, T2, T3).
heap_tree_to_list([], T, T) :- !.
heap_tree_to_list(T, [], T).
:- comment(list_to_heap/2, [
summary:"takes a list of Key-Datum pairs and forms them into a heap",
template:"list_to_heap(+List, -Heap)",
desc:html("
takes a list of Key-Datum pairs (such as keysort could be used to
sort) and forms them into a heap. We could do that a wee bit
faster by keysorting the list and building the tree directly, but
this algorithm makes it obvious that the result is a heap, and
could be adapted for use when the ordering predicate is not @<
and hence keysort is inapplicable.
")]).
list_to_heap(List, Heap) :-
list_to_heap(List, 0, t, Heap).
list_to_heap([], N, Tree, t(N,[],Tree)) :- !.
list_to_heap([Key-Datum|Rest], M, OldTree, Heap) :-
N is M+1,
add_to_heap(N, Key, Datum, OldTree, MidTree),
list_to_heap(Rest, N, MidTree, Heap).
:- comment(min_of_heap/3, [
summary:"returns the Key-Datum pair at the top of the heap",
template:"min_of_heap(+Heap, ?Key, ?Datum)",
desc:html("
returns the Key-Datum pair at the top of the heap (which is of
course the pair with the smallest Key), but does not remove it
from the heap. It fails if the heap is empty.
")]).
:- comment(min_of_heap/5, [
summary:"returns the smallest and second smallest pairs in the heap",
template:"min_of_heap(+Heap, ?Key1, ?Datum1, ?Key2, ?Datum2)",
desc:html("
returns the smallest (Key1) and second smallest (Key2) pairs in
the heap, without deleting them. It fails if the heap does not
have at least two elements.
")]).
min_of_heap(t(_,_,t(Key,Datum,_,_)), Key, Datum).
min_of_heap(t(_,_,t(Key1,Datum1,Lson,Rson)), Key1, Datum1, Key2, Datum2) :-
min_of_heap(Lson, Rson, Key2, Datum2).
min_of_heap(t(Ka,_Da,_,_), t(Kb,Db,_,_), Kb, Db) :-
Kb @< Ka, !.
min_of_heap(t(Ka,Da,_,_), _, Ka, Da).
min_of_heap(t, t(Kb,Db,_,_), Kb, Db).
| linusyang/barrelfish | usr/skb/eclipse_kernel/lib/heaps.pl | Perl | mit | 9,599 |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _createSvgIcon = _interopRequireDefault(require("../../utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
/**
* @ignore - internal component.
*/
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"
}), 'Star');
exports.default = _default; | cdnjs/cdnjs | ajax/libs/material-ui/5.0.0-alpha.36/node/internal/svg-icons/Star.js | JavaScript | mit | 738 |
/**
* Copyright (c) 2014,2019 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.smarthome.core.library.items;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.smarthome.core.library.CoreItemFactory;
import org.eclipse.smarthome.core.library.types.IncreaseDecreaseType;
import org.eclipse.smarthome.core.library.types.OnOffType;
import org.eclipse.smarthome.core.library.types.PercentType;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.RefreshType;
import org.eclipse.smarthome.core.types.State;
import org.eclipse.smarthome.core.types.UnDefType;
/**
* A DimmerItem can be used as a switch (ON/OFF), but it also accepts percent values
* to reflect the dimmed state.
*
* @author Kai Kreuzer - Initial contribution and API
* @author Markus Rathgeb - Support more types for getStateAs
*
*/
@NonNullByDefault
public class DimmerItem extends SwitchItem {
private static List<Class<? extends State>> acceptedDataTypes = new ArrayList<Class<? extends State>>();
private static List<Class<? extends Command>> acceptedCommandTypes = new ArrayList<Class<? extends Command>>();
static {
acceptedDataTypes.add(PercentType.class);
acceptedDataTypes.add(OnOffType.class);
acceptedDataTypes.add(UnDefType.class);
acceptedCommandTypes.add(PercentType.class);
acceptedCommandTypes.add(OnOffType.class);
acceptedCommandTypes.add(IncreaseDecreaseType.class);
acceptedCommandTypes.add(RefreshType.class);
}
public DimmerItem(String name) {
super(CoreItemFactory.DIMMER, name);
}
/* package */ DimmerItem(String type, String name) {
super(type, name);
}
public void send(PercentType command) {
internalSend(command);
}
@Override
public List<Class<? extends State>> getAcceptedDataTypes() {
return Collections.unmodifiableList(acceptedDataTypes);
}
@Override
public List<Class<? extends Command>> getAcceptedCommandTypes() {
return Collections.unmodifiableList(acceptedCommandTypes);
}
@Override
public void setState(State state) {
if (isAcceptedState(acceptedDataTypes, state)) {
// try conversion
State convertedState = state.as(PercentType.class);
if (convertedState != null) {
applyState(convertedState);
} else {
applyState(state);
}
} else {
logSetTypeError(state);
}
}
}
| Snickermicker/smarthome | bundles/core/org.eclipse.smarthome.core/src/main/java/org/eclipse/smarthome/core/library/items/DimmerItem.java | Java | epl-1.0 | 3,066 |
blueberry=$(date -d "$(stat -c $(%z) blueberry.exe)")
| jerr/jbossforge-core | text/src/test/resources/examples/bash/nested_shells.in.sh | Shell | epl-1.0 | 54 |
/*
*
* Copyright (c) 2005
* Francois Dumont
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#ifndef _STLP_STLPORT_VERSION_H
#define _STLP_STLPORT_VERSION_H
/* The last SGI STL release we merged with */
#define __SGI_STL 0x330
/* STLport version */
#define _STLPORT_MAJOR 5
#define _STLPORT_MINOR 1
#define _STLPORT_PATCHLEVEL 5
#define _STLPORT_VERSION 0x515
#endif /* _STLP_STLPORT_VERSION_H */
| yeKcim/warmux | trunk/build/symbian/lib/stlport/stlport/stl/_stlport_version.h | C | gpl-2.0 | 847 |
/*
* ath79-mbox.c -- ALSA MBOX DMA management functions
*
* Copyright (c) 2013 The Linux Foundation. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <linux/dma-mapping.h>
#include <linux/types.h>
#include <linux/dmapool.h>
#include <linux/delay.h>
#include <sound/core.h>
#include <asm/mach-ath79/ar71xx_regs.h>
#include <asm/mach-ath79/ath79.h>
#include "ath79-pcm.h"
#include "ath79-i2s.h"
spinlock_t ath79_pcm_lock;
static struct dma_pool *ath79_pcm_cache;
void ath79_mbox_reset(void)
{
u32 t;
spin_lock(&ath79_pcm_lock);
t = ath79_reset_rr(AR934X_RESET_REG_RESET_MODULE);
t |= AR934X_RESET_MBOX;
ath79_reset_wr(AR934X_RESET_REG_RESET_MODULE, t);
udelay(50);
t &= ~(AR934X_RESET_MBOX);
ath79_reset_wr(AR934X_RESET_REG_RESET_MODULE, t);
spin_unlock(&ath79_pcm_lock);
}
void ath79_mbox_fifo_reset(u32 mask)
{
ath79_dma_wr(AR934X_DMA_REG_MBOX_FIFO_RESET, mask);
udelay(50);
/* Datasheet says we should reset the stereo controller whenever
* we reset the MBOX DMA controller */
ath79_stereo_reset();
}
void ath79_mbox_interrupt_enable(u32 mask)
{
u32 t;
spin_lock(&ath79_pcm_lock);
t = ath79_dma_rr(AR934X_DMA_REG_MBOX_INT_ENABLE);
t |= mask;
ath79_dma_wr(AR934X_DMA_REG_MBOX_INT_ENABLE, t);
spin_unlock(&ath79_pcm_lock);
}
void ath79_mbox_interrupt_ack(u32 mask)
{
ath79_dma_wr(AR934X_DMA_REG_MBOX_INT_STATUS, mask);
ath79_reset_wr(AR71XX_RESET_REG_MISC_INT_STATUS, ~(MISC_INT_DMA));
/* Flush these two registers */
ath79_dma_rr(AR934X_DMA_REG_MBOX_INT_STATUS);
ath79_reset_rr(AR71XX_RESET_REG_MISC_INT_STATUS);
}
void ath79_mbox_dma_start(struct ath79_pcm_rt_priv *rtpriv)
{
if (rtpriv->direction == SNDRV_PCM_STREAM_PLAYBACK) {
ath79_dma_wr(AR934X_DMA_REG_MBOX0_DMA_RX_CONTROL,
AR934X_DMA_MBOX_DMA_CONTROL_START);
ath79_dma_rr(AR934X_DMA_REG_MBOX0_DMA_RX_CONTROL);
} else {
ath79_dma_wr(AR934X_DMA_REG_MBOX0_DMA_TX_CONTROL,
AR934X_DMA_MBOX_DMA_CONTROL_START);
ath79_dma_rr(AR934X_DMA_REG_MBOX0_DMA_TX_CONTROL);
}
}
void ath79_mbox_dma_stop(struct ath79_pcm_rt_priv *rtpriv)
{
if (rtpriv->direction == SNDRV_PCM_STREAM_PLAYBACK) {
ath79_dma_wr(AR934X_DMA_REG_MBOX0_DMA_RX_CONTROL,
AR934X_DMA_MBOX_DMA_CONTROL_STOP);
ath79_dma_rr(AR934X_DMA_REG_MBOX0_DMA_RX_CONTROL);
} else {
ath79_dma_wr(AR934X_DMA_REG_MBOX0_DMA_TX_CONTROL,
AR934X_DMA_MBOX_DMA_CONTROL_STOP);
ath79_dma_rr(AR934X_DMA_REG_MBOX0_DMA_TX_CONTROL);
}
/* Delay for the dynamically calculated max time based on
sample size, channel, sample rate + margin to ensure that the
DMA engine will be truly idle. */
mdelay(rtpriv->delay_time);
}
void ath79_mbox_dma_reset(void)
{
ath79_mbox_reset();
ath79_mbox_fifo_reset(AR934X_DMA_MBOX0_FIFO_RESET_RX |
AR934X_DMA_MBOX0_FIFO_RESET_TX);
}
void ath79_mbox_dma_prepare(struct ath79_pcm_rt_priv *rtpriv)
{
struct ath79_pcm_desc *desc;
u32 t;
if (rtpriv->direction == SNDRV_PCM_STREAM_PLAYBACK) {
/* Request the DMA channel to the controller */
t = ath79_dma_rr(AR934X_DMA_REG_MBOX_DMA_POLICY);
ath79_dma_wr(AR934X_DMA_REG_MBOX_DMA_POLICY,
t | AR934X_DMA_MBOX_DMA_POLICY_RX_QUANTUM |
(6 << AR934X_DMA_MBOX_DMA_POLICY_TX_FIFO_THRESH_SHIFT));
/* The direction is indicated from the DMA engine perspective
* i.e. we'll be using the RX registers for Playback and
* the TX registers for capture */
desc = list_first_entry(&rtpriv->dma_head, struct ath79_pcm_desc, list);
ath79_dma_wr(AR934X_DMA_REG_MBOX0_DMA_RX_DESCRIPTOR_BASE,
(u32) desc->phys);
ath79_mbox_interrupt_enable(AR934X_DMA_MBOX0_INT_RX_COMPLETE);
} else {
/* Request the DMA channel to the controller */
t = ath79_dma_rr(AR934X_DMA_REG_MBOX_DMA_POLICY);
ath79_dma_wr(AR934X_DMA_REG_MBOX_DMA_POLICY,
t | AR934X_DMA_MBOX_DMA_POLICY_TX_QUANTUM |
(6 << AR934X_DMA_MBOX_DMA_POLICY_TX_FIFO_THRESH_SHIFT));
desc = list_first_entry(&rtpriv->dma_head, struct ath79_pcm_desc, list);
ath79_dma_wr(AR934X_DMA_REG_MBOX0_DMA_TX_DESCRIPTOR_BASE,
(u32) desc->phys);
ath79_mbox_interrupt_enable(AR934X_DMA_MBOX0_INT_TX_COMPLETE);
}
}
int ath79_mbox_dma_map(struct ath79_pcm_rt_priv *rtpriv, dma_addr_t baseaddr,
int period_bytes,int bufsize)
{
struct list_head *head = &rtpriv->dma_head;
struct ath79_pcm_desc *desc, *prev;
dma_addr_t desc_p;
unsigned int offset = 0;
spin_lock(&ath79_pcm_lock);
rtpriv->elapsed_size = 0;
/* We loop until we have enough buffers to map the requested DMA area */
do {
/* Allocate a descriptor and insert it into the DMA ring */
desc = dma_pool_alloc(ath79_pcm_cache, GFP_KERNEL, &desc_p);
if(!desc) {
return -ENOMEM;
}
memset(desc, 0, sizeof(struct ath79_pcm_desc));
desc->phys = desc_p;
list_add_tail(&desc->list, head);
desc->OWN = 1;
desc->rsvd1 = desc->rsvd2 = desc->rsvd3 = desc->EOM = 0;
/* buffer size may not be a multiple of period_bytes */
if (bufsize >= offset + period_bytes) {
desc->size = period_bytes;
} else {
desc->size = bufsize - offset;
}
desc->BufPtr = baseaddr + offset;
/* For now, we assume the buffer is always full
* -->length == size */
desc->length = desc->size;
/* We need to make sure we are not the first descriptor.
* If we are, prev doesn't point to a struct ath79_pcm_desc */
if (desc->list.prev != head) {
prev =
list_entry(desc->list.prev, struct ath79_pcm_desc,
list);
prev->NextPtr = desc->phys;
}
offset += desc->size;
} while (offset < bufsize);
/* Once all the descriptors have been created, we can close the loop
* by pointing from the last one to the first one */
desc = list_first_entry(head, struct ath79_pcm_desc, list);
prev = list_entry(head->prev, struct ath79_pcm_desc, list);
prev->NextPtr = desc->phys;
spin_unlock(&ath79_pcm_lock);
return 0;
}
void ath79_mbox_dma_unmap(struct ath79_pcm_rt_priv *rtpriv)
{
struct list_head *head = &rtpriv->dma_head;
struct ath79_pcm_desc *desc, *n;
spin_lock(&ath79_pcm_lock);
list_for_each_entry_safe(desc, n, head, list) {
list_del(&desc->list);
dma_pool_free(ath79_pcm_cache, desc, desc->phys);
}
spin_unlock(&ath79_pcm_lock);
return;
}
int ath79_mbox_dma_init(struct device *dev)
{
int ret = 0;
/* Allocate a DMA pool to store the MBOX descriptor */
ath79_pcm_cache = dma_pool_create("ath79_pcm_pool", dev,
sizeof(struct ath79_pcm_desc), 4, 0);
if (!ath79_pcm_cache)
ret = -ENOMEM;
return ret;
}
void ath79_mbox_dma_exit(void)
{
dma_pool_destroy(ath79_pcm_cache);
ath79_pcm_cache = NULL;
}
| male-puppies/opwrt12 | target/linux/ar71xx/files/sound/soc/ath79/ath79-mbox.c | C | gpl-2.0 | 7,215 |
/*
* ome.server.itests.ImmutabilityTest
*
* Copyright 2006 University of Dundee. All rights reserved.
* Use is subject to license terms supplied in LICENSE.txt
*/
package ome.server.itests;
// Java imports
// Third-party libraries
import org.testng.annotations.Test;
// Application-internal dependencies
import ome.model.core.Image;
import ome.model.meta.Event;
import ome.parameters.Filter;
import ome.parameters.Parameters;
/**
*
* @author Josh Moore <a
* href="mailto:josh.moore@gmx.de">josh.moore@gmx.de</a>
* @version 1.0 <small> (<b>Internal version:</b> $Rev$ $Date$) </small>
* @since 1.0
*/
public class ImmutabilityTest extends AbstractManagedContextTest {
@Test
public void testCreationEventWillBeSilentlyUnchanged() throws Exception {
loginRoot();
Image i = new_Image("immutable creation");
i = iUpdate.saveAndReturnObject(i);
Event oldEvent = i.getDetails().getCreationEvent();
Event newEvent = iQuery.findByQuery(
"select e from Event e where id != :id", new Parameters(
new Filter().page(0, 1)).addId(oldEvent.getId()));
i.getDetails().setCreationEvent(newEvent);
// This fails because it gets silently copied to our new instance. See:
// http://trac.openmicroscopy.org.uk/ome/ticket/346
// i = iUpdate.saveAndReturnObject(i);
// assertEquals( i.getDetails().getCreationEvent().getId(),
// oldEvent.getId());
// Saving and reacquiring to be sure.
iUpdate.saveObject(i);
// unfortunately still not working properly i = iQuery.refresh(i);
i = iQuery.get(i.getClass(), i.getId());
assertEquals(i.getDetails().getCreationEvent().getId(), oldEvent
.getId());
}
}
| bramalingam/openmicroscopy | components/server/test/ome/server/itests/ImmutabilityTest.java | Java | gpl-2.0 | 1,831 |
/****************************************************************************************
* Copyright (c) 2007 Nikolaj Hald Nielsen <nhn@kde.org> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 2 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
#include "core/capabilities/ActionsCapability.h"
Capabilities::ActionsCapability::ActionsCapability()
: Capabilities::Capability()
{
//nothing to do
}
Capabilities::ActionsCapability::ActionsCapability( const QList<QAction*> &actions )
: Capabilities::Capability()
, m_actions( actions )
{
//nothing to do
}
Capabilities::ActionsCapability::~ActionsCapability()
{
//nothing to do.
}
QList<QAction *>
Capabilities::ActionsCapability::actions() const
{
return m_actions;
}
#include "ActionsCapability.moc"
| orangejulius/amarok | src/core/capabilities/ActionsCapability.cpp | C++ | gpl-2.0 | 1,889 |
/* PR target/95211 target/95256 */
/* { dg-do compile { target { ! ia32 } } } */
/* { dg-options "-O2 -ftree-slp-vectorize -march=skylake-avx512" } */
extern float f[4];
extern long long l[2];
extern long long ul[2];
void
fix_128 (void)
{
l[0] = f[0];
l[1] = f[1];
}
void
fixuns_128 (void)
{
ul[0] = f[0];
ul[1] = f[1];
}
void
float_128 (void)
{
f[0] = l[0];
f[1] = l[1];
}
void
floatuns_128 (void)
{
f[0] = ul[0];
f[1] = ul[1];
}
/* { dg-final { scan-assembler-times "vcvttps2qq" 2 } } */
/* { dg-final { scan-assembler-times "vcvtqq2ps" 2 } } */
| Gurgel100/gcc | gcc/testsuite/gcc.target/i386/pr95211.c | C | gpl-2.0 | 570 |
/*
* Copyright (c) 2018, 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.
*/
#include "native_thread.cpp"
#include "nsk_tools.cpp"
#include "jni_tools.cpp"
#include "jvmti_tools.cpp"
#include "agent_tools.cpp"
#include "jvmti_FollowRefObjects.cpp"
#include "Injector.cpp"
#include "JVMTITools.cpp"
#include "SetNativeMethodPrefix002Main.cpp"
| md-5/jdk10 | test/hotspot/jtreg/vmTestbase/nsk/jvmti/SetNativeMethodPrefix/SetNativeMethodPrefix002/libSetNativeMethodPrefix002Main.cpp | C++ | gpl-2.0 | 1,317 |
// SPDX-License-Identifier: GPL-2.0
/*
* Functions for working with device tree overlays
*
* Copyright (C) 2012 Pantelis Antoniou <panto@antoniou-consulting.com>
* Copyright (C) 2012 Texas Instruments Inc.
*/
#define pr_fmt(fmt) "OF: overlay: " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/of_fdt.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/libfdt.h>
#include <linux/err.h>
#include <linux/idr.h>
#include "of_private.h"
/**
* struct target - info about current target node as recursing through overlay
* @np: node where current level of overlay will be applied
* @in_livetree: @np is a node in the live devicetree
*
* Used in the algorithm to create the portion of a changeset that describes
* an overlay fragment, which is a devicetree subtree. Initially @np is a node
* in the live devicetree where the overlay subtree is targeted to be grafted
* into. When recursing to the next level of the overlay subtree, the target
* also recurses to the next level of the live devicetree, as long as overlay
* subtree node also exists in the live devicetree. When a node in the overlay
* subtree does not exist at the same level in the live devicetree, target->np
* points to a newly allocated node, and all subsequent targets in the subtree
* will be newly allocated nodes.
*/
struct target {
struct device_node *np;
bool in_livetree;
};
/**
* struct fragment - info about fragment nodes in overlay expanded device tree
* @target: target of the overlay operation
* @overlay: pointer to the __overlay__ node
*/
struct fragment {
struct device_node *overlay;
struct device_node *target;
};
/**
* struct overlay_changeset
* @id: changeset identifier
* @ovcs_list: list on which we are located
* @fdt: FDT that was unflattened to create @overlay_tree
* @overlay_tree: expanded device tree that contains the fragment nodes
* @count: count of fragment structures
* @fragments: fragment nodes in the overlay expanded device tree
* @symbols_fragment: last element of @fragments[] is the __symbols__ node
* @cset: changeset to apply fragments to live device tree
*/
struct overlay_changeset {
int id;
struct list_head ovcs_list;
const void *fdt;
struct device_node *overlay_tree;
int count;
struct fragment *fragments;
bool symbols_fragment;
struct of_changeset cset;
};
/* flags are sticky - once set, do not reset */
static int devicetree_state_flags;
#define DTSF_APPLY_FAIL 0x01
#define DTSF_REVERT_FAIL 0x02
/*
* If a changeset apply or revert encounters an error, an attempt will
* be made to undo partial changes, but may fail. If the undo fails
* we do not know the state of the devicetree.
*/
static int devicetree_corrupt(void)
{
return devicetree_state_flags &
(DTSF_APPLY_FAIL | DTSF_REVERT_FAIL);
}
static int build_changeset_next_level(struct overlay_changeset *ovcs,
struct target *target, const struct device_node *overlay_node);
/*
* of_resolve_phandles() finds the largest phandle in the live tree.
* of_overlay_apply() may add a larger phandle to the live tree.
* Do not allow race between two overlays being applied simultaneously:
* mutex_lock(&of_overlay_phandle_mutex)
* of_resolve_phandles()
* of_overlay_apply()
* mutex_unlock(&of_overlay_phandle_mutex)
*/
static DEFINE_MUTEX(of_overlay_phandle_mutex);
void of_overlay_mutex_lock(void)
{
mutex_lock(&of_overlay_phandle_mutex);
}
void of_overlay_mutex_unlock(void)
{
mutex_unlock(&of_overlay_phandle_mutex);
}
static LIST_HEAD(ovcs_list);
static DEFINE_IDR(ovcs_idr);
static BLOCKING_NOTIFIER_HEAD(overlay_notify_chain);
/**
* of_overlay_notifier_register() - Register notifier for overlay operations
* @nb: Notifier block to register
*
* Register for notification on overlay operations on device tree nodes. The
* reported actions definied by @of_reconfig_change. The notifier callback
* furthermore receives a pointer to the affected device tree node.
*
* Note that a notifier callback is not supposed to store pointers to a device
* tree node or its content beyond @OF_OVERLAY_POST_REMOVE corresponding to the
* respective node it received.
*/
int of_overlay_notifier_register(struct notifier_block *nb)
{
return blocking_notifier_chain_register(&overlay_notify_chain, nb);
}
EXPORT_SYMBOL_GPL(of_overlay_notifier_register);
/**
* of_overlay_notifier_register() - Unregister notifier for overlay operations
* @nb: Notifier block to unregister
*/
int of_overlay_notifier_unregister(struct notifier_block *nb)
{
return blocking_notifier_chain_unregister(&overlay_notify_chain, nb);
}
EXPORT_SYMBOL_GPL(of_overlay_notifier_unregister);
static char *of_overlay_action_name[] = {
"pre-apply",
"post-apply",
"pre-remove",
"post-remove",
};
static int overlay_notify(struct overlay_changeset *ovcs,
enum of_overlay_notify_action action)
{
struct of_overlay_notify_data nd;
int i, ret;
for (i = 0; i < ovcs->count; i++) {
struct fragment *fragment = &ovcs->fragments[i];
nd.target = fragment->target;
nd.overlay = fragment->overlay;
ret = blocking_notifier_call_chain(&overlay_notify_chain,
action, &nd);
if (ret == NOTIFY_OK || ret == NOTIFY_STOP)
return 0;
if (ret) {
ret = notifier_to_errno(ret);
pr_err("overlay changeset %s notifier error %d, target: %pOF\n",
of_overlay_action_name[action], ret, nd.target);
return ret;
}
}
return 0;
}
/*
* The values of properties in the "/__symbols__" node are paths in
* the ovcs->overlay_tree. When duplicating the properties, the paths
* need to be adjusted to be the correct path for the live device tree.
*
* The paths refer to a node in the subtree of a fragment node's "__overlay__"
* node, for example "/fragment@0/__overlay__/symbol_path_tail",
* where symbol_path_tail can be a single node or it may be a multi-node path.
*
* The duplicated property value will be modified by replacing the
* "/fragment_name/__overlay/" portion of the value with the target
* path from the fragment node.
*/
static struct property *dup_and_fixup_symbol_prop(
struct overlay_changeset *ovcs, const struct property *prop)
{
struct fragment *fragment;
struct property *new_prop;
struct device_node *fragment_node;
struct device_node *overlay_node;
const char *path;
const char *path_tail;
const char *target_path;
int k;
int overlay_name_len;
int path_len;
int path_tail_len;
int target_path_len;
if (!prop->value)
return NULL;
if (strnlen(prop->value, prop->length) >= prop->length)
return NULL;
path = prop->value;
path_len = strlen(path);
if (path_len < 1)
return NULL;
fragment_node = __of_find_node_by_path(ovcs->overlay_tree, path + 1);
overlay_node = __of_find_node_by_path(fragment_node, "__overlay__/");
of_node_put(fragment_node);
of_node_put(overlay_node);
for (k = 0; k < ovcs->count; k++) {
fragment = &ovcs->fragments[k];
if (fragment->overlay == overlay_node)
break;
}
if (k >= ovcs->count)
return NULL;
overlay_name_len = snprintf(NULL, 0, "%pOF", fragment->overlay);
if (overlay_name_len > path_len)
return NULL;
path_tail = path + overlay_name_len;
path_tail_len = strlen(path_tail);
target_path = kasprintf(GFP_KERNEL, "%pOF", fragment->target);
if (!target_path)
return NULL;
target_path_len = strlen(target_path);
new_prop = kzalloc(sizeof(*new_prop), GFP_KERNEL);
if (!new_prop)
goto err_free_target_path;
new_prop->name = kstrdup(prop->name, GFP_KERNEL);
new_prop->length = target_path_len + path_tail_len + 1;
new_prop->value = kzalloc(new_prop->length, GFP_KERNEL);
if (!new_prop->name || !new_prop->value)
goto err_free_new_prop;
strcpy(new_prop->value, target_path);
strcpy(new_prop->value + target_path_len, path_tail);
of_property_set_flag(new_prop, OF_DYNAMIC);
return new_prop;
err_free_new_prop:
kfree(new_prop->name);
kfree(new_prop->value);
kfree(new_prop);
err_free_target_path:
kfree(target_path);
return NULL;
}
/**
* add_changeset_property() - add @overlay_prop to overlay changeset
* @ovcs: overlay changeset
* @target: where @overlay_prop will be placed
* @overlay_prop: property to add or update, from overlay tree
* @is_symbols_prop: 1 if @overlay_prop is from node "/__symbols__"
*
* If @overlay_prop does not already exist in live devicetree, add changeset
* entry to add @overlay_prop in @target, else add changeset entry to update
* value of @overlay_prop.
*
* @target may be either in the live devicetree or in a new subtree that
* is contained in the changeset.
*
* Some special properties are not added or updated (no error returned):
* "name", "phandle", "linux,phandle".
*
* Properties "#address-cells" and "#size-cells" are not updated if they
* are already in the live tree, but if present in the live tree, the values
* in the overlay must match the values in the live tree.
*
* Update of property in symbols node is not allowed.
*
* Returns 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if
* invalid @overlay.
*/
static int add_changeset_property(struct overlay_changeset *ovcs,
struct target *target, struct property *overlay_prop,
bool is_symbols_prop)
{
struct property *new_prop = NULL, *prop;
int ret = 0;
if (target->in_livetree)
if (!of_prop_cmp(overlay_prop->name, "name") ||
!of_prop_cmp(overlay_prop->name, "phandle") ||
!of_prop_cmp(overlay_prop->name, "linux,phandle"))
return 0;
if (target->in_livetree)
prop = of_find_property(target->np, overlay_prop->name, NULL);
else
prop = NULL;
if (prop) {
if (!of_prop_cmp(prop->name, "#address-cells")) {
if (!of_prop_val_eq(prop, overlay_prop)) {
pr_err("ERROR: changing value of #address-cells is not allowed in %pOF\n",
target->np);
ret = -EINVAL;
}
return ret;
} else if (!of_prop_cmp(prop->name, "#size-cells")) {
if (!of_prop_val_eq(prop, overlay_prop)) {
pr_err("ERROR: changing value of #size-cells is not allowed in %pOF\n",
target->np);
ret = -EINVAL;
}
return ret;
}
}
if (is_symbols_prop) {
if (prop)
return -EINVAL;
new_prop = dup_and_fixup_symbol_prop(ovcs, overlay_prop);
} else {
new_prop = __of_prop_dup(overlay_prop, GFP_KERNEL);
}
if (!new_prop)
return -ENOMEM;
if (!prop) {
if (!target->in_livetree) {
new_prop->next = target->np->deadprops;
target->np->deadprops = new_prop;
}
ret = of_changeset_add_property(&ovcs->cset, target->np,
new_prop);
} else {
ret = of_changeset_update_property(&ovcs->cset, target->np,
new_prop);
}
if (!of_node_check_flag(target->np, OF_OVERLAY))
pr_err("WARNING: memory leak will occur if overlay removed, property: %pOF/%s\n",
target->np, new_prop->name);
if (ret) {
kfree(new_prop->name);
kfree(new_prop->value);
kfree(new_prop);
}
return ret;
}
/**
* add_changeset_node() - add @node (and children) to overlay changeset
* @ovcs: overlay changeset
* @target: where @node will be placed in live tree or changeset
* @node: node from within overlay device tree fragment
*
* If @node does not already exist in @target, add changeset entry
* to add @node in @target.
*
* If @node already exists in @target, and the existing node has
* a phandle, the overlay node is not allowed to have a phandle.
*
* If @node has child nodes, add the children recursively via
* build_changeset_next_level().
*
* NOTE_1: A live devicetree created from a flattened device tree (FDT) will
* not contain the full path in node->full_name. Thus an overlay
* created from an FDT also will not contain the full path in
* node->full_name. However, a live devicetree created from Open
* Firmware may have the full path in node->full_name.
*
* add_changeset_node() follows the FDT convention and does not include
* the full path in node->full_name. Even though it expects the overlay
* to not contain the full path, it uses kbasename() to remove the
* full path should it exist. It also uses kbasename() in comparisons
* to nodes in the live devicetree so that it can apply an overlay to
* a live devicetree created from Open Firmware.
*
* NOTE_2: Multiple mods of created nodes not supported.
*
* Returns 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if
* invalid @overlay.
*/
static int add_changeset_node(struct overlay_changeset *ovcs,
struct target *target, struct device_node *node)
{
const char *node_kbasename;
const __be32 *phandle;
struct device_node *tchild;
struct target target_child;
int ret = 0, size;
node_kbasename = kbasename(node->full_name);
for_each_child_of_node(target->np, tchild)
if (!of_node_cmp(node_kbasename, kbasename(tchild->full_name)))
break;
if (!tchild) {
tchild = __of_node_dup(NULL, node_kbasename);
if (!tchild)
return -ENOMEM;
tchild->parent = target->np;
tchild->name = __of_get_property(node, "name", NULL);
if (!tchild->name)
tchild->name = "<NULL>";
/* ignore obsolete "linux,phandle" */
phandle = __of_get_property(node, "phandle", &size);
if (phandle && (size == 4))
tchild->phandle = be32_to_cpup(phandle);
of_node_set_flag(tchild, OF_OVERLAY);
ret = of_changeset_attach_node(&ovcs->cset, tchild);
if (ret)
return ret;
target_child.np = tchild;
target_child.in_livetree = false;
ret = build_changeset_next_level(ovcs, &target_child, node);
of_node_put(tchild);
return ret;
}
if (node->phandle && tchild->phandle) {
ret = -EINVAL;
} else {
target_child.np = tchild;
target_child.in_livetree = target->in_livetree;
ret = build_changeset_next_level(ovcs, &target_child, node);
}
of_node_put(tchild);
return ret;
}
/**
* build_changeset_next_level() - add level of overlay changeset
* @ovcs: overlay changeset
* @target: where to place @overlay_node in live tree
* @overlay_node: node from within an overlay device tree fragment
*
* Add the properties (if any) and nodes (if any) from @overlay_node to the
* @ovcs->cset changeset. If an added node has child nodes, they will
* be added recursively.
*
* Do not allow symbols node to have any children.
*
* Returns 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if
* invalid @overlay_node.
*/
static int build_changeset_next_level(struct overlay_changeset *ovcs,
struct target *target, const struct device_node *overlay_node)
{
struct device_node *child;
struct property *prop;
int ret;
for_each_property_of_node(overlay_node, prop) {
ret = add_changeset_property(ovcs, target, prop, 0);
if (ret) {
pr_debug("Failed to apply prop @%pOF/%s, err=%d\n",
target->np, prop->name, ret);
return ret;
}
}
for_each_child_of_node(overlay_node, child) {
ret = add_changeset_node(ovcs, target, child);
if (ret) {
pr_debug("Failed to apply node @%pOF/%pOFn, err=%d\n",
target->np, child, ret);
of_node_put(child);
return ret;
}
}
return 0;
}
/*
* Add the properties from __overlay__ node to the @ovcs->cset changeset.
*/
static int build_changeset_symbols_node(struct overlay_changeset *ovcs,
struct target *target,
const struct device_node *overlay_symbols_node)
{
struct property *prop;
int ret;
for_each_property_of_node(overlay_symbols_node, prop) {
ret = add_changeset_property(ovcs, target, prop, 1);
if (ret) {
pr_debug("Failed to apply symbols prop @%pOF/%s, err=%d\n",
target->np, prop->name, ret);
return ret;
}
}
return 0;
}
static int find_dup_cset_node_entry(struct overlay_changeset *ovcs,
struct of_changeset_entry *ce_1)
{
struct of_changeset_entry *ce_2;
char *fn_1, *fn_2;
int node_path_match;
if (ce_1->action != OF_RECONFIG_ATTACH_NODE &&
ce_1->action != OF_RECONFIG_DETACH_NODE)
return 0;
ce_2 = ce_1;
list_for_each_entry_continue(ce_2, &ovcs->cset.entries, node) {
if ((ce_2->action != OF_RECONFIG_ATTACH_NODE &&
ce_2->action != OF_RECONFIG_DETACH_NODE) ||
of_node_cmp(ce_1->np->full_name, ce_2->np->full_name))
continue;
fn_1 = kasprintf(GFP_KERNEL, "%pOF", ce_1->np);
fn_2 = kasprintf(GFP_KERNEL, "%pOF", ce_2->np);
node_path_match = !strcmp(fn_1, fn_2);
kfree(fn_1);
kfree(fn_2);
if (node_path_match) {
pr_err("ERROR: multiple fragments add and/or delete node %pOF\n",
ce_1->np);
return -EINVAL;
}
}
return 0;
}
static int find_dup_cset_prop(struct overlay_changeset *ovcs,
struct of_changeset_entry *ce_1)
{
struct of_changeset_entry *ce_2;
char *fn_1, *fn_2;
int node_path_match;
if (ce_1->action != OF_RECONFIG_ADD_PROPERTY &&
ce_1->action != OF_RECONFIG_REMOVE_PROPERTY &&
ce_1->action != OF_RECONFIG_UPDATE_PROPERTY)
return 0;
ce_2 = ce_1;
list_for_each_entry_continue(ce_2, &ovcs->cset.entries, node) {
if ((ce_2->action != OF_RECONFIG_ADD_PROPERTY &&
ce_2->action != OF_RECONFIG_REMOVE_PROPERTY &&
ce_2->action != OF_RECONFIG_UPDATE_PROPERTY) ||
of_node_cmp(ce_1->np->full_name, ce_2->np->full_name))
continue;
fn_1 = kasprintf(GFP_KERNEL, "%pOF", ce_1->np);
fn_2 = kasprintf(GFP_KERNEL, "%pOF", ce_2->np);
node_path_match = !strcmp(fn_1, fn_2);
kfree(fn_1);
kfree(fn_2);
if (node_path_match &&
!of_prop_cmp(ce_1->prop->name, ce_2->prop->name)) {
pr_err("ERROR: multiple fragments add, update, and/or delete property %pOF/%s\n",
ce_1->np, ce_1->prop->name);
return -EINVAL;
}
}
return 0;
}
/**
* changeset_dup_entry_check() - check for duplicate entries
* @ovcs: Overlay changeset
*
* Check changeset @ovcs->cset for multiple {add or delete} node entries for
* the same node or duplicate {add, delete, or update} properties entries
* for the same property.
*
* Returns 0 on success, or -EINVAL if duplicate changeset entry found.
*/
static int changeset_dup_entry_check(struct overlay_changeset *ovcs)
{
struct of_changeset_entry *ce_1;
int dup_entry = 0;
list_for_each_entry(ce_1, &ovcs->cset.entries, node) {
dup_entry |= find_dup_cset_node_entry(ovcs, ce_1);
dup_entry |= find_dup_cset_prop(ovcs, ce_1);
}
return dup_entry ? -EINVAL : 0;
}
/**
* build_changeset() - populate overlay changeset in @ovcs from @ovcs->fragments
* @ovcs: Overlay changeset
*
* Create changeset @ovcs->cset to contain the nodes and properties of the
* overlay device tree fragments in @ovcs->fragments[]. If an error occurs,
* any portions of the changeset that were successfully created will remain
* in @ovcs->cset.
*
* Returns 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if
* invalid overlay in @ovcs->fragments[].
*/
static int build_changeset(struct overlay_changeset *ovcs)
{
struct fragment *fragment;
struct target target;
int fragments_count, i, ret;
/*
* if there is a symbols fragment in ovcs->fragments[i] it is
* the final element in the array
*/
if (ovcs->symbols_fragment)
fragments_count = ovcs->count - 1;
else
fragments_count = ovcs->count;
for (i = 0; i < fragments_count; i++) {
fragment = &ovcs->fragments[i];
target.np = fragment->target;
target.in_livetree = true;
ret = build_changeset_next_level(ovcs, &target,
fragment->overlay);
if (ret) {
pr_debug("fragment apply failed '%pOF'\n",
fragment->target);
return ret;
}
}
if (ovcs->symbols_fragment) {
fragment = &ovcs->fragments[ovcs->count - 1];
target.np = fragment->target;
target.in_livetree = true;
ret = build_changeset_symbols_node(ovcs, &target,
fragment->overlay);
if (ret) {
pr_debug("symbols fragment apply failed '%pOF'\n",
fragment->target);
return ret;
}
}
return changeset_dup_entry_check(ovcs);
}
/*
* Find the target node using a number of different strategies
* in order of preference:
*
* 1) "target" property containing the phandle of the target
* 2) "target-path" property containing the path of the target
*/
static struct device_node *find_target(struct device_node *info_node)
{
struct device_node *node;
const char *path;
u32 val;
int ret;
ret = of_property_read_u32(info_node, "target", &val);
if (!ret) {
node = of_find_node_by_phandle(val);
if (!node)
pr_err("find target, node: %pOF, phandle 0x%x not found\n",
info_node, val);
return node;
}
ret = of_property_read_string(info_node, "target-path", &path);
if (!ret) {
node = of_find_node_by_path(path);
if (!node)
pr_err("find target, node: %pOF, path '%s' not found\n",
info_node, path);
return node;
}
pr_err("find target, node: %pOF, no target property\n", info_node);
return NULL;
}
/**
* init_overlay_changeset() - initialize overlay changeset from overlay tree
* @ovcs: Overlay changeset to build
* @fdt: the FDT that was unflattened to create @tree
* @tree: Contains all the overlay fragments and overlay fixup nodes
*
* Initialize @ovcs. Populate @ovcs->fragments with node information from
* the top level of @tree. The relevant top level nodes are the fragment
* nodes and the __symbols__ node. Any other top level node will be ignored.
*
* Returns 0 on success, -ENOMEM if memory allocation failure, -EINVAL if error
* detected in @tree, or -ENOSPC if idr_alloc() error.
*/
static int init_overlay_changeset(struct overlay_changeset *ovcs,
const void *fdt, struct device_node *tree)
{
struct device_node *node, *overlay_node;
struct fragment *fragment;
struct fragment *fragments;
int cnt, id, ret;
/*
* Warn for some issues. Can not return -EINVAL for these until
* of_unittest_apply_overlay() is fixed to pass these checks.
*/
if (!of_node_check_flag(tree, OF_DYNAMIC))
pr_debug("%s() tree is not dynamic\n", __func__);
if (!of_node_check_flag(tree, OF_DETACHED))
pr_debug("%s() tree is not detached\n", __func__);
if (!of_node_is_root(tree))
pr_debug("%s() tree is not root\n", __func__);
ovcs->overlay_tree = tree;
ovcs->fdt = fdt;
INIT_LIST_HEAD(&ovcs->ovcs_list);
of_changeset_init(&ovcs->cset);
id = idr_alloc(&ovcs_idr, ovcs, 1, 0, GFP_KERNEL);
if (id <= 0)
return id;
cnt = 0;
/* fragment nodes */
for_each_child_of_node(tree, node) {
overlay_node = of_get_child_by_name(node, "__overlay__");
if (overlay_node) {
cnt++;
of_node_put(overlay_node);
}
}
node = of_get_child_by_name(tree, "__symbols__");
if (node) {
cnt++;
of_node_put(node);
}
fragments = kcalloc(cnt, sizeof(*fragments), GFP_KERNEL);
if (!fragments) {
ret = -ENOMEM;
goto err_free_idr;
}
cnt = 0;
for_each_child_of_node(tree, node) {
overlay_node = of_get_child_by_name(node, "__overlay__");
if (!overlay_node)
continue;
fragment = &fragments[cnt];
fragment->overlay = overlay_node;
fragment->target = find_target(node);
if (!fragment->target) {
of_node_put(fragment->overlay);
ret = -EINVAL;
goto err_free_fragments;
}
cnt++;
}
/*
* if there is a symbols fragment in ovcs->fragments[i] it is
* the final element in the array
*/
node = of_get_child_by_name(tree, "__symbols__");
if (node) {
ovcs->symbols_fragment = 1;
fragment = &fragments[cnt];
fragment->overlay = node;
fragment->target = of_find_node_by_path("/__symbols__");
if (!fragment->target) {
pr_err("symbols in overlay, but not in live tree\n");
ret = -EINVAL;
goto err_free_fragments;
}
cnt++;
}
if (!cnt) {
pr_err("no fragments or symbols in overlay\n");
ret = -EINVAL;
goto err_free_fragments;
}
ovcs->id = id;
ovcs->count = cnt;
ovcs->fragments = fragments;
return 0;
err_free_fragments:
kfree(fragments);
err_free_idr:
idr_remove(&ovcs_idr, id);
pr_err("%s() failed, ret = %d\n", __func__, ret);
return ret;
}
static void free_overlay_changeset(struct overlay_changeset *ovcs)
{
int i;
if (ovcs->cset.entries.next)
of_changeset_destroy(&ovcs->cset);
if (ovcs->id)
idr_remove(&ovcs_idr, ovcs->id);
for (i = 0; i < ovcs->count; i++) {
of_node_put(ovcs->fragments[i].target);
of_node_put(ovcs->fragments[i].overlay);
}
kfree(ovcs->fragments);
/*
* There should be no live pointers into ovcs->overlay_tree and
* ovcs->fdt due to the policy that overlay notifiers are not allowed
* to retain pointers into the overlay devicetree.
*/
kfree(ovcs->overlay_tree);
kfree(ovcs->fdt);
kfree(ovcs);
}
/*
* internal documentation
*
* of_overlay_apply() - Create and apply an overlay changeset
* @fdt: the FDT that was unflattened to create @tree
* @tree: Expanded overlay device tree
* @ovcs_id: Pointer to overlay changeset id
*
* Creates and applies an overlay changeset.
*
* If an error occurs in a pre-apply notifier, then no changes are made
* to the device tree.
*
* A non-zero return value will not have created the changeset if error is from:
* - parameter checks
* - building the changeset
* - overlay changeset pre-apply notifier
*
* If an error is returned by an overlay changeset pre-apply notifier
* then no further overlay changeset pre-apply notifier will be called.
*
* A non-zero return value will have created the changeset if error is from:
* - overlay changeset entry notifier
* - overlay changeset post-apply notifier
*
* If an error is returned by an overlay changeset post-apply notifier
* then no further overlay changeset post-apply notifier will be called.
*
* If more than one notifier returns an error, then the last notifier
* error to occur is returned.
*
* If an error occurred while applying the overlay changeset, then an
* attempt is made to revert any changes that were made to the
* device tree. If there were any errors during the revert attempt
* then the state of the device tree can not be determined, and any
* following attempt to apply or remove an overlay changeset will be
* refused.
*
* Returns 0 on success, or a negative error number. Overlay changeset
* id is returned to *ovcs_id.
*/
static int of_overlay_apply(const void *fdt, struct device_node *tree,
int *ovcs_id)
{
struct overlay_changeset *ovcs;
int ret = 0, ret_revert, ret_tmp;
/*
* As of this point, fdt and tree belong to the overlay changeset.
* overlay changeset code is responsible for freeing them.
*/
if (devicetree_corrupt()) {
pr_err("devicetree state suspect, refuse to apply overlay\n");
kfree(fdt);
kfree(tree);
ret = -EBUSY;
goto out;
}
ovcs = kzalloc(sizeof(*ovcs), GFP_KERNEL);
if (!ovcs) {
kfree(fdt);
kfree(tree);
ret = -ENOMEM;
goto out;
}
of_overlay_mutex_lock();
mutex_lock(&of_mutex);
ret = of_resolve_phandles(tree);
if (ret)
goto err_free_tree;
ret = init_overlay_changeset(ovcs, fdt, tree);
if (ret)
goto err_free_tree;
/*
* after overlay_notify(), ovcs->overlay_tree related pointers may have
* leaked to drivers, so can not kfree() tree, aka ovcs->overlay_tree;
* and can not free fdt, aka ovcs->fdt
*/
ret = overlay_notify(ovcs, OF_OVERLAY_PRE_APPLY);
if (ret) {
pr_err("overlay changeset pre-apply notify error %d\n", ret);
goto err_free_overlay_changeset;
}
ret = build_changeset(ovcs);
if (ret)
goto err_free_overlay_changeset;
ret_revert = 0;
ret = __of_changeset_apply_entries(&ovcs->cset, &ret_revert);
if (ret) {
if (ret_revert) {
pr_debug("overlay changeset revert error %d\n",
ret_revert);
devicetree_state_flags |= DTSF_APPLY_FAIL;
}
goto err_free_overlay_changeset;
}
of_populate_phandle_cache();
ret = __of_changeset_apply_notify(&ovcs->cset);
if (ret)
pr_err("overlay apply changeset entry notify error %d\n", ret);
/* notify failure is not fatal, continue */
list_add_tail(&ovcs->ovcs_list, &ovcs_list);
*ovcs_id = ovcs->id;
ret_tmp = overlay_notify(ovcs, OF_OVERLAY_POST_APPLY);
if (ret_tmp) {
pr_err("overlay changeset post-apply notify error %d\n",
ret_tmp);
if (!ret)
ret = ret_tmp;
}
goto out_unlock;
err_free_tree:
kfree(fdt);
kfree(tree);
err_free_overlay_changeset:
free_overlay_changeset(ovcs);
out_unlock:
mutex_unlock(&of_mutex);
of_overlay_mutex_unlock();
out:
pr_debug("%s() err=%d\n", __func__, ret);
return ret;
}
int of_overlay_fdt_apply(const void *overlay_fdt, u32 overlay_fdt_size,
int *ovcs_id)
{
const void *new_fdt;
int ret;
u32 size;
struct device_node *overlay_root;
*ovcs_id = 0;
ret = 0;
if (overlay_fdt_size < sizeof(struct fdt_header) ||
fdt_check_header(overlay_fdt)) {
pr_err("Invalid overlay_fdt header\n");
return -EINVAL;
}
size = fdt_totalsize(overlay_fdt);
if (overlay_fdt_size < size)
return -EINVAL;
/*
* Must create permanent copy of FDT because of_fdt_unflatten_tree()
* will create pointers to the passed in FDT in the unflattened tree.
*/
new_fdt = kmemdup(overlay_fdt, size, GFP_KERNEL);
if (!new_fdt)
return -ENOMEM;
of_fdt_unflatten_tree(new_fdt, NULL, &overlay_root);
if (!overlay_root) {
pr_err("unable to unflatten overlay_fdt\n");
ret = -EINVAL;
goto out_free_new_fdt;
}
ret = of_overlay_apply(new_fdt, overlay_root, ovcs_id);
if (ret < 0) {
/*
* new_fdt and overlay_root now belong to the overlay
* changeset.
* overlay changeset code is responsible for freeing them.
*/
goto out;
}
return 0;
out_free_new_fdt:
kfree(new_fdt);
out:
return ret;
}
EXPORT_SYMBOL_GPL(of_overlay_fdt_apply);
/*
* Find @np in @tree.
*
* Returns 1 if @np is @tree or is contained in @tree, else 0
*/
static int find_node(struct device_node *tree, struct device_node *np)
{
struct device_node *child;
if (tree == np)
return 1;
for_each_child_of_node(tree, child) {
if (find_node(child, np)) {
of_node_put(child);
return 1;
}
}
return 0;
}
/*
* Is @remove_ce_node a child of, a parent of, or the same as any
* node in an overlay changeset more topmost than @remove_ovcs?
*
* Returns 1 if found, else 0
*/
static int node_overlaps_later_cs(struct overlay_changeset *remove_ovcs,
struct device_node *remove_ce_node)
{
struct overlay_changeset *ovcs;
struct of_changeset_entry *ce;
list_for_each_entry_reverse(ovcs, &ovcs_list, ovcs_list) {
if (ovcs == remove_ovcs)
break;
list_for_each_entry(ce, &ovcs->cset.entries, node) {
if (find_node(ce->np, remove_ce_node)) {
pr_err("%s: #%d overlaps with #%d @%pOF\n",
__func__, remove_ovcs->id, ovcs->id,
remove_ce_node);
return 1;
}
if (find_node(remove_ce_node, ce->np)) {
pr_err("%s: #%d overlaps with #%d @%pOF\n",
__func__, remove_ovcs->id, ovcs->id,
remove_ce_node);
return 1;
}
}
}
return 0;
}
/*
* We can safely remove the overlay only if it's the top-most one.
* Newly applied overlays are inserted at the tail of the overlay list,
* so a top most overlay is the one that is closest to the tail.
*
* The topmost check is done by exploiting this property. For each
* affected device node in the log list we check if this overlay is
* the one closest to the tail. If another overlay has affected this
* device node and is closest to the tail, then removal is not permited.
*/
static int overlay_removal_is_ok(struct overlay_changeset *remove_ovcs)
{
struct of_changeset_entry *remove_ce;
list_for_each_entry(remove_ce, &remove_ovcs->cset.entries, node) {
if (node_overlaps_later_cs(remove_ovcs, remove_ce->np)) {
pr_err("overlay #%d is not topmost\n", remove_ovcs->id);
return 0;
}
}
return 1;
}
/**
* of_overlay_remove() - Revert and free an overlay changeset
* @ovcs_id: Pointer to overlay changeset id
*
* Removes an overlay if it is permissible. @ovcs_id was previously returned
* by of_overlay_fdt_apply().
*
* If an error occurred while attempting to revert the overlay changeset,
* then an attempt is made to re-apply any changeset entry that was
* reverted. If an error occurs on re-apply then the state of the device
* tree can not be determined, and any following attempt to apply or remove
* an overlay changeset will be refused.
*
* A non-zero return value will not revert the changeset if error is from:
* - parameter checks
* - overlay changeset pre-remove notifier
* - overlay changeset entry revert
*
* If an error is returned by an overlay changeset pre-remove notifier
* then no further overlay changeset pre-remove notifier will be called.
*
* If more than one notifier returns an error, then the last notifier
* error to occur is returned.
*
* A non-zero return value will revert the changeset if error is from:
* - overlay changeset entry notifier
* - overlay changeset post-remove notifier
*
* If an error is returned by an overlay changeset post-remove notifier
* then no further overlay changeset post-remove notifier will be called.
*
* Returns 0 on success, or a negative error number. *ovcs_id is set to
* zero after reverting the changeset, even if a subsequent error occurs.
*/
int of_overlay_remove(int *ovcs_id)
{
struct overlay_changeset *ovcs;
int ret, ret_apply, ret_tmp;
ret = 0;
if (devicetree_corrupt()) {
pr_err("suspect devicetree state, refuse to remove overlay\n");
ret = -EBUSY;
goto out;
}
mutex_lock(&of_mutex);
ovcs = idr_find(&ovcs_idr, *ovcs_id);
if (!ovcs) {
ret = -ENODEV;
pr_err("remove: Could not find overlay #%d\n", *ovcs_id);
goto out_unlock;
}
if (!overlay_removal_is_ok(ovcs)) {
ret = -EBUSY;
goto out_unlock;
}
ret = overlay_notify(ovcs, OF_OVERLAY_PRE_REMOVE);
if (ret) {
pr_err("overlay changeset pre-remove notify error %d\n", ret);
goto out_unlock;
}
list_del(&ovcs->ovcs_list);
/*
* Disable phandle cache. Avoids race condition that would arise
* from removing cache entry when the associated node is deleted.
*/
of_free_phandle_cache();
ret_apply = 0;
ret = __of_changeset_revert_entries(&ovcs->cset, &ret_apply);
of_populate_phandle_cache();
if (ret) {
if (ret_apply)
devicetree_state_flags |= DTSF_REVERT_FAIL;
goto out_unlock;
}
ret = __of_changeset_revert_notify(&ovcs->cset);
if (ret)
pr_err("overlay remove changeset entry notify error %d\n", ret);
/* notify failure is not fatal, continue */
*ovcs_id = 0;
ret_tmp = overlay_notify(ovcs, OF_OVERLAY_POST_REMOVE);
if (ret_tmp) {
pr_err("overlay changeset post-remove notify error %d\n",
ret_tmp);
if (!ret)
ret = ret_tmp;
}
free_overlay_changeset(ovcs);
out_unlock:
mutex_unlock(&of_mutex);
out:
pr_debug("%s() err=%d\n", __func__, ret);
return ret;
}
EXPORT_SYMBOL_GPL(of_overlay_remove);
/**
* of_overlay_remove_all() - Reverts and frees all overlay changesets
*
* Removes all overlays from the system in the correct order.
*
* Returns 0 on success, or a negative error number
*/
int of_overlay_remove_all(void)
{
struct overlay_changeset *ovcs, *ovcs_n;
int ret;
/* the tail of list is guaranteed to be safe to remove */
list_for_each_entry_safe_reverse(ovcs, ovcs_n, &ovcs_list, ovcs_list) {
ret = of_overlay_remove(&ovcs->id);
if (ret)
return ret;
}
return 0;
}
EXPORT_SYMBOL_GPL(of_overlay_remove_all);
| Pingmin/linux | drivers/of/overlay.c | C | gpl-2.0 | 34,958 |
<?php
$lan = array (
'This page can only be called from the commandline' => '这个页面只能够透过指令模式启用',
'Bounce processing error' => '退信处理错误',
'Bounce Processing info' => '退信处理讯息',
'error' => '错误',
'info' => '讯息',
'system message bounced, user marked unconfirmed' => '系统退信产生,使用者标示为未确认',
'Bounced system message' => '系统退信',
'User marked unconfirmed' => '使用者标示为未确认',
'View Bounce' => '浏览退信',
'Cannot create POP3 connection to' => '无法建立 POP3 连线于',
'Cannot open mailbox file' => '无法开启邮件档桉',
'bounces to fetch from the mailbox' => '封退信于信箱',
'Please do not interrupt this process' => '请不要中断这个处理程序',
'bounces to process' => '封退信待处理',
'Processing first' => '处理第一',
'bounces' => '封退信',
'Running in test mode, not deleting messages from mailbox' => '目前在测试模式中,无法从信箱删除信件',
'Processed messages will be deleted from mailbox' => '处理的信件将会从信箱删除',
'Deleting message' => '删除信件中',
'Closing mailbox, and purging messages' => '关闭信箱并且清除信件',
'IMAP is not included in your PHP installation, cannot continue' => '您的 PHP 不支援 IMAP ,无法继续',
'Check out' => '签出',
'Bounce mechanism not properly configured' => '退信机制也许还没设定',
'bounce_protocol not supported' => '不支援 bounce_protocol',
'Identifying consecutive bounces' => '辨识连续性退信',
'Nothing to do' => '没有动作',
'Process Killed by other process' => '处理程序被其他程序中止',
'User' => '使用者',
'has consecutive bounces' => '有连续退信',
'over threshold, user marked unconfirmed' => '超过系统设定,因此标示为未确认',
'Auto Unsubscribed' => '自动取消订阅',
'User auto unsubscribed for' => '使用者自动取消订阅于',
'consecutive bounces' => '连续退信',
'of' => '于',
'users processed' => '个使用者处理完成',
'processing first' => '处理第一封',
'Report:' => '报表:',
'Below are users who have been marked unconfirmed. The number in [' => '下面是未确认的使用者, [] 中的数字是他们的编号, () 中的数字代表他们有多少封退信',
'Processing bounces based on active bounce rules' => '透过启用中的退信规则处理退信',
'Auto Blacklisted' => '自动列为黑名单',
'User auto blacklisted for' => '使用者自动被列为黑名单于',
'bounce rule' => '退信规则',
'system message bounced, but unknown user' => '系统退回信件,但是没有符合的使用者',
'bounces processed by advanced processing' => '封退信经由进阶处理程序处理',
'bounces were not matched by advanced processing rules' => '封退信不符合进阶处理规则',
'Report of advanced bounce processing:' => '进阶退信处理报表:',
);
?> | washingtonstateuniversity/WSU-Lists | www/admin/lan/zh_CN/processbounces.php | PHP | gpl-2.0 | 3,020 |
<?php
// $Header: /cvsroot/html2ps/box.text.php,v 1.56 2007/05/07 12:15:53 Konstantin Exp $
require_once(HTML2PS_DIR.'box.inline.simple.php');
// TODO: from my POV, it wll be better to pass the font- or CSS-controlling object to the constructor
// instead of using globally visible functions in 'show'.
define('SYMBOL_NBSP', chr(160));
class TextBox extends SimpleInlineBox {
var $words;
var $encodings;
var $hyphens;
var $_widths;
var $_word_widths;
var $_wrappable;
var $wrapped;
function TextBox() {
$this->SimpleInlineBox();
$this->words = array();
$this->encodings = array();
$this->hyphens = array();
$this->_word_widths = array();
$this->_wrappable = array();
$this->wrapped = null;
$this->_widths = array();
$this->font_size = 0;
$this->ascender = 0;
$this->descender = 0;
$this->width = 0;
$this->height = 0;
}
/**
* Check if given subword contains soft hyphens and calculate
*/
function _make_wrappable(&$driver, $base_width, $font_name, $font_size, $subword_index) {
$hyphens = $this->hyphens[$subword_index];
$wrappable = array();
foreach ($hyphens as $hyphen) {
$subword_wrappable_index = $hyphen;
$subword_wrappable_width = $base_width + $driver->stringwidth(substr($this->words[$subword_index], 0, $subword_wrappable_index),
$font_name,
$this->encodings[$subword_index],
$font_size);
$subword_full_width = $subword_wrappable_width + $driver->stringwidth('-',
$font_name,
"iso-8859-1",
$font_size);
$wrappable[] = array($subword_index, $subword_wrappable_index, $subword_wrappable_width, $subword_full_width);
};
return $wrappable;
}
function get_content() {
return join('', array_map(array($this, 'get_content_callback'), $this->words, $this->encodings));
}
function get_content_callback($word, $encoding) {
$manager_encoding =& ManagerEncoding::get();
return $manager_encoding->toUTF8($word, $encoding);
}
function get_height() {
return $this->height;
}
function put_height($value) {
$this->height = $value;
}
// Apply 'line-height' CSS property; modifies the default_baseline value
// (NOT baseline, as it is calculated - and is overwritten - in the close_line
// method of container box
//
// Note that underline position (or 'descender' in terms of PDFLIB) -
// so, simple that space of text box under the baseline - is scaled too
// when 'line-height' is applied
//
function _apply_line_height() {
$height = $this->get_height();
$under = $height - $this->default_baseline;
$line_height = $this->getCSSProperty(CSS_LINE_HEIGHT);
if ($height > 0) {
$scale = $line_height->apply($this->ascender + $this->descender) / ($this->ascender + $this->descender);
} else {
$scale = 0;
};
// Calculate the height delta of the text box
$delta = $height * ($scale-1);
$this->put_height(($this->ascender + $this->descender)*$scale);
$this->default_baseline = $this->default_baseline + $delta/2;
}
function _get_font_name(&$viewport, $subword_index) {
if (isset($this->_cache[CACHE_TYPEFACE][$subword_index])) {
return $this->_cache[CACHE_TYPEFACE][$subword_index];
};
$font_resolver =& $viewport->get_font_resolver();
$font = $this->getCSSProperty(CSS_FONT);
$typeface = $font_resolver->getTypefaceName($font->family,
$font->weight,
$font->style,
$this->encodings[$subword_index]);
$this->_cache[CACHE_TYPEFACE][$subword_index] = $typeface;
return $typeface;
}
function add_subword($raw_subword, $encoding, $hyphens) {
$text_transform = $this->getCSSProperty(CSS_TEXT_TRANSFORM);
switch ($text_transform) {
case CSS_TEXT_TRANSFORM_CAPITALIZE:
$subword = ucwords($raw_subword);
break;
case CSS_TEXT_TRANSFORM_UPPERCASE:
$subword = strtoupper($raw_subword);
break;
case CSS_TEXT_TRANSFORM_LOWERCASE:
$subword = strtolower($raw_subword);
break;
case CSS_TEXT_TRANSFORM_NONE:
$subword = $raw_subword;
break;
}
$this->words[] = $subword;
$this->encodings[] = $encoding;
$this->hyphens[] = $hyphens;
}
function &create($text, $encoding, &$pipeline) {
$box =& TextBox::create_empty($pipeline);
$box->add_subword($text, $encoding, array());
return $box;
}
function &create_empty(&$pipeline) {
$box =& new TextBox();
$css_state = $pipeline->getCurrentCSSState();
$box->readCSS($css_state);
$css_state = $pipeline->getCurrentCSSState();
return $box;
}
function readCSS(&$state) {
parent::readCSS($state);
$this->_readCSSLengths($state,
array(CSS_TEXT_INDENT,
CSS_LETTER_SPACING));
}
// Inherited from GenericFormattedBox
function get_descender() {
return $this->descender;
}
function get_ascender() {
return $this->ascender;
}
function get_baseline() {
return $this->baseline;
}
function get_min_width_natural(&$context) {
return $this->get_full_width();
}
function get_min_width(&$context) {
return $this->get_full_width();
}
function get_max_width(&$context) {
return $this->get_full_width();
}
// Checks if current inline box should cause a line break inside the parent box
//
// @param $parent reference to a parent box
// @param $content flow context
// @return true if line break occurred; false otherwise
//
function maybe_line_break(&$parent, &$context) {
if (!$parent->line_break_allowed()) {
return false;
};
$last =& $parent->last_in_line();
if ($last) {
// Check if last box was a note call box. Punctuation marks
// after a note-call box should not be wrapped to new line,
// while "plain" words may be wrapped.
if ($last->is_note_call() && $this->is_punctuation()) {
return false;
};
};
// Calculate the x-coordinate of this box right edge
$right_x = $this->get_full_width() + $parent->_current_x;
$need_break = false;
// Check for right-floating boxes
// If upper-right corner of this inline box is inside of some float, wrap the line
$float = $context->point_in_floats($right_x, $parent->_current_y);
if ($float) {
$need_break = true;
};
// No floats; check if we had run out the right edge of container
// TODO: nobr-before, nobr-after
if (($right_x > $parent->get_right()+EPSILON)) {
// Now check if parent line box contains any other boxes;
// if not, we should draw this box unless we have a floating box to the left
$first = $parent->get_first();
$ti = $this->getCSSProperty(CSS_TEXT_INDENT);
$indent_offset = $ti->calculate($parent);
if ($parent->_current_x > $parent->get_left() + $indent_offset + EPSILON) {
$need_break = true;
};
}
// As close-line will not change the current-Y parent coordinate if no
// items were in the line box, we need to offset this explicitly in this case
//
if ($parent->line_box_empty() && $need_break) {
$parent->_current_y -= $this->get_height();
};
if ($need_break) {
// Check if current box contains soft hyphens and use them, breaking word into parts
$size = count($this->_wrappable);
if ($size > 0) {
$width_delta = $right_x - $parent->get_right();
if (!is_null($float)) {
$width_delta = $right_x - $float->get_left_margin();
};
$this->_find_soft_hyphen($parent, $width_delta);
};
$parent->close_line($context);
// Check if parent inline boxes have left padding/margins and add them to current_x
$element = $this->parent;
while (!is_null($element) && is_a($element,"GenericInlineBox")) {
$parent->_current_x += $element->get_extra_left();
$element = $element->parent;
};
};
return $need_break;
}
function _find_soft_hyphen(&$parent, $width_delta) {
/**
* Now we search for soft hyphen closest to the right margin
*/
$size = count($this->_wrappable);
for ($i=$size-1; $i>=0; $i--) {
$wrappable = $this->_wrappable[$i];
if ($this->get_width() - $wrappable[3] > $width_delta) {
$this->save_wrapped($wrappable, $parent, $context);
$parent->append_line($this);
return;
};
};
}
function save_wrapped($wrappable, &$parent, &$context) {
$this->wrapped = array($wrappable,
$parent->_current_x + $this->get_extra_left(),
$parent->_current_y - $this->get_extra_top());
}
function reflow(&$parent, &$context) {
// Check if we need a line break here (possilble several times in a row, if we
// have a long word and a floating box intersecting with this word
//
// To prevent infinite loop, we'll use a limit of 100 sequental line feeds
$i=0;
do { $i++; } while ($this->maybe_line_break($parent, $context) && $i < 100);
// Determine the baseline position and height of the text-box using line-height CSS property
$this->_apply_line_height();
// set default baseline
$this->baseline = $this->default_baseline;
// append current box to parent line box
$parent->append_line($this);
// Determine coordinates of upper-left _margin_ corner
$this->guess_corner($parent);
// Offset parent current X coordinate
if (!is_null($this->wrapped)) {
$parent->_current_x += $this->get_full_width() - $this->wrapped[0][2];
} else {
$parent->_current_x += $this->get_full_width();
};
// Extends parents height
$parent->extend_height($this->get_bottom());
// Update the value of current collapsed margin; pure text (non-span)
// boxes always have zero margin
$context->pop_collapsed_margin();
$context->push_collapsed_margin( 0 );
}
function getWrappedWidthAndHyphen() {
return $this->wrapped[0][3];
}
function getWrappedWidth() {
return $this->wrapped[0][2];
}
function reflow_text(&$driver) {
$num_words = count($this->words);
/**
* Empty text box
*/
if ($num_words == 0) {
return true;
};
/**
* A simple assumption is made: fonts used for different encodings
* have equal ascender/descender values (while they have the same
* typeface, style and weight).
*/
$font_name = $this->_get_font_name($driver, 0);
/**
* Get font vertical metrics
*/
$ascender = $driver->font_ascender($font_name, $this->encodings[0]);
if (is_null($ascender)) {
error_log("TextBox::reflow_text: cannot get font ascender");
return null;
};
$descender = $driver->font_descender($font_name, $this->encodings[0]);
if (is_null($descender)) {
error_log("TextBox::reflow_text: cannot get font descender");
return null;
};
/**
* Setup box size
*/
$font = $this->getCSSProperty(CSS_FONT_SIZE);
$font_size = $font->getPoints();
// Both ascender and descender should make $font_size
// as it is not guaranteed that $ascender + $descender == 1,
// we should normalize the result
$koeff = $font_size / ($ascender + $descender);
$this->ascender = $ascender * $koeff;
$this->descender = $descender * $koeff;
$this->default_baseline = $this->ascender;
$this->height = $this->ascender + $this->descender;
/**
* Determine box width
*/
if ($font_size > 0) {
$width = 0;
for ($i=0; $i<$num_words; $i++) {
$font_name = $this->_get_font_name($driver, $i);
$current_width = $driver->stringwidth($this->words[$i],
$font_name,
$this->encodings[$i],
$font_size);
$this->_word_widths[] = $current_width;
// Add information about soft hyphens
$this->_wrappable = array_merge($this->_wrappable, $this->_make_wrappable($driver, $width, $font_name, $font_size, $i));
$width += $current_width;
};
$this->width = $width;
} else {
$this->width = 0;
};
$letter_spacing = $this->getCSSProperty(CSS_LETTER_SPACING);
if ($letter_spacing->getPoints() != 0) {
$this->_widths = array();
for ($i=0; $i<$num_words; $i++) {
$num_chars = strlen($this->words[$i]);
for ($j=0; $j<$num_chars; $j++) {
$this->_widths[] = $driver->stringwidth($this->words[$i]{$j},
$font_name,
$this->encodings[$i],
$font_size);
};
$this->width += $letter_spacing->getPoints()*$num_chars;
};
};
return true;
}
function show(&$driver) {
/**
* Check if font-size have been set to 0; in this case we should not draw this box at all
*/
$font_size = $this->getCSSProperty(CSS_FONT_SIZE);
if ($font_size->getPoints() == 0) {
return true;
}
// Check if current text box will be cut-off by the page edge
// Get Y coordinate of the top edge of the box
$top = $this->get_top_margin();
// Get Y coordinate of the bottom edge of the box
$bottom = $this->get_bottom_margin();
$top_inside = $top >= $driver->getPageBottom()-EPSILON;
$bottom_inside = $bottom >= $driver->getPageBottom()-EPSILON;
if (!$top_inside && !$bottom_inside) {
return true;
}
return $this->_showText($driver);
}
function _showText(&$driver) {
if (!is_null($this->wrapped)) {
return $this->_showTextWrapped($driver);
} else {
return $this->_showTextNormal($driver);
};
}
function _showTextWrapped(&$driver) {
// draw generic box
parent::show($driver);
$font_size = $this->getCSSProperty(CSS_FONT_SIZE);
$decoration = $this->getCSSProperty(CSS_TEXT_DECORATION);
// draw text decoration
$driver->decoration($decoration['U'],
$decoration['O'],
$decoration['T']);
$letter_spacing = $this->getCSSProperty(CSS_LETTER_SPACING);
// Output text with the selected font
// note that we're using $default_baseline;
// the alignment offset - the difference between baseline and default_baseline values
// is taken into account inside the get_top/get_bottom functions
//
$current_char = 0;
$left = $this->wrapped[1];
$top = $this->get_top() - $this->default_baseline;
$num_words = count($this->words);
/**
* First part of wrapped word (before hyphen)
*/
for ($i=0; $i<$this->wrapped[0][0]; $i++) {
// Activate font
$status = $driver->setfont($this->_get_font_name($driver, $i),
$this->encodings[$i],
$font_size->getPoints());
if (is_null($status)) {
error_log("TextBox::show: setfont call failed");
return null;
};
$driver->show_xy($this->words[$i],
$left,
$this->wrapped[2] - $this->default_baseline);
$left += $this->_word_widths[$i];
};
$index = $this->wrapped[0][0];
$status = $driver->setfont($this->_get_font_name($driver, $index),
$this->encodings[$index],
$font_size->getPoints());
if (is_null($status)) {
error_log("TextBox::show: setfont call failed");
return null;
};
$driver->show_xy(substr($this->words[$index],0,$this->wrapped[0][1])."-",
$left,
$this->wrapped[2] - $this->default_baseline);
/**
* Second part of wrapped word (after hyphen)
*/
$left = $this->get_left();
$top = $this->get_top();
$driver->show_xy(substr($this->words[$index],$this->wrapped[0][1]),
$left,
$top - $this->default_baseline);
$size = count($this->words);
for ($i = $this->wrapped[0][0]+1; $i<$size; $i++) {
// Activate font
$status = $driver->setfont($this->_get_font_name($driver, $i),
$this->encodings[$i],
$font_size->getPoints());
if (is_null($status)) {
error_log("TextBox::show: setfont call failed");
return null;
};
$driver->show_xy($this->words[$i],
$left,
$top - $this->default_baseline);
$left += $this->_word_widths[$i];
};
return true;
}
function _showTextNormal(&$driver) {
// draw generic box
parent::show($driver);
$font_size = $this->getCSSProperty(CSS_FONT_SIZE);
$decoration = $this->getCSSProperty(CSS_TEXT_DECORATION);
// draw text decoration
$driver->decoration($decoration['U'],
$decoration['O'],
$decoration['T']);
$letter_spacing = $this->getCSSProperty(CSS_LETTER_SPACING);
if ($letter_spacing->getPoints() == 0) {
// Output text with the selected font
// note that we're using $default_baseline;
// the alignment offset - the difference between baseline and default_baseline values
// is taken into account inside the get_top/get_bottom functions
//
$size = count($this->words);
$left = $this->get_left();
for ($i=0; $i<$size; $i++) {
// Activate font
$status = $driver->setfont($this->_get_font_name($driver, $i),
$this->encodings[$i],
$font_size->getPoints());
if (is_null($status)) {
error_log("TextBox::show: setfont call failed");
return null;
};
$driver->show_xy($this->words[$i],
$left,
$this->get_top() - $this->default_baseline);
$left += $this->_word_widths[$i];
};
} else {
$current_char = 0;
$left = $this->get_left();
$top = $this->get_top() - $this->default_baseline;
$num_words = count($this->words);
for ($i=0; $i<$num_words; $i++) {
$num_chars = strlen($this->words[$i]);
for ($j=0; $j<$num_chars; $j++) {
$status = $driver->setfont($this->_get_font_name($driver, $i),
$this->encodings[$i],
$font_size->getPoints());
$driver->show_xy($this->words[$i]{$j}, $left, $top);
$left += $this->_widths[$current_char] + $letter_spacing->getPoints();
$current_char++;
};
};
};
return true;
}
function show_fixed(&$driver) {
$font_size = $this->getCSSProperty(CSS_FONT_SIZE);
// Check if font-size have been set to 0; in this case we should not draw this box at all
if ($font_size->getPoints() == 0) {
return true;
}
return $this->_showText($driver);
}
function offset($dx, $dy) {
parent::offset($dx, $dy);
// Note that horizonal offset should be called explicitly from text-align routines
// otherwise wrapped part will be offset twice (as offset is called both for
// wrapped and non-wrapped parts).
if (!is_null($this->wrapped)) {
$this->offset_wrapped($dx, $dy);
};
}
function offset_wrapped($dx, $dy) {
$this->wrapped[1] += $dx;
$this->wrapped[2] += $dy;
}
function reflow_whitespace(&$linebox_started, &$previous_whitespace) {
$linebox_started = true;
$previous_whitespace = false;
return;
}
function is_null() { return false; }
}
?> | maent45/PersianFeast | simpleinvoices/library/pdf/box.text.php | PHP | gpl-2.0 | 20,574 |
/*
* Freescale SSI ALSA SoC Digital Audio Interface (DAI) driver
*
* Author: Timur Tabi <timur@freescale.com>
*
* Copyright 2007-2015 Freescale Semiconductor, Inc.
*
* This file is licensed under the terms of the GNU General Public License
* version 2. This program is licensed "as is" without any warranty of any
* kind, whether express or implied.
*
*
* Some notes why imx-pcm-fiq is used instead of DMA on some boards:
*
* The i.MX SSI core has some nasty limitations in AC97 mode. While most
* sane processor vendors have a FIFO per AC97 slot, the i.MX has only
* one FIFO which combines all valid receive slots. We cannot even select
* which slots we want to receive. The WM9712 with which this driver
* was developed with always sends GPIO status data in slot 12 which
* we receive in our (PCM-) data stream. The only chance we have is to
* manually skip this data in the FIQ handler. With sampling rates different
* from 48000Hz not every frame has valid receive data, so the ratio
* between pcm data and GPIO status data changes. Our FIQ handler is not
* able to handle this, hence this driver only works with 48000Hz sampling
* rate.
* Reading and writing AC97 registers is another challenge. The core
* provides us status bits when the read register is updated with *another*
* value. When we read the same register two times (and the register still
* contains the same value) these status bits are not set. We work
* around this by not polling these bits but only wait a fixed delay.
*/
#include <linux/init.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/clk.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <linux/of_platform.h>
#include <linux/pm_runtime.h>
#include <linux/busfreq-imx.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/initval.h>
#include <sound/soc.h>
#include <sound/dmaengine_pcm.h>
#include "fsl_ssi.h"
#include "imx-pcm.h"
/**
* FSLSSI_I2S_RATES: sample rates supported by the I2S
*
* This driver currently only supports the SSI running in I2S slave mode,
* which means the codec determines the sample rate. Therefore, we tell
* ALSA that we support all rates and let the codec driver decide what rates
* are really supported.
*/
#define FSLSSI_I2S_RATES SNDRV_PCM_RATE_CONTINUOUS
/**
* FSLSSI_I2S_FORMATS: audio formats supported by the SSI
*
* This driver currently only supports the SSI running in I2S slave mode.
*
* The SSI has a limitation in that the samples must be in the same byte
* order as the host CPU. This is because when multiple bytes are written
* to the STX register, the bytes and bits must be written in the same
* order. The STX is a shift register, so all the bits need to be aligned
* (bit-endianness must match byte-endianness). Processors typically write
* the bits within a byte in the same order that the bytes of a word are
* written in. So if the host CPU is big-endian, then only big-endian
* samples will be written to STX properly.
*/
#ifdef __BIG_ENDIAN
#define FSLSSI_I2S_FORMATS (SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_S16_BE | \
SNDRV_PCM_FMTBIT_S18_3BE | SNDRV_PCM_FMTBIT_S20_3BE | \
SNDRV_PCM_FMTBIT_S24_3BE | SNDRV_PCM_FMTBIT_S24_BE)
#else
#define FSLSSI_I2S_FORMATS (SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_S16_LE | \
SNDRV_PCM_FMTBIT_S18_3LE | SNDRV_PCM_FMTBIT_S20_3LE | \
SNDRV_PCM_FMTBIT_S24_3LE | SNDRV_PCM_FMTBIT_S24_LE)
#endif
#define FSLSSI_SIER_DBG_RX_FLAGS (CCSR_SSI_SIER_RFF0_EN | \
CCSR_SSI_SIER_RLS_EN | CCSR_SSI_SIER_RFS_EN | \
CCSR_SSI_SIER_ROE0_EN | CCSR_SSI_SIER_RFRC_EN)
#define FSLSSI_SIER_DBG_TX_FLAGS (CCSR_SSI_SIER_TFE0_EN | \
CCSR_SSI_SIER_TLS_EN | CCSR_SSI_SIER_TFS_EN | \
CCSR_SSI_SIER_TUE0_EN | CCSR_SSI_SIER_TFRC_EN)
enum fsl_ssi_type {
FSL_SSI_MCP8610,
FSL_SSI_MX21,
FSL_SSI_MX35,
FSL_SSI_MX51,
};
struct fsl_ssi_reg_val {
u32 sier;
u32 srcr;
u32 stcr;
u32 scr;
};
struct fsl_ssi_rxtx_reg_val {
struct fsl_ssi_reg_val rx;
struct fsl_ssi_reg_val tx;
};
static bool fsl_ssi_readable_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case CCSR_SSI_STX0:
case CCSR_SSI_STX1:
case CCSR_SSI_SRX0:
case CCSR_SSI_SRX1:
case CCSR_SSI_SCR:
case CCSR_SSI_SISR:
case CCSR_SSI_SIER:
case CCSR_SSI_STCR:
case CCSR_SSI_SRCR:
case CCSR_SSI_STCCR:
case CCSR_SSI_SRCCR:
case CCSR_SSI_SFCSR:
case CCSR_SSI_STR:
case CCSR_SSI_SOR:
case CCSR_SSI_SACNT:
case CCSR_SSI_SACADD:
case CCSR_SSI_SACDAT:
case CCSR_SSI_SATAG:
case CCSR_SSI_STMSK:
case CCSR_SSI_SRMSK:
case CCSR_SSI_SACCST:
case CCSR_SSI_SACCEN:
case CCSR_SSI_SACCDIS:
return true;
default:
return false;
}
}
static bool fsl_ssi_volatile_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case CCSR_SSI_STX0:
case CCSR_SSI_STX1:
case CCSR_SSI_SRX0:
case CCSR_SSI_SRX1:
case CCSR_SSI_SISR:
case CCSR_SSI_SFCSR:
case CCSR_SSI_SACADD:
case CCSR_SSI_SACDAT:
case CCSR_SSI_SATAG:
case CCSR_SSI_SACCST:
return true;
default:
return false;
}
}
static bool fsl_ssi_writeable_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case CCSR_SSI_STX0:
case CCSR_SSI_STX1:
case CCSR_SSI_SCR:
case CCSR_SSI_SISR:
case CCSR_SSI_SIER:
case CCSR_SSI_STCR:
case CCSR_SSI_SRCR:
case CCSR_SSI_STCCR:
case CCSR_SSI_SRCCR:
case CCSR_SSI_SFCSR:
case CCSR_SSI_STR:
case CCSR_SSI_SOR:
case CCSR_SSI_SACNT:
case CCSR_SSI_SACADD:
case CCSR_SSI_SACDAT:
case CCSR_SSI_SATAG:
case CCSR_SSI_STMSK:
case CCSR_SSI_SRMSK:
case CCSR_SSI_SACCEN:
case CCSR_SSI_SACCDIS:
return true;
default:
return false;
}
}
static const struct regmap_config fsl_ssi_regconfig = {
.max_register = CCSR_SSI_SACCDIS,
.reg_bits = 32,
.val_bits = 32,
.reg_stride = 4,
.val_format_endian = REGMAP_ENDIAN_NATIVE,
.readable_reg = fsl_ssi_readable_reg,
.volatile_reg = fsl_ssi_volatile_reg,
.writeable_reg = fsl_ssi_writeable_reg,
.cache_type = REGCACHE_RBTREE,
};
struct fsl_ssi_soc_data {
bool imx;
bool offline_config;
u32 sisr_write_mask;
};
/**
* fsl_ssi_private: per-SSI private data
*
* @reg: Pointer to the regmap registers
* @irq: IRQ of this SSI
* @cpu_dai_drv: CPU DAI driver for this device
*
* @dai_fmt: DAI configuration this device is currently used with
* @i2s_mode: i2s and network mode configuration of the device. Is used to
* switch between normal and i2s/network mode
* mode depending on the number of channels
* @use_dma: DMA is used or FIQ with stream filter
* @use_dual_fifo: DMA with support for both FIFOs used
* @fifo_deph: Depth of the SSI FIFOs
* @rxtx_reg_val: Specific register settings for receive/transmit configuration
*
* @clk: SSI clock
* @baudclk: SSI baud clock for master mode
* @baudclk_streams: Active streams that are using baudclk
* @bitclk_freq: bitclock frequency set by .set_dai_sysclk
*
* @dma_params_tx: DMA transmit parameters
* @dma_params_rx: DMA receive parameters
* @ssi_phys: physical address of the SSI registers
*
* @fiq_params: FIQ stream filtering parameters
*
* @pdev: Pointer to pdev used for deprecated fsl-ssi sound card
*
* @dbg_stats: Debugging statistics
*
* @soc: SoC specifc data
*/
struct fsl_ssi_private {
struct regmap *regs;
unsigned int irq;
struct snd_soc_dai_driver cpu_dai_drv;
unsigned int dai_fmt;
u8 i2s_mode;
bool use_dma;
bool use_dual_fifo;
bool has_ipg_clk_name;
unsigned int fifo_depth;
struct fsl_ssi_rxtx_reg_val rxtx_reg_val;
struct clk *clk;
struct clk *baudclk;
unsigned int baudclk_streams;
unsigned int bitclk_freq;
/*regcache for SFCSR*/
u32 regcache_sfcsr;
/* DMA params */
struct snd_dmaengine_dai_dma_data dma_params_tx;
struct snd_dmaengine_dai_dma_data dma_params_rx;
dma_addr_t ssi_phys;
/* params for non-dma FIQ stream filtered mode */
struct imx_pcm_fiq_params fiq_params;
/* Used when using fsl-ssi as sound-card. This is only used by ppc and
* should be replaced with simple-sound-card. */
struct platform_device *pdev;
struct fsl_ssi_dbg dbg_stats;
const struct fsl_ssi_soc_data *soc;
};
/*
* imx51 and later SoCs have a slightly different IP that allows the
* SSI configuration while the SSI unit is running.
*
* More important, it is necessary on those SoCs to configure the
* sperate TX/RX DMA bits just before starting the stream
* (fsl_ssi_trigger). The SDMA unit has to be configured before fsl_ssi
* sends any DMA requests to the SDMA unit, otherwise it is not defined
* how the SDMA unit handles the DMA request.
*
* SDMA units are present on devices starting at imx35 but the imx35
* reference manual states that the DMA bits should not be changed
* while the SSI unit is running (SSIEN). So we support the necessary
* online configuration of fsl-ssi starting at imx51.
*/
static struct fsl_ssi_soc_data fsl_ssi_mpc8610 = {
.imx = false,
.offline_config = true,
.sisr_write_mask = CCSR_SSI_SISR_RFRC | CCSR_SSI_SISR_TFRC |
CCSR_SSI_SISR_ROE0 | CCSR_SSI_SISR_ROE1 |
CCSR_SSI_SISR_TUE0 | CCSR_SSI_SISR_TUE1,
};
static struct fsl_ssi_soc_data fsl_ssi_imx21 = {
.imx = true,
.offline_config = true,
.sisr_write_mask = 0,
};
static struct fsl_ssi_soc_data fsl_ssi_imx35 = {
.imx = true,
.offline_config = true,
.sisr_write_mask = CCSR_SSI_SISR_RFRC | CCSR_SSI_SISR_TFRC |
CCSR_SSI_SISR_ROE0 | CCSR_SSI_SISR_ROE1 |
CCSR_SSI_SISR_TUE0 | CCSR_SSI_SISR_TUE1,
};
static struct fsl_ssi_soc_data fsl_ssi_imx51 = {
.imx = true,
.offline_config = false,
.sisr_write_mask = CCSR_SSI_SISR_ROE0 | CCSR_SSI_SISR_ROE1 |
CCSR_SSI_SISR_TUE0 | CCSR_SSI_SISR_TUE1,
};
static const struct of_device_id fsl_ssi_ids[] = {
{ .compatible = "fsl,mpc8610-ssi", .data = &fsl_ssi_mpc8610 },
{ .compatible = "fsl,imx51-ssi", .data = &fsl_ssi_imx51 },
{ .compatible = "fsl,imx35-ssi", .data = &fsl_ssi_imx35 },
{ .compatible = "fsl,imx21-ssi", .data = &fsl_ssi_imx21 },
{}
};
MODULE_DEVICE_TABLE(of, fsl_ssi_ids);
static bool fsl_ssi_is_ac97(struct fsl_ssi_private *ssi_private)
{
return !!(ssi_private->dai_fmt & SND_SOC_DAIFMT_AC97);
}
static bool fsl_ssi_is_i2s_master(struct fsl_ssi_private *ssi_private)
{
return (ssi_private->dai_fmt & SND_SOC_DAIFMT_MASTER_MASK) ==
SND_SOC_DAIFMT_CBS_CFS;
}
/**
* fsl_ssi_isr: SSI interrupt handler
*
* Although it's possible to use the interrupt handler to send and receive
* data to/from the SSI, we use the DMA instead. Programming is more
* complicated, but the performance is much better.
*
* This interrupt handler is used only to gather statistics.
*
* @irq: IRQ of the SSI device
* @dev_id: pointer to the ssi_private structure for this SSI device
*/
static irqreturn_t fsl_ssi_isr(int irq, void *dev_id)
{
struct fsl_ssi_private *ssi_private = dev_id;
struct regmap *regs = ssi_private->regs;
__be32 sisr;
__be32 sisr2;
/* We got an interrupt, so read the status register to see what we
were interrupted for. We mask it with the Interrupt Enable register
so that we only check for events that we're interested in.
*/
regmap_read(regs, CCSR_SSI_SISR, &sisr);
sisr2 = sisr & ssi_private->soc->sisr_write_mask;
/* Clear the bits that we set */
if (sisr2)
regmap_write(regs, CCSR_SSI_SISR, sisr2);
fsl_ssi_dbg_isr(&ssi_private->dbg_stats, sisr);
return IRQ_HANDLED;
}
/*
* Enable/Disable all rx/tx config flags at once.
*/
static void fsl_ssi_rxtx_config(struct fsl_ssi_private *ssi_private,
bool enable)
{
struct regmap *regs = ssi_private->regs;
struct fsl_ssi_rxtx_reg_val *vals = &ssi_private->rxtx_reg_val;
if (enable) {
regmap_update_bits(regs, CCSR_SSI_SIER,
vals->rx.sier | vals->tx.sier,
vals->rx.sier | vals->tx.sier);
regmap_update_bits(regs, CCSR_SSI_SRCR,
vals->rx.srcr | vals->tx.srcr,
vals->rx.srcr | vals->tx.srcr);
regmap_update_bits(regs, CCSR_SSI_STCR,
vals->rx.stcr | vals->tx.stcr,
vals->rx.stcr | vals->tx.stcr);
} else {
regmap_update_bits(regs, CCSR_SSI_SRCR,
vals->rx.srcr | vals->tx.srcr, 0);
regmap_update_bits(regs, CCSR_SSI_STCR,
vals->rx.stcr | vals->tx.stcr, 0);
regmap_update_bits(regs, CCSR_SSI_SIER,
vals->rx.sier | vals->tx.sier, 0);
}
}
/*
* Calculate the bits that have to be disabled for the current stream that is
* getting disabled. This keeps the bits enabled that are necessary for the
* second stream to work if 'stream_active' is true.
*
* Detailed calculation:
* These are the values that need to be active after disabling. For non-active
* second stream, this is 0:
* vals_stream * !!stream_active
*
* The following computes the overall differences between the setup for the
* to-disable stream and the active stream, a simple XOR:
* vals_disable ^ (vals_stream * !!(stream_active))
*
* The full expression adds a mask on all values we care about
*/
#define fsl_ssi_disable_val(vals_disable, vals_stream, stream_active) \
((vals_disable) & \
((vals_disable) ^ ((vals_stream) * (u32)!!(stream_active))))
/*
* Enable/Disable a ssi configuration. You have to pass either
* ssi_private->rxtx_reg_val.rx or tx as vals parameter.
*/
static void fsl_ssi_config(struct fsl_ssi_private *ssi_private, bool enable,
struct fsl_ssi_reg_val *vals)
{
struct regmap *regs = ssi_private->regs;
struct fsl_ssi_reg_val *avals;
int nr_active_streams;
u32 scr_val;
int keep_active;
regmap_read(regs, CCSR_SSI_SCR, &scr_val);
nr_active_streams = !!(scr_val & CCSR_SSI_SCR_TE) +
!!(scr_val & CCSR_SSI_SCR_RE);
if (nr_active_streams - 1 > 0)
keep_active = 1;
else
keep_active = 0;
/* Find the other direction values rx or tx which we do not want to
* modify */
if (&ssi_private->rxtx_reg_val.rx == vals)
avals = &ssi_private->rxtx_reg_val.tx;
else
avals = &ssi_private->rxtx_reg_val.rx;
/* If vals should be disabled, start with disabling the unit */
if (!enable) {
u32 scr = fsl_ssi_disable_val(vals->scr, avals->scr,
keep_active);
regmap_update_bits(regs, CCSR_SSI_SCR, scr, 0);
}
/*
* We are running on a SoC which does not support online SSI
* reconfiguration, so we have to enable all necessary flags at once
* even if we do not use them later (capture and playback configuration)
*/
if (ssi_private->soc->offline_config) {
if ((enable && !nr_active_streams) ||
(!enable && !keep_active))
fsl_ssi_rxtx_config(ssi_private, enable);
goto config_done;
}
/*
* Configure single direction units while the SSI unit is running
* (online configuration)
*/
if (enable) {
regmap_update_bits(regs, CCSR_SSI_SIER, vals->sier, vals->sier);
regmap_update_bits(regs, CCSR_SSI_SRCR, vals->srcr, vals->srcr);
regmap_update_bits(regs, CCSR_SSI_STCR, vals->stcr, vals->stcr);
} else {
u32 sier;
u32 srcr;
u32 stcr;
/*
* Disabling the necessary flags for one of rx/tx while the
* other stream is active is a little bit more difficult. We
* have to disable only those flags that differ between both
* streams (rx XOR tx) and that are set in the stream that is
* disabled now. Otherwise we could alter flags of the other
* stream
*/
/* These assignments are simply vals without bits set in avals*/
sier = fsl_ssi_disable_val(vals->sier, avals->sier,
keep_active);
srcr = fsl_ssi_disable_val(vals->srcr, avals->srcr,
keep_active);
stcr = fsl_ssi_disable_val(vals->stcr, avals->stcr,
keep_active);
regmap_update_bits(regs, CCSR_SSI_SRCR, srcr, 0);
regmap_update_bits(regs, CCSR_SSI_STCR, stcr, 0);
regmap_update_bits(regs, CCSR_SSI_SIER, sier, 0);
}
config_done:
/* Enabling of subunits is done after configuration */
if (enable)
regmap_update_bits(regs, CCSR_SSI_SCR, vals->scr, vals->scr);
}
static void fsl_ssi_rx_config(struct fsl_ssi_private *ssi_private, bool enable)
{
fsl_ssi_config(ssi_private, enable, &ssi_private->rxtx_reg_val.rx);
}
static void fsl_ssi_tx_config(struct fsl_ssi_private *ssi_private, bool enable)
{
fsl_ssi_config(ssi_private, enable, &ssi_private->rxtx_reg_val.tx);
}
/*
* Setup rx/tx register values used to enable/disable the streams. These will
* be used later in fsl_ssi_config to setup the streams without the need to
* check for all different SSI modes.
*/
static void fsl_ssi_setup_reg_vals(struct fsl_ssi_private *ssi_private)
{
struct fsl_ssi_rxtx_reg_val *reg = &ssi_private->rxtx_reg_val;
reg->rx.sier = CCSR_SSI_SIER_RFF0_EN;
reg->rx.srcr = CCSR_SSI_SRCR_RFEN0;
reg->rx.scr = 0;
reg->tx.sier = CCSR_SSI_SIER_TFE0_EN;
reg->tx.stcr = CCSR_SSI_STCR_TFEN0;
reg->tx.scr = 0;
if (!fsl_ssi_is_ac97(ssi_private)) {
reg->rx.scr = CCSR_SSI_SCR_SSIEN | CCSR_SSI_SCR_RE;
reg->rx.sier |= CCSR_SSI_SIER_RFF0_EN;
reg->tx.scr = CCSR_SSI_SCR_SSIEN | CCSR_SSI_SCR_TE;
reg->tx.sier |= CCSR_SSI_SIER_TFE0_EN;
}
if (ssi_private->use_dma) {
reg->rx.sier |= CCSR_SSI_SIER_RDMAE;
reg->tx.sier |= CCSR_SSI_SIER_TDMAE;
} else {
reg->rx.sier |= CCSR_SSI_SIER_RIE;
reg->tx.sier |= CCSR_SSI_SIER_TIE;
}
reg->rx.sier |= FSLSSI_SIER_DBG_RX_FLAGS;
reg->tx.sier |= FSLSSI_SIER_DBG_TX_FLAGS;
}
static void fsl_ssi_setup_ac97(struct fsl_ssi_private *ssi_private)
{
struct regmap *regs = ssi_private->regs;
/*
* Setup the clock control register
*/
regmap_write(regs, CCSR_SSI_STCCR,
CCSR_SSI_SxCCR_WL(17) | CCSR_SSI_SxCCR_DC(13));
regmap_write(regs, CCSR_SSI_SRCCR,
CCSR_SSI_SxCCR_WL(17) | CCSR_SSI_SxCCR_DC(13));
/*
* Enable AC97 mode and startup the SSI
*/
regmap_write(regs, CCSR_SSI_SACNT,
CCSR_SSI_SACNT_AC97EN | CCSR_SSI_SACNT_FV);
regmap_write(regs, CCSR_SSI_SACCDIS, 0xff);
regmap_write(regs, CCSR_SSI_SACCEN, 0x300);
/*
* Enable SSI, Transmit and Receive. AC97 has to communicate with the
* codec before a stream is started.
*/
regmap_update_bits(regs, CCSR_SSI_SCR,
CCSR_SSI_SCR_SSIEN | CCSR_SSI_SCR_TE | CCSR_SSI_SCR_RE,
CCSR_SSI_SCR_SSIEN | CCSR_SSI_SCR_TE | CCSR_SSI_SCR_RE);
regmap_write(regs, CCSR_SSI_SOR, CCSR_SSI_SOR_WAIT(3));
}
/**
* fsl_ssi_startup: create a new substream
*
* This is the first function called when a stream is opened.
*
* If this is the first stream open, then grab the IRQ and program most of
* the SSI registers.
*/
static int fsl_ssi_startup(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct fsl_ssi_private *ssi_private =
snd_soc_dai_get_drvdata(rtd->cpu_dai);
int ret;
ret = clk_prepare_enable(ssi_private->clk);
if (ret)
return ret;
pm_runtime_get_sync(dai->dev);
/* When using dual fifo mode, it is safer to ensure an even period
* size. If appearing to an odd number while DMA always starts its
* task from fifo0, fifo1 would be neglected at the end of each
* period. But SSI would still access fifo1 with an invalid data.
*/
if (ssi_private->use_dual_fifo)
snd_pcm_hw_constraint_step(substream->runtime, 0,
SNDRV_PCM_HW_PARAM_PERIOD_SIZE, 2);
return 0;
}
/**
* fsl_ssi_shutdown: shutdown the SSI
*
*/
static void fsl_ssi_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct fsl_ssi_private *ssi_private =
snd_soc_dai_get_drvdata(rtd->cpu_dai);
pm_runtime_put_sync(dai->dev);
clk_disable_unprepare(ssi_private->clk);
}
/**
* fsl_ssi_set_bclk - configure Digital Audio Interface bit clock
*
* Note: This function can be only called when using SSI as DAI master
*
* Quick instruction for parameters:
* freq: Output BCLK frequency = samplerate * 32 (fixed) * channels
* dir: SND_SOC_CLOCK_OUT -> TxBCLK, SND_SOC_CLOCK_IN -> RxBCLK.
*/
static int fsl_ssi_set_bclk(struct snd_pcm_substream *substream,
struct snd_soc_dai *cpu_dai,
struct snd_pcm_hw_params *hw_params)
{
struct fsl_ssi_private *ssi_private = snd_soc_dai_get_drvdata(cpu_dai);
struct regmap *regs = ssi_private->regs;
int synchronous = ssi_private->cpu_dai_drv.symmetric_rates, ret;
u32 pm = 999, div2, psr, stccr, mask, afreq, factor, i;
unsigned long clkrate, baudrate, tmprate;
u64 sub, savesub = 100000;
unsigned int freq;
bool baudclk_is_used;
/* Prefer the explicitly set bitclock frequency */
if (ssi_private->bitclk_freq)
freq = ssi_private->bitclk_freq;
else
freq = params_channels(hw_params) * 32 * params_rate(hw_params);
/* Don't apply it to any non-baudclk circumstance */
if (IS_ERR(ssi_private->baudclk))
return -EINVAL;
baudclk_is_used = ssi_private->baudclk_streams & ~(BIT(substream->stream));
/* It should be already enough to divide clock by setting pm alone */
psr = 0;
div2 = 0;
factor = (div2 + 1) * (7 * psr + 1) * 2;
for (i = 0; i < 255; i++) {
/* The bclk rate must be smaller than 1/5 sysclk rate */
if (factor * (i + 1) < 5)
continue;
tmprate = freq * factor * (i + 2);
if (baudclk_is_used)
clkrate = clk_get_rate(ssi_private->baudclk);
else
clkrate = clk_round_rate(ssi_private->baudclk, tmprate);
clkrate /= factor;
afreq = clkrate / (i + 1);
if (freq == afreq)
sub = 0;
else if (freq / afreq == 1)
sub = freq - afreq;
else if (afreq / freq == 1)
sub = afreq - freq;
else
continue;
/* Calculate the fraction */
sub *= 100000;
do_div(sub, freq);
if (sub < savesub) {
baudrate = tmprate;
savesub = sub;
pm = i;
}
/* We are lucky */
if (savesub == 0)
break;
}
/* No proper pm found if it is still remaining the initial value */
if (pm == 999) {
dev_err(cpu_dai->dev, "failed to handle the required sysclk\n");
return -EINVAL;
}
stccr = CCSR_SSI_SxCCR_PM(pm + 1) | (div2 ? CCSR_SSI_SxCCR_DIV2 : 0) |
(psr ? CCSR_SSI_SxCCR_PSR : 0);
mask = CCSR_SSI_SxCCR_PM_MASK | CCSR_SSI_SxCCR_DIV2 |
CCSR_SSI_SxCCR_PSR;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK || synchronous)
regmap_update_bits(regs, CCSR_SSI_STCCR, mask, stccr);
else
regmap_update_bits(regs, CCSR_SSI_SRCCR, mask, stccr);
if (!baudclk_is_used) {
ret = clk_set_rate(ssi_private->baudclk, baudrate);
if (ret) {
dev_err(cpu_dai->dev, "failed to set baudclk rate\n");
return -EINVAL;
}
}
return 0;
}
static int fsl_ssi_set_dai_sysclk(struct snd_soc_dai *cpu_dai,
int clk_id, unsigned int freq, int dir)
{
struct fsl_ssi_private *ssi_private = snd_soc_dai_get_drvdata(cpu_dai);
ssi_private->bitclk_freq = freq;
return 0;
}
/**
* fsl_ssi_hw_params - program the sample size
*
* Most of the SSI registers have been programmed in the startup function,
* but the word length must be programmed here. Unfortunately, programming
* the SxCCR.WL bits requires the SSI to be temporarily disabled. This can
* cause a problem with supporting simultaneous playback and capture. If
* the SSI is already playing a stream, then that stream may be temporarily
* stopped when you start capture.
*
* Note: The SxCCR.DC and SxCCR.PM bits are only used if the SSI is the
* clock master.
*/
static int fsl_ssi_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params, struct snd_soc_dai *cpu_dai)
{
struct fsl_ssi_private *ssi_private = snd_soc_dai_get_drvdata(cpu_dai);
struct regmap *regs = ssi_private->regs;
unsigned int channels = params_channels(hw_params);
unsigned int sample_size =
snd_pcm_format_width(params_format(hw_params));
u32 wl = CCSR_SSI_SxCCR_WL(sample_size);
int ret;
u32 scr_val;
int enabled;
regmap_read(regs, CCSR_SSI_SCR, &scr_val);
enabled = scr_val & CCSR_SSI_SCR_SSIEN;
/*
* If we're in synchronous mode, and the SSI is already enabled,
* then STCCR is already set properly.
*/
if (enabled && ssi_private->cpu_dai_drv.symmetric_rates)
return 0;
if (fsl_ssi_is_i2s_master(ssi_private)) {
ret = fsl_ssi_set_bclk(substream, cpu_dai, hw_params);
if (ret)
return ret;
/* Do not enable the clock if it is already enabled */
if (!(ssi_private->baudclk_streams & BIT(substream->stream))) {
ret = clk_prepare_enable(ssi_private->baudclk);
if (ret)
return ret;
ssi_private->baudclk_streams |= BIT(substream->stream);
}
}
/*
* FIXME: The documentation says that SxCCR[WL] should not be
* modified while the SSI is enabled. The only time this can
* happen is if we're trying to do simultaneous playback and
* capture in asynchronous mode. Unfortunately, I have been enable
* to get that to work at all on the P1022DS. Therefore, we don't
* bother to disable/enable the SSI when setting SxCCR[WL], because
* the SSI will stop anyway. Maybe one day, this will get fixed.
*/
/* In synchronous mode, the SSI uses STCCR for capture */
if ((substream->stream == SNDRV_PCM_STREAM_PLAYBACK) ||
ssi_private->cpu_dai_drv.symmetric_rates)
regmap_update_bits(regs, CCSR_SSI_STCCR, CCSR_SSI_SxCCR_WL_MASK,
wl);
else
regmap_update_bits(regs, CCSR_SSI_SRCCR, CCSR_SSI_SxCCR_WL_MASK,
wl);
if (!fsl_ssi_is_ac97(ssi_private))
regmap_update_bits(regs, CCSR_SSI_SCR,
CCSR_SSI_SCR_NET | CCSR_SSI_SCR_I2S_MODE_MASK,
channels == 1 ? 0 : ssi_private->i2s_mode);
return 0;
}
static int fsl_ssi_hw_free(struct snd_pcm_substream *substream,
struct snd_soc_dai *cpu_dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct fsl_ssi_private *ssi_private =
snd_soc_dai_get_drvdata(rtd->cpu_dai);
if (fsl_ssi_is_i2s_master(ssi_private) &&
ssi_private->baudclk_streams & BIT(substream->stream)) {
clk_disable_unprepare(ssi_private->baudclk);
ssi_private->baudclk_streams &= ~BIT(substream->stream);
}
return 0;
}
static int _fsl_ssi_set_dai_fmt(struct fsl_ssi_private *ssi_private,
unsigned int fmt)
{
struct regmap *regs = ssi_private->regs;
u32 strcr = 0, stcr, srcr, scr, mask;
u8 wm;
ssi_private->dai_fmt = fmt;
if (fsl_ssi_is_i2s_master(ssi_private) && IS_ERR(ssi_private->baudclk)) {
dev_err(&ssi_private->pdev->dev, "baudclk is missing which is necessary for master mode\n");
return -EINVAL;
}
fsl_ssi_setup_reg_vals(ssi_private);
regmap_read(regs, CCSR_SSI_SCR, &scr);
scr &= ~(CCSR_SSI_SCR_SYN | CCSR_SSI_SCR_I2S_MODE_MASK);
scr |= CCSR_SSI_SCR_SYNC_TX_FS;
mask = CCSR_SSI_STCR_TXBIT0 | CCSR_SSI_STCR_TFDIR | CCSR_SSI_STCR_TXDIR |
CCSR_SSI_STCR_TSCKP | CCSR_SSI_STCR_TFSI | CCSR_SSI_STCR_TFSL |
CCSR_SSI_STCR_TEFS;
regmap_read(regs, CCSR_SSI_STCR, &stcr);
regmap_read(regs, CCSR_SSI_SRCR, &srcr);
stcr &= ~mask;
srcr &= ~mask;
ssi_private->i2s_mode = CCSR_SSI_SCR_NET;
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBS_CFS:
ssi_private->i2s_mode |= CCSR_SSI_SCR_I2S_MODE_MASTER;
regmap_update_bits(regs, CCSR_SSI_STCCR,
CCSR_SSI_SxCCR_DC_MASK,
CCSR_SSI_SxCCR_DC(2));
regmap_update_bits(regs, CCSR_SSI_SRCCR,
CCSR_SSI_SxCCR_DC_MASK,
CCSR_SSI_SxCCR_DC(2));
break;
case SND_SOC_DAIFMT_CBM_CFM:
ssi_private->i2s_mode |= CCSR_SSI_SCR_I2S_MODE_SLAVE;
break;
default:
return -EINVAL;
}
/* Data on rising edge of bclk, frame low, 1clk before data */
strcr |= CCSR_SSI_STCR_TFSI | CCSR_SSI_STCR_TSCKP |
CCSR_SSI_STCR_TXBIT0 | CCSR_SSI_STCR_TEFS;
break;
case SND_SOC_DAIFMT_LEFT_J:
/* Data on rising edge of bclk, frame high */
strcr |= CCSR_SSI_STCR_TXBIT0 | CCSR_SSI_STCR_TSCKP;
break;
case SND_SOC_DAIFMT_DSP_A:
/* Data on rising edge of bclk, frame high, 1clk before data */
strcr |= CCSR_SSI_STCR_TFSL | CCSR_SSI_STCR_TSCKP |
CCSR_SSI_STCR_TXBIT0 | CCSR_SSI_STCR_TEFS;
break;
case SND_SOC_DAIFMT_DSP_B:
/* Data on rising edge of bclk, frame high */
strcr |= CCSR_SSI_STCR_TFSL | CCSR_SSI_STCR_TSCKP |
CCSR_SSI_STCR_TXBIT0;
break;
case SND_SOC_DAIFMT_AC97:
ssi_private->i2s_mode |= CCSR_SSI_SCR_I2S_MODE_NORMAL;
break;
default:
return -EINVAL;
}
scr |= ssi_private->i2s_mode;
/* DAI clock inversion */
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
/* Nothing to do for both normal cases */
break;
case SND_SOC_DAIFMT_IB_NF:
/* Invert bit clock */
strcr ^= CCSR_SSI_STCR_TSCKP;
break;
case SND_SOC_DAIFMT_NB_IF:
/* Invert frame clock */
strcr ^= CCSR_SSI_STCR_TFSI;
break;
case SND_SOC_DAIFMT_IB_IF:
/* Invert both clocks */
strcr ^= CCSR_SSI_STCR_TSCKP;
strcr ^= CCSR_SSI_STCR_TFSI;
break;
default:
return -EINVAL;
}
/* DAI clock master masks */
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBS_CFS:
strcr |= CCSR_SSI_STCR_TFDIR | CCSR_SSI_STCR_TXDIR;
scr |= CCSR_SSI_SCR_SYS_CLK_EN;
break;
case SND_SOC_DAIFMT_CBM_CFM:
scr &= ~CCSR_SSI_SCR_SYS_CLK_EN;
break;
default:
return -EINVAL;
}
stcr |= strcr;
srcr |= strcr;
if (ssi_private->cpu_dai_drv.symmetric_rates) {
/* Need to clear RXDIR when using SYNC mode */
srcr &= ~CCSR_SSI_SRCR_RXDIR;
scr |= CCSR_SSI_SCR_SYN;
}
regmap_write(regs, CCSR_SSI_STCR, stcr);
regmap_write(regs, CCSR_SSI_SRCR, srcr);
regmap_write(regs, CCSR_SSI_SCR, scr);
/*
* Set the watermark for transmit FIFI 0 and receive FIFO 0. We don't
* use FIFO 1. We program the transmit water to signal a DMA transfer
* if there are only two (or fewer) elements left in the FIFO. Two
* elements equals one frame (left channel, right channel). This value,
* however, depends on the depth of the transmit buffer.
*
* We set the watermark on the same level as the DMA burstsize. For
* fiq it is probably better to use the biggest possible watermark
* size.
*/
if (ssi_private->use_dma)
wm = ssi_private->fifo_depth - 2;
else
wm = ssi_private->fifo_depth;
regmap_write(regs, CCSR_SSI_SFCSR,
CCSR_SSI_SFCSR_TFWM0(wm) | CCSR_SSI_SFCSR_RFWM0(wm) |
CCSR_SSI_SFCSR_TFWM1(wm) | CCSR_SSI_SFCSR_RFWM1(wm));
if (ssi_private->use_dual_fifo) {
regmap_update_bits(regs, CCSR_SSI_SRCR, CCSR_SSI_SRCR_RFEN1,
CCSR_SSI_SRCR_RFEN1);
regmap_update_bits(regs, CCSR_SSI_STCR, CCSR_SSI_STCR_TFEN1,
CCSR_SSI_STCR_TFEN1);
regmap_update_bits(regs, CCSR_SSI_SCR, CCSR_SSI_SCR_TCH_EN,
CCSR_SSI_SCR_TCH_EN);
}
if (fmt & SND_SOC_DAIFMT_AC97)
fsl_ssi_setup_ac97(ssi_private);
return 0;
}
/**
* fsl_ssi_set_dai_fmt - configure Digital Audio Interface Format.
*/
static int fsl_ssi_set_dai_fmt(struct snd_soc_dai *cpu_dai, unsigned int fmt)
{
struct fsl_ssi_private *ssi_private = snd_soc_dai_get_drvdata(cpu_dai);
return _fsl_ssi_set_dai_fmt(ssi_private, fmt);
}
/**
* fsl_ssi_set_dai_tdm_slot - set TDM slot number
*
* Note: This function can be only called when using SSI as DAI master
*/
static int fsl_ssi_set_dai_tdm_slot(struct snd_soc_dai *cpu_dai, u32 tx_mask,
u32 rx_mask, int slots, int slot_width)
{
struct fsl_ssi_private *ssi_private = snd_soc_dai_get_drvdata(cpu_dai);
struct regmap *regs = ssi_private->regs;
u32 val;
/* The slot number should be >= 2 if using Network mode or I2S mode */
regmap_read(regs, CCSR_SSI_SCR, &val);
val &= CCSR_SSI_SCR_I2S_MODE_MASK | CCSR_SSI_SCR_NET;
if (val && slots < 2) {
dev_err(cpu_dai->dev, "slot number should be >= 2 in I2S or NET\n");
return -EINVAL;
}
regmap_update_bits(regs, CCSR_SSI_STCCR, CCSR_SSI_SxCCR_DC_MASK,
CCSR_SSI_SxCCR_DC(slots));
regmap_update_bits(regs, CCSR_SSI_SRCCR, CCSR_SSI_SxCCR_DC_MASK,
CCSR_SSI_SxCCR_DC(slots));
/* The register SxMSKs needs SSI to provide essential clock due to
* hardware design. So we here temporarily enable SSI to set them.
*/
regmap_read(regs, CCSR_SSI_SCR, &val);
val &= CCSR_SSI_SCR_SSIEN;
regmap_update_bits(regs, CCSR_SSI_SCR, CCSR_SSI_SCR_SSIEN,
CCSR_SSI_SCR_SSIEN);
regmap_write(regs, CCSR_SSI_STMSK, tx_mask);
regmap_write(regs, CCSR_SSI_SRMSK, rx_mask);
regmap_update_bits(regs, CCSR_SSI_SCR, CCSR_SSI_SCR_SSIEN, val);
return 0;
}
/**
* fsl_ssi_trigger: start and stop the DMA transfer.
*
* This function is called by ALSA to start, stop, pause, and resume the DMA
* transfer of data.
*
* The DMA channel is in external master start and pause mode, which
* means the SSI completely controls the flow of data.
*/
static int fsl_ssi_trigger(struct snd_pcm_substream *substream, int cmd,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct fsl_ssi_private *ssi_private = snd_soc_dai_get_drvdata(rtd->cpu_dai);
struct regmap *regs = ssi_private->regs;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
fsl_ssi_tx_config(ssi_private, true);
else
fsl_ssi_rx_config(ssi_private, true);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
fsl_ssi_tx_config(ssi_private, false);
else
fsl_ssi_rx_config(ssi_private, false);
break;
default:
return -EINVAL;
}
if (fsl_ssi_is_ac97(ssi_private)) {
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
regmap_write(regs, CCSR_SSI_SOR, CCSR_SSI_SOR_TX_CLR);
else
regmap_write(regs, CCSR_SSI_SOR, CCSR_SSI_SOR_RX_CLR);
}
return 0;
}
static int fsl_ssi_dai_probe(struct snd_soc_dai *dai)
{
struct fsl_ssi_private *ssi_private = snd_soc_dai_get_drvdata(dai);
if (ssi_private->soc->imx && ssi_private->use_dma) {
dai->playback_dma_data = &ssi_private->dma_params_tx;
dai->capture_dma_data = &ssi_private->dma_params_rx;
}
return 0;
}
static const struct snd_soc_dai_ops fsl_ssi_dai_ops = {
.startup = fsl_ssi_startup,
.shutdown = fsl_ssi_shutdown,
.hw_params = fsl_ssi_hw_params,
.hw_free = fsl_ssi_hw_free,
.set_fmt = fsl_ssi_set_dai_fmt,
.set_sysclk = fsl_ssi_set_dai_sysclk,
.set_tdm_slot = fsl_ssi_set_dai_tdm_slot,
.trigger = fsl_ssi_trigger,
};
/* Template for the CPU dai driver structure */
static struct snd_soc_dai_driver fsl_ssi_dai_template = {
.probe = fsl_ssi_dai_probe,
.playback = {
.stream_name = "CPU-Playback",
.channels_min = 1,
.channels_max = 2,
.rates = FSLSSI_I2S_RATES,
.formats = FSLSSI_I2S_FORMATS,
},
.capture = {
.stream_name = "CPU-Capture",
.channels_min = 1,
.channels_max = 2,
.rates = FSLSSI_I2S_RATES,
.formats = FSLSSI_I2S_FORMATS,
},
.ops = &fsl_ssi_dai_ops,
};
static const struct snd_soc_component_driver fsl_ssi_component = {
.name = "fsl-ssi",
};
static struct snd_soc_dai_driver fsl_ssi_ac97_dai = {
.ac97_control = 1,
.playback = {
.stream_name = "AC97 Playback",
.channels_min = 2,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
},
.capture = {
.stream_name = "AC97 Capture",
.channels_min = 2,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_48000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
},
.ops = &fsl_ssi_dai_ops,
};
static struct fsl_ssi_private *fsl_ac97_data;
static void fsl_ssi_ac97_write(struct snd_ac97 *ac97, unsigned short reg,
unsigned short val)
{
struct regmap *regs = fsl_ac97_data->regs;
unsigned int lreg;
unsigned int lval;
if (reg > 0x7f)
return;
lreg = reg << 12;
regmap_write(regs, CCSR_SSI_SACADD, lreg);
lval = val << 4;
regmap_write(regs, CCSR_SSI_SACDAT, lval);
regmap_update_bits(regs, CCSR_SSI_SACNT, CCSR_SSI_SACNT_RDWR_MASK,
CCSR_SSI_SACNT_WR);
udelay(100);
}
static unsigned short fsl_ssi_ac97_read(struct snd_ac97 *ac97,
unsigned short reg)
{
struct regmap *regs = fsl_ac97_data->regs;
unsigned short val = -1;
u32 reg_val;
unsigned int lreg;
lreg = (reg & 0x7f) << 12;
regmap_write(regs, CCSR_SSI_SACADD, lreg);
regmap_update_bits(regs, CCSR_SSI_SACNT, CCSR_SSI_SACNT_RDWR_MASK,
CCSR_SSI_SACNT_RD);
udelay(100);
regmap_read(regs, CCSR_SSI_SACDAT, ®_val);
val = (reg_val >> 4) & 0xffff;
return val;
}
static struct snd_ac97_bus_ops fsl_ssi_ac97_ops = {
.read = fsl_ssi_ac97_read,
.write = fsl_ssi_ac97_write,
};
/**
* Make every character in a string lower-case
*/
static void make_lowercase(char *s)
{
char *p = s;
char c;
while ((c = *p)) {
if ((c >= 'A') && (c <= 'Z'))
*p = c + ('a' - 'A');
p++;
}
}
static int fsl_ssi_imx_probe(struct platform_device *pdev,
struct fsl_ssi_private *ssi_private, void __iomem *iomem)
{
struct device_node *np = pdev->dev.of_node;
u32 dmas[4];
int ret;
u32 buffer_size;
if (ssi_private->has_ipg_clk_name)
ssi_private->clk = devm_clk_get(&pdev->dev, "ipg");
else
ssi_private->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(ssi_private->clk)) {
ret = PTR_ERR(ssi_private->clk);
dev_err(&pdev->dev, "could not get clock: %d\n", ret);
return ret;
}
if (!ssi_private->has_ipg_clk_name) {
ret = clk_prepare_enable(ssi_private->clk);
if (ret) {
dev_err(&pdev->dev, "clk_prepare_enable failed: %d\n", ret);
return ret;
}
}
/* For those SLAVE implementations, we ingore non-baudclk cases
* and, instead, abandon MASTER mode that needs baud clock.
*/
ssi_private->baudclk = devm_clk_get(&pdev->dev, "baud");
if (IS_ERR(ssi_private->baudclk))
dev_dbg(&pdev->dev, "could not get baud clock: %ld\n",
PTR_ERR(ssi_private->baudclk));
/*
* We have burstsize be "fifo_depth - 2" to match the SSI
* watermark setting in fsl_ssi_startup().
*/
ssi_private->dma_params_tx.maxburst = ssi_private->fifo_depth - 2;
ssi_private->dma_params_rx.maxburst = ssi_private->fifo_depth - 2;
ssi_private->dma_params_tx.addr = ssi_private->ssi_phys + CCSR_SSI_STX0;
ssi_private->dma_params_rx.addr = ssi_private->ssi_phys + CCSR_SSI_SRX0;
ret = of_property_read_u32_array(np, "dmas", dmas, 4);
if (ssi_private->use_dma && !ret && dmas[2] == IMX_DMATYPE_SSI_DUAL) {
ssi_private->use_dual_fifo = true;
/* When using dual fifo mode, we need to keep watermark
* as even numbers due to dma script limitation.
*/
ssi_private->dma_params_tx.maxburst &= ~0x1;
ssi_private->dma_params_rx.maxburst &= ~0x1;
}
if (of_property_read_u32(np, "fsl,dma-buffer-size", &buffer_size))
buffer_size = IMX_SSI_DMABUF_SIZE;
if (!ssi_private->use_dma) {
/*
* Some boards use an incompatible codec. To get it
* working, we are using imx-fiq-pcm-audio, that
* can handle those codecs. DMA is not possible in this
* situation.
*/
ssi_private->fiq_params.irq = ssi_private->irq;
ssi_private->fiq_params.base = iomem;
ssi_private->fiq_params.dma_params_rx =
&ssi_private->dma_params_rx;
ssi_private->fiq_params.dma_params_tx =
&ssi_private->dma_params_tx;
ret = imx_pcm_fiq_init(pdev, &ssi_private->fiq_params);
if (ret)
goto error_pcm;
} else {
ret = imx_pcm_dma_init(pdev, buffer_size);
if (ret)
goto error_pcm;
}
return 0;
error_pcm:
if (!ssi_private->has_ipg_clk_name)
clk_disable_unprepare(ssi_private->clk);
return ret;
}
static void fsl_ssi_imx_clean(struct platform_device *pdev,
struct fsl_ssi_private *ssi_private)
{
if (!ssi_private->use_dma)
imx_pcm_fiq_exit(pdev);
if (!ssi_private->has_ipg_clk_name)
clk_disable_unprepare(ssi_private->clk);
}
static int fsl_ssi_probe(struct platform_device *pdev)
{
struct fsl_ssi_private *ssi_private;
int ret = 0;
struct device_node *np = pdev->dev.of_node;
const struct of_device_id *of_id;
const char *p, *sprop;
const uint32_t *iprop;
struct resource res;
void __iomem *iomem;
char name[64];
/* SSIs that are not connected on the board should have a
* status = "disabled"
* property in their device tree nodes.
*/
if (!of_device_is_available(np))
return -ENODEV;
of_id = of_match_device(fsl_ssi_ids, &pdev->dev);
if (!of_id || !of_id->data)
return -EINVAL;
ssi_private = devm_kzalloc(&pdev->dev, sizeof(*ssi_private),
GFP_KERNEL);
if (!ssi_private) {
dev_err(&pdev->dev, "could not allocate DAI object\n");
return -ENOMEM;
}
ssi_private->soc = of_id->data;
sprop = of_get_property(np, "fsl,mode", NULL);
if (sprop) {
if (!strcmp(sprop, "ac97-slave"))
ssi_private->dai_fmt = SND_SOC_DAIFMT_AC97;
else if (!strcmp(sprop, "i2s-slave"))
ssi_private->dai_fmt = SND_SOC_DAIFMT_I2S |
SND_SOC_DAIFMT_CBM_CFM;
}
ssi_private->use_dma = !of_property_read_bool(np,
"fsl,fiq-stream-filter");
if (fsl_ssi_is_ac97(ssi_private)) {
memcpy(&ssi_private->cpu_dai_drv, &fsl_ssi_ac97_dai,
sizeof(fsl_ssi_ac97_dai));
fsl_ac97_data = ssi_private;
snd_soc_set_ac97_ops_of_reset(&fsl_ssi_ac97_ops, pdev);
} else {
/* Initialize this copy of the CPU DAI driver structure */
memcpy(&ssi_private->cpu_dai_drv, &fsl_ssi_dai_template,
sizeof(fsl_ssi_dai_template));
}
ssi_private->cpu_dai_drv.name = dev_name(&pdev->dev);
/* Get the addresses and IRQ */
ret = of_address_to_resource(np, 0, &res);
if (ret) {
dev_err(&pdev->dev, "could not determine device resources\n");
return ret;
}
ssi_private->ssi_phys = res.start;
iomem = devm_ioremap(&pdev->dev, res.start, resource_size(&res));
if (!iomem) {
dev_err(&pdev->dev, "could not map device resources\n");
return -ENOMEM;
}
ret = of_property_match_string(np, "clock-names", "ipg");
if (ret < 0) {
ssi_private->has_ipg_clk_name = false;
ssi_private->regs = devm_regmap_init_mmio(&pdev->dev, iomem,
&fsl_ssi_regconfig);
} else {
ssi_private->has_ipg_clk_name = true;
ssi_private->regs = devm_regmap_init_mmio_clk(&pdev->dev,
"ipg", iomem, &fsl_ssi_regconfig);
}
if (IS_ERR(ssi_private->regs)) {
dev_err(&pdev->dev, "Failed to init register map\n");
return PTR_ERR(ssi_private->regs);
}
ssi_private->irq = irq_of_parse_and_map(np, 0);
if (!ssi_private->irq) {
dev_err(&pdev->dev, "no irq for node %s\n", np->full_name);
return -ENXIO;
}
/* Are the RX and the TX clocks locked? */
if (!of_find_property(np, "fsl,ssi-asynchronous", NULL)) {
ssi_private->cpu_dai_drv.symmetric_rates = 1;
ssi_private->cpu_dai_drv.symmetric_channels = 1;
ssi_private->cpu_dai_drv.symmetric_samplebits = 1;
}
/* Determine the FIFO depth. */
iprop = of_get_property(np, "fsl,fifo-depth", NULL);
if (iprop)
ssi_private->fifo_depth = be32_to_cpup(iprop);
else
/* Older 8610 DTs didn't have the fifo-depth property */
ssi_private->fifo_depth = 8;
pm_runtime_enable(&pdev->dev);
dev_set_drvdata(&pdev->dev, ssi_private);
if (ssi_private->soc->imx) {
ret = fsl_ssi_imx_probe(pdev, ssi_private, iomem);
if (ret)
goto error_irqmap;
}
ret = snd_soc_register_component(&pdev->dev, &fsl_ssi_component,
&ssi_private->cpu_dai_drv, 1);
if (ret) {
dev_err(&pdev->dev, "failed to register DAI: %d\n", ret);
goto error_asoc_register;
}
if (ssi_private->use_dma) {
ret = devm_request_irq(&pdev->dev, ssi_private->irq,
fsl_ssi_isr, 0, dev_name(&pdev->dev),
ssi_private);
if (ret < 0) {
dev_err(&pdev->dev, "could not claim irq %u\n",
ssi_private->irq);
goto error_irq;
}
}
ret = fsl_ssi_debugfs_create(&ssi_private->dbg_stats, &pdev->dev);
if (ret)
goto error_asoc_register;
/*
* If codec-handle property is missing from SSI node, we assume
* that the machine driver uses new binding which does not require
* SSI driver to trigger machine driver's probe.
*/
if (!of_get_property(np, "codec-handle", NULL))
goto done;
/* Trigger the machine driver's probe function. The platform driver
* name of the machine driver is taken from /compatible property of the
* device tree. We also pass the address of the CPU DAI driver
* structure.
*/
sprop = of_get_property(of_find_node_by_path("/"), "compatible", NULL);
/* Sometimes the compatible name has a "fsl," prefix, so we strip it. */
p = strrchr(sprop, ',');
if (p)
sprop = p + 1;
snprintf(name, sizeof(name), "snd-soc-%s", sprop);
make_lowercase(name);
ssi_private->pdev =
platform_device_register_data(&pdev->dev, name, 0, NULL, 0);
if (IS_ERR(ssi_private->pdev)) {
ret = PTR_ERR(ssi_private->pdev);
dev_err(&pdev->dev, "failed to register platform: %d\n", ret);
goto error_sound_card;
}
done:
if (ssi_private->dai_fmt)
_fsl_ssi_set_dai_fmt(ssi_private, ssi_private->dai_fmt);
return 0;
error_sound_card:
fsl_ssi_debugfs_remove(&ssi_private->dbg_stats);
error_irq:
snd_soc_unregister_component(&pdev->dev);
error_asoc_register:
if (ssi_private->soc->imx)
fsl_ssi_imx_clean(pdev, ssi_private);
error_irqmap:
if (ssi_private->use_dma)
irq_dispose_mapping(ssi_private->irq);
return ret;
}
static int fsl_ssi_remove(struct platform_device *pdev)
{
struct fsl_ssi_private *ssi_private = dev_get_drvdata(&pdev->dev);
fsl_ssi_debugfs_remove(&ssi_private->dbg_stats);
if (ssi_private->pdev)
platform_device_unregister(ssi_private->pdev);
snd_soc_unregister_component(&pdev->dev);
if (ssi_private->soc->imx)
fsl_ssi_imx_clean(pdev, ssi_private);
if (ssi_private->use_dma)
irq_dispose_mapping(ssi_private->irq);
return 0;
}
#ifdef CONFIG_PM_RUNTIME
static int fsl_ssi_runtime_resume(struct device *dev)
{
request_bus_freq(BUS_FREQ_AUDIO);
return 0;
}
static int fsl_ssi_runtime_suspend(struct device *dev)
{
release_bus_freq(BUS_FREQ_AUDIO);
return 0;
}
#endif
#ifdef CONFIG_PM_SLEEP
static int fsl_ssi_suspend(struct device *dev)
{
struct fsl_ssi_private *ssi_private = dev_get_drvdata(dev);
struct regmap *regs = ssi_private->regs;
regmap_read(regs, CCSR_SSI_SFCSR,
&ssi_private->regcache_sfcsr);
regcache_cache_only(regs, true);
regcache_mark_dirty(regs);
return 0;
}
static int fsl_ssi_resume(struct device *dev)
{
struct fsl_ssi_private *ssi_private = dev_get_drvdata(dev);
struct regmap *regs = ssi_private->regs;
regcache_cache_only(regs, false);
regmap_update_bits(regs, CCSR_SSI_SFCSR,
CCSR_SSI_SFCSR_RFWM1_MASK | CCSR_SSI_SFCSR_TFWM1_MASK |
CCSR_SSI_SFCSR_RFWM0_MASK | CCSR_SSI_SFCSR_TFWM0_MASK,
ssi_private->regcache_sfcsr);
return regcache_sync(regs);
}
#endif /* CONFIG_PM_SLEEP */
static const struct dev_pm_ops fsl_ssi_pm = {
SET_RUNTIME_PM_OPS(fsl_ssi_runtime_suspend,
fsl_ssi_runtime_resume,
NULL)
SET_SYSTEM_SLEEP_PM_OPS(fsl_ssi_suspend, fsl_ssi_resume)
};
static struct platform_driver fsl_ssi_driver = {
.driver = {
.name = "fsl-ssi-dai",
.owner = THIS_MODULE,
.of_match_table = fsl_ssi_ids,
.pm = &fsl_ssi_pm,
},
.probe = fsl_ssi_probe,
.remove = fsl_ssi_remove,
};
module_platform_driver(fsl_ssi_driver);
MODULE_ALIAS("platform:fsl-ssi-dai");
MODULE_AUTHOR("Timur Tabi <timur@freescale.com>");
MODULE_DESCRIPTION("Freescale Synchronous Serial Interface (SSI) ASoC Driver");
MODULE_LICENSE("GPL v2");
| FEDEVEL/openrex-linux-3.14 | sound/soc/fsl/fsl_ssi.c | C | gpl-2.0 | 46,256 |
/*
* Copyright (c) 2003, 2007-14 Matteo Frigo
* Copyright (c) 2003, 2007-14 Massachusetts Institute of Technology
*
* 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
*
*/
/* This file was automatically generated --- DO NOT EDIT */
/* Generated on Tue Mar 4 13:50:34 EST 2014 */
#include "codelet-rdft.h"
#ifdef HAVE_FMA
/* Generated by: ../../../genfft/gen_r2cb.native -fma -reorder-insns -schedule-for-pipeline -compact -variables 4 -pipeline-latency 4 -sign 1 -n 16 -name r2cbIII_16 -dft-III -include r2cbIII.h */
/*
* This function contains 66 FP additions, 36 FP multiplications,
* (or, 46 additions, 16 multiplications, 20 fused multiply/add),
* 55 stack variables, 9 constants, and 32 memory accesses
*/
#include "r2cbIII.h"
static void r2cbIII_16(R *R0, R *R1, R *Cr, R *Ci, stride rs, stride csr, stride csi, INT v, INT ivs, INT ovs)
{
DK(KP668178637, +0.668178637919298919997757686523080761552472251);
DK(KP1_662939224, +1.662939224605090474157576755235811513477121624);
DK(KP198912367, +0.198912367379658006911597622644676228597850501);
DK(KP1_961570560, +1.961570560806460898252364472268478073947867462);
DK(KP707106781, +0.707106781186547524400844362104849039284835938);
DK(KP1_414213562, +1.414213562373095048801688724209698078569671875);
DK(KP414213562, +0.414213562373095048801688724209698078569671875);
DK(KP1_847759065, +1.847759065022573512256366378793576573644833252);
DK(KP2_000000000, +2.000000000000000000000000000000000000000000000);
{
INT i;
for (i = v; i > 0; i = i - 1, R0 = R0 + ovs, R1 = R1 + ovs, Cr = Cr + ivs, Ci = Ci + ivs, MAKE_VOLATILE_STRIDE(64, rs), MAKE_VOLATILE_STRIDE(64, csr), MAKE_VOLATILE_STRIDE(64, csi)) {
E TA, TD, Tv, TG, TE, TF;
{
E TK, TP, T7, T13, TW, TH, Tj, TC, To, Te, TX, TS, T12, Tt, TB;
{
E T4, Tf, T3, TU, Tz, T5, Tg, Th;
{
E T1, T2, Tx, Ty;
T1 = Cr[0];
T2 = Cr[WS(csr, 7)];
Tx = Ci[0];
Ty = Ci[WS(csi, 7)];
T4 = Cr[WS(csr, 4)];
Tf = T1 - T2;
T3 = T1 + T2;
TU = Ty - Tx;
Tz = Tx + Ty;
T5 = Cr[WS(csr, 3)];
Tg = Ci[WS(csi, 4)];
Th = Ci[WS(csi, 3)];
}
{
E Tb, Tk, Ta, TR, Tn, Tc, Tq, Tr;
{
E T8, T9, Tl, Tm;
T8 = Cr[WS(csr, 2)];
{
E Tw, T6, TV, Ti;
Tw = T4 - T5;
T6 = T4 + T5;
TV = Th - Tg;
Ti = Tg + Th;
TK = Tw - Tz;
TA = Tw + Tz;
TP = T3 - T6;
T7 = T3 + T6;
T13 = TV + TU;
TW = TU - TV;
TH = Tf + Ti;
Tj = Tf - Ti;
T9 = Cr[WS(csr, 5)];
}
Tl = Ci[WS(csi, 2)];
Tm = Ci[WS(csi, 5)];
Tb = Cr[WS(csr, 1)];
Tk = T8 - T9;
Ta = T8 + T9;
TR = Tl - Tm;
Tn = Tl + Tm;
Tc = Cr[WS(csr, 6)];
Tq = Ci[WS(csi, 1)];
Tr = Ci[WS(csi, 6)];
}
TC = Tk + Tn;
To = Tk - Tn;
{
E Tp, Td, TQ, Ts;
Tp = Tb - Tc;
Td = Tb + Tc;
TQ = Tr - Tq;
Ts = Tq + Tr;
Te = Ta + Td;
TX = Ta - Td;
TS = TQ - TR;
T12 = TR + TQ;
Tt = Tp - Ts;
TB = Tp + Ts;
}
}
}
{
E T10, TT, TY, TZ;
R0[0] = KP2_000000000 * (T7 + Te);
R0[WS(rs, 4)] = KP2_000000000 * (T13 - T12);
T10 = TP - TS;
TT = TP + TS;
TY = TW - TX;
TZ = TX + TW;
{
E T11, T14, TI, TL, Tu;
T11 = T7 - Te;
T14 = T12 + T13;
R0[WS(rs, 5)] = KP1_847759065 * (FNMS(KP414213562, TT, TY));
R0[WS(rs, 1)] = KP1_847759065 * (FMA(KP414213562, TY, TT));
R0[WS(rs, 6)] = KP1_414213562 * (T14 - T11);
R0[WS(rs, 2)] = KP1_414213562 * (T11 + T14);
TD = TB - TC;
TI = TC + TB;
TL = To - Tt;
Tu = To + Tt;
{
E TO, TJ, TN, TM;
R0[WS(rs, 7)] = -(KP1_847759065 * (FNMS(KP414213562, TZ, T10)));
R0[WS(rs, 3)] = KP1_847759065 * (FMA(KP414213562, T10, TZ));
TO = FMA(KP707106781, TI, TH);
TJ = FNMS(KP707106781, TI, TH);
TN = FMA(KP707106781, TL, TK);
TM = FNMS(KP707106781, TL, TK);
Tv = FMA(KP707106781, Tu, Tj);
TG = FNMS(KP707106781, Tu, Tj);
R1[WS(rs, 3)] = KP1_961570560 * (FMA(KP198912367, TO, TN));
R1[WS(rs, 7)] = -(KP1_961570560 * (FNMS(KP198912367, TN, TO)));
R1[WS(rs, 5)] = KP1_662939224 * (FNMS(KP668178637, TJ, TM));
R1[WS(rs, 1)] = KP1_662939224 * (FMA(KP668178637, TM, TJ));
}
}
}
}
TE = FNMS(KP707106781, TD, TA);
TF = FMA(KP707106781, TD, TA);
R1[WS(rs, 2)] = -(KP1_662939224 * (FNMS(KP668178637, TG, TF)));
R1[WS(rs, 6)] = -(KP1_662939224 * (FMA(KP668178637, TF, TG)));
R1[WS(rs, 4)] = -(KP1_961570560 * (FMA(KP198912367, Tv, TE)));
R1[0] = KP1_961570560 * (FNMS(KP198912367, TE, Tv));
}
}
}
static const kr2c_desc desc = { 16, "r2cbIII_16", {46, 16, 20, 0}, &GENUS };
void X(codelet_r2cbIII_16) (planner *p) {
X(kr2c_register) (p, r2cbIII_16, &desc);
}
#else /* HAVE_FMA */
/* Generated by: ../../../genfft/gen_r2cb.native -compact -variables 4 -pipeline-latency 4 -sign 1 -n 16 -name r2cbIII_16 -dft-III -include r2cbIII.h */
/*
* This function contains 66 FP additions, 32 FP multiplications,
* (or, 54 additions, 20 multiplications, 12 fused multiply/add),
* 40 stack variables, 9 constants, and 32 memory accesses
*/
#include "r2cbIII.h"
static void r2cbIII_16(R *R0, R *R1, R *Cr, R *Ci, stride rs, stride csr, stride csi, INT v, INT ivs, INT ovs)
{
DK(KP1_961570560, +1.961570560806460898252364472268478073947867462);
DK(KP390180644, +0.390180644032256535696569736954044481855383236);
DK(KP1_111140466, +1.111140466039204449485661627897065748749874382);
DK(KP1_662939224, +1.662939224605090474157576755235811513477121624);
DK(KP707106781, +0.707106781186547524400844362104849039284835938);
DK(KP1_414213562, +1.414213562373095048801688724209698078569671875);
DK(KP765366864, +0.765366864730179543456919968060797733522689125);
DK(KP1_847759065, +1.847759065022573512256366378793576573644833252);
DK(KP2_000000000, +2.000000000000000000000000000000000000000000000);
{
INT i;
for (i = v; i > 0; i = i - 1, R0 = R0 + ovs, R1 = R1 + ovs, Cr = Cr + ivs, Ci = Ci + ivs, MAKE_VOLATILE_STRIDE(64, rs), MAKE_VOLATILE_STRIDE(64, csr), MAKE_VOLATILE_STRIDE(64, csi)) {
E T7, TW, T13, Tj, TD, TK, TP, TH, Te, TX, T12, To, Tt, Tx, TS;
E Tw, TT, TY;
{
E T3, Tf, TC, TV, T6, Tz, Ti, TU;
{
E T1, T2, TA, TB;
T1 = Cr[0];
T2 = Cr[WS(csr, 7)];
T3 = T1 + T2;
Tf = T1 - T2;
TA = Ci[0];
TB = Ci[WS(csi, 7)];
TC = TA + TB;
TV = TB - TA;
}
{
E T4, T5, Tg, Th;
T4 = Cr[WS(csr, 4)];
T5 = Cr[WS(csr, 3)];
T6 = T4 + T5;
Tz = T4 - T5;
Tg = Ci[WS(csi, 4)];
Th = Ci[WS(csi, 3)];
Ti = Tg + Th;
TU = Tg - Th;
}
T7 = T3 + T6;
TW = TU + TV;
T13 = TV - TU;
Tj = Tf - Ti;
TD = Tz + TC;
TK = Tz - TC;
TP = T3 - T6;
TH = Tf + Ti;
}
{
E Ta, Tk, Tn, TR, Td, Tp, Ts, TQ;
{
E T8, T9, Tl, Tm;
T8 = Cr[WS(csr, 2)];
T9 = Cr[WS(csr, 5)];
Ta = T8 + T9;
Tk = T8 - T9;
Tl = Ci[WS(csi, 2)];
Tm = Ci[WS(csi, 5)];
Tn = Tl + Tm;
TR = Tl - Tm;
}
{
E Tb, Tc, Tq, Tr;
Tb = Cr[WS(csr, 1)];
Tc = Cr[WS(csr, 6)];
Td = Tb + Tc;
Tp = Tb - Tc;
Tq = Ci[WS(csi, 1)];
Tr = Ci[WS(csi, 6)];
Ts = Tq + Tr;
TQ = Tr - Tq;
}
Te = Ta + Td;
TX = Ta - Td;
T12 = TR + TQ;
To = Tk - Tn;
Tt = Tp - Ts;
Tx = Tp + Ts;
TS = TQ - TR;
Tw = Tk + Tn;
}
R0[0] = KP2_000000000 * (T7 + Te);
R0[WS(rs, 4)] = KP2_000000000 * (T13 - T12);
TT = TP + TS;
TY = TW - TX;
R0[WS(rs, 1)] = FMA(KP1_847759065, TT, KP765366864 * TY);
R0[WS(rs, 5)] = FNMS(KP765366864, TT, KP1_847759065 * TY);
{
E T11, T14, TZ, T10;
T11 = T7 - Te;
T14 = T12 + T13;
R0[WS(rs, 2)] = KP1_414213562 * (T11 + T14);
R0[WS(rs, 6)] = KP1_414213562 * (T14 - T11);
TZ = TP - TS;
T10 = TX + TW;
R0[WS(rs, 3)] = FMA(KP765366864, TZ, KP1_847759065 * T10);
R0[WS(rs, 7)] = FNMS(KP1_847759065, TZ, KP765366864 * T10);
}
{
E TJ, TN, TM, TO, TI, TL;
TI = KP707106781 * (Tw + Tx);
TJ = TH - TI;
TN = TH + TI;
TL = KP707106781 * (To - Tt);
TM = TK - TL;
TO = TL + TK;
R1[WS(rs, 1)] = FMA(KP1_662939224, TJ, KP1_111140466 * TM);
R1[WS(rs, 7)] = FNMS(KP1_961570560, TN, KP390180644 * TO);
R1[WS(rs, 5)] = FNMS(KP1_111140466, TJ, KP1_662939224 * TM);
R1[WS(rs, 3)] = FMA(KP390180644, TN, KP1_961570560 * TO);
}
{
E Tv, TF, TE, TG, Tu, Ty;
Tu = KP707106781 * (To + Tt);
Tv = Tj + Tu;
TF = Tj - Tu;
Ty = KP707106781 * (Tw - Tx);
TE = Ty + TD;
TG = Ty - TD;
R1[0] = FNMS(KP390180644, TE, KP1_961570560 * Tv);
R1[WS(rs, 6)] = FNMS(KP1_662939224, TF, KP1_111140466 * TG);
R1[WS(rs, 4)] = -(FMA(KP390180644, Tv, KP1_961570560 * TE));
R1[WS(rs, 2)] = FMA(KP1_111140466, TF, KP1_662939224 * TG);
}
}
}
}
static const kr2c_desc desc = { 16, "r2cbIII_16", {54, 20, 12, 0}, &GENUS };
void X(codelet_r2cbIII_16) (planner *p) {
X(kr2c_register) (p, r2cbIII_16, &desc);
}
#endif /* HAVE_FMA */
| Starlink/fftw | rdft/scalar/r2cb/r2cbIII_16.c | C | gpl-2.0 | 10,274 |
<?php
namespace TYPO3\CMS\Extbase\Tests\Unit\Persistence\Generic\Mapper;
/**
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3\CMS\Core\Tests\AccessibleObjectInterface;
use TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap;
use TYPO3\CMS\Core\DataHandling\TableColumnType;
use TYPO3\CMS\Core\DataHandling\TableColumnSubType;
/**
* Test case
*/
class DataMapFactoryTest extends \TYPO3\CMS\Core\Tests\UnitTestCase {
/**
* @return array
*/
public function oneToOneRelation() {
return array(
array('Tx_Myext_Domain_Model_Foo'),
array('TYPO3\\CMS\\Extbase\\Domain\\Model\\FrontendUser')
);
}
/**
* @test
* @dataProvider oneToOneRelation
*/
public function setRelationsDetectsOneToOneRelation($className) {
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$columnConfiguration = array(
'type' => 'select',
'foreign_table' => 'tx_myextension_bar',
'foreign_field' => 'parentid'
);
$propertyMetaData = array(
'type' => $className,
'elementType' => NULL
);
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('setOneToOneRelation', 'setOneToManyRelation', 'setManyToManyRelation'), array(), '', FALSE);
$mockDataMapFactory->expects($this->once())->method('setOneToOneRelation')->will($this->returnValue($mockColumnMap));
$mockDataMapFactory->expects($this->never())->method('setOneToManyRelation');
$mockDataMapFactory->expects($this->never())->method('setManyToManyRelation');
$mockDataMapFactory->_callRef('setRelations', $mockColumnMap, $columnConfiguration, $propertyMetaData);
}
/**
* @test
*/
public function settingOneToOneRelationSetsRelationTableMatchFields() {
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$matchFields = array(
'fieldname' => 'foo_model'
);
$columnConfiguration = array(
'type' => 'select',
'foreign_table' => 'tx_myextension_bar',
'foreign_field' => 'parentid',
'foreign_match_fields' => $matchFields
);
$mockColumnMap->expects($this->once())
->method('setRelationTableMatchFields')
->with($matchFields);
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy'), array(), '', FALSE);
$mockDataMapFactory->_call('setOneToOneRelation', $mockColumnMap, $columnConfiguration);
}
/**
* @test
*/
public function settingOneToManyRelationSetsRelationTableMatchFields() {
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$matchFields = array(
'fieldname' => 'foo_model'
);
$columnConfiguration = array(
'type' => 'select',
'foreign_table' => 'tx_myextension_bar',
'foreign_field' => 'parentid',
'foreign_match_fields' => $matchFields
);
$mockColumnMap->expects($this->once())
->method('setRelationTableMatchFields')
->with($matchFields);
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy'), array(), '', FALSE);
$mockDataMapFactory->_call('setOneToManyRelation', $mockColumnMap, $columnConfiguration);
}
/**
* @test
*/
public function setRelationsDetectsOneToOneRelationWithIntermediateTable() {
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$columnConfiguration = array(
'type' => 'select',
'foreign_table' => 'tx_myextension_bar',
'MM' => 'tx_myextension_mm'
);
$propertyMetaData = array(
'type' => 'Tx_Myext_Domain_Model_Foo',
'elementType' => NULL
);
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('setOneToOneRelation', 'setOneToManyRelation', 'setManyToManyRelation'), array(), '', FALSE);
$mockDataMapFactory->expects($this->never())->method('setOneToOneRelation');
$mockDataMapFactory->expects($this->never())->method('setOneToManyRelation');
$mockDataMapFactory->expects($this->once())->method('setManyToManyRelation')->will($this->returnValue($mockColumnMap));
$mockDataMapFactory->_callRef('setRelations', $mockColumnMap, $columnConfiguration, $propertyMetaData);
}
/**
* @test
*/
public function setRelationsDetectsOneToManyRelation() {
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$columnConfiguration = array(
'type' => 'select',
'foreign_table' => 'tx_myextension_bar',
'foreign_field' => 'parentid',
'foreign_table_field' => 'parenttable'
);
$propertyMetaData = array(
'type' => 'TYPO3\\CMS\\Extbase\\Persistence\\ObjectStorage',
'elementType' => 'Tx_Myext_Domain_Model_Foo'
);
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('setOneToOneRelation', 'setOneToManyRelation', 'setManyToManyRelation'), array(), '', FALSE);
$mockDataMapFactory->expects($this->never())->method('setOneToOneRelation');
$mockDataMapFactory->expects($this->once())->method('setOneToManyRelation')->will($this->returnValue($mockColumnMap));
$mockDataMapFactory->expects($this->never())->method('setManyToManyRelation');
$mockDataMapFactory->_callRef('setRelations', $mockColumnMap, $columnConfiguration, $propertyMetaData);
}
/**
* @test
*/
public function setRelationsDetectsManyToManyRelationOfTypeSelect() {
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$columnConfiguration = array(
'type' => 'select',
'foreign_table' => 'tx_myextension_bar',
'MM' => 'tx_myextension_mm'
);
$propertyMetaData = array(
'type' => 'TYPO3\\CMS\\Extbase\\Persistence\\ObjectStorage',
'elementType' => 'Tx_Myext_Domain_Model_Foo'
);
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('setOneToOneRelation', 'setOneToManyRelation', 'setManyToManyRelation'), array(), '', FALSE);
$mockDataMapFactory->expects($this->never())->method('setOneToOneRelation');
$mockDataMapFactory->expects($this->never())->method('setOneToManyRelation');
$mockDataMapFactory->expects($this->once())->method('setManyToManyRelation')->will($this->returnValue($mockColumnMap));
$mockDataMapFactory->_callRef('setRelations', $mockColumnMap, $columnConfiguration, $propertyMetaData);
}
/**
* @test
*/
public function setRelationsDetectsManyToManyRelationOfTypeInlineWithIntermediateTable() {
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$columnConfiguration = array(
'type' => 'inline',
'foreign_table' => 'tx_myextension_righttable',
'MM' => 'tx_myextension_mm'
);
$propertyMetaData = array(
'type' => 'TYPO3\\CMS\\Extbase\\Persistence\\ObjectStorage',
'elementType' => 'Tx_Myext_Domain_Model_Foo'
);
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('setOneToOneRelation', 'setOneToManyRelation', 'setManyToManyRelation'), array(), '', FALSE);
$mockDataMapFactory->expects($this->never())->method('setOneToOneRelation');
$mockDataMapFactory->expects($this->never())->method('setOneToManyRelation');
$mockDataMapFactory->expects($this->once())->method('setManyToManyRelation')->will($this->returnValue($mockColumnMap));
$mockDataMapFactory->_callRef('setRelations', $mockColumnMap, $columnConfiguration, $propertyMetaData);
}
/**
* @test
*/
public function columnMapIsInitializedWithManyToManyRelationOfTypeSelect() {
$leftColumnsDefinition = array(
'rights' => array(
'type' => 'select',
'foreign_table' => 'tx_myextension_righttable',
'foreign_table_where' => 'WHERE 1=1',
'MM' => 'tx_myextension_mm',
'MM_table_where' => 'WHERE 2=2'
)
);
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$mockColumnMap->expects($this->once())->method('setTypeOfRelation')->with($this->equalTo(\TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY));
$mockColumnMap->expects($this->once())->method('setRelationTableName')->with($this->equalTo('tx_myextension_mm'));
$mockColumnMap->expects($this->once())->method('setChildTableName')->with($this->equalTo('tx_myextension_righttable'));
$mockColumnMap->expects($this->once())->method('setChildTableWhereStatement')->with($this->equalTo('WHERE 1=1'));
$mockColumnMap->expects($this->once())->method('setChildSortByFieldName')->with($this->equalTo('sorting'));
$mockColumnMap->expects($this->once())->method('setParentKeyFieldName')->with($this->equalTo('uid_local'));
$mockColumnMap->expects($this->never())->method('setParentTableFieldName');
$mockColumnMap->expects($this->never())->method('setRelationTableMatchFields');
$mockColumnMap->expects($this->never())->method('setRelationTableInsertFields');
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy'), array(), '', FALSE);
$mockDataMapFactory->_callRef('setManyToManyRelation', $mockColumnMap, $leftColumnsDefinition['rights']);
}
/**
* @test
*/
public function columnMapIsInitializedWithOppositeManyToManyRelationOfTypeSelect() {
$rightColumnsDefinition = array(
'lefts' => array(
'type' => 'select',
'foreign_table' => 'tx_myextension_lefttable',
'MM' => 'tx_myextension_mm',
'MM_opposite_field' => 'rights'
)
);
$leftColumnsDefinition['rights']['MM_opposite_field'] = 'opposite_field';
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$mockColumnMap->expects($this->once())->method('setTypeOfRelation')->with($this->equalTo(\TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY));
$mockColumnMap->expects($this->once())->method('setRelationTableName')->with($this->equalTo('tx_myextension_mm'));
$mockColumnMap->expects($this->once())->method('setChildTableName')->with($this->equalTo('tx_myextension_lefttable'));
$mockColumnMap->expects($this->once())->method('setChildTableWhereStatement')->with(NULL);
$mockColumnMap->expects($this->once())->method('setChildSortByFieldName')->with($this->equalTo('sorting_foreign'));
$mockColumnMap->expects($this->once())->method('setParentKeyFieldName')->with($this->equalTo('uid_foreign'));
$mockColumnMap->expects($this->never())->method('setParentTableFieldName');
$mockColumnMap->expects($this->never())->method('setRelationTableMatchFields');
$mockColumnMap->expects($this->never())->method('setRelationTableInsertFields');
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy'), array(), '', FALSE);
$mockDataMapFactory->_callRef('setManyToManyRelation', $mockColumnMap, $rightColumnsDefinition['lefts']);
}
/**
* @test
*/
public function columnMapIsInitializedWithManyToManyRelationOfTypeInlineAndIntermediateTable() {
$leftColumnsDefinition = array(
'rights' => array(
'type' => 'inline',
'foreign_table' => 'tx_myextension_righttable',
'MM' => 'tx_myextension_mm',
'foreign_sortby' => 'sorting'
)
);
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$mockColumnMap->expects($this->once())->method('setTypeOfRelation')->with($this->equalTo(\TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY));
$mockColumnMap->expects($this->once())->method('setRelationTableName')->with($this->equalTo('tx_myextension_mm'));
$mockColumnMap->expects($this->once())->method('setChildTableName')->with($this->equalTo('tx_myextension_righttable'));
$mockColumnMap->expects($this->once())->method('setChildTableWhereStatement');
$mockColumnMap->expects($this->once())->method('setChildSortByFieldName')->with($this->equalTo('sorting'));
$mockColumnMap->expects($this->once())->method('setParentKeyFieldName')->with($this->equalTo('uid_local'));
$mockColumnMap->expects($this->never())->method('setParentTableFieldName');
$mockColumnMap->expects($this->never())->method('setRelationTableMatchFields');
$mockColumnMap->expects($this->never())->method('setRelationTableInsertFields');
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('getColumnsDefinition'), array(), '', FALSE);
$mockDataMapFactory->expects($this->never())->method('getColumnsDefinition');
$mockDataMapFactory->_callRef('setManyToManyRelation', $mockColumnMap, $leftColumnsDefinition['rights']);
}
/**
* @test
*/
public function columnMapIsInitializedWithManyToManyRelationWithoutPidColumn() {
$leftColumnsDefinition = array(
'rights' => array(
'type' => 'select',
'foreign_table' => 'tx_myextension_righttable',
'foreign_table_where' => 'WHERE 1=1',
'MM' => 'tx_myextension_mm'
)
);
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$mockColumnMap->expects($this->once())->method('setRelationTableName')->with($this->equalTo('tx_myextension_mm'));
$mockColumnMap->expects($this->once())->method('getRelationTableName')->will($this->returnValue('tx_myextension_mm'));
$mockColumnMap->expects($this->never())->method('setrelationTablePageIdColumnName');
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('getControlSection'), array(), '', FALSE);
$mockDataMapFactory->expects($this->once())->method('getControlSection')->with($this->equalTo('tx_myextension_mm'))->will($this->returnValue(NULL));
$mockDataMapFactory->_callRef('setManyToManyRelation', $mockColumnMap, $leftColumnsDefinition['rights']);
}
/**
* @test
*/
public function columnMapIsInitializedWithManyToManyRelationWithPidColumn() {
$leftColumnsDefinition = array(
'rights' => array(
'type' => 'select',
'foreign_table' => 'tx_myextension_righttable',
'foreign_table_where' => 'WHERE 1=1',
'MM' => 'tx_myextension_mm'
)
);
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$mockColumnMap->expects($this->once())->method('setRelationTableName')->with($this->equalTo('tx_myextension_mm'));
$mockColumnMap->expects($this->once())->method('getRelationTableName')->will($this->returnValue('tx_myextension_mm'));
$mockColumnMap->expects($this->once())->method('setrelationTablePageIdColumnName')->with($this->equalTo('pid'));
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('getControlSection'), array(), '', FALSE);
$mockDataMapFactory->expects($this->once())->method('getControlSection')->with($this->equalTo('tx_myextension_mm'))->will($this->returnValue(array('ctrl' => array('foo' => 'bar'))));
$mockDataMapFactory->_callRef('setManyToManyRelation', $mockColumnMap, $leftColumnsDefinition['rights']);
}
/**
* @return array
*/
public function columnMapIsInitializedWithFieldEvaluationsForDateTimeFieldsDataProvider() {
return array(
'date field' => array('date', 'date'),
'datetime field' => array('datetime', 'datetime'),
'no date/datetime field' => array('', NULL),
);
}
/**
* @param string $type
* @param NULL|string $expectedValue
* @test
* @dataProvider columnMapIsInitializedWithFieldEvaluationsForDateTimeFieldsDataProvider
*/
public function columnMapIsInitializedWithFieldEvaluationsForDateTimeFields($type, $expectedValue) {
$columnDefinition = array(
'type' => 'input',
'dbType' => $type,
'eval' => $type,
);
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array('setDateTimeStorageFormat'), array(), '', FALSE);
if ($expectedValue !== NULL) {
$mockColumnMap->expects($this->once())->method('setDateTimeStorageFormat')->with($this->equalTo($type));
} else {
$mockColumnMap->expects($this->never())->method('setDateTimeStorageFormat');
}
$accessibleClassName = $this->buildAccessibleProxy('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory');
$accessibleDataMapFactory = new $accessibleClassName();
$accessibleDataMapFactory->_callRef('setFieldEvaluations', $mockColumnMap, $columnDefinition);
}
/**
* @test
* @expectedException \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InvalidClassException
*/
public function buildDataMapThrowsExceptionIfClassNameIsNotKnown() {
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('getControlSection'), array(), '', FALSE);
$cacheMock = $this->getMock('TYPO3\\CMS\\Core\\Cache\\Frontend\\VariableFrontend', array('get'), array(), '', FALSE);
$cacheMock->expects($this->any())->method('get')->will($this->returnValue(FALSE));
$mockDataMapFactory->_set('dataMapCache', $cacheMock);
$mockDataMapFactory->buildDataMap('UnknownObject');
}
/**
* @test
*/
public function buildDataMapFetchesSubclassesRecursively() {
$this->markTestSkipped('Incomplete mocking in a complex scenario. This should be a functional test');
$configuration = array(
'persistence' => array(
'classes' => array(
'TYPO3\\CMS\\Extbase\\Domain\\Model\\FrontendUser' => array(
'subclasses' => array(
'Tx_SampleExt_Domain_Model_LevelOne1' => 'Tx_SampleExt_Domain_Model_LevelOne1',
'Tx_SampleExt_Domain_Model_LevelOne2' => 'Tx_SampleExt_Domain_Model_LevelOne2'
)
),
'Tx_SampleExt_Domain_Model_LevelOne1' => array(
'subclasses' => array(
'Tx_SampleExt_Domain_Model_LevelTwo1' => 'Tx_SampleExt_Domain_Model_LevelTwo1',
'Tx_SampleExt_Domain_Model_LevelTwo2' => 'Tx_SampleExt_Domain_Model_LevelTwo2'
)
),
'Tx_SampleExt_Domain_Model_LevelOne2' => array(
'subclasses' => array()
)
)
)
);
$expectedSubclasses = array(
'Tx_SampleExt_Domain_Model_LevelOne1',
'Tx_SampleExt_Domain_Model_LevelTwo1',
'Tx_SampleExt_Domain_Model_LevelTwo2',
'Tx_SampleExt_Domain_Model_LevelOne2'
);
/** @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject $objectManager */
$objectManager = $this->getMock('TYPO3\\CMS\\Extbase\\Object\\ObjectManager', array('dummy'), array(), '', FALSE);
/** @var $configurationManager \TYPO3\CMS\Extbase\Configuration\ConfigurationManager|\PHPUnit_Framework_MockObject_MockObject */
$configurationManager = $this->getMock('TYPO3\\CMS\\Extbase\\Configuration\\ConfigurationManager');
$configurationManager->expects($this->once())->method('getConfiguration')->with('Framework')->will($this->returnValue($configuration));
/** @var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapFactory $dataMapFactory */
$dataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('test'));
$dataMapFactory->_set('reflectionService', new \TYPO3\CMS\Extbase\Reflection\ReflectionService());
$dataMapFactory->_set('objectManager', $objectManager);
$dataMapFactory->_set('configurationManager', $configurationManager);
$cacheMock = $this->getMock('TYPO3\\CMS\\Core\\Cache\\Frontend\\VariableFrontend', array(), array(), '', FALSE);
$cacheMock->expects($this->any())->method('get')->will($this->returnValue(FALSE));
$dataMapFactory->_set('dataMapCache', $cacheMock);
$dataMap = $dataMapFactory->buildDataMap('TYPO3\\CMS\\Extbase\\Domain\\Model\\FrontendUser');
$this->assertSame($expectedSubclasses, $dataMap->getSubclasses());
}
/**
* @return array
*/
public function classNameTableNameMappings() {
return array(
'Core classes' => array('TYPO3\\CMS\\Belog\\Domain\\Model\\LogEntry', 'tx_belog_domain_model_logentry'),
'Core classes with namespaces and leading backslash' => array('\\TYPO3\\CMS\\Belog\\Domain\\Model\\LogEntry', 'tx_belog_domain_model_logentry'),
'Extension classes' => array('ExtbaseTeam\\BlogExample\\Domain\\Model\\Blog', 'tx_blogexample_domain_model_blog'),
'Extension classes with namespaces and leading backslash' => array('\\ExtbaseTeam\\BlogExample\\Domain\\Model\\Blog', 'tx_blogexample_domain_model_blog'),
'Extension classes without namespace' => array('Tx_News_Domain_Model_News', 'tx_news_domain_model_news'),
'Extension classes without namespace but leading slash' => array('\\Tx_News_Domain_Model_News', 'tx_news_domain_model_news'),
);
}
/**
* @test
* @dataProvider classNameTableNameMappings
*/
public function resolveTableNameReturnsExpectedTablenames($className, $expected) {
$dataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy'));
$this->assertSame($expected, $dataMapFactory->_call('resolveTableName', $className));
}
/**
* @test
*/
public function createColumnMapReturnsAValidColumnMap() {
/** @var $dataMapFactory \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapFactory */
$dataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy'));
/** @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject $objectManager */
$objectManager = $this->getMock('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
$columnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array('column', 'property'));
$objectManager->expects($this->once())->method('get')->will($this->returnValue($columnMap));
$dataMapFactory->_set('objectManager', $objectManager);
$this->assertEquals(
$columnMap,
$dataMapFactory->_call('createColumnMap', 'column', 'property')
);
}
/**
* @return array
*/
public function tcaConfigurationsContainingTypeAndInternalType() {
return array(
array(array('type' => 'input'), TableColumnType::INPUT, NULL),
array(array('type' => 'text'), TableColumnType::TEXT, NULL),
array(array('type' => 'check'), TableColumnType::CHECK, NULL),
array(array('type' => 'radio'), TableColumnType::RADIO, NULL),
array(array('type' => 'select'), TableColumnType::SELECT, NULL),
array(array('type' => 'group', 'internal_type' => 'db'), TableColumnType::GROUP, TableColumnSubType::DB),
array(array('type' => 'group', 'internal_type' => 'file'), TableColumnType::GROUP, TableColumnSubType::FILE),
array(array('type' => 'group', 'internal_type' => 'file_reference'), TableColumnType::GROUP, TableColumnSubType::FILE_REFERENCE),
array(array('type' => 'group', 'internal_type' => 'folder'), TableColumnType::GROUP, TableColumnSubType::FOLDER),
array(array('type' => 'none'), TableColumnType::NONE, NULL),
array(array('type' => 'passthrough'), TableColumnType::PASSTHROUGH, NULL),
array(array('type' => 'user'), TableColumnType::USER, NULL),
array(array('type' => 'flex'), TableColumnType::FLEX, NULL),
array(array('type' => 'inline'), TableColumnType::INLINE, NULL),
);
}
/**
* @test
* @dataProvider tcaConfigurationsContainingTypeAndInternalType
*
* @param array $columnConfiguration
* @param string $type
* @param string $internalType
*/
public function setTypeDetectsTypeAndInternalTypeProperly(array $columnConfiguration, $type, $internalType) {
/** @var $dataMapFactory \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapFactory | AccessibleObjectInterface */
$dataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy'));
/** @var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap $columnMap */
$columnMap = $this->getAccessibleMock('TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap', array('dummy'), array(), '', FALSE);
$dataMapFactory->_call('setType', $columnMap, $columnConfiguration);
$this->assertEquals($type, (string) $columnMap->getType());
$this->assertEquals($internalType, (string) $columnMap->getInternalType());
}
}
| TimboDynamite/TYPO3-Testprojekt | typo3/sysext/extbase/Tests/Unit/Persistence/Generic/Mapper/DataMapFactoryTest.php | PHP | gpl-2.0 | 24,950 |
# ---------------------------------------------------
# Compile Options
# ---------------------------------------------------
include $(MTK_PATH_BUILD)/Makefile
WLAN_CHIP_LIST:=-UMT6620 -UMT6628 -UMT5931 -UMT6630
ccflags-y += $(WLAN_CHIP_LIST)
WLAN_CHIP_ID=MT6630
ccflags-y:=$(filter-out -U$(WLAN_CHIP_ID),$(ccflags-y))
ccflags-y += -DLINUX -D$(WLAN_CHIP_ID)
ifeq ($(HAVE_XLOG_FEATURE), yes)
ccflags-y += -DCFG_SUPPORT_XLOG=1
else
ccflags-y += -DCFG_SUPPORT_XLOG=0
endif
ifeq ($(HAVE_AEE_FEATURE), yes)
ccflags-y += -DCFG_SUPPORT_AEE=1
else
ccflags-y += -DCFG_SUPPORT_AEE=0
endif
# Disable ASSERT() for user load, enable for others
ifneq ($(TARGET_BUILD_VARIANT),user)
ccflags-y += -DBUILD_QA_DBG=1
else
ccflags-y += -DBUILD_QA_DBG=0
endif
ifeq ($(CONFIG_MTK_COMBO_WIFI),y)
ccflags-y += -DCFG_BUILT_IN_DRIVER=1
else
ccflags-y += -DCFG_BUILT_IN_DRIVER=0
endif
#ifeq ($(CONFIG_MTK_COMBO_WIFI_HIF_SDIO1), y)
# ccflags-y += -D_HIF_SDIO=1
#endif
ifeq ($(MTK_PASSPOINT_R1_SUPPORT), yes)
ccflags-y += -DCFG_SUPPORT_PASSPOINT=1
ccflags-y += -DCFG_HS20_DEBUG=1
ccflags-y += -DCFG_ENABLE_GTK_FRAME_FILTER=1
else ifeq ($(MTK_PASSPOINT_R2_SUPPORT), yes)
ccflags-y += -DCFG_SUPPORT_PASSPOINT=1
ccflags-y += -DCFG_HS20_DEBUG=1
ccflags-y += -DCFG_ENABLE_GTK_FRAME_FILTER=1
else
ccflags-y += -DCFG_SUPPORT_PASSPOINT=0
ccflags-y += -DCFG_HS20_DEBUG=0
ccflags-y += -DCFG_ENABLE_GTK_FRAME_FILTER=0
endif
MODULE_NAME := wlan_$(shell echo $(strip $(WLAN_CHIP_ID)) | tr A-Z a-z)
ccflags-y += -D_HIF_SDIO=1
ccflags-y += -DDBG=0
ccflags-y += -I$(src)/os -I$(src)/os/linux/include -I$(src)/os/linux/hif/sdio/include
ccflags-y += -I$(src)/include -I$(src)/include/nic -I$(src)/include/mgmt
obj-$(CONFIG_MTK_COMBO_WIFI) += $(MODULE_NAME).o
#obj-y += $(MODULE_NAME).o
# ---------------------------------------------------
# Directory List
# ---------------------------------------------------
COMMON_DIR := common/
OS_DIR := os/linux/
HIF_DIR := os/linux/hif/sdio/
NIC_DIR := nic/
MGMT_DIR := mgmt/
# ---------------------------------------------------
# Objects List
# ---------------------------------------------------
COMMON_OBJS := $(COMMON_DIR)dump.o \
$(COMMON_DIR)wlan_lib.o \
$(COMMON_DIR)wlan_oid.o \
$(COMMON_DIR)wlan_bow.o
NIC_OBJS := $(NIC_DIR)nic.o \
$(NIC_DIR)nic_tx.o \
$(NIC_DIR)nic_rx.o \
$(NIC_DIR)nic_pwr_mgt.o \
$(NIC_DIR)nic_rate.o \
$(NIC_DIR)cmd_buf.o \
$(NIC_DIR)que_mgt.o \
$(NIC_DIR)nic_cmd_event.o
OS_OBJS := $(OS_DIR)gl_init.o \
$(OS_DIR)gl_kal.o \
$(OS_DIR)gl_bow.o \
$(OS_DIR)gl_wext.o \
$(OS_DIR)gl_wext_priv.o \
$(OS_DIR)gl_rst.o \
$(OS_DIR)gl_cfg80211.o \
$(OS_DIR)platform.o
MGMT_OBJS := $(MGMT_DIR)ais_fsm.o \
$(MGMT_DIR)aaa_fsm.o \
$(MGMT_DIR)assoc.o \
$(MGMT_DIR)auth.o \
$(MGMT_DIR)bss.o \
$(MGMT_DIR)cnm.o \
$(MGMT_DIR)cnm_timer.o \
$(MGMT_DIR)cnm_mem.o \
$(MGMT_DIR)hem_mbox.o \
$(MGMT_DIR)mib.o \
$(MGMT_DIR)privacy.o \
$(MGMT_DIR)rate.o \
$(MGMT_DIR)rlm.o \
$(MGMT_DIR)rlm_domain.o \
$(MGMT_DIR)rlm_obss.o \
$(MGMT_DIR)rlm_protection.o \
$(MGMT_DIR)rsn.o \
$(MGMT_DIR)saa_fsm.o \
$(MGMT_DIR)scan.o \
$(MGMT_DIR)scan_fsm.o \
$(MGMT_DIR)swcr.o \
$(MGMT_DIR)roaming_fsm.o \
$(MGMT_DIR)tkip_mic.o \
$(MGMT_DIR)hs20.o \
$(MGMT_DIR)tdls.o
# ---------------------------------------------------
# P2P Objects List
# ---------------------------------------------------
COMMON_OBJS += $(COMMON_DIR)wlan_p2p.o
NIC_OBJS += $(NIC_DIR)p2p_nic.o
OS_OBJS += $(OS_DIR)gl_p2p.o \
$(OS_DIR)gl_p2p_cfg80211.o \
$(OS_DIR)gl_p2p_init.o \
$(OS_DIR)gl_p2p_kal.o
MGMT_OBJS += $(MGMT_DIR)p2p_dev_fsm.o\
$(MGMT_DIR)p2p_dev_state.o\
$(MGMT_DIR)p2p_role_fsm.o\
$(MGMT_DIR)p2p_role_state.o\
$(MGMT_DIR)p2p_func.o\
$(MGMT_DIR)p2p_scan.o\
$(MGMT_DIR)p2p_ie.o\
$(MGMT_DIR)p2p_rlm.o\
$(MGMT_DIR)p2p_assoc.o\
$(MGMT_DIR)p2p_bss.o\
$(MGMT_DIR)p2p_rlm_obss.o
MGMT_OBJS += $(MGMT_DIR)wapi.o
ifeq ($(WLAN_PROC), y)
OS_OBJS += gl_proc.o
endif
HIF_OBJS := $(HIF_DIR)arm.o \
$(HIF_DIR)sdio.o
$(MODULE_NAME)-objs += $(COMMON_OBJS)
$(MODULE_NAME)-objs += $(NIC_OBJS)
$(MODULE_NAME)-objs += $(OS_OBJS)
$(MODULE_NAME)-objs += $(HIF_OBJS)
$(MODULE_NAME)-objs += $(MGMT_OBJS)
| visi0nary/mediatek | mt6732/mediatek/kernel/drivers/combo/drv_wlan/mt6630/wlan/Makefile | Makefile | gpl-2.0 | 4,596 |
#
# Makefile for the kernel USB device drivers.
#
# Object files in subdirectories
obj-$(CONFIG_USB) += core/
obj-$(CONFIG_USB_DWC3) += dwc3/
obj-$(CONFIG_USB_DWC2) += dwc2/
obj-$(CONFIG_USB_MON) += mon/
obj-$(CONFIG_PCI) += host/
obj-$(CONFIG_USB_EHCI_HCD) += host/
obj-$(CONFIG_USB_ISP116X_HCD) += host/
obj-$(CONFIG_USB_OHCI_HCD) += host/
obj-$(CONFIG_USB_UHCI_HCD) += host/
obj-$(CONFIG_USB_FHCI_HCD) += host/
obj-$(CONFIG_USB_XHCI_HCD) += host/
obj-$(CONFIG_USB_SL811_HCD) += host/
obj-$(CONFIG_USB_ISP1362_HCD) += host/
obj-$(CONFIG_USB_U132_HCD) += host/
obj-$(CONFIG_USB_R8A66597_HCD) += host/
obj-$(CONFIG_USB_HWA_HCD) += host/
obj-$(CONFIG_USB_ISP1760_HCD) += host/
obj-$(CONFIG_USB_IMX21_HCD) += host/
obj-$(CONFIG_USB_FSL_MPH_DR_OF) += host/
obj-$(CONFIG_USB_FUSBH200_HCD) += host/
obj-$(CONFIG_USB_FOTG210_HCD) += host/
obj-$(CONFIG_USB_MAX3421_HCD) += host/
obj-$(CONFIG_USB_C67X00_HCD) += c67x00/
obj-$(CONFIG_USB_WUSB) += wusbcore/
obj-$(CONFIG_USB_ACM) += class/
obj-$(CONFIG_USB_PRINTER) += class/
obj-$(CONFIG_USB_WDM) += class/
obj-$(CONFIG_USB_TMC) += class/
obj-$(CONFIG_USB_STORAGE) += storage/
obj-$(CONFIG_USB) += storage/
obj-$(CONFIG_USB_MDC800) += image/
obj-$(CONFIG_USB_MICROTEK) += image/
obj-$(CONFIG_USB_SERIAL) += serial/
obj-$(CONFIG_USB) += misc/
obj-$(CONFIG_USB_SUPPORT) += phy/
obj-$(CONFIG_EARLY_PRINTK_DBGP) += early/
obj-$(CONFIG_USB_ATM) += atm/
obj-$(CONFIG_USB_SPEEDTOUCH) += atm/
obj-$(CONFIG_USB_MUSB_HDRC) += musb/
obj-$(CONFIG_USB_CHIPIDEA) += chipidea/
obj-$(CONFIG_USB_RENESAS_USBHS) += renesas_usbhs/
obj-$(CONFIG_USB_GADGET) += gadget/
obj-$(CONFIG_USB_COMMON) += common/
obj-$(CONFIG_USBIP_CORE) += usbip/
obj-$(CONFIG_USB_NOTIFY_LAYER) += notify/
obj-$(CONFIG_USB_TYPEC_MANAGER_NOTIFIER) += manager/
| lyapota/n7_port2edge | drivers/usb/Makefile | Makefile | gpl-2.0 | 1,783 |
/*
* \brief Regulator-session component
* \author Stefan Kalkowski
* \date 2013-06-13
*/
/*
* Copyright (C) 2013 Genode Labs GmbH
*
* This file is part of the Genode OS framework, which is distributed
* under the terms of the GNU General Public License version 2.
*/
#ifndef _INCLUDE__REGULATOR__COMPONENT_H_
#define _INCLUDE__REGULATOR__COMPONENT_H_
#include <root/component.h>
#include <regulator_session/rpc_object.h>
#include <regulator/driver.h>
namespace Regulator {
class Session_component;
class Root;
}
class Regulator::Session_component : public Regulator::Session_rpc_object
{
private:
Driver_factory &_driver_factory;
Driver &_driver;
public:
/**
* Constructor
*/
Session_component(Regulator_id regulator_id,
Driver_factory &driver_factory)
: Session_rpc_object(regulator_id),
_driver_factory(driver_factory),
_driver(_driver_factory.create(regulator_id)) { }
/**
* Destructor
*/
~Session_component()
{
_driver.state(_id, false);
_driver_factory.destroy(_driver);
}
/***********************************
** Regulator session interface **
***********************************/
void level(unsigned long level) { _driver.level(_id, level); }
unsigned long level() { return _driver.level(_id); }
void state(bool enable) { _driver.state(_id, enable); }
bool state() { return _driver.state(_id); }
};
class Regulator::Root :
public Genode::Root_component<Regulator::Session_component>
{
private:
Driver_factory &_driver_factory;
Genode::Rpc_entrypoint &_ep;
protected:
Session_component *_create_session(const char *args)
{
using namespace Genode;
char reg_name[64];
Arg_string::find_arg(args, "regulator").string(reg_name,
sizeof(reg_name), 0);
size_t ram_quota =
Arg_string::find_arg(args, "ram_quota").ulong_value(0);
/* delete ram quota by the memory needed for the session */
size_t session_size = max((size_t)4096,
sizeof(Session_component));
if (ram_quota < session_size)
throw Root::Quota_exceeded();
if (!strlen(reg_name))
throw Root::Invalid_args();
return new (md_alloc())
Session_component(regulator_id_by_name(reg_name),
_driver_factory);
}
public:
Root(Genode::Rpc_entrypoint *session_ep,
Genode::Allocator *md_alloc,
Driver_factory &driver_factory)
: Genode::Root_component<Regulator::Session_component>(session_ep,
md_alloc),
_driver_factory(driver_factory), _ep(*session_ep) { }
};
#endif /* _INCLUDE__REGULATOR__COMPONENT_H_ */
| waylon531/genode | repos/os/include/regulator/component.h | C | gpl-2.0 | 2,773 |
/*
Copyright (C) 2009
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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace WikiFunctions
{
/// <summary>
/// Factory class for making instances of IArticleComparer
/// </summary>
public static class ArticleComparerFactory
{
/// <summary>
///
/// </summary>
/// <param name="comparator">The test string</param>
/// <param name="isCaseSensitive">Whether the comparison should be case sensitive</param>
/// <param name="isRegex">Whether to employ regular expression matching when comparing the test string</param>
/// <param name="isSingleLine">Whether to apply the regular expression Single Line option</param>
/// <param name="isMultiLine">Whether to apply the regular expression Multi Line option</param>
/// <returns>An instance of IArticleComparer which can carry out the specified comparison</returns>
public static IArticleComparer Create(string comparator, bool isCaseSensitive, bool isRegex, bool isSingleLine, bool isMultiLine)
{
if (comparator == null)
throw new ArgumentNullException("comparator");
if (isRegex)
{
try
{
RegexOptions opts = RegexOptions.None;
if (!isCaseSensitive)
opts |= RegexOptions.IgnoreCase;
if (isSingleLine)
opts |= RegexOptions.Singleline;
if (isMultiLine)
opts |= RegexOptions.Multiline;
return comparator.Contains("%%")
? (IArticleComparer)new DynamicRegexArticleComparer(comparator, opts)
: new RegexArticleComparer(new Regex(comparator, opts | RegexOptions.Compiled));
}
catch (ArgumentException ex)
{
//TODO: handle things like "bad regex" here
// For now, tell the user then let normal exception handling process it as well
MessageBox.Show(ex.Message, "Bad Regex");
throw;
}
}
if (comparator.Contains("%%"))
return isCaseSensitive
? (IArticleComparer)new CaseSensitiveArticleComparerWithKeywords(comparator)
: new CaseInsensitiveArticleComparerWithKeywords(comparator);
return isCaseSensitive
? (IArticleComparer)new CaseSensitiveArticleComparer(comparator)
: new CaseInsensitiveArticleComparer(comparator);
}
}
/// <summary>
/// Class for scanning an article for content
/// </summary>
public interface IArticleComparer
{
/// <summary>
/// Compares the article text against the criteria provided
/// </summary>
/// <param name="article">An article to check</param>
/// <returns>Whether the article's text matches the criteria</returns>
bool Matches(Article article);
}
} | svn2github/autowikibrowser | tags/REL_5_3_1/WikiFunctions/Article/Comparers/ArticleComparerFactory.cs | C# | gpl-2.0 | 3,930 |
<?php
/**
* Tabs GK5 - main PHP file
* @package Joomla!
* @Copyright (C) 2009-2012 Gavick.com
* @ All rights reserved
* @ Joomla! is Free Software
* @ Released under GNU/GPL License : http://www.gnu.org/copyleft/gpl.html
* @ version $Revision: GK5 1.0 $
**/
defined('JPATH_BASE') or die;
jimport('joomla.form.formfield');
class JFormFieldAbout extends JFormField {
protected $type = 'About';
protected function getInput() {
return '<div id="gk_about_us">' . JText::_('MOD_TABS_ABOUT_US_CONTENT') . '</div>';
}
}
// EOF | volodymyrdmytriv/levin-25-2 | modules/mod_tabs_gk5/admin/elements/about.php | PHP | gpl-2.0 | 529 |
INSERT INTO spell_script_names VALUES
(2823, 'spell_rog_poisons'),
(8679, 'spell_rog_poisons'),
(5761, 'spell_rog_poisons'),
(3408, 'spell_rog_poisons'); | MistCore/MistCore | sql/updates/world/worldpanda_old_world_updates_2012_2013/2012/2012_01_08_world_spell_script_names_2.sql | SQL | gpl-2.0 | 153 |
/* testlib.c for c++ - test expectlib */
#include <stdio.h>
#include "expect.h"
extern "C" {
extern int write(...);
extern int strlen(...);
}
void
timedout()
{
fprintf(stderr,"timed out\n");
exit(-1);
}
char move[100];
void
read_first_move(int fd)
{
if (EXP_TIMEOUT == exp_expectl(fd,exp_glob,"first\r\n1.*\r\n",0,exp_end)) {
timedout();
}
sscanf(exp_match,"%*s 1. %s",move);
}
/* moves and counter-moves are printed out in different formats, sigh... */
void
read_counter_move(int fd)
{
switch (exp_expectl(fd,exp_glob,"*...*\r\n",0,exp_end)) {
case EXP_TIMEOUT: timedout();
case EXP_EOF: exit(-1);
}
sscanf(exp_match,"%*s %*s %*s %*s ... %s",move);
}
void
read_move(int fd)
{
switch (exp_expectl(fd,exp_glob,"*...*\r\n*.*\r\n",0,exp_end)) {
case EXP_TIMEOUT: timedout();
case EXP_EOF: exit(-1);
}
sscanf(exp_match,"%*s %*s ... %*s %*s %s",move);
}
void
send_move(int fd)
{
write(fd,move,strlen(move));
}
main(){
int fd1, fd2;
exp_loguser = 1;
exp_timeout = 3600;
if (-1 == (fd1 = exp_spawnl("chess","chess",(char *)0))) {
perror("chess");
exit(-1);
}
if (-1 == exp_expectl(fd1,exp_glob,"Chess\r\n",0,exp_end)) exit;
if (-1 == write(fd1,"first\r",6)) exit;
read_first_move(fd1);
fd2 = exp_spawnl("chess","chess",(char *)0);
if (-1 == exp_expectl(fd2,exp_glob,"Chess\r\n",0,exp_end)) exit;
for (;;) {
send_move(fd2);
read_counter_move(fd2);
send_move(fd1);
read_move(fd1);
}
}
| atmark-techno/atmark-dist | user/expect/expect-5.43.0/example/chesslib++.c | C | gpl-2.0 | 1,443 |
/*
* uiComponents.CustomLabel
*
*------------------------------------------------------------------------------
* Copyright (C) 2006-2008 University of Dundee. All rights reserved.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*------------------------------------------------------------------------------
*/
package org.openmicroscopy.shoola.agents.editor.uiComponents;
//Java imports
import javax.swing.Icon;
import javax.swing.JLabel;
//Third-party libraries
//Application-internal dependencies
/**
* A Custom Label, which should be used by the UI instead of using
* JLabel. Sets the font to CUSTOM FONT.
*
* This font is also used by many other Custom UI components in this
* package, making it easy to change the font in many components in
* one place (here!).
*
* @author William Moore
* <a href="mailto:will@lifesci.dundee.ac.uk">will@lifesci.dundee.ac.uk</a>
* @version 3.0
* <small>
* (<b>Internal version:</b> $Revision: $Date: $)
* </small>
* @since OME3.0
*/
public class CustomLabel
extends JLabel {
private int fontSize;
/**
* Simply delegates to JLabel superclass.
*/
public CustomLabel() {
super();
setFont();
}
/**
* Simply delegates to JLabel superclass.
*/
public CustomLabel(Icon image) {
super(image);
setFont();
}
/**
* Simply delegates to JLabel superclass.
*/
public CustomLabel(String text) {
super(text);
setFont();
}
/**
* Simply delegates to JLabel superclass.
*/
public CustomLabel(String text, int fontSize) {
super(text);
this.fontSize = fontSize;
setFont();
}
private void setFont()
{
if (fontSize == 0)
setFont(new CustomFont());
else {
setFont(CustomFont.getFontBySize(fontSize));
}
}
}
| jballanc/openmicroscopy | components/insight/SRC/org/openmicroscopy/shoola/agents/editor/uiComponents/CustomLabel.java | Java | gpl-2.0 | 2,450 |
<?php
/**
* PEAR_Command_Common base class
*
* PHP versions 4 and 5
*
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_0.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
*
* @category pear
* @package PEAR
* @author Stig Bakken <ssb@php.net>
* @author Greg Beaver <cellog@php.net>
* @copyright 1997-2006 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version CVS: $Id: Common.php 6775 2007-05-22 12:39:39Z andrew.hill@openads.org $
* @link http://pear.php.net/package/PEAR
* @since File available since Release 0.1
*/
/**
* base class
*/
require_once 'PEAR.php';
/**
* PEAR commands base class
*
* @category pear
* @package PEAR
* @author Stig Bakken <ssb@php.net>
* @author Greg Beaver <cellog@php.net>
* @copyright 1997-2006 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version Release: 1.5.4
* @link http://pear.php.net/package/PEAR
* @since Class available since Release 0.1
*/
class PEAR_Command_Common extends PEAR
{
// {{{ properties
/**
* PEAR_Config object used to pass user system and configuration
* on when executing commands
*
* @var PEAR_Config
*/
var $config;
/**
* @var PEAR_Registry
* @access protected
*/
var $_registry;
/**
* User Interface object, for all interaction with the user.
* @var object
*/
var $ui;
var $_deps_rel_trans = array(
'lt' => '<',
'le' => '<=',
'eq' => '=',
'ne' => '!=',
'gt' => '>',
'ge' => '>=',
'has' => '=='
);
var $_deps_type_trans = array(
'pkg' => 'package',
'ext' => 'extension',
'php' => 'PHP',
'prog' => 'external program',
'ldlib' => 'external library for linking',
'rtlib' => 'external runtime library',
'os' => 'operating system',
'websrv' => 'web server',
'sapi' => 'SAPI backend'
);
// }}}
// {{{ constructor
/**
* PEAR_Command_Common constructor.
*
* @access public
*/
function PEAR_Command_Common(&$ui, &$config)
{
parent::PEAR();
$this->config = &$config;
$this->ui = &$ui;
}
// }}}
// {{{ getCommands()
/**
* Return a list of all the commands defined by this class.
* @return array list of commands
* @access public
*/
function getCommands()
{
$ret = array();
foreach (array_keys($this->commands) as $command) {
$ret[$command] = $this->commands[$command]['summary'];
}
return $ret;
}
// }}}
// {{{ getShortcuts()
/**
* Return a list of all the command shortcuts defined by this class.
* @return array shortcut => command
* @access public
*/
function getShortcuts()
{
$ret = array();
foreach (array_keys($this->commands) as $command) {
if (isset($this->commands[$command]['shortcut'])) {
$ret[$this->commands[$command]['shortcut']] = $command;
}
}
return $ret;
}
// }}}
// {{{ getOptions()
function getOptions($command)
{
$shortcuts = $this->getShortcuts();
if (isset($shortcuts[$command])) {
$command = $shortcuts[$command];
}
if (isset($this->commands[$command]) &&
isset($this->commands[$command]['options'])) {
return $this->commands[$command]['options'];
} else {
return null;
}
}
// }}}
// {{{ getGetoptArgs()
function getGetoptArgs($command, &$short_args, &$long_args)
{
$short_args = "";
$long_args = array();
if (empty($this->commands[$command]) || empty($this->commands[$command]['options'])) {
return;
}
reset($this->commands[$command]['options']);
while (list($option, $info) = each($this->commands[$command]['options'])) {
$larg = $sarg = '';
if (isset($info['arg'])) {
if ($info['arg']{0} == '(') {
$larg = '==';
$sarg = '::';
$arg = substr($info['arg'], 1, -1);
} else {
$larg = '=';
$sarg = ':';
$arg = $info['arg'];
}
}
if (isset($info['shortopt'])) {
$short_args .= $info['shortopt'] . $sarg;
}
$long_args[] = $option . $larg;
}
}
// }}}
// {{{ getHelp()
/**
* Returns the help message for the given command
*
* @param string $command The command
* @return mixed A fail string if the command does not have help or
* a two elements array containing [0]=>help string,
* [1]=> help string for the accepted cmd args
*/
function getHelp($command)
{
$config = &PEAR_Config::singleton();
if (!isset($this->commands[$command])) {
return "No such command \"$command\"";
}
$help = null;
if (isset($this->commands[$command]['doc'])) {
$help = $this->commands[$command]['doc'];
}
if (empty($help)) {
// XXX (cox) Fallback to summary if there is no doc (show both?)
if (!isset($this->commands[$command]['summary'])) {
return "No help for command \"$command\"";
}
$help = $this->commands[$command]['summary'];
}
if (preg_match_all('/{config\s+([^\}]+)}/e', $help, $matches)) {
foreach($matches[0] as $k => $v) {
$help = preg_replace("/$v/", $config->get($matches[1][$k]), $help);
}
}
return array($help, $this->getHelpArgs($command));
}
// }}}
// {{{ getHelpArgs()
/**
* Returns the help for the accepted arguments of a command
*
* @param string $command
* @return string The help string
*/
function getHelpArgs($command)
{
if (isset($this->commands[$command]['options']) &&
count($this->commands[$command]['options']))
{
$help = "Options:\n";
foreach ($this->commands[$command]['options'] as $k => $v) {
if (isset($v['arg'])) {
if ($v['arg'][0] == '(') {
$arg = substr($v['arg'], 1, -1);
$sapp = " [$arg]";
$lapp = "[=$arg]";
} else {
$sapp = " $v[arg]";
$lapp = "=$v[arg]";
}
} else {
$sapp = $lapp = "";
}
if (isset($v['shortopt'])) {
$s = $v['shortopt'];
$help .= " -$s$sapp, --$k$lapp\n";
} else {
$help .= " --$k$lapp\n";
}
$p = " ";
$doc = rtrim(str_replace("\n", "\n$p", $v['doc']));
$help .= " $doc\n";
}
return $help;
}
return null;
}
// }}}
// {{{ run()
function run($command, $options, $params)
{
if (empty($this->commands[$command]['function'])) {
// look for shortcuts
foreach (array_keys($this->commands) as $cmd) {
if (isset($this->commands[$cmd]['shortcut']) && $this->commands[$cmd]['shortcut'] == $command) {
if (empty($this->commands[$cmd]['function'])) {
return $this->raiseError("unknown command `$command'");
} else {
$func = $this->commands[$cmd]['function'];
}
$command = $cmd;
break;
}
}
} else {
$func = $this->commands[$command]['function'];
}
return $this->$func($command, $options, $params);
}
// }}}
}
?>
| soeffing/openx_test | lib/pear/PEAR/Command/Common.php | PHP | gpl-2.0 | 8,908 |
/*
* refclock_ulink - clock driver for Ultralink WWVB receiver
*/
/***********************************************************************
* *
* Copyright (c) David L. Mills 1992-1998 *
* *
* Permission to use, copy, modify, and distribute this software and *
* its documentation for any purpose and without fee is hereby *
* granted, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission *
* notice appear in supporting documentation, and that the name *
* University of Delaware not be used in advertising or publicity *
* pertaining to distribution of the software without specific, *
* written prior permission. The University of Delaware makes no *
* representations about the suitability this software for any *
* purpose. It is provided "as is" without express or implied *
* warranty. *
**********************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#if defined(REFCLOCK) && defined(CLOCK_ULINK)
#include <stdio.h>
#include <ctype.h>
#include "ntpd.h"
#include "ntp_io.h"
#include "ntp_refclock.h"
#include "ntp_stdlib.h"
/* This driver supports ultralink Model 320,325,330,331,332 WWVB radios
*
* this driver was based on the refclock_wwvb.c driver
* in the ntp distribution.
*
* Fudge Factors
*
* fudge flag1 0 don't poll clock
* 1 send poll character
*
* revision history:
* 99/9/09 j.c.lang original edit's
* 99/9/11 j.c.lang changed timecode parse to
* match what the radio actually
* sends.
* 99/10/11 j.c.lang added support for continous
* time code mode (dipsw2)
* 99/11/26 j.c.lang added support for 320 decoder
* (taken from Dave Strout's
* Model 320 driver)
* 99/11/29 j.c.lang added fudge flag 1 to control
* clock polling
* 99/12/15 j.c.lang fixed 320 quality flag
* 01/02/21 s.l.smith fixed 33x quality flag
* added more debugging stuff
* updated 33x time code explanation
* 04/01/23 frank migge added support for 325 decoder
* (tested with ULM325.F)
*
* Questions, bugs, ideas send to:
* Joseph C. Lang
* tcnojl1@earthlink.net
*
* Dave Strout
* dstrout@linuxfoundry.com
*
* Frank Migge
* frank.migge@oracle.com
*
*
* on the Ultralink model 33X decoder Dip switch 2 controls
* polled or continous timecode
* set fudge flag1 if using polled (needed for model 320 and 325)
* dont set fudge flag1 if dip switch 2 is set on model 33x decoder
*/
/*
* Interface definitions
*/
#define DEVICE "/dev/wwvb%d" /* device name and unit */
#define SPEED232 B9600 /* uart speed (9600 baud) */
#define PRECISION (-10) /* precision assumed (about 10 ms) */
#define REFID "WWVB" /* reference ID */
#define DESCRIPTION "Ultralink WWVB Receiver" /* WRU */
#define LEN33X 32 /* timecode length Model 33X and 325 */
#define LEN320 24 /* timecode length Model 320 */
#define SIGLCHAR33x 'S' /* signal strength identifier char 325 */
#define SIGLCHAR325 'R' /* signal strength identifier char 33x */
/*
* unit control structure
*/
struct ulinkunit {
u_char tcswitch; /* timecode switch */
l_fp laststamp; /* last receive timestamp */
};
/*
* Function prototypes
*/
static int ulink_start P((int, struct peer *));
static void ulink_shutdown P((int, struct peer *));
static void ulink_receive P((struct recvbuf *));
static void ulink_poll P((int, struct peer *));
/*
* Transfer vector
*/
struct refclock refclock_ulink = {
ulink_start, /* start up driver */
ulink_shutdown, /* shut down driver */
ulink_poll, /* transmit poll message */
noentry, /* not used */
noentry, /* not used */
noentry, /* not used */
NOFLAGS
};
/*
* ulink_start - open the devices and initialize data for processing
*/
static int
ulink_start(
int unit,
struct peer *peer
)
{
register struct ulinkunit *up;
struct refclockproc *pp;
int fd;
char device[20];
/*
* Open serial port. Use CLK line discipline, if available.
*/
(void)sprintf(device, DEVICE, unit);
if (!(fd = refclock_open(device, SPEED232, LDISC_CLK)))
return (0);
/*
* Allocate and initialize unit structure
*/
if (!(up = (struct ulinkunit *)
emalloc(sizeof(struct ulinkunit)))) {
(void) close(fd);
return (0);
}
memset((char *)up, 0, sizeof(struct ulinkunit));
pp = peer->procptr;
pp->unitptr = (caddr_t)up;
pp->io.clock_recv = ulink_receive;
pp->io.srcclock = (caddr_t)peer;
pp->io.datalen = 0;
pp->io.fd = fd;
if (!io_addclock(&pp->io)) {
(void) close(fd);
free(up);
return (0);
}
/*
* Initialize miscellaneous variables
*/
peer->precision = PRECISION;
peer->burst = NSTAGE;
pp->clockdesc = DESCRIPTION;
memcpy((char *)&pp->refid, REFID, 4);
return (1);
}
/*
* ulink_shutdown - shut down the clock
*/
static void
ulink_shutdown(
int unit,
struct peer *peer
)
{
register struct ulinkunit *up;
struct refclockproc *pp;
pp = peer->procptr;
up = (struct ulinkunit *)pp->unitptr;
io_closeclock(&pp->io);
free(up);
}
/*
* ulink_receive - receive data from the serial interface
*/
static void
ulink_receive(
struct recvbuf *rbufp
)
{
struct ulinkunit *up;
struct refclockproc *pp;
struct peer *peer;
l_fp trtmp; /* arrival timestamp */
int quality; /* quality indicator */
int temp; /* int temp */
char syncchar; /* synchronization indicator */
char leapchar; /* leap indicator */
char modechar; /* model 320 mode flag */
char siglchar; /* model difference between 33x/325 */
char char_quality[2]; /* temp quality flag */
/*
* Initialize pointers and read the timecode and timestamp
*/
peer = (struct peer *)rbufp->recv_srcclock;
pp = peer->procptr;
up = (struct ulinkunit *)pp->unitptr;
temp = refclock_gtlin(rbufp, pp->a_lastcode, BMAX, &trtmp);
/*
* Note we get a buffer and timestamp for both a <cr> and <lf>,
* but only the <cr> timestamp is retained.
*/
if (temp == 0) {
if (up->tcswitch == 0) {
up->tcswitch = 1;
up->laststamp = trtmp;
} else
up->tcswitch = 0;
return;
}
pp->lencode = temp;
pp->lastrec = up->laststamp;
up->laststamp = trtmp;
up->tcswitch = 1;
#ifdef DEBUG
if (debug)
printf("ulink: timecode %d %s\n", pp->lencode,
pp->a_lastcode);
#endif
/*
* We get down to business, check the timecode format and decode
* its contents. If the timecode has invalid length or is not in
* proper format, we declare bad format and exit.
*/
syncchar = leapchar = modechar = siglchar = ' ';
switch (pp->lencode ) {
case LEN33X:
/*
* First we check if the format is 33x or 325:
* <CR><LF>S9+D 00 YYYY+DDDUTCS HH:MM:SSL+5 (33x)
* <CR><LF>R5_1C00LYYYY+DDDUTCS HH:MM:SSL+5 (325)
* simply by comparing if the signal level is 'S' or 'R'
*/
if (sscanf(pp->a_lastcode, "%c%*31c",
&siglchar) == 1) {
if(siglchar == SIGLCHAR325) {
/*
* decode for a Model 325 decoder.
* Timecode format from January 23, 2004 datasheet is:
*
* <CR><LF>R5_1C00LYYYY+DDDUTCS HH:MM:SSL+5
*
* R WWVB decodersignal readability R1 - R5
* 5 R1 is unreadable, R5 is best
* space a space (0x20)
* 1 Data bit 0, 1, M (pos mark), or ? (unknown).
* C Reception from either (C)olorado or (H)awaii
* 00 Hours since last good WWVB frame sync. Will
* be 00-99
* space Space char (0x20) or (0xa5) if locked to wwvb
* YYYY Current year, 2000-2099
* + Leap year indicator. '+' if a leap year,
* a space (0x20) if not.
* DDD Day of year, 000 - 365.
* UTC Timezone (always 'UTC').
* S Daylight savings indicator
* S - standard time (STD) in effect
* O - during STD to DST day 0000-2400
* D - daylight savings time (DST) in effect
* I - during DST to STD day 0000-2400
* space Space character (0x20)
* HH Hours 00-23
* : This is the REAL in sync indicator (: = insync)
* MM Minutes 00-59
* : : = in sync ? = NOT in sync
* SS Seconds 00-59
* L Leap second flag. Changes from space (0x20)
* to 'I' or 'D' during month preceding leap
* second adjustment. (I)nsert or (D)elete
* +5 UT1 correction (sign + digit ))
*/
if (sscanf(pp->a_lastcode,
"%*2c %*2c%2c%*c%4d%*c%3d%*4c %2d%c%2d:%2d%c%*2c",
char_quality, &pp->year, &pp->day,
&pp->hour, &syncchar, &pp->minute, &pp->second,
&leapchar) == 8) {
if (char_quality[0] == '0') {
quality = 0;
} else if (char_quality[0] == '0') {
quality = (char_quality[1] & 0x0f);
} else {
quality = 99;
}
if (leapchar == 'I' ) leapchar = '+';
if (leapchar == 'D' ) leapchar = '-';
/*
#ifdef DEBUG
if (debug) {
printf("ulink: char_quality %c %c\n",
char_quality[0], char_quality[1]);
printf("ulink: quality %d\n", quality);
printf("ulink: syncchar %x\n", syncchar);
printf("ulink: leapchar %x\n", leapchar);
}
#endif
*/
}
}
if(siglchar == SIGLCHAR33x) {
/*
* We got a Model 33X decoder.
* Timecode format from January 29, 2001 datasheet is:
* <CR><LF>S9+D 00 YYYY+DDDUTCS HH:MM:SSL+5
* S WWVB decoder sync indicator. S for in-sync(?)
* or N for noisy signal.
* 9+ RF signal level in S-units, 0-9 followed by
* a space (0x20). The space turns to '+' if the
* level is over 9.
* D Data bit 0, 1, 2 (position mark), or
* 3 (unknown).
* space Space character (0x20)
* 00 Hours since last good WWVB frame sync. Will
* be 00-23 hrs, or '1d' to '7d'. Will be 'Lk'
* if currently in sync.
* space Space character (0x20)
* YYYY Current year, 1990-2089
* + Leap year indicator. '+' if a leap year,
* a space (0x20) if not.
* DDD Day of year, 001 - 366.
* UTC Timezone (always 'UTC').
* S Daylight savings indicator
* S - standard time (STD) in effect
* O - during STD to DST day 0000-2400
* D - daylight savings time (DST) in effect
* I - during DST to STD day 0000-2400
* space Space character (0x20)
* HH Hours 00-23
* : This is the REAL in sync indicator (: = insync)
* MM Minutes 00-59
* : : = in sync ? = NOT in sync
* SS Seconds 00-59
* L Leap second flag. Changes from space (0x20)
* to '+' or '-' during month preceding leap
* second adjustment.
* +5 UT1 correction (sign + digit ))
*/
if (sscanf(pp->a_lastcode,
"%*4c %2c %4d%*c%3d%*4c %2d%c%2d:%2d%c%*2c",
char_quality, &pp->year, &pp->day,
&pp->hour, &syncchar, &pp->minute, &pp->second,
&leapchar) == 8) {
if (char_quality[0] == 'L') {
quality = 0;
} else if (char_quality[0] == '0') {
quality = (char_quality[1] & 0x0f);
} else {
quality = 99;
}
/*
#ifdef DEBUG
if (debug) {
printf("ulink: char_quality %c %c\n",
char_quality[0], char_quality[1]);
printf("ulink: quality %d\n", quality);
printf("ulink: syncchar %x\n", syncchar);
printf("ulink: leapchar %x\n", leapchar);
}
#endif
*/
}
}
break;
}
case LEN320:
/*
* Model 320 Decoder
* The timecode format is:
*
* <cr><lf>SQRYYYYDDD+HH:MM:SS.mmLT<cr>
*
* where:
*
* S = 'S' -- sync'd in last hour,
* '0'-'9' - hours x 10 since last update,
* '?' -- not in sync
* Q = Number of correlating time-frames, from 0 to 5
* R = 'R' -- reception in progress,
* 'N' -- Noisy reception,
* ' ' -- standby mode
* YYYY = year from 1990 to 2089
* DDD = current day from 1 to 366
* + = '+' if current year is a leap year, else ' '
* HH = UTC hour 0 to 23
* MM = Minutes of current hour from 0 to 59
* SS = Seconds of current minute from 0 to 59
* mm = 10's milliseconds of the current second from 00 to 99
* L = Leap second pending at end of month
* 'I' = insert, 'D'= delete
* T = DST <-> STD transition indicators
*
*/
if (sscanf(pp->a_lastcode, "%c%1d%c%4d%3d%*c%2d:%2d:%2d.%2ld%c",
&syncchar, &quality, &modechar, &pp->year, &pp->day,
&pp->hour, &pp->minute, &pp->second,
&pp->nsec, &leapchar) == 10) {
pp->nsec *= 10000000; /* M320 returns 10's of msecs */
if (leapchar == 'I' ) leapchar = '+';
if (leapchar == 'D' ) leapchar = '-';
if (syncchar != '?' ) syncchar = ':';
break;
}
default:
refclock_report(peer, CEVNT_BADREPLY);
return;
}
/*
* Decode quality indicator
* For the 325 & 33x series, the lower the number the "better"
* the time is. I used the dispersion as the measure of time
* quality. The quality indicator in the 320 is the number of
* correlating time frames (the more the better)
*/
/*
* The spec sheet for the 325 & 33x series states the clock will
* maintain +/-0.002 seconds accuracy when locked to WWVB. This
* is indicated by 'Lk' in the quality portion of the incoming
* string. When not in lock, a drift of +/-0.015 seconds should
* be allowed for.
* With the quality indicator decoding scheme above, the 'Lk'
* condition will produce a quality value of 0. If the quality
* indicator starts with '0' then the second character is the
* number of hours since we were last locked. If the first
* character is anything other than 'L' or '0' then we have been
* out of lock for more than 9 hours so we assume the worst and
* force a quality value that selects the 'default' maximum
* dispersion. The dispersion values below are what came with the
* driver. They're not unreasonable so they've not been changed.
*/
if (pp->lencode == LEN33X) {
switch (quality) {
case 0 :
pp->disp=.002;
break;
case 1 :
pp->disp=.02;
break;
case 2 :
pp->disp=.04;
break;
case 3 :
pp->disp=.08;
break;
default:
pp->disp=MAXDISPERSE;
break;
}
} else {
switch (quality) {
case 5 :
pp->disp=.002;
break;
case 4 :
pp->disp=.02;
break;
case 3 :
pp->disp=.04;
break;
case 2 :
pp->disp=.08;
break;
case 1 :
pp->disp=.16;
break;
default:
pp->disp=MAXDISPERSE;
break;
}
}
/*
* Decode synchronization, and leap characters. If
* unsynchronized, set the leap bits accordingly and exit.
* Otherwise, set the leap bits according to the leap character.
*/
if (syncchar != ':')
pp->leap = LEAP_NOTINSYNC;
else if (leapchar == '+')
pp->leap = LEAP_ADDSECOND;
else if (leapchar == '-')
pp->leap = LEAP_DELSECOND;
else
pp->leap = LEAP_NOWARNING;
/*
* Process the new sample in the median filter and determine the
* timecode timestamp.
*/
if (!refclock_process(pp)) {
refclock_report(peer, CEVNT_BADTIME);
}
}
/*
* ulink_poll - called by the transmit procedure
*/
static void
ulink_poll(
int unit,
struct peer *peer
)
{
struct refclockproc *pp;
char pollchar;
pp = peer->procptr;
pollchar = 'T';
if (pp->sloppyclockflag & CLK_FLAG1) {
if (write(pp->io.fd, &pollchar, 1) != 1)
refclock_report(peer, CEVNT_FAULT);
else
pp->polls++;
}
else
pp->polls++;
if (peer->burst > 0)
return;
if (pp->coderecv == pp->codeproc) {
refclock_report(peer, CEVNT_TIMEOUT);
return;
}
pp->lastref = pp->lastrec;
refclock_receive(peer);
record_clock_stats(&peer->srcadr, pp->a_lastcode);
peer->burst = NSTAGE;
}
#else
int refclock_ulink_bs;
#endif /* REFCLOCK */
| rhuitl/uClinux | user/ntp/ntpd/refclock_ulink.c | C | gpl-2.0 | 17,372 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_XmlConnect
* @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Xmlconnect Form field renderer interface
*
* @category Mage
* @package Mage_XmlConnect
* @author Magento Core Team <core@magentocommerce.com>
*/
interface Mage_XmlConnect_Model_Simplexml_Form_Element_Renderer_Interface
{
public function render(Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract $element);
}
| keegan2149/magento | sites/default/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Renderer/Interface.php | PHP | gpl-2.0 | 1,306 |
// SPDX-License-Identifier: GPL-2.0
#ifndef SMRTK2SSRFC_WINDOW_H
#define SMRTK2SSRFC_WINDOW_H
#include <QMainWindow>
#include <QFileDialog>
#include <QFileInfo>
extern "C" void smartrak_import(const char *file, struct dive_table *divetable);
namespace Ui {
class Smrtk2ssrfcWindow;
}
class Smrtk2ssrfcWindow : public QMainWindow
{
Q_OBJECT
public:
explicit Smrtk2ssrfcWindow(QWidget *parent = 0);
~Smrtk2ssrfcWindow();
private:
Ui::Smrtk2ssrfcWindow *ui;
QString filter();
void updateLastUsedDir(const QString &s);
void closeCurrentFile();
private
slots:
void on_inputFilesButton_clicked();
void on_outputFileButton_clicked();
void on_importButton_clicked();
void on_exitButton_clicked();
void on_outputLine_textEdited();
void on_inputLine_textEdited();
};
#endif // SMRTK2SSRFC_WINDOW_H
| mturkia/subsurface | smtk-import/smrtk2ssrfc_window.h | C | gpl-2.0 | 809 |
package org.zarroboogs.weibo.hot.bean.hotweibo;
import org.json.*;
public class TopicStruct {
private String topicTitle;
private String topicUrl;
public TopicStruct () {
}
public TopicStruct (JSONObject json) {
this.topicTitle = json.optString("topic_title");
this.topicUrl = json.optString("topic_url");
}
public String getTopicTitle() {
return this.topicTitle;
}
public void setTopicTitle(String topicTitle) {
this.topicTitle = topicTitle;
}
public String getTopicUrl() {
return this.topicUrl;
}
public void setTopicUrl(String topicUrl) {
this.topicUrl = topicUrl;
}
}
| JohnTsaiAndroid/iBeebo | app/src/main/java/org/zarroboogs/weibo/hot/bean/hotweibo/TopicStruct.java | Java | gpl-3.0 | 718 |
/*
===========================================================================
Doom 3 BFG Edition GPL Source Code
Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
Doom 3 BFG Edition Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 BFG Edition Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#ifndef __SWF_SPRITEINSTANCE_H__
#define __SWF_SPRITEINSTANCE_H__
/*
================================================
There can be multiple instances of a single sprite running
================================================
*/
class idSWFSpriteInstance
{
public:
idSWFSpriteInstance();
~idSWFSpriteInstance();
void Init( idSWFSprite* sprite, idSWFSpriteInstance* parent, int depth );
bool Run();
bool RunActions();
const char* GetName() const
{
return name.c_str();
}
idSWFScriptObject* GetScriptObject()
{
return scriptObject;
}
void SetAlignment( float x, float y )
{
xOffset = x;
yOffset = y;
}
void SetMaterial( const idMaterial* material, int width = -1, int height = -1 );
void SetVisible( bool visible );
bool IsVisible()
{
return isVisible;
}
void PlayFrame( const idSWFParmList& parms );
void PlayFrame( const char* frameName )
{
idSWFParmList parms;
parms.Append( frameName );
PlayFrame( parms );
}
void PlayFrame( const int frameNum )
{
idSWFParmList parms;
parms.Append( frameNum );
PlayFrame( parms );
}
void StopFrame( const idSWFParmList& parms );
void StopFrame( const char* frameName )
{
idSWFParmList parms;
parms.Append( frameName );
StopFrame( parms );
}
void StopFrame( const int frameNum )
{
idSWFParmList parms;
parms.Append( frameNum );
StopFrame( parms );
}
// FIXME: Why do all the Set functions have defaults of -1.0f? This seems arbitrar.
// Probably better to not have a default at all, so any non-parametized calls throw a
// compilation error.
float GetXPos() const;
float GetYPos( bool overallPos = false ) const;
void SetXPos( float xPos = -1.0f );
void SetYPos( float yPos = -1.0f );
void SetPos( float xPos = -1.0f, float yPos = -1.0f );
void SetAlpha( float val );
void SetScale( float x = -1.0f, float y = -1.0f );
void SetMoveToScale( float x = -1.0f, float y = -1.0f );
bool UpdateMoveToScale( float speed ); // returns true if the update was successful
void SetRotation( float rot );
uint16 GetCurrentFrame()
{
return currentFrame;
}
bool IsPlaying() const
{
return isPlaying;
}
int GetStereoDepth()
{
return stereoDepth;
}
// Removing the private access control statement due to cl 214702
// Apparently MS's C++ compiler supports the newer C++ standard, and GCC supports C++03
// In the new C++ standard, nested members of a friend class have access to private/protected members of the class granting friendship
// In C++03, nested members defined in a friend class do NOT have access to private/protected members of the class granting friendship friend class idSWF;
bool isPlaying;
bool isVisible;
bool childrenRunning;
bool firstRun;
// currentFrame is the frame number currently in the displayList
// we use 1 based frame numbers because currentFrame = 0 means nothing is in the display list
// it's also convenient because Flash also uses 1 based frame numbers
uint16 currentFrame;
uint16 frameCount;
// the sprite this is an instance of
idSWFSprite* sprite;
// sprite instances can be nested
idSWFSpriteInstance* parent;
// depth of this sprite instance in the parent's display list
int depth;
// if this is set, apply this material when rendering any child shapes
int itemIndex;
const idMaterial* materialOverride;
uint16 materialWidth;
uint16 materialHeight;
float xOffset;
float yOffset;
float moveToXScale;
float moveToYScale;
float moveToSpeed;
int stereoDepth;
idSWFScriptObject* scriptObject;
// children display entries
idList< swfDisplayEntry_t, TAG_SWF > displayList;
swfDisplayEntry_t* FindDisplayEntry( int depth );
// name of this sprite instance
idStr name;
struct swfAction_t
{
const byte* data;
uint32 dataLength;
};
idList< swfAction_t, TAG_SWF > actions;
idSWFScriptFunction_Script* actionScript;
idSWFScriptVar onEnterFrame;
//idSWFScriptVar onLoad;
// Removing the private access control statement due to cl 214702
// Apparently MS's C++ compiler supports the newer C++ standard, and GCC supports C++03
// In the new C++ standard, nested members of a friend class have access to private/protected members of the class granting friendship
// In C++03, nested members defined in a friend class do NOT have access to private/protected members of the class granting friendship
//----------------------------------
// SWF_PlaceObject.cpp
//----------------------------------
void PlaceObject2( idSWFBitStream& bitstream );
void PlaceObject3( idSWFBitStream& bitstream );
void RemoveObject2( idSWFBitStream& bitstream );
//----------------------------------
// SWF_Sounds.cpp
//----------------------------------
void StartSound( idSWFBitStream& bitstream );
//----------------------------------
// SWF_SpriteInstance.cpp
//----------------------------------
void NextFrame();
void PrevFrame();
void RunTo( int frameNum );
void Play();
void Stop();
void FreeDisplayList();
swfDisplayEntry_t* AddDisplayEntry( int depth, int characterID );
void RemoveDisplayEntry( int depth );
void SwapDepths( int depth1, int depth2 );
void DoAction( idSWFBitStream& bitstream );
idSWFSpriteInstance* FindChildSprite( const char* childName );
idSWFSpriteInstance* ResolveTarget( const char* targetName );
uint32 FindFrame( const char* frameLabel ) const;
bool FrameExists( const char* frameLabel ) const;
bool IsBetweenFrames( const char* frameLabel1, const char* frameLabel2 ) const;
};
/*
================================================
This is the prototype object that all the sprite instance script objects reference
================================================
*/
class idSWFScriptObject_SpriteInstancePrototype : public idSWFScriptObject
{
public:
idSWFScriptObject_SpriteInstancePrototype();
#define SWF_SPRITE_FUNCTION_DECLARE( x ) \
class idSWFScriptFunction_##x : public idSWFScriptFunction { \
public: \
void AddRef() {} \
void Release() {} \
idSWFScriptVar Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ); \
} scriptFunction_##x
SWF_SPRITE_FUNCTION_DECLARE( duplicateMovieClip );
SWF_SPRITE_FUNCTION_DECLARE( gotoAndPlay );
SWF_SPRITE_FUNCTION_DECLARE( gotoAndStop );
SWF_SPRITE_FUNCTION_DECLARE( swapDepths );
SWF_SPRITE_FUNCTION_DECLARE( nextFrame );
SWF_SPRITE_FUNCTION_DECLARE( prevFrame );
SWF_SPRITE_FUNCTION_DECLARE( play );
SWF_SPRITE_FUNCTION_DECLARE( stop );
SWF_NATIVE_VAR_DECLARE( _x );
SWF_NATIVE_VAR_DECLARE( _y );
SWF_NATIVE_VAR_DECLARE( _xscale );
SWF_NATIVE_VAR_DECLARE( _yscale );
SWF_NATIVE_VAR_DECLARE( _alpha );
SWF_NATIVE_VAR_DECLARE( _brightness );
SWF_NATIVE_VAR_DECLARE( _visible );
SWF_NATIVE_VAR_DECLARE( _width );
SWF_NATIVE_VAR_DECLARE( _height );
SWF_NATIVE_VAR_DECLARE( _rotation );
SWF_NATIVE_VAR_DECLARE_READONLY( _name );
SWF_NATIVE_VAR_DECLARE_READONLY( _currentframe );
SWF_NATIVE_VAR_DECLARE_READONLY( _totalframes );
SWF_NATIVE_VAR_DECLARE_READONLY( _target );
SWF_NATIVE_VAR_DECLARE_READONLY( _framesloaded );
SWF_NATIVE_VAR_DECLARE_READONLY( _droptarget );
SWF_NATIVE_VAR_DECLARE_READONLY( _url );
SWF_NATIVE_VAR_DECLARE_READONLY( _highquality );
SWF_NATIVE_VAR_DECLARE_READONLY( _focusrect );
SWF_NATIVE_VAR_DECLARE_READONLY( _soundbuftime );
SWF_NATIVE_VAR_DECLARE_READONLY( _quality );
SWF_NATIVE_VAR_DECLARE_READONLY( _mousex );
SWF_NATIVE_VAR_DECLARE_READONLY( _mousey );
SWF_NATIVE_VAR_DECLARE( _stereoDepth );
SWF_NATIVE_VAR_DECLARE( _itemindex );
SWF_NATIVE_VAR_DECLARE( material );
SWF_NATIVE_VAR_DECLARE( materialWidth );
SWF_NATIVE_VAR_DECLARE( materialHeight );
SWF_NATIVE_VAR_DECLARE( xOffset );
SWF_NATIVE_VAR_DECLARE( onEnterFrame );
//SWF_NATIVE_VAR_DECLARE( onLoad );
};
#endif
| rfare/Skyline | neo/swf/SWF_SpriteInstance.h | C | gpl-3.0 | 9,360 |
/*
=============================
Remote Potato - rectv.css
(C)2010 FatAttitude
These styles are used on the 'Recorded TV' page.
TIP: To make this page a different width from others, why not use this style sheet to override existing tags defined in the main styles.css file, e.g.
body{ width: 800px; }
=============================
*/
/* HOLDS A THUMBNAIL AND ITS TEXT */
div.rectvlistthumbnailcontainer
{
float: left;
margin: 0px 15px 6px 0px;
font-size: 0.6em;
width: 100px;
height: 110px;
overflow: hidden;
}
/* THE THUMBNAIL IMAGE */
img.rectvlistthumbnail
{
margin: 0px 0px 2px 0px;
width: 95px;
height: 76px;
border: solid 1px #CCCCEE;
}
/* ONE OF THESE IS PLACED BETWEEN EACH GROUP OF THUMBNAILS */
div.rectvlistthumbnailseparator
{
clear: both;
margin: 35px 0px 6px 0px;
font-size: 1.0em;
font-weight: bold;
}
/* THE LINK AT THE BOTTOM TO VIEW A DIFFERENT DATE RANGE */
#rectvdaterangeselect
{
clear: both;
font-size: 0.9em;
} | isawred2/RemotePotatoLiveTV | Server/RemotePotatoUI/bin/Release/static/skins/custom/rectv.css | CSS | gpl-3.0 | 1,003 |
/*
* Driver O/S-independent utility routines
*
* $Copyright Open Broadcom Corporation$
* $Id: bcmutils.c 496061 2014-08-11 06:14:48Z $
*/
#include <bcm_cfg.h>
#include <typedefs.h>
#include <bcmdefs.h>
#include <stdarg.h>
#ifdef BCMDRIVER
#include <osl.h>
#include <bcmutils.h>
#else /* !BCMDRIVER */
#include <stdio.h>
#include <string.h>
#include <bcmutils.h>
#if defined(BCMEXTSUP)
#include <bcm_osl.h>
#endif
#ifndef ASSERT
#define ASSERT(exp)
#endif
#endif /* !BCMDRIVER */
#include <bcmendian.h>
#include <bcmdevs.h>
#include <proto/ethernet.h>
#include <proto/vlan.h>
#include <proto/bcmip.h>
#include <proto/802.1d.h>
#include <proto/802.11.h>
void *_bcmutils_dummy_fn = NULL;
#ifdef CUSTOM_DSCP_TO_PRIO_MAPPING
#define CUST_IPV4_TOS_PREC_MASK 0x3F
#define DCSP_MAX_VALUE 64
/* 0:BE,1:BK,2:RESV(BK):,3:EE,:4:CL,5:VI,6:VO,7:NC */
int dscp2priomap[DCSP_MAX_VALUE]=
{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, /* BK->BE */
2, 0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0, 0,
4, 0, 0, 0, 0, 0, 0, 0,
5, 0, 0, 0, 0, 0, 0, 0,
6, 0, 0, 0, 0, 0, 0, 0,
7, 0, 0, 0, 0, 0, 0, 0
};
#endif /* CUSTOM_DSCP_TO_PRIO_MAPPING */
#ifdef BCMDRIVER
/* copy a pkt buffer chain into a buffer */
uint
pktcopy(osl_t *osh, void *p, uint offset, int len, uchar *buf)
{
uint n, ret = 0;
if (len < 0)
len = 4096; /* "infinite" */
/* skip 'offset' bytes */
for (; p && offset; p = PKTNEXT(osh, p)) {
if (offset < (uint)PKTLEN(osh, p))
break;
offset -= PKTLEN(osh, p);
}
if (!p)
return 0;
/* copy the data */
for (; p && len; p = PKTNEXT(osh, p)) {
n = MIN((uint)PKTLEN(osh, p) - offset, (uint)len);
bcopy(PKTDATA(osh, p) + offset, buf, n);
buf += n;
len -= n;
ret += n;
offset = 0;
}
return ret;
}
/* copy a buffer into a pkt buffer chain */
uint
pktfrombuf(osl_t *osh, void *p, uint offset, int len, uchar *buf)
{
uint n, ret = 0;
/* skip 'offset' bytes */
for (; p && offset; p = PKTNEXT(osh, p)) {
if (offset < (uint)PKTLEN(osh, p))
break;
offset -= PKTLEN(osh, p);
}
if (!p)
return 0;
/* copy the data */
for (; p && len; p = PKTNEXT(osh, p)) {
n = MIN((uint)PKTLEN(osh, p) - offset, (uint)len);
bcopy(buf, PKTDATA(osh, p) + offset, n);
buf += n;
len -= n;
ret += n;
offset = 0;
}
return ret;
}
/* return total length of buffer chain */
uint BCMFASTPATH
pkttotlen(osl_t *osh, void *p)
{
uint total;
int len;
total = 0;
for (; p; p = PKTNEXT(osh, p)) {
len = PKTLEN(osh, p);
total += len;
#ifdef BCMLFRAG
if (BCMLFRAG_ENAB()) {
if (PKTISFRAG(osh, p)) {
total += PKTFRAGTOTLEN(osh, p);
}
}
#endif
}
return (total);
}
/* return the last buffer of chained pkt */
void *
pktlast(osl_t *osh, void *p)
{
for (; PKTNEXT(osh, p); p = PKTNEXT(osh, p))
;
return (p);
}
/* count segments of a chained packet */
uint BCMFASTPATH
pktsegcnt(osl_t *osh, void *p)
{
uint cnt;
for (cnt = 0; p; p = PKTNEXT(osh, p)) {
cnt++;
#ifdef BCMLFRAG
if (BCMLFRAG_ENAB()) {
if (PKTISFRAG(osh, p)) {
cnt += PKTFRAGTOTNUM(osh, p);
}
}
#endif
}
return cnt;
}
/* count segments of a chained packet */
uint BCMFASTPATH
pktsegcnt_war(osl_t *osh, void *p)
{
uint cnt;
uint8 *pktdata;
uint len, remain, align64;
for (cnt = 0; p; p = PKTNEXT(osh, p)) {
cnt++;
len = PKTLEN(osh, p);
if (len > 128) {
pktdata = (uint8 *)PKTDATA(osh, p); /* starting address of data */
/* Check for page boundary straddle (2048B) */
if (((uintptr)pktdata & ~0x7ff) != ((uintptr)(pktdata+len) & ~0x7ff))
cnt++;
align64 = (uint)((uintptr)pktdata & 0x3f); /* aligned to 64B */
align64 = (64 - align64) & 0x3f;
len -= align64; /* bytes from aligned 64B to end */
/* if aligned to 128B, check for MOD 128 between 1 to 4B */
remain = len % 128;
if (remain > 0 && remain <= 4)
cnt++; /* add extra seg */
}
}
return cnt;
}
uint8 * BCMFASTPATH
pktdataoffset(osl_t *osh, void *p, uint offset)
{
uint total = pkttotlen(osh, p);
uint pkt_off = 0, len = 0;
uint8 *pdata = (uint8 *) PKTDATA(osh, p);
if (offset > total)
return NULL;
for (; p; p = PKTNEXT(osh, p)) {
pdata = (uint8 *) PKTDATA(osh, p);
pkt_off = offset - len;
len += PKTLEN(osh, p);
if (len > offset)
break;
}
return (uint8*) (pdata+pkt_off);
}
/* given a offset in pdata, find the pkt seg hdr */
void *
pktoffset(osl_t *osh, void *p, uint offset)
{
uint total = pkttotlen(osh, p);
uint len = 0;
if (offset > total)
return NULL;
for (; p; p = PKTNEXT(osh, p)) {
len += PKTLEN(osh, p);
if (len > offset)
break;
}
return p;
}
#endif /* BCMDRIVER */
#if !defined(BCMROMOFFLOAD_EXCLUDE_BCMUTILS_FUNCS)
const unsigned char bcm_ctype[] = {
_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C, /* 0-7 */
_BCM_C, _BCM_C|_BCM_S, _BCM_C|_BCM_S, _BCM_C|_BCM_S, _BCM_C|_BCM_S, _BCM_C|_BCM_S, _BCM_C,
_BCM_C, /* 8-15 */
_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C, /* 16-23 */
_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C, /* 24-31 */
_BCM_S|_BCM_SP,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P, /* 32-39 */
_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P, /* 40-47 */
_BCM_D,_BCM_D,_BCM_D,_BCM_D,_BCM_D,_BCM_D,_BCM_D,_BCM_D, /* 48-55 */
_BCM_D,_BCM_D,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P, /* 56-63 */
_BCM_P, _BCM_U|_BCM_X, _BCM_U|_BCM_X, _BCM_U|_BCM_X, _BCM_U|_BCM_X, _BCM_U|_BCM_X,
_BCM_U|_BCM_X, _BCM_U, /* 64-71 */
_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U, /* 72-79 */
_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U, /* 80-87 */
_BCM_U,_BCM_U,_BCM_U,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P, /* 88-95 */
_BCM_P, _BCM_L|_BCM_X, _BCM_L|_BCM_X, _BCM_L|_BCM_X, _BCM_L|_BCM_X, _BCM_L|_BCM_X,
_BCM_L|_BCM_X, _BCM_L, /* 96-103 */
_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L, /* 104-111 */
_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L, /* 112-119 */
_BCM_L,_BCM_L,_BCM_L,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_C, /* 120-127 */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 128-143 */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 144-159 */
_BCM_S|_BCM_SP, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P,
_BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, /* 160-175 */
_BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P,
_BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, /* 176-191 */
_BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U,
_BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, /* 192-207 */
_BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_P, _BCM_U, _BCM_U, _BCM_U,
_BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_L, /* 208-223 */
_BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L,
_BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, /* 224-239 */
_BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_P, _BCM_L, _BCM_L, _BCM_L,
_BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L /* 240-255 */
};
ulong
bcm_strtoul(const char *cp, char **endp, uint base)
{
ulong result, last_result = 0, value;
bool minus;
minus = FALSE;
while (bcm_isspace(*cp))
cp++;
if (cp[0] == '+')
cp++;
else if (cp[0] == '-') {
minus = TRUE;
cp++;
}
if (base == 0) {
if (cp[0] == '0') {
if ((cp[1] == 'x') || (cp[1] == 'X')) {
base = 16;
cp = &cp[2];
} else {
base = 8;
cp = &cp[1];
}
} else
base = 10;
} else if (base == 16 && (cp[0] == '0') && ((cp[1] == 'x') || (cp[1] == 'X'))) {
cp = &cp[2];
}
result = 0;
while (bcm_isxdigit(*cp) &&
(value = bcm_isdigit(*cp) ? *cp-'0' : bcm_toupper(*cp)-'A'+10) < base) {
result = result*base + value;
/* Detected overflow */
if (result < last_result && !minus)
return (ulong)-1;
last_result = result;
cp++;
}
if (minus)
result = (ulong)(-(long)result);
if (endp)
*endp = DISCARD_QUAL(cp, char);
return (result);
}
int
bcm_atoi(const char *s)
{
return (int)bcm_strtoul(s, NULL, 10);
}
/* return pointer to location of substring 'needle' in 'haystack' */
char *
bcmstrstr(const char *haystack, const char *needle)
{
int len, nlen;
int i;
if ((haystack == NULL) || (needle == NULL))
return DISCARD_QUAL(haystack, char);
nlen = (int)strlen(needle);
len = (int)strlen(haystack) - nlen + 1;
for (i = 0; i < len; i++)
if (memcmp(needle, &haystack[i], nlen) == 0)
return DISCARD_QUAL(&haystack[i], char);
return (NULL);
}
char *
bcmstrnstr(const char *s, uint s_len, const char *substr, uint substr_len)
{
for (; s_len >= substr_len; s++, s_len--)
if (strncmp(s, substr, substr_len) == 0)
return DISCARD_QUAL(s, char);
return NULL;
}
char *
bcmstrcat(char *dest, const char *src)
{
char *p;
p = dest + strlen(dest);
while ((*p++ = *src++) != '\0')
;
return (dest);
}
char *
bcmstrncat(char *dest, const char *src, uint size)
{
char *endp;
char *p;
p = dest + strlen(dest);
endp = p + size;
while (p != endp && (*p++ = *src++) != '\0')
;
return (dest);
}
/****************************************************************************
* Function: bcmstrtok
*
* Purpose:
* Tokenizes a string. This function is conceptually similiar to ANSI C strtok(),
* but allows strToken() to be used by different strings or callers at the same
* time. Each call modifies '*string' by substituting a NULL character for the
* first delimiter that is encountered, and updates 'string' to point to the char
* after the delimiter. Leading delimiters are skipped.
*
* Parameters:
* string (mod) Ptr to string ptr, updated by token.
* delimiters (in) Set of delimiter characters.
* tokdelim (out) Character that delimits the returned token. (May
* be set to NULL if token delimiter is not required).
*
* Returns: Pointer to the next token found. NULL when no more tokens are found.
*****************************************************************************
*/
char *
bcmstrtok(char **string, const char *delimiters, char *tokdelim)
{
unsigned char *str;
unsigned long map[8];
int count;
char *nextoken;
if (tokdelim != NULL) {
/* Prime the token delimiter */
*tokdelim = '\0';
}
/* Clear control map */
for (count = 0; count < 8; count++) {
map[count] = 0;
}
/* Set bits in delimiter table */
do {
map[*delimiters >> 5] |= (1 << (*delimiters & 31));
}
while (*delimiters++);
str = (unsigned char*)*string;
/* Find beginning of token (skip over leading delimiters). Note that
* there is no token iff this loop sets str to point to the terminal
* null (*str == '\0')
*/
while (((map[*str >> 5] & (1 << (*str & 31))) && *str) || (*str == ' ')) {
str++;
}
nextoken = (char*)str;
/* Find the end of the token. If it is not the end of the string,
* put a null there.
*/
for (; *str; str++) {
if (map[*str >> 5] & (1 << (*str & 31))) {
if (tokdelim != NULL) {
*tokdelim = *str;
}
*str++ = '\0';
break;
}
}
*string = (char*)str;
/* Determine if a token has been found. */
if (nextoken == (char *) str) {
return NULL;
}
else {
return nextoken;
}
}
#define xToLower(C) \
((C >= 'A' && C <= 'Z') ? (char)((int)C - (int)'A' + (int)'a') : C)
/****************************************************************************
* Function: bcmstricmp
*
* Purpose: Compare to strings case insensitively.
*
* Parameters: s1 (in) First string to compare.
* s2 (in) Second string to compare.
*
* Returns: Return 0 if the two strings are equal, -1 if t1 < t2 and 1 if
* t1 > t2, when ignoring case sensitivity.
*****************************************************************************
*/
int
bcmstricmp(const char *s1, const char *s2)
{
char dc, sc;
while (*s2 && *s1) {
dc = xToLower(*s1);
sc = xToLower(*s2);
if (dc < sc) return -1;
if (dc > sc) return 1;
s1++;
s2++;
}
if (*s1 && !*s2) return 1;
if (!*s1 && *s2) return -1;
return 0;
}
/****************************************************************************
* Function: bcmstrnicmp
*
* Purpose: Compare to strings case insensitively, upto a max of 'cnt'
* characters.
*
* Parameters: s1 (in) First string to compare.
* s2 (in) Second string to compare.
* cnt (in) Max characters to compare.
*
* Returns: Return 0 if the two strings are equal, -1 if t1 < t2 and 1 if
* t1 > t2, when ignoring case sensitivity.
*****************************************************************************
*/
int
bcmstrnicmp(const char* s1, const char* s2, int cnt)
{
char dc, sc;
while (*s2 && *s1 && cnt) {
dc = xToLower(*s1);
sc = xToLower(*s2);
if (dc < sc) return -1;
if (dc > sc) return 1;
s1++;
s2++;
cnt--;
}
if (!cnt) return 0;
if (*s1 && !*s2) return 1;
if (!*s1 && *s2) return -1;
return 0;
}
/* parse a xx:xx:xx:xx:xx:xx format ethernet address */
int
bcm_ether_atoe(const char *p, struct ether_addr *ea)
{
int i = 0;
char *ep;
for (;;) {
ea->octet[i++] = (char) bcm_strtoul(p, &ep, 16);
p = ep;
if (!*p++ || i == 6)
break;
}
return (i == 6);
}
int
bcm_atoipv4(const char *p, struct ipv4_addr *ip)
{
int i = 0;
char *c;
for (;;) {
ip->addr[i++] = (uint8)bcm_strtoul(p, &c, 0);
if (*c++ != '.' || i == IPV4_ADDR_LEN)
break;
p = c;
}
return (i == IPV4_ADDR_LEN);
}
#endif /* !BCMROMOFFLOAD_EXCLUDE_BCMUTILS_FUNCS */
#if defined(CONFIG_USBRNDIS_RETAIL) || defined(NDIS_MINIPORT_DRIVER)
/* registry routine buffer preparation utility functions:
* parameter order is like strncpy, but returns count
* of bytes copied. Minimum bytes copied is null char(1)/wchar(2)
*/
ulong
wchar2ascii(char *abuf, ushort *wbuf, ushort wbuflen, ulong abuflen)
{
ulong copyct = 1;
ushort i;
if (abuflen == 0)
return 0;
/* wbuflen is in bytes */
wbuflen /= sizeof(ushort);
for (i = 0; i < wbuflen; ++i) {
if (--abuflen == 0)
break;
*abuf++ = (char) *wbuf++;
++copyct;
}
*abuf = '\0';
return copyct;
}
#endif /* CONFIG_USBRNDIS_RETAIL || NDIS_MINIPORT_DRIVER */
char *
bcm_ether_ntoa(const struct ether_addr *ea, char *buf)
{
static const char hex[] =
{
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
const uint8 *octet = ea->octet;
char *p = buf;
int i;
for (i = 0; i < 6; i++, octet++) {
*p++ = hex[(*octet >> 4) & 0xf];
*p++ = hex[*octet & 0xf];
*p++ = ':';
}
*(p-1) = '\0';
return (buf);
}
char *
bcm_ip_ntoa(struct ipv4_addr *ia, char *buf)
{
snprintf(buf, 16, "%d.%d.%d.%d",
ia->addr[0], ia->addr[1], ia->addr[2], ia->addr[3]);
return (buf);
}
char *
bcm_ipv6_ntoa(void *ipv6, char *buf)
{
/* Implementing RFC 5952 Sections 4 + 5 */
/* Not thoroughly tested */
uint16 tmp[8];
uint16 *a = &tmp[0];
char *p = buf;
int i, i_max = -1, cnt = 0, cnt_max = 1;
uint8 *a4 = NULL;
memcpy((uint8 *)&tmp[0], (uint8 *)ipv6, IPV6_ADDR_LEN);
for (i = 0; i < IPV6_ADDR_LEN/2; i++) {
if (a[i]) {
if (cnt > cnt_max) {
cnt_max = cnt;
i_max = i - cnt;
}
cnt = 0;
} else
cnt++;
}
if (cnt > cnt_max) {
cnt_max = cnt;
i_max = i - cnt;
}
if (i_max == 0 &&
/* IPv4-translated: ::ffff:0:a.b.c.d */
((cnt_max == 4 && a[4] == 0xffff && a[5] == 0) ||
/* IPv4-mapped: ::ffff:a.b.c.d */
(cnt_max == 5 && a[5] == 0xffff)))
a4 = (uint8*) (a + 6);
for (i = 0; i < IPV6_ADDR_LEN/2; i++) {
if ((uint8*) (a + i) == a4) {
snprintf(p, 16, ":%u.%u.%u.%u", a4[0], a4[1], a4[2], a4[3]);
break;
} else if (i == i_max) {
*p++ = ':';
i += cnt_max - 1;
p[0] = ':';
p[1] = '\0';
} else {
if (i)
*p++ = ':';
p += snprintf(p, 8, "%x", ntoh16(a[i]));
}
}
return buf;
}
#ifdef BCMDRIVER
void
bcm_mdelay(uint ms)
{
uint i;
for (i = 0; i < ms; i++) {
OSL_DELAY(1000);
}
}
#if defined(DHD_DEBUG)
/* pretty hex print a pkt buffer chain */
void
prpkt(const char *msg, osl_t *osh, void *p0)
{
void *p;
if (msg && (msg[0] != '\0'))
printf("%s:\n", msg);
for (p = p0; p; p = PKTNEXT(osh, p))
prhex(NULL, PKTDATA(osh, p), PKTLEN(osh, p));
}
#endif
/* Takes an Ethernet frame and sets out-of-bound PKTPRIO.
* Also updates the inplace vlan tag if requested.
* For debugging, it returns an indication of what it did.
*/
uint BCMFASTPATH
pktsetprio(void *pkt, bool update_vtag)
{
struct ether_header *eh;
struct ethervlan_header *evh;
uint8 *pktdata;
int priority = 0;
int rc = 0;
pktdata = (uint8 *)PKTDATA(OSH_NULL, pkt);
ASSERT(ISALIGNED((uintptr)pktdata, sizeof(uint16)));
eh = (struct ether_header *) pktdata;
if (eh->ether_type == hton16(ETHER_TYPE_8021Q)) {
uint16 vlan_tag;
int vlan_prio, dscp_prio = 0;
evh = (struct ethervlan_header *)eh;
vlan_tag = ntoh16(evh->vlan_tag);
vlan_prio = (int) (vlan_tag >> VLAN_PRI_SHIFT) & VLAN_PRI_MASK;
if ((evh->ether_type == hton16(ETHER_TYPE_IP)) ||
(evh->ether_type == hton16(ETHER_TYPE_IPV6))) {
uint8 *ip_body = pktdata + sizeof(struct ethervlan_header);
uint8 tos_tc = IP_TOS46(ip_body);
dscp_prio = (int)(tos_tc >> IPV4_TOS_PREC_SHIFT);
}
/* DSCP priority gets precedence over 802.1P (vlan tag) */
if (dscp_prio != 0) {
priority = dscp_prio;
rc |= PKTPRIO_VDSCP;
} else {
priority = vlan_prio;
rc |= PKTPRIO_VLAN;
}
/*
* If the DSCP priority is not the same as the VLAN priority,
* then overwrite the priority field in the vlan tag, with the
* DSCP priority value. This is required for Linux APs because
* the VLAN driver on Linux, overwrites the skb->priority field
* with the priority value in the vlan tag
*/
if (update_vtag && (priority != vlan_prio)) {
vlan_tag &= ~(VLAN_PRI_MASK << VLAN_PRI_SHIFT);
vlan_tag |= (uint16)priority << VLAN_PRI_SHIFT;
evh->vlan_tag = hton16(vlan_tag);
rc |= PKTPRIO_UPD;
}
} else if ((eh->ether_type == hton16(ETHER_TYPE_IP)) ||
(eh->ether_type == hton16(ETHER_TYPE_IPV6))) {
uint8 *ip_body = pktdata + sizeof(struct ether_header);
uint8 tos_tc = IP_TOS46(ip_body);
uint8 dscp = tos_tc >> IPV4_TOS_DSCP_SHIFT;
switch (dscp) {
case DSCP_EF:
priority = PRIO_8021D_VO;
break;
case DSCP_AF31:
case DSCP_AF32:
case DSCP_AF33:
priority = PRIO_8021D_CL;
break;
case DSCP_AF21:
case DSCP_AF22:
case DSCP_AF23:
case DSCP_AF11:
case DSCP_AF12:
case DSCP_AF13:
priority = PRIO_8021D_EE;
break;
default:
#ifndef CUSTOM_DSCP_TO_PRIO_MAPPING
priority = (int)(tos_tc >> IPV4_TOS_PREC_SHIFT);
#else
priority = (int)dscp2priomap[((tos_tc >> IPV4_TOS_DSCP_SHIFT)
& CUST_IPV4_TOS_PREC_MASK)];
#endif
break;
}
rc |= PKTPRIO_DSCP;
}
ASSERT(priority >= 0 && priority <= MAXPRIO);
PKTSETPRIO(pkt, priority);
return (rc | priority);
}
/* Returns TRUE and DSCP if IP header found, FALSE otherwise.
*/
bool BCMFASTPATH
pktgetdscp(uint8 *pktdata, uint pktlen, uint8 *dscp)
{
struct ether_header *eh;
struct ethervlan_header *evh;
uint8 *ip_body;
bool rc = FALSE;
/* minimum length is ether header and IP header */
if (pktlen < sizeof(struct ether_header) + IPV4_MIN_HEADER_LEN)
return FALSE;
eh = (struct ether_header *) pktdata;
if (eh->ether_type == HTON16(ETHER_TYPE_IP)) {
ip_body = pktdata + sizeof(struct ether_header);
*dscp = IP_DSCP46(ip_body);
rc = TRUE;
}
else if (eh->ether_type == HTON16(ETHER_TYPE_8021Q)) {
evh = (struct ethervlan_header *)eh;
/* minimum length is ethervlan header and IP header */
if (pktlen >= sizeof(struct ethervlan_header) + IPV4_MIN_HEADER_LEN &&
evh->ether_type == HTON16(ETHER_TYPE_IP)) {
ip_body = pktdata + sizeof(struct ethervlan_header);
*dscp = IP_DSCP46(ip_body);
rc = TRUE;
}
}
return rc;
}
/* The 0.5KB string table is not removed by compiler even though it's unused */
static char bcm_undeferrstr[32];
static const char *bcmerrorstrtable[] = BCMERRSTRINGTABLE;
/* Convert the error codes into related error strings */
const char *
bcmerrorstr(int bcmerror)
{
/* check if someone added a bcmerror code but forgot to add errorstring */
ASSERT(ABS(BCME_LAST) == (ARRAYSIZE(bcmerrorstrtable) - 1));
if (bcmerror > 0 || bcmerror < BCME_LAST) {
snprintf(bcm_undeferrstr, sizeof(bcm_undeferrstr), "Undefined error %d", bcmerror);
return bcm_undeferrstr;
}
ASSERT(strlen(bcmerrorstrtable[-bcmerror]) < BCME_STRLEN);
return bcmerrorstrtable[-bcmerror];
}
/* iovar table lookup */
/* could mandate sorted tables and do a binary search */
const bcm_iovar_t*
bcm_iovar_lookup(const bcm_iovar_t *table, const char *name)
{
const bcm_iovar_t *vi;
const char *lookup_name;
/* skip any ':' delimited option prefixes */
lookup_name = strrchr(name, ':');
if (lookup_name != NULL)
lookup_name++;
else
lookup_name = name;
ASSERT(table != NULL);
for (vi = table; vi->name; vi++) {
if (!strcmp(vi->name, lookup_name))
return vi;
}
/* ran to end of table */
return NULL; /* var name not found */
}
int
bcm_iovar_lencheck(const bcm_iovar_t *vi, void *arg, int len, bool set)
{
int bcmerror = 0;
/* length check on io buf */
switch (vi->type) {
case IOVT_BOOL:
case IOVT_INT8:
case IOVT_INT16:
case IOVT_INT32:
case IOVT_UINT8:
case IOVT_UINT16:
case IOVT_UINT32:
/* all integers are int32 sized args at the ioctl interface */
if (len < (int)sizeof(int)) {
bcmerror = BCME_BUFTOOSHORT;
}
break;
case IOVT_BUFFER:
/* buffer must meet minimum length requirement */
if (len < vi->minlen) {
bcmerror = BCME_BUFTOOSHORT;
}
break;
case IOVT_VOID:
if (!set) {
/* Cannot return nil... */
bcmerror = BCME_UNSUPPORTED;
} else if (len) {
/* Set is an action w/o parameters */
bcmerror = BCME_BUFTOOLONG;
}
break;
default:
/* unknown type for length check in iovar info */
ASSERT(0);
bcmerror = BCME_UNSUPPORTED;
}
return bcmerror;
}
#endif /* BCMDRIVER */
uint8 *
bcm_write_tlv(int type, const void *data, int datalen, uint8 *dst)
{
uint8 *new_dst = dst;
bcm_tlv_t *dst_tlv = (bcm_tlv_t *)dst;
/* dst buffer should always be valid */
ASSERT(dst);
/* data len must be within valid range */
ASSERT((datalen >= 0) && (datalen <= BCM_TLV_MAX_DATA_SIZE));
/* source data buffer pointer should be valid, unless datalen is 0
* meaning no data with this TLV
*/
ASSERT((data != NULL) || (datalen == 0));
/* only do work if the inputs are valid
* - must have a dst to write to AND
* - datalen must be within range AND
* - the source data pointer must be non-NULL if datalen is non-zero
* (this last condition detects datalen > 0 with a NULL data pointer)
*/
if ((dst != NULL) &&
((datalen >= 0) && (datalen <= BCM_TLV_MAX_DATA_SIZE)) &&
((data != NULL) || (datalen == 0))) {
/* write type, len fields */
dst_tlv->id = (uint8)type;
dst_tlv->len = (uint8)datalen;
/* if data is present, copy to the output buffer and update
* pointer to output buffer
*/
if (datalen > 0) {
memcpy(dst_tlv->data, data, datalen);
}
/* update the output destination poitner to point past
* the TLV written
*/
new_dst = dst + BCM_TLV_HDR_SIZE + datalen;
}
return (new_dst);
}
uint8 *
bcm_write_tlv_safe(int type, const void *data, int datalen, uint8 *dst, int dst_maxlen)
{
uint8 *new_dst = dst;
if ((datalen >= 0) && (datalen <= BCM_TLV_MAX_DATA_SIZE)) {
/* if len + tlv hdr len is more than destlen, don't do anything
* just return the buffer untouched
*/
if ((int)(datalen + BCM_TLV_HDR_SIZE) <= dst_maxlen) {
new_dst = bcm_write_tlv(type, data, datalen, dst);
}
}
return (new_dst);
}
uint8 *
bcm_copy_tlv(const void *src, uint8 *dst)
{
uint8 *new_dst = dst;
const bcm_tlv_t *src_tlv = (const bcm_tlv_t *)src;
uint totlen;
ASSERT(dst && src);
if (dst && src) {
totlen = BCM_TLV_HDR_SIZE + src_tlv->len;
memcpy(dst, src_tlv, totlen);
new_dst = dst + totlen;
}
return (new_dst);
}
uint8 *bcm_copy_tlv_safe(const void *src, uint8 *dst, int dst_maxlen)
{
uint8 *new_dst = dst;
const bcm_tlv_t *src_tlv = (const bcm_tlv_t *)src;
ASSERT(src);
if (src) {
if (bcm_valid_tlv(src_tlv, dst_maxlen)) {
new_dst = bcm_copy_tlv(src, dst);
}
}
return (new_dst);
}
#if !defined(BCMROMOFFLOAD_EXCLUDE_BCMUTILS_FUNCS)
/*******************************************************************************
* crc8
*
* Computes a crc8 over the input data using the polynomial:
*
* x^8 + x^7 +x^6 + x^4 + x^2 + 1
*
* The caller provides the initial value (either CRC8_INIT_VALUE
* or the previous returned value) to allow for processing of
* discontiguous blocks of data. When generating the CRC the
* caller is responsible for complementing the final return value
* and inserting it into the byte stream. When checking, a final
* return value of CRC8_GOOD_VALUE indicates a valid CRC.
*
* Reference: Dallas Semiconductor Application Note 27
* Williams, Ross N., "A Painless Guide to CRC Error Detection Algorithms",
* ver 3, Aug 1993, ross@guest.adelaide.edu.au, Rocksoft Pty Ltd.,
* ftp://ftp.rocksoft.com/clients/rocksoft/papers/crc_v3.txt
*
* ****************************************************************************
*/
static const uint8 crc8_table[256] = {
0x00, 0xF7, 0xB9, 0x4E, 0x25, 0xD2, 0x9C, 0x6B,
0x4A, 0xBD, 0xF3, 0x04, 0x6F, 0x98, 0xD6, 0x21,
0x94, 0x63, 0x2D, 0xDA, 0xB1, 0x46, 0x08, 0xFF,
0xDE, 0x29, 0x67, 0x90, 0xFB, 0x0C, 0x42, 0xB5,
0x7F, 0x88, 0xC6, 0x31, 0x5A, 0xAD, 0xE3, 0x14,
0x35, 0xC2, 0x8C, 0x7B, 0x10, 0xE7, 0xA9, 0x5E,
0xEB, 0x1C, 0x52, 0xA5, 0xCE, 0x39, 0x77, 0x80,
0xA1, 0x56, 0x18, 0xEF, 0x84, 0x73, 0x3D, 0xCA,
0xFE, 0x09, 0x47, 0xB0, 0xDB, 0x2C, 0x62, 0x95,
0xB4, 0x43, 0x0D, 0xFA, 0x91, 0x66, 0x28, 0xDF,
0x6A, 0x9D, 0xD3, 0x24, 0x4F, 0xB8, 0xF6, 0x01,
0x20, 0xD7, 0x99, 0x6E, 0x05, 0xF2, 0xBC, 0x4B,
0x81, 0x76, 0x38, 0xCF, 0xA4, 0x53, 0x1D, 0xEA,
0xCB, 0x3C, 0x72, 0x85, 0xEE, 0x19, 0x57, 0xA0,
0x15, 0xE2, 0xAC, 0x5B, 0x30, 0xC7, 0x89, 0x7E,
0x5F, 0xA8, 0xE6, 0x11, 0x7A, 0x8D, 0xC3, 0x34,
0xAB, 0x5C, 0x12, 0xE5, 0x8E, 0x79, 0x37, 0xC0,
0xE1, 0x16, 0x58, 0xAF, 0xC4, 0x33, 0x7D, 0x8A,
0x3F, 0xC8, 0x86, 0x71, 0x1A, 0xED, 0xA3, 0x54,
0x75, 0x82, 0xCC, 0x3B, 0x50, 0xA7, 0xE9, 0x1E,
0xD4, 0x23, 0x6D, 0x9A, 0xF1, 0x06, 0x48, 0xBF,
0x9E, 0x69, 0x27, 0xD0, 0xBB, 0x4C, 0x02, 0xF5,
0x40, 0xB7, 0xF9, 0x0E, 0x65, 0x92, 0xDC, 0x2B,
0x0A, 0xFD, 0xB3, 0x44, 0x2F, 0xD8, 0x96, 0x61,
0x55, 0xA2, 0xEC, 0x1B, 0x70, 0x87, 0xC9, 0x3E,
0x1F, 0xE8, 0xA6, 0x51, 0x3A, 0xCD, 0x83, 0x74,
0xC1, 0x36, 0x78, 0x8F, 0xE4, 0x13, 0x5D, 0xAA,
0x8B, 0x7C, 0x32, 0xC5, 0xAE, 0x59, 0x17, 0xE0,
0x2A, 0xDD, 0x93, 0x64, 0x0F, 0xF8, 0xB6, 0x41,
0x60, 0x97, 0xD9, 0x2E, 0x45, 0xB2, 0xFC, 0x0B,
0xBE, 0x49, 0x07, 0xF0, 0x9B, 0x6C, 0x22, 0xD5,
0xF4, 0x03, 0x4D, 0xBA, 0xD1, 0x26, 0x68, 0x9F
};
#define CRC_INNER_LOOP(n, c, x) \
(c) = ((c) >> 8) ^ crc##n##_table[((c) ^ (x)) & 0xff]
uint8
hndcrc8(
uint8 *pdata, /* pointer to array of data to process */
uint nbytes, /* number of input data bytes to process */
uint8 crc /* either CRC8_INIT_VALUE or previous return value */
)
{
/* hard code the crc loop instead of using CRC_INNER_LOOP macro
* to avoid the undefined and unnecessary (uint8 >> 8) operation.
*/
while (nbytes-- > 0)
crc = crc8_table[(crc ^ *pdata++) & 0xff];
return crc;
}
/*******************************************************************************
* crc16
*
* Computes a crc16 over the input data using the polynomial:
*
* x^16 + x^12 +x^5 + 1
*
* The caller provides the initial value (either CRC16_INIT_VALUE
* or the previous returned value) to allow for processing of
* discontiguous blocks of data. When generating the CRC the
* caller is responsible for complementing the final return value
* and inserting it into the byte stream. When checking, a final
* return value of CRC16_GOOD_VALUE indicates a valid CRC.
*
* Reference: Dallas Semiconductor Application Note 27
* Williams, Ross N., "A Painless Guide to CRC Error Detection Algorithms",
* ver 3, Aug 1993, ross@guest.adelaide.edu.au, Rocksoft Pty Ltd.,
* ftp://ftp.rocksoft.com/clients/rocksoft/papers/crc_v3.txt
*
* ****************************************************************************
*/
static const uint16 crc16_table[256] = {
0x0000, 0x1189, 0x2312, 0x329B, 0x4624, 0x57AD, 0x6536, 0x74BF,
0x8C48, 0x9DC1, 0xAF5A, 0xBED3, 0xCA6C, 0xDBE5, 0xE97E, 0xF8F7,
0x1081, 0x0108, 0x3393, 0x221A, 0x56A5, 0x472C, 0x75B7, 0x643E,
0x9CC9, 0x8D40, 0xBFDB, 0xAE52, 0xDAED, 0xCB64, 0xF9FF, 0xE876,
0x2102, 0x308B, 0x0210, 0x1399, 0x6726, 0x76AF, 0x4434, 0x55BD,
0xAD4A, 0xBCC3, 0x8E58, 0x9FD1, 0xEB6E, 0xFAE7, 0xC87C, 0xD9F5,
0x3183, 0x200A, 0x1291, 0x0318, 0x77A7, 0x662E, 0x54B5, 0x453C,
0xBDCB, 0xAC42, 0x9ED9, 0x8F50, 0xFBEF, 0xEA66, 0xD8FD, 0xC974,
0x4204, 0x538D, 0x6116, 0x709F, 0x0420, 0x15A9, 0x2732, 0x36BB,
0xCE4C, 0xDFC5, 0xED5E, 0xFCD7, 0x8868, 0x99E1, 0xAB7A, 0xBAF3,
0x5285, 0x430C, 0x7197, 0x601E, 0x14A1, 0x0528, 0x37B3, 0x263A,
0xDECD, 0xCF44, 0xFDDF, 0xEC56, 0x98E9, 0x8960, 0xBBFB, 0xAA72,
0x6306, 0x728F, 0x4014, 0x519D, 0x2522, 0x34AB, 0x0630, 0x17B9,
0xEF4E, 0xFEC7, 0xCC5C, 0xDDD5, 0xA96A, 0xB8E3, 0x8A78, 0x9BF1,
0x7387, 0x620E, 0x5095, 0x411C, 0x35A3, 0x242A, 0x16B1, 0x0738,
0xFFCF, 0xEE46, 0xDCDD, 0xCD54, 0xB9EB, 0xA862, 0x9AF9, 0x8B70,
0x8408, 0x9581, 0xA71A, 0xB693, 0xC22C, 0xD3A5, 0xE13E, 0xF0B7,
0x0840, 0x19C9, 0x2B52, 0x3ADB, 0x4E64, 0x5FED, 0x6D76, 0x7CFF,
0x9489, 0x8500, 0xB79B, 0xA612, 0xD2AD, 0xC324, 0xF1BF, 0xE036,
0x18C1, 0x0948, 0x3BD3, 0x2A5A, 0x5EE5, 0x4F6C, 0x7DF7, 0x6C7E,
0xA50A, 0xB483, 0x8618, 0x9791, 0xE32E, 0xF2A7, 0xC03C, 0xD1B5,
0x2942, 0x38CB, 0x0A50, 0x1BD9, 0x6F66, 0x7EEF, 0x4C74, 0x5DFD,
0xB58B, 0xA402, 0x9699, 0x8710, 0xF3AF, 0xE226, 0xD0BD, 0xC134,
0x39C3, 0x284A, 0x1AD1, 0x0B58, 0x7FE7, 0x6E6E, 0x5CF5, 0x4D7C,
0xC60C, 0xD785, 0xE51E, 0xF497, 0x8028, 0x91A1, 0xA33A, 0xB2B3,
0x4A44, 0x5BCD, 0x6956, 0x78DF, 0x0C60, 0x1DE9, 0x2F72, 0x3EFB,
0xD68D, 0xC704, 0xF59F, 0xE416, 0x90A9, 0x8120, 0xB3BB, 0xA232,
0x5AC5, 0x4B4C, 0x79D7, 0x685E, 0x1CE1, 0x0D68, 0x3FF3, 0x2E7A,
0xE70E, 0xF687, 0xC41C, 0xD595, 0xA12A, 0xB0A3, 0x8238, 0x93B1,
0x6B46, 0x7ACF, 0x4854, 0x59DD, 0x2D62, 0x3CEB, 0x0E70, 0x1FF9,
0xF78F, 0xE606, 0xD49D, 0xC514, 0xB1AB, 0xA022, 0x92B9, 0x8330,
0x7BC7, 0x6A4E, 0x58D5, 0x495C, 0x3DE3, 0x2C6A, 0x1EF1, 0x0F78
};
uint16
hndcrc16(
uint8 *pdata, /* pointer to array of data to process */
uint nbytes, /* number of input data bytes to process */
uint16 crc /* either CRC16_INIT_VALUE or previous return value */
)
{
while (nbytes-- > 0)
CRC_INNER_LOOP(16, crc, *pdata++);
return crc;
}
static const uint32 crc32_table[256] = {
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
};
/*
* crc input is CRC32_INIT_VALUE for a fresh start, or previous return value if
* accumulating over multiple pieces.
*/
uint32
hndcrc32(uint8 *pdata, uint nbytes, uint32 crc)
{
uint8 *pend;
pend = pdata + nbytes;
while (pdata < pend)
CRC_INNER_LOOP(32, crc, *pdata++);
return crc;
}
#ifdef notdef
#define CLEN 1499 /* CRC Length */
#define CBUFSIZ (CLEN+4)
#define CNBUFS 5 /* # of bufs */
void
testcrc32(void)
{
uint j, k, l;
uint8 *buf;
uint len[CNBUFS];
uint32 crcr;
uint32 crc32tv[CNBUFS] =
{0xd2cb1faa, 0xd385c8fa, 0xf5b4f3f3, 0x55789e20, 0x00343110};
ASSERT((buf = MALLOC(CBUFSIZ*CNBUFS)) != NULL);
/* step through all possible alignments */
for (l = 0; l <= 4; l++) {
for (j = 0; j < CNBUFS; j++) {
len[j] = CLEN;
for (k = 0; k < len[j]; k++)
*(buf + j*CBUFSIZ + (k+l)) = (j+k) & 0xff;
}
for (j = 0; j < CNBUFS; j++) {
crcr = crc32(buf + j*CBUFSIZ + l, len[j], CRC32_INIT_VALUE);
ASSERT(crcr == crc32tv[j]);
}
}
MFREE(buf, CBUFSIZ*CNBUFS);
return;
}
#endif /* notdef */
/*
* Advance from the current 1-byte tag/1-byte length/variable-length value
* triple, to the next, returning a pointer to the next.
* If the current or next TLV is invalid (does not fit in given buffer length),
* NULL is returned.
* *buflen is not modified if the TLV elt parameter is invalid, or is decremented
* by the TLV parameter's length if it is valid.
*/
bcm_tlv_t *
bcm_next_tlv(bcm_tlv_t *elt, int *buflen)
{
int len;
/* validate current elt */
if (!bcm_valid_tlv(elt, *buflen)) {
return NULL;
}
/* advance to next elt */
len = elt->len;
elt = (bcm_tlv_t*)(elt->data + len);
*buflen -= (TLV_HDR_LEN + len);
/* validate next elt */
if (!bcm_valid_tlv(elt, *buflen)) {
return NULL;
}
return elt;
}
/*
* Traverse a string of 1-byte tag/1-byte length/variable-length value
* triples, returning a pointer to the substring whose first element
* matches tag
*/
bcm_tlv_t *
bcm_parse_tlvs(void *buf, int buflen, uint key)
{
bcm_tlv_t *elt;
int totlen;
elt = (bcm_tlv_t*)buf;
totlen = buflen;
/* find tagged parameter */
while (totlen >= TLV_HDR_LEN) {
int len = elt->len;
/* validate remaining totlen */
if ((elt->id == key) && (totlen >= (int)(len + TLV_HDR_LEN))) {
return (elt);
}
elt = (bcm_tlv_t*)((uint8*)elt + (len + TLV_HDR_LEN));
totlen -= (len + TLV_HDR_LEN);
}
return NULL;
}
/*
* Traverse a string of 1-byte tag/1-byte length/variable-length value
* triples, returning a pointer to the substring whose first element
* matches tag
* return NULL if not found or length field < min_varlen
*/
bcm_tlv_t *
bcm_parse_tlvs_min_bodylen(void *buf, int buflen, uint key, int min_bodylen)
{
bcm_tlv_t * ret = bcm_parse_tlvs(buf, buflen, key);
if (ret == NULL || ret->len < min_bodylen) {
return NULL;
}
return ret;
}
/*
* Traverse a string of 1-byte tag/1-byte length/variable-length value
* triples, returning a pointer to the substring whose first element
* matches tag. Stop parsing when we see an element whose ID is greater
* than the target key.
*/
bcm_tlv_t *
bcm_parse_ordered_tlvs(void *buf, int buflen, uint key)
{
bcm_tlv_t *elt;
int totlen;
elt = (bcm_tlv_t*)buf;
totlen = buflen;
/* find tagged parameter */
while (totlen >= TLV_HDR_LEN) {
uint id = elt->id;
int len = elt->len;
/* Punt if we start seeing IDs > than target key */
if (id > key) {
return (NULL);
}
/* validate remaining totlen */
if ((id == key) && (totlen >= (int)(len + TLV_HDR_LEN))) {
return (elt);
}
elt = (bcm_tlv_t*)((uint8*)elt + (len + TLV_HDR_LEN));
totlen -= (len + TLV_HDR_LEN);
}
return NULL;
}
#endif /* !BCMROMOFFLOAD_EXCLUDE_BCMUTILS_FUNCS */
#if defined(WLMSG_PRHDRS) || defined(WLMSG_PRPKT) || defined(WLMSG_ASSOC) || \
defined(DHD_DEBUG)
int
bcm_format_field(const bcm_bit_desc_ex_t *bd, uint32 flags, char* buf, int len)
{
int i, slen = 0;
uint32 bit, mask;
const char *name;
mask = bd->mask;
if (len < 2 || !buf)
return 0;
buf[0] = '\0';
for (i = 0; (name = bd->bitfield[i].name) != NULL; i++) {
bit = bd->bitfield[i].bit;
if ((flags & mask) == bit) {
if (len > (int)strlen(name)) {
slen = strlen(name);
strncpy(buf, name, slen+1);
}
break;
}
}
return slen;
}
int
bcm_format_flags(const bcm_bit_desc_t *bd, uint32 flags, char* buf, int len)
{
int i;
char* p = buf;
char hexstr[16];
int slen = 0, nlen = 0;
uint32 bit;
const char* name;
if (len < 2 || !buf)
return 0;
buf[0] = '\0';
for (i = 0; flags != 0; i++) {
bit = bd[i].bit;
name = bd[i].name;
if (bit == 0 && flags != 0) {
/* print any unnamed bits */
snprintf(hexstr, 16, "0x%X", flags);
name = hexstr;
flags = 0; /* exit loop */
} else if ((flags & bit) == 0)
continue;
flags &= ~bit;
nlen = strlen(name);
slen += nlen;
/* count btwn flag space */
if (flags != 0)
slen += 1;
/* need NULL char as well */
if (len <= slen)
break;
/* copy NULL char but don't count it */
strncpy(p, name, nlen + 1);
p += nlen;
/* copy btwn flag space and NULL char */
if (flags != 0)
p += snprintf(p, 2, " ");
}
/* indicate the str was too short */
if (flags != 0) {
if (len < 2)
p -= 2 - len; /* overwrite last char */
p += snprintf(p, 2, ">");
}
return (int)(p - buf);
}
#endif
/* print bytes formatted as hex to a string. return the resulting string length */
int
bcm_format_hex(char *str, const void *bytes, int len)
{
int i;
char *p = str;
const uint8 *src = (const uint8*)bytes;
for (i = 0; i < len; i++) {
p += snprintf(p, 3, "%02X", *src);
src++;
}
return (int)(p - str);
}
/* pretty hex print a contiguous buffer */
void
prhex(const char *msg, uchar *buf, uint nbytes)
{
char line[128], *p;
int len = sizeof(line);
int nchar;
uint i;
if (msg && (msg[0] != '\0'))
printf("%s:\n", msg);
p = line;
for (i = 0; i < nbytes; i++) {
if (i % 16 == 0) {
nchar = snprintf(p, len, " %04d: ", i); /* line prefix */
p += nchar;
len -= nchar;
}
if (len > 0) {
nchar = snprintf(p, len, "%02x ", buf[i]);
p += nchar;
len -= nchar;
}
if (i % 16 == 15) {
printf("%s\n", line); /* flush line */
p = line;
len = sizeof(line);
}
}
/* flush last partial line */
if (p != line)
printf("%s\n", line);
}
static const char *crypto_algo_names[] = {
"NONE",
"WEP1",
"TKIP",
"WEP128",
"AES_CCM",
"AES_OCB_MSDU",
"AES_OCB_MPDU",
#ifdef BCMCCX
"CKIP",
"CKIP_MMH",
"WEP_MMH",
"NALG",
#else
"NALG",
"UNDEF",
"UNDEF",
"UNDEF",
#endif /* BCMCCX */
"WAPI",
"PMK",
"BIP",
"AES_GCM",
"AES_CCM256",
"AES_GCM256",
"BIP_CMAC256",
"BIP_GMAC",
"BIP_GMAC256",
"UNDEF"
};
const char *
bcm_crypto_algo_name(uint algo)
{
return (algo < ARRAYSIZE(crypto_algo_names)) ? crypto_algo_names[algo] : "ERR";
}
char *
bcm_chipname(uint chipid, char *buf, uint len)
{
const char *fmt;
fmt = ((chipid > 0xa000) || (chipid < 0x4000)) ? "%d" : "%x";
snprintf(buf, len, fmt, chipid);
return buf;
}
/* Produce a human-readable string for boardrev */
char *
bcm_brev_str(uint32 brev, char *buf)
{
if (brev < 0x100)
snprintf(buf, 8, "%d.%d", (brev & 0xf0) >> 4, brev & 0xf);
else
snprintf(buf, 8, "%c%03x", ((brev & 0xf000) == 0x1000) ? 'P' : 'A', brev & 0xfff);
return (buf);
}
#define BUFSIZE_TODUMP_ATONCE 512 /* Buffer size */
/* dump large strings to console */
void
printbig(char *buf)
{
uint len, max_len;
char c;
len = (uint)strlen(buf);
max_len = BUFSIZE_TODUMP_ATONCE;
while (len > max_len) {
c = buf[max_len];
buf[max_len] = '\0';
printf("%s", buf);
buf[max_len] = c;
buf += max_len;
len -= max_len;
}
/* print the remaining string */
printf("%s\n", buf);
return;
}
/* routine to dump fields in a fileddesc structure */
uint
bcmdumpfields(bcmutl_rdreg_rtn read_rtn, void *arg0, uint arg1, struct fielddesc *fielddesc_array,
char *buf, uint32 bufsize)
{
uint filled_len;
int len;
struct fielddesc *cur_ptr;
filled_len = 0;
cur_ptr = fielddesc_array;
while (bufsize > 1) {
if (cur_ptr->nameandfmt == NULL)
break;
len = snprintf(buf, bufsize, cur_ptr->nameandfmt,
read_rtn(arg0, arg1, cur_ptr->offset));
/* check for snprintf overflow or error */
if (len < 0 || (uint32)len >= bufsize)
len = bufsize - 1;
buf += len;
bufsize -= len;
filled_len += len;
cur_ptr++;
}
return filled_len;
}
uint
bcm_mkiovar(char *name, char *data, uint datalen, char *buf, uint buflen)
{
uint len;
len = (uint)strlen(name) + 1;
if ((len + datalen) > buflen)
return 0;
strncpy(buf, name, buflen);
/* append data onto the end of the name string */
memcpy(&buf[len], data, datalen);
len += datalen;
return len;
}
/* Quarter dBm units to mW
* Table starts at QDBM_OFFSET, so the first entry is mW for qdBm=153
* Table is offset so the last entry is largest mW value that fits in
* a uint16.
*/
#define QDBM_OFFSET 153 /* Offset for first entry */
#define QDBM_TABLE_LEN 40 /* Table size */
/* Smallest mW value that will round up to the first table entry, QDBM_OFFSET.
* Value is ( mW(QDBM_OFFSET - 1) + mW(QDBM_OFFSET) ) / 2
*/
#define QDBM_TABLE_LOW_BOUND 6493 /* Low bound */
/* Largest mW value that will round down to the last table entry,
* QDBM_OFFSET + QDBM_TABLE_LEN-1.
* Value is ( mW(QDBM_OFFSET + QDBM_TABLE_LEN - 1) + mW(QDBM_OFFSET + QDBM_TABLE_LEN) ) / 2.
*/
#define QDBM_TABLE_HIGH_BOUND 64938 /* High bound */
static const uint16 nqdBm_to_mW_map[QDBM_TABLE_LEN] = {
/* qdBm: +0 +1 +2 +3 +4 +5 +6 +7 */
/* 153: */ 6683, 7079, 7499, 7943, 8414, 8913, 9441, 10000,
/* 161: */ 10593, 11220, 11885, 12589, 13335, 14125, 14962, 15849,
/* 169: */ 16788, 17783, 18836, 19953, 21135, 22387, 23714, 25119,
/* 177: */ 26607, 28184, 29854, 31623, 33497, 35481, 37584, 39811,
/* 185: */ 42170, 44668, 47315, 50119, 53088, 56234, 59566, 63096
};
uint16
bcm_qdbm_to_mw(uint8 qdbm)
{
uint factor = 1;
int idx = qdbm - QDBM_OFFSET;
if (idx >= QDBM_TABLE_LEN) {
/* clamp to max uint16 mW value */
return 0xFFFF;
}
/* scale the qdBm index up to the range of the table 0-40
* where an offset of 40 qdBm equals a factor of 10 mW.
*/
while (idx < 0) {
idx += 40;
factor *= 10;
}
/* return the mW value scaled down to the correct factor of 10,
* adding in factor/2 to get proper rounding.
*/
return ((nqdBm_to_mW_map[idx] + factor/2) / factor);
}
uint8
bcm_mw_to_qdbm(uint16 mw)
{
uint8 qdbm;
int offset;
uint mw_uint = mw;
uint boundary;
/* handle boundary case */
if (mw_uint <= 1)
return 0;
offset = QDBM_OFFSET;
/* move mw into the range of the table */
while (mw_uint < QDBM_TABLE_LOW_BOUND) {
mw_uint *= 10;
offset -= 40;
}
for (qdbm = 0; qdbm < QDBM_TABLE_LEN-1; qdbm++) {
boundary = nqdBm_to_mW_map[qdbm] + (nqdBm_to_mW_map[qdbm+1] -
nqdBm_to_mW_map[qdbm])/2;
if (mw_uint < boundary) break;
}
qdbm += (uint8)offset;
return (qdbm);
}
uint
bcm_bitcount(uint8 *bitmap, uint length)
{
uint bitcount = 0, i;
uint8 tmp;
for (i = 0; i < length; i++) {
tmp = bitmap[i];
while (tmp) {
bitcount++;
tmp &= (tmp - 1);
}
}
return bitcount;
}
#ifdef BCMDRIVER
/* Initialization of bcmstrbuf structure */
void
bcm_binit(struct bcmstrbuf *b, char *buf, uint size)
{
b->origsize = b->size = size;
b->origbuf = b->buf = buf;
}
/* Buffer sprintf wrapper to guard against buffer overflow */
int
bcm_bprintf(struct bcmstrbuf *b, const char *fmt, ...)
{
va_list ap;
int r;
va_start(ap, fmt);
r = vsnprintf(b->buf, b->size, fmt, ap);
/* Non Ansi C99 compliant returns -1,
* Ansi compliant return r >= b->size,
* bcmstdlib returns 0, handle all
*/
/* r == 0 is also the case when strlen(fmt) is zero.
* typically the case when "" is passed as argument.
*/
if ((r == -1) || (r >= (int)b->size)) {
b->size = 0;
} else {
b->size -= r;
b->buf += r;
}
va_end(ap);
return r;
}
void
bcm_bprhex(struct bcmstrbuf *b, const char *msg, bool newline, uint8 *buf, int len)
{
int i;
if (msg != NULL && msg[0] != '\0')
bcm_bprintf(b, "%s", msg);
for (i = 0; i < len; i ++)
bcm_bprintf(b, "%02X", buf[i]);
if (newline)
bcm_bprintf(b, "\n");
}
void
bcm_inc_bytes(uchar *num, int num_bytes, uint8 amount)
{
int i;
for (i = 0; i < num_bytes; i++) {
num[i] += amount;
if (num[i] >= amount)
break;
amount = 1;
}
}
int
bcm_cmp_bytes(const uchar *arg1, const uchar *arg2, uint8 nbytes)
{
int i;
for (i = nbytes - 1; i >= 0; i--) {
if (arg1[i] != arg2[i])
return (arg1[i] - arg2[i]);
}
return 0;
}
void
bcm_print_bytes(const char *name, const uchar *data, int len)
{
int i;
int per_line = 0;
printf("%s: %d \n", name ? name : "", len);
for (i = 0; i < len; i++) {
printf("%02x ", *data++);
per_line++;
if (per_line == 16) {
per_line = 0;
printf("\n");
}
}
printf("\n");
}
/* Look for vendor-specific IE with specified OUI and optional type */
bcm_tlv_t *
bcm_find_vendor_ie(void *tlvs, int tlvs_len, const char *voui, uint8 *type, int type_len)
{
bcm_tlv_t *ie;
uint8 ie_len;
ie = (bcm_tlv_t*)tlvs;
/* make sure we are looking at a valid IE */
if (ie == NULL || !bcm_valid_tlv(ie, tlvs_len)) {
return NULL;
}
/* Walk through the IEs looking for an OUI match */
do {
ie_len = ie->len;
if ((ie->id == DOT11_MNG_PROPR_ID) &&
(ie_len >= (DOT11_OUI_LEN + type_len)) &&
!bcmp(ie->data, voui, DOT11_OUI_LEN))
{
/* compare optional type */
if (type_len == 0 ||
!bcmp(&ie->data[DOT11_OUI_LEN], type, type_len)) {
return (ie); /* a match */
}
}
} while ((ie = bcm_next_tlv(ie, &tlvs_len)) != NULL);
return NULL;
}
#if defined(WLTINYDUMP) || defined(WLMSG_INFORM) || defined(WLMSG_ASSOC) || \
defined(WLMSG_PRPKT) || defined(WLMSG_WSEC)
#define SSID_FMT_BUF_LEN ((4 * DOT11_MAX_SSID_LEN) + 1)
int
bcm_format_ssid(char* buf, const uchar ssid[], uint ssid_len)
{
uint i, c;
char *p = buf;
char *endp = buf + SSID_FMT_BUF_LEN;
if (ssid_len > DOT11_MAX_SSID_LEN) ssid_len = DOT11_MAX_SSID_LEN;
for (i = 0; i < ssid_len; i++) {
c = (uint)ssid[i];
if (c == '\\') {
*p++ = '\\';
*p++ = '\\';
} else if (bcm_isprint((uchar)c)) {
*p++ = (char)c;
} else {
p += snprintf(p, (endp - p), "\\x%02X", c);
}
}
*p = '\0';
ASSERT(p < endp);
return (int)(p - buf);
}
#endif
#endif /* BCMDRIVER */
/*
* ProcessVars:Takes a buffer of "<var>=<value>\n" lines read from a file and ending in a NUL.
* also accepts nvram files which are already in the format of <var1>=<value>\0\<var2>=<value2>\0
* Removes carriage returns, empty lines, comment lines, and converts newlines to NULs.
* Shortens buffer as needed and pads with NULs. End of buffer is marked by two NULs.
*/
unsigned int
process_nvram_vars(char *varbuf, unsigned int len)
{
char *dp;
bool findNewline;
int column;
unsigned int buf_len, n;
unsigned int pad = 0;
dp = varbuf;
findNewline = FALSE;
column = 0;
// terence 20130914: print out NVRAM version
if (varbuf[0] == '#') {
printf("NVRAM version: ");
for (n=1; n<len; n++) {
if (varbuf[n] == '\n')
break;
printf("%c", varbuf[n]);
}
printf("\n");
}
for (n = 0; n < len; n++) {
if (varbuf[n] == '\r')
continue;
if (findNewline && varbuf[n] != '\n')
continue;
findNewline = FALSE;
if (varbuf[n] == '#') {
findNewline = TRUE;
continue;
}
if (varbuf[n] == '\n') {
if (column == 0)
continue;
*dp++ = 0;
column = 0;
continue;
}
*dp++ = varbuf[n];
column++;
}
buf_len = (unsigned int)(dp - varbuf);
if (buf_len % 4) {
pad = 4 - buf_len % 4;
if (pad && (buf_len + pad <= len)) {
buf_len += pad;
}
}
while (dp < varbuf + n)
*dp++ = 0;
return buf_len;
}
/* calculate a * b + c */
void
bcm_uint64_multiple_add(uint32* r_high, uint32* r_low, uint32 a, uint32 b, uint32 c)
{
#define FORMALIZE(var) {cc += (var & 0x80000000) ? 1 : 0; var &= 0x7fffffff;}
uint32 r1, r0;
uint32 a1, a0, b1, b0, t, cc = 0;
a1 = a >> 16;
a0 = a & 0xffff;
b1 = b >> 16;
b0 = b & 0xffff;
r0 = a0 * b0;
FORMALIZE(r0);
t = (a1 * b0) << 16;
FORMALIZE(t);
r0 += t;
FORMALIZE(r0);
t = (a0 * b1) << 16;
FORMALIZE(t);
r0 += t;
FORMALIZE(r0);
FORMALIZE(c);
r0 += c;
FORMALIZE(r0);
r0 |= (cc % 2) ? 0x80000000 : 0;
r1 = a1 * b1 + ((a1 * b0) >> 16) + ((b1 * a0) >> 16) + (cc / 2);
*r_high = r1;
*r_low = r0;
}
/* calculate a / b */
void
bcm_uint64_divide(uint32* r, uint32 a_high, uint32 a_low, uint32 b)
{
uint32 a1 = a_high, a0 = a_low, r0 = 0;
if (b < 2)
return;
while (a1 != 0) {
r0 += (0xffffffff / b) * a1;
bcm_uint64_multiple_add(&a1, &a0, ((0xffffffff % b) + 1) % b, a1, a0);
}
r0 += a0 / b;
*r = r0;
}
#ifndef setbit /* As in the header file */
#ifdef BCMUTILS_BIT_MACROS_USE_FUNCS
/* Set bit in byte array. */
void
setbit(void *array, uint bit)
{
((uint8 *)array)[bit / NBBY] |= 1 << (bit % NBBY);
}
/* Clear bit in byte array. */
void
clrbit(void *array, uint bit)
{
((uint8 *)array)[bit / NBBY] &= ~(1 << (bit % NBBY));
}
/* Test if bit is set in byte array. */
bool
isset(const void *array, uint bit)
{
return (((const uint8 *)array)[bit / NBBY] & (1 << (bit % NBBY)));
}
/* Test if bit is clear in byte array. */
bool
isclr(const void *array, uint bit)
{
return ((((const uint8 *)array)[bit / NBBY] & (1 << (bit % NBBY))) == 0);
}
#endif /* BCMUTILS_BIT_MACROS_USE_FUNCS */
#endif /* setbit */
void
set_bitrange(void *array, uint start, uint end, uint maxbit)
{
uint startbyte = start/NBBY;
uint endbyte = end/NBBY;
uint i, startbytelastbit, endbytestartbit;
if (end >= start) {
if (endbyte - startbyte > 1)
{
startbytelastbit = (startbyte+1)*NBBY - 1;
endbytestartbit = endbyte*NBBY;
for (i = startbyte+1; i < endbyte; i++)
((uint8 *)array)[i] = 0xFF;
for (i = start; i <= startbytelastbit; i++)
setbit(array, i);
for (i = endbytestartbit; i <= end; i++)
setbit(array, i);
} else {
for (i = start; i <= end; i++)
setbit(array, i);
}
}
else {
set_bitrange(array, start, maxbit, maxbit);
set_bitrange(array, 0, end, maxbit);
}
}
void
bcm_bitprint32(const uint32 u32)
{
int i;
for (i = NBITS(uint32) - 1; i >= 0; i--) {
isbitset(u32, i) ? printf("1") : printf("0");
if ((i % NBBY) == 0) printf(" ");
}
printf("\n");
}
/* calculate checksum for ip header, tcp / udp header / data */
uint16
bcm_ip_cksum(uint8 *buf, uint32 len, uint32 sum)
{
while (len > 1) {
sum += (buf[0] << 8) | buf[1];
buf += 2;
len -= 2;
}
if (len > 0) {
sum += (*buf) << 8;
}
while (sum >> 16) {
sum = (sum & 0xffff) + (sum >> 16);
}
return ((uint16)~sum);
}
#ifdef BCMDRIVER
/*
* Hierarchical Multiword bitmap based small id allocator.
*
* Multilevel hierarchy bitmap. (maximum 2 levels)
* First hierarchy uses a multiword bitmap to identify 32bit words in the
* second hierarchy that have at least a single bit set. Each bit in a word of
* the second hierarchy represents a unique ID that may be allocated.
*
* BCM_MWBMAP_ITEMS_MAX: Maximum number of IDs managed.
* BCM_MWBMAP_BITS_WORD: Number of bits in a bitmap word word
* BCM_MWBMAP_WORDS_MAX: Maximum number of bitmap words needed for free IDs.
* BCM_MWBMAP_WDMAP_MAX: Maximum number of bitmap wordss identifying first non
* non-zero bitmap word carrying at least one free ID.
* BCM_MWBMAP_SHIFT_OP: Used in MOD, DIV and MUL operations.
* BCM_MWBMAP_INVALID_IDX: Value ~0U is treated as an invalid ID
*
* Design Notes:
* BCM_MWBMAP_USE_CNTSETBITS trades CPU for memory. A runtime count of how many
* bits are computed each time on allocation and deallocation, requiring 4
* array indexed access and 3 arithmetic operations. When not defined, a runtime
* count of set bits state is maintained. Upto 32 Bytes per 1024 IDs is needed.
* In a 4K max ID allocator, up to 128Bytes are hence used per instantiation.
* In a memory limited system e.g. dongle builds, a CPU for memory tradeoff may
* be used by defining BCM_MWBMAP_USE_CNTSETBITS.
*
* Note: wd_bitmap[] is statically declared and is not ROM friendly ... array
* size is fixed. No intention to support larger than 4K indice allocation. ID
* allocators for ranges smaller than 4K will have a wastage of only 12Bytes
* with savings in not having to use an indirect access, had it been dynamically
* allocated.
*/
#define BCM_MWBMAP_ITEMS_MAX (4 * 1024) /* May increase to 16K */
#define BCM_MWBMAP_BITS_WORD (NBITS(uint32))
#define BCM_MWBMAP_WORDS_MAX (BCM_MWBMAP_ITEMS_MAX / BCM_MWBMAP_BITS_WORD)
#define BCM_MWBMAP_WDMAP_MAX (BCM_MWBMAP_WORDS_MAX / BCM_MWBMAP_BITS_WORD)
#define BCM_MWBMAP_SHIFT_OP (5)
#define BCM_MWBMAP_MODOP(ix) ((ix) & (BCM_MWBMAP_BITS_WORD - 1))
#define BCM_MWBMAP_DIVOP(ix) ((ix) >> BCM_MWBMAP_SHIFT_OP)
#define BCM_MWBMAP_MULOP(ix) ((ix) << BCM_MWBMAP_SHIFT_OP)
/* Redefine PTR() and/or HDL() conversion to invoke audit for debugging */
#define BCM_MWBMAP_PTR(hdl) ((struct bcm_mwbmap *)(hdl))
#define BCM_MWBMAP_HDL(ptr) ((void *)(ptr))
#if defined(BCM_MWBMAP_DEBUG)
#define BCM_MWBMAP_AUDIT(mwb) \
do { \
ASSERT((mwb != NULL) && \
(((struct bcm_mwbmap *)(mwb))->magic == (void *)(mwb))); \
bcm_mwbmap_audit(mwb); \
} while (0)
#define MWBMAP_ASSERT(exp) ASSERT(exp)
#define MWBMAP_DBG(x) printf x
#else /* !BCM_MWBMAP_DEBUG */
#define BCM_MWBMAP_AUDIT(mwb) do {} while (0)
#define MWBMAP_ASSERT(exp) do {} while (0)
#define MWBMAP_DBG(x)
#endif /* !BCM_MWBMAP_DEBUG */
typedef struct bcm_mwbmap { /* Hierarchical multiword bitmap allocator */
uint16 wmaps; /* Total number of words in free wd bitmap */
uint16 imaps; /* Total number of words in free id bitmap */
int16 ifree; /* Count of free indices. Used only in audits */
uint16 total; /* Total indices managed by multiword bitmap */
void * magic; /* Audit handle parameter from user */
uint32 wd_bitmap[BCM_MWBMAP_WDMAP_MAX]; /* 1st level bitmap of */
#if !defined(BCM_MWBMAP_USE_CNTSETBITS)
int8 wd_count[BCM_MWBMAP_WORDS_MAX]; /* free id running count, 1st lvl */
#endif /* ! BCM_MWBMAP_USE_CNTSETBITS */
uint32 id_bitmap[0]; /* Second level bitmap */
} bcm_mwbmap_t;
/* Incarnate a hierarchical multiword bitmap based small index allocator. */
struct bcm_mwbmap *
bcm_mwbmap_init(osl_t *osh, uint32 items_max)
{
struct bcm_mwbmap * mwbmap_p;
uint32 wordix, size, words, extra;
/* Implementation Constraint: Uses 32bit word bitmap */
MWBMAP_ASSERT(BCM_MWBMAP_BITS_WORD == 32U);
MWBMAP_ASSERT(BCM_MWBMAP_SHIFT_OP == 5U);
MWBMAP_ASSERT(ISPOWEROF2(BCM_MWBMAP_ITEMS_MAX));
MWBMAP_ASSERT((BCM_MWBMAP_ITEMS_MAX % BCM_MWBMAP_BITS_WORD) == 0U);
ASSERT(items_max <= BCM_MWBMAP_ITEMS_MAX);
/* Determine the number of words needed in the multiword bitmap */
extra = BCM_MWBMAP_MODOP(items_max);
words = BCM_MWBMAP_DIVOP(items_max) + ((extra != 0U) ? 1U : 0U);
/* Allocate runtime state of multiword bitmap */
/* Note: wd_count[] or wd_bitmap[] are not dynamically allocated */
size = sizeof(bcm_mwbmap_t) + (sizeof(uint32) * words);
mwbmap_p = (bcm_mwbmap_t *)MALLOC(osh, size);
if (mwbmap_p == (bcm_mwbmap_t *)NULL) {
ASSERT(0);
goto error1;
}
memset(mwbmap_p, 0, size);
/* Initialize runtime multiword bitmap state */
mwbmap_p->imaps = (uint16)words;
mwbmap_p->ifree = (int16)items_max;
mwbmap_p->total = (uint16)items_max;
/* Setup magic, for use in audit of handle */
mwbmap_p->magic = BCM_MWBMAP_HDL(mwbmap_p);
/* Setup the second level bitmap of free indices */
/* Mark all indices as available */
for (wordix = 0U; wordix < mwbmap_p->imaps; wordix++) {
mwbmap_p->id_bitmap[wordix] = (uint32)(~0U);
#if !defined(BCM_MWBMAP_USE_CNTSETBITS)
mwbmap_p->wd_count[wordix] = BCM_MWBMAP_BITS_WORD;
#endif /* ! BCM_MWBMAP_USE_CNTSETBITS */
}
/* Ensure that extra indices are tagged as un-available */
if (extra) { /* fixup the free ids in last bitmap and wd_count */
uint32 * bmap_p = &mwbmap_p->id_bitmap[mwbmap_p->imaps - 1];
*bmap_p ^= (uint32)(~0U << extra); /* fixup bitmap */
#if !defined(BCM_MWBMAP_USE_CNTSETBITS)
mwbmap_p->wd_count[mwbmap_p->imaps - 1] = (int8)extra; /* fixup count */
#endif /* ! BCM_MWBMAP_USE_CNTSETBITS */
}
/* Setup the first level bitmap hierarchy */
extra = BCM_MWBMAP_MODOP(mwbmap_p->imaps);
words = BCM_MWBMAP_DIVOP(mwbmap_p->imaps) + ((extra != 0U) ? 1U : 0U);
mwbmap_p->wmaps = (uint16)words;
for (wordix = 0U; wordix < mwbmap_p->wmaps; wordix++)
mwbmap_p->wd_bitmap[wordix] = (uint32)(~0U);
if (extra) {
uint32 * bmap_p = &mwbmap_p->wd_bitmap[mwbmap_p->wmaps - 1];
*bmap_p ^= (uint32)(~0U << extra); /* fixup bitmap */
}
return mwbmap_p;
error1:
return BCM_MWBMAP_INVALID_HDL;
}
/* Release resources used by multiword bitmap based small index allocator. */
void
bcm_mwbmap_fini(osl_t * osh, struct bcm_mwbmap * mwbmap_hdl)
{
bcm_mwbmap_t * mwbmap_p;
BCM_MWBMAP_AUDIT(mwbmap_hdl);
mwbmap_p = BCM_MWBMAP_PTR(mwbmap_hdl);
MFREE(osh, mwbmap_p, sizeof(struct bcm_mwbmap)
+ (sizeof(uint32) * mwbmap_p->imaps));
return;
}
/* Allocate a unique small index using a multiword bitmap index allocator. */
uint32 BCMFASTPATH
bcm_mwbmap_alloc(struct bcm_mwbmap * mwbmap_hdl)
{
bcm_mwbmap_t * mwbmap_p;
uint32 wordix, bitmap;
BCM_MWBMAP_AUDIT(mwbmap_hdl);
mwbmap_p = BCM_MWBMAP_PTR(mwbmap_hdl);
/* Start with the first hierarchy */
for (wordix = 0; wordix < mwbmap_p->wmaps; ++wordix) {
bitmap = mwbmap_p->wd_bitmap[wordix]; /* get the word bitmap */
if (bitmap != 0U) {
uint32 count, bitix, *bitmap_p;
bitmap_p = &mwbmap_p->wd_bitmap[wordix];
/* clear all except trailing 1 */
bitmap = (uint32)(((int)(bitmap)) & (-((int)(bitmap))));
MWBMAP_ASSERT(C_bcm_count_leading_zeros(bitmap) ==
bcm_count_leading_zeros(bitmap));
bitix = (BCM_MWBMAP_BITS_WORD - 1)
- bcm_count_leading_zeros(bitmap); /* use asm clz */
wordix = BCM_MWBMAP_MULOP(wordix) + bitix;
/* Clear bit if wd count is 0, without conditional branch */
#if defined(BCM_MWBMAP_USE_CNTSETBITS)
count = bcm_cntsetbits(mwbmap_p->id_bitmap[wordix]) - 1;
#else /* ! BCM_MWBMAP_USE_CNTSETBITS */
mwbmap_p->wd_count[wordix]--;
count = mwbmap_p->wd_count[wordix];
MWBMAP_ASSERT(count ==
(bcm_cntsetbits(mwbmap_p->id_bitmap[wordix]) - 1));
#endif /* ! BCM_MWBMAP_USE_CNTSETBITS */
MWBMAP_ASSERT(count >= 0);
/* clear wd_bitmap bit if id_map count is 0 */
bitmap = (count == 0) << bitix;
MWBMAP_DBG((
"Lvl1: bitix<%02u> wordix<%02u>: %08x ^ %08x = %08x wfree %d",
bitix, wordix, *bitmap_p, bitmap, (*bitmap_p) ^ bitmap, count));
*bitmap_p ^= bitmap;
/* Use bitix in the second hierarchy */
bitmap_p = &mwbmap_p->id_bitmap[wordix];
bitmap = mwbmap_p->id_bitmap[wordix]; /* get the id bitmap */
MWBMAP_ASSERT(bitmap != 0U);
/* clear all except trailing 1 */
bitmap = (uint32)(((int)(bitmap)) & (-((int)(bitmap))));
MWBMAP_ASSERT(C_bcm_count_leading_zeros(bitmap) ==
bcm_count_leading_zeros(bitmap));
bitix = BCM_MWBMAP_MULOP(wordix)
+ (BCM_MWBMAP_BITS_WORD - 1)
- bcm_count_leading_zeros(bitmap); /* use asm clz */
mwbmap_p->ifree--; /* decrement system wide free count */
MWBMAP_ASSERT(mwbmap_p->ifree >= 0);
MWBMAP_DBG((
"Lvl2: bitix<%02u> wordix<%02u>: %08x ^ %08x = %08x ifree %d",
bitix, wordix, *bitmap_p, bitmap, (*bitmap_p) ^ bitmap,
mwbmap_p->ifree));
*bitmap_p ^= bitmap; /* mark as allocated = 1b0 */
return bitix;
}
}
ASSERT(mwbmap_p->ifree == 0);
return BCM_MWBMAP_INVALID_IDX;
}
/* Force an index at a specified position to be in use */
void
bcm_mwbmap_force(struct bcm_mwbmap * mwbmap_hdl, uint32 bitix)
{
bcm_mwbmap_t * mwbmap_p;
uint32 count, wordix, bitmap, *bitmap_p;
BCM_MWBMAP_AUDIT(mwbmap_hdl);
mwbmap_p = BCM_MWBMAP_PTR(mwbmap_hdl);
ASSERT(bitix < mwbmap_p->total);
/* Start with second hierarchy */
wordix = BCM_MWBMAP_DIVOP(bitix);
bitmap = (uint32)(1U << BCM_MWBMAP_MODOP(bitix));
bitmap_p = &mwbmap_p->id_bitmap[wordix];
ASSERT((*bitmap_p & bitmap) == bitmap);
mwbmap_p->ifree--; /* update free count */
ASSERT(mwbmap_p->ifree >= 0);
MWBMAP_DBG(("Lvl2: bitix<%u> wordix<%u>: %08x ^ %08x = %08x ifree %d",
bitix, wordix, *bitmap_p, bitmap, (*bitmap_p) ^ bitmap,
mwbmap_p->ifree));
*bitmap_p ^= bitmap; /* mark as in use */
/* Update first hierarchy */
bitix = wordix;
wordix = BCM_MWBMAP_DIVOP(bitix);
bitmap_p = &mwbmap_p->wd_bitmap[wordix];
#if defined(BCM_MWBMAP_USE_CNTSETBITS)
count = bcm_cntsetbits(mwbmap_p->id_bitmap[bitix]);
#else /* ! BCM_MWBMAP_USE_CNTSETBITS */
mwbmap_p->wd_count[bitix]--;
count = mwbmap_p->wd_count[bitix];
MWBMAP_ASSERT(count == bcm_cntsetbits(mwbmap_p->id_bitmap[bitix]));
#endif /* ! BCM_MWBMAP_USE_CNTSETBITS */
MWBMAP_ASSERT(count >= 0);
bitmap = (count == 0) << BCM_MWBMAP_MODOP(bitix);
MWBMAP_DBG(("Lvl1: bitix<%02lu> wordix<%02u>: %08x ^ %08x = %08x wfree %d",
BCM_MWBMAP_MODOP(bitix), wordix, *bitmap_p, bitmap,
(*bitmap_p) ^ bitmap, count));
*bitmap_p ^= bitmap; /* mark as in use */
return;
}
/* Free a previously allocated index back into the multiword bitmap allocator */
void BCMFASTPATH
bcm_mwbmap_free(struct bcm_mwbmap * mwbmap_hdl, uint32 bitix)
{
bcm_mwbmap_t * mwbmap_p;
uint32 wordix, bitmap, *bitmap_p;
BCM_MWBMAP_AUDIT(mwbmap_hdl);
mwbmap_p = BCM_MWBMAP_PTR(mwbmap_hdl);
ASSERT(bitix < mwbmap_p->total);
/* Start with second level hierarchy */
wordix = BCM_MWBMAP_DIVOP(bitix);
bitmap = (1U << BCM_MWBMAP_MODOP(bitix));
bitmap_p = &mwbmap_p->id_bitmap[wordix];
ASSERT((*bitmap_p & bitmap) == 0U); /* ASSERT not a double free */
mwbmap_p->ifree++; /* update free count */
ASSERT(mwbmap_p->ifree <= mwbmap_p->total);
MWBMAP_DBG(("Lvl2: bitix<%02u> wordix<%02u>: %08x | %08x = %08x ifree %d",
bitix, wordix, *bitmap_p, bitmap, (*bitmap_p) | bitmap,
mwbmap_p->ifree));
*bitmap_p |= bitmap; /* mark as available */
/* Now update first level hierarchy */
bitix = wordix;
wordix = BCM_MWBMAP_DIVOP(bitix); /* first level's word index */
bitmap = (1U << BCM_MWBMAP_MODOP(bitix));
bitmap_p = &mwbmap_p->wd_bitmap[wordix];
#if !defined(BCM_MWBMAP_USE_CNTSETBITS)
mwbmap_p->wd_count[bitix]++;
#endif
#if defined(BCM_MWBMAP_DEBUG)
{
uint32 count;
#if defined(BCM_MWBMAP_USE_CNTSETBITS)
count = bcm_cntsetbits(mwbmap_p->id_bitmap[bitix]);
#else /* ! BCM_MWBMAP_USE_CNTSETBITS */
count = mwbmap_p->wd_count[bitix];
MWBMAP_ASSERT(count == bcm_cntsetbits(mwbmap_p->id_bitmap[bitix]));
#endif /* ! BCM_MWBMAP_USE_CNTSETBITS */
MWBMAP_ASSERT(count <= BCM_MWBMAP_BITS_WORD);
MWBMAP_DBG(("Lvl1: bitix<%02u> wordix<%02u>: %08x | %08x = %08x wfree %d",
bitix, wordix, *bitmap_p, bitmap, (*bitmap_p) | bitmap, count));
}
#endif /* BCM_MWBMAP_DEBUG */
*bitmap_p |= bitmap;
return;
}
/* Fetch the toal number of free indices in the multiword bitmap allocator */
uint32
bcm_mwbmap_free_cnt(struct bcm_mwbmap * mwbmap_hdl)
{
bcm_mwbmap_t * mwbmap_p;
BCM_MWBMAP_AUDIT(mwbmap_hdl);
mwbmap_p = BCM_MWBMAP_PTR(mwbmap_hdl);
ASSERT(mwbmap_p->ifree >= 0);
return mwbmap_p->ifree;
}
/* Determine whether an index is inuse or free */
bool
bcm_mwbmap_isfree(struct bcm_mwbmap * mwbmap_hdl, uint32 bitix)
{
bcm_mwbmap_t * mwbmap_p;
uint32 wordix, bitmap;
BCM_MWBMAP_AUDIT(mwbmap_hdl);
mwbmap_p = BCM_MWBMAP_PTR(mwbmap_hdl);
ASSERT(bitix < mwbmap_p->total);
wordix = BCM_MWBMAP_DIVOP(bitix);
bitmap = (1U << BCM_MWBMAP_MODOP(bitix));
return ((mwbmap_p->id_bitmap[wordix] & bitmap) != 0U);
}
/* Debug dump a multiword bitmap allocator */
void
bcm_mwbmap_show(struct bcm_mwbmap * mwbmap_hdl)
{
uint32 ix, count;
bcm_mwbmap_t * mwbmap_p;
BCM_MWBMAP_AUDIT(mwbmap_hdl);
mwbmap_p = BCM_MWBMAP_PTR(mwbmap_hdl);
printf("mwbmap_p %p wmaps %u imaps %u ifree %d total %u\n", mwbmap_p,
mwbmap_p->wmaps, mwbmap_p->imaps, mwbmap_p->ifree, mwbmap_p->total);
for (ix = 0U; ix < mwbmap_p->wmaps; ix++) {
printf("\tWDMAP:%2u. 0x%08x\t", ix, mwbmap_p->wd_bitmap[ix]);
bcm_bitprint32(mwbmap_p->wd_bitmap[ix]);
printf("\n");
}
for (ix = 0U; ix < mwbmap_p->imaps; ix++) {
#if defined(BCM_MWBMAP_USE_CNTSETBITS)
count = bcm_cntsetbits(mwbmap_p->id_bitmap[ix]);
#else /* ! BCM_MWBMAP_USE_CNTSETBITS */
count = mwbmap_p->wd_count[ix];
MWBMAP_ASSERT(count == bcm_cntsetbits(mwbmap_p->id_bitmap[ix]));
#endif /* ! BCM_MWBMAP_USE_CNTSETBITS */
printf("\tIDMAP:%2u. 0x%08x %02u\t", ix, mwbmap_p->id_bitmap[ix], count);
bcm_bitprint32(mwbmap_p->id_bitmap[ix]);
printf("\n");
}
return;
}
/* Audit a hierarchical multiword bitmap */
void
bcm_mwbmap_audit(struct bcm_mwbmap * mwbmap_hdl)
{
bcm_mwbmap_t * mwbmap_p;
uint32 count, free_cnt = 0U, wordix, idmap_ix, bitix, *bitmap_p;
mwbmap_p = BCM_MWBMAP_PTR(mwbmap_hdl);
for (wordix = 0U; wordix < mwbmap_p->wmaps; ++wordix) {
bitmap_p = &mwbmap_p->wd_bitmap[wordix];
for (bitix = 0U; bitix < BCM_MWBMAP_BITS_WORD; bitix++) {
if ((*bitmap_p) & (1 << bitix)) {
idmap_ix = BCM_MWBMAP_MULOP(wordix) + bitix;
#if defined(BCM_MWBMAP_USE_CNTSETBITS)
count = bcm_cntsetbits(mwbmap_p->id_bitmap[idmap_ix]);
#else /* ! BCM_MWBMAP_USE_CNTSETBITS */
count = mwbmap_p->wd_count[idmap_ix];
ASSERT(count == bcm_cntsetbits(mwbmap_p->id_bitmap[idmap_ix]));
#endif /* ! BCM_MWBMAP_USE_CNTSETBITS */
ASSERT(count != 0U);
free_cnt += count;
}
}
}
ASSERT((int)free_cnt == mwbmap_p->ifree);
}
/* END : Multiword bitmap based 64bit to Unique 32bit Id allocator. */
/* Simple 16bit Id allocator using a stack implementation. */
typedef struct id16_map {
uint16 total; /* total number of ids managed by allocator */
uint16 start; /* start value of 16bit ids to be managed */
uint32 failures; /* count of failures */
void *dbg; /* debug placeholder */
int stack_idx; /* index into stack of available ids */
uint16 stack[0]; /* stack of 16 bit ids */
} id16_map_t;
#define ID16_MAP_SZ(items) (sizeof(id16_map_t) + \
(sizeof(uint16) * (items)))
#if defined(BCM_DBG)
/* Uncomment BCM_DBG_ID16 to debug double free */
/* #define BCM_DBG_ID16 */
typedef struct id16_map_dbg {
uint16 total;
bool avail[0];
} id16_map_dbg_t;
#define ID16_MAP_DBG_SZ(items) (sizeof(id16_map_dbg_t) + \
(sizeof(bool) * (items)))
#define ID16_MAP_MSG(x) print x
#else
#define ID16_MAP_MSG(x)
#endif /* BCM_DBG */
void * /* Construct an id16 allocator: [start_val16 .. start_val16+total_ids) */
id16_map_init(osl_t *osh, uint16 total_ids, uint16 start_val16)
{
uint16 idx, val16;
id16_map_t * id16_map;
ASSERT(total_ids > 0);
ASSERT((start_val16 + total_ids) < ID16_INVALID);
id16_map = (id16_map_t *) MALLOC(osh, ID16_MAP_SZ(total_ids));
if (id16_map == NULL) {
return NULL;
}
id16_map->total = total_ids;
id16_map->start = start_val16;
id16_map->failures = 0;
id16_map->dbg = NULL;
/* Populate stack with 16bit id values, commencing with start_val16 */
id16_map->stack_idx = 0;
val16 = start_val16;
for (idx = 0; idx < total_ids; idx++, val16++) {
id16_map->stack_idx = idx;
id16_map->stack[id16_map->stack_idx] = val16;
}
#if defined(BCM_DBG) && defined(BCM_DBG_ID16)
id16_map->dbg = MALLOC(osh, ID16_MAP_DBG_SZ(total_ids));
if (id16_map->dbg) {
id16_map_dbg_t *id16_map_dbg = (id16_map_dbg_t *)id16_map->dbg;
id16_map_dbg->total = total_ids;
for (idx = 0; idx < total_ids; idx++) {
id16_map_dbg->avail[idx] = TRUE;
}
}
#endif /* BCM_DBG && BCM_DBG_ID16 */
return (void *)id16_map;
}
void * /* Destruct an id16 allocator instance */
id16_map_fini(osl_t *osh, void * id16_map_hndl)
{
uint16 total_ids;
id16_map_t * id16_map;
if (id16_map_hndl == NULL)
return NULL;
id16_map = (id16_map_t *)id16_map_hndl;
total_ids = id16_map->total;
ASSERT(total_ids > 0);
#if defined(BCM_DBG) && defined(BCM_DBG_ID16)
if (id16_map->dbg) {
MFREE(osh, id16_map->dbg, ID16_MAP_DBG_SZ(total_ids));
id16_map->dbg = NULL;
}
#endif /* BCM_DBG && BCM_DBG_ID16 */
id16_map->total = 0;
MFREE(osh, id16_map, ID16_MAP_SZ(total_ids));
return NULL;
}
void
id16_map_clear(void * id16_map_hndl, uint16 total_ids, uint16 start_val16)
{
uint16 idx, val16;
id16_map_t * id16_map;
ASSERT(total_ids > 0);
ASSERT((start_val16 + total_ids) < ID16_INVALID);
id16_map = (id16_map_t *)id16_map_hndl;
if (id16_map == NULL) {
return;
}
id16_map->total = total_ids;
id16_map->start = start_val16;
id16_map->failures = 0;
/* Populate stack with 16bit id values, commencing with start_val16 */
id16_map->stack_idx = 0;
val16 = start_val16;
for (idx = 0; idx < total_ids; idx++, val16++) {
id16_map->stack_idx = idx;
id16_map->stack[id16_map->stack_idx] = val16;
}
#if defined(BCM_DBG) && defined(BCM_DBG_ID16)
if (id16_map->dbg) {
id16_map_dbg_t *id16_map_dbg = (id16_map_dbg_t *)id16_map->dbg;
id16_map_dbg->total = total_ids;
for (idx = 0; idx < total_ids; idx++) {
id16_map_dbg->avail[idx] = TRUE;
}
}
#endif /* BCM_DBG && BCM_DBG_ID16 */
}
uint16 BCMFASTPATH /* Allocate a unique 16bit id */
id16_map_alloc(void * id16_map_hndl)
{
uint16 val16;
id16_map_t * id16_map;
ASSERT(id16_map_hndl != NULL);
id16_map = (id16_map_t *)id16_map_hndl;
ASSERT(id16_map->total > 0);
if (id16_map->stack_idx < 0) {
id16_map->failures++;
return ID16_INVALID;
}
val16 = id16_map->stack[id16_map->stack_idx];
id16_map->stack_idx--;
#if defined(BCM_DBG) && defined(BCM_DBG_ID16)
ASSERT(val16 < (id16_map->start + id16_map->total));
if (id16_map->dbg) { /* Validate val16 */
id16_map_dbg_t *id16_map_dbg = (id16_map_dbg_t *)id16_map->dbg;
ASSERT(id16_map_dbg->avail[val16 - id16_map->start] == TRUE);
id16_map_dbg->avail[val16 - id16_map->start] = FALSE;
}
#endif /* BCM_DBG && BCM_DBG_ID16 */
return val16;
}
void BCMFASTPATH /* Free a 16bit id value into the id16 allocator */
id16_map_free(void * id16_map_hndl, uint16 val16)
{
id16_map_t * id16_map;
ASSERT(id16_map_hndl != NULL);
id16_map = (id16_map_t *)id16_map_hndl;
#if defined(BCM_DBG) && defined(BCM_DBG_ID16)
ASSERT(val16 < (id16_map->start + id16_map->total));
if (id16_map->dbg) { /* Validate val16 */
id16_map_dbg_t *id16_map_dbg = (id16_map_dbg_t *)id16_map->dbg;
ASSERT(id16_map_dbg->avail[val16 - id16_map->start] == FALSE);
id16_map_dbg->avail[val16 - id16_map->start] = TRUE;
}
#endif /* BCM_DBG && BCM_DBG_ID16 */
id16_map->stack_idx++;
id16_map->stack[id16_map->stack_idx] = val16;
}
uint32 /* Returns number of failures to allocate an unique id16 */
id16_map_failures(void * id16_map_hndl)
{
ASSERT(id16_map_hndl != NULL);
return ((id16_map_t *)id16_map_hndl)->failures;
}
bool
id16_map_audit(void * id16_map_hndl)
{
int idx;
int insane = 0;
id16_map_t * id16_map;
ASSERT(id16_map_hndl != NULL);
id16_map = (id16_map_t *)id16_map_hndl;
ASSERT((id16_map->stack_idx > 0) && (id16_map->stack_idx < id16_map->total));
for (idx = 0; idx <= id16_map->stack_idx; idx++) {
ASSERT(id16_map->stack[idx] >= id16_map->start);
ASSERT(id16_map->stack[idx] < (id16_map->start + id16_map->total));
#if defined(BCM_DBG) && defined(BCM_DBG_ID16)
if (id16_map->dbg) {
uint16 val16 = id16_map->stack[idx];
if (((id16_map_dbg_t *)(id16_map->dbg))->avail[val16] != TRUE) {
insane |= 1;
ID16_MAP_MSG(("id16_map<%p>: stack_idx %u invalid val16 %u\n",
id16_map_hndl, idx, val16));
}
}
#endif /* BCM_DBG && BCM_DBG_ID16 */
}
#if defined(BCM_DBG) && defined(BCM_DBG_ID16)
if (id16_map->dbg) {
uint16 avail = 0; /* Audit available ids counts */
for (idx = 0; idx < id16_map_dbg->total; idx++) {
if (((id16_map_dbg_t *)(id16_map->dbg))->avail[idx16] == TRUE)
avail++;
}
if (avail && (avail != (id16_map->stack_idx + 1))) {
insane |= 1;
ID16_MAP_MSG(("id16_map<%p>: avail %u stack_idx %u\n",
id16_map_hndl, avail, id16_map->stack_idx));
}
}
#endif /* BCM_DBG && BCM_DBG_ID16 */
return (!!insane);
}
/* END: Simple id16 allocator */
#endif /* BCMDRIVER */
/* calculate a >> b; and returns only lower 32 bits */
void
bcm_uint64_right_shift(uint32* r, uint32 a_high, uint32 a_low, uint32 b)
{
uint32 a1 = a_high, a0 = a_low, r0 = 0;
if (b == 0) {
r0 = a_low;
*r = r0;
return;
}
if (b < 32) {
a0 = a0 >> b;
a1 = a1 & ((1 << b) - 1);
a1 = a1 << (32 - b);
r0 = a0 | a1;
*r = r0;
return;
} else {
r0 = a1 >> (b - 32);
*r = r0;
return;
}
}
/* calculate a + b where a is a 64 bit number and b is a 32 bit number */
void
bcm_add_64(uint32* r_hi, uint32* r_lo, uint32 offset)
{
uint32 r1_lo = *r_lo;
(*r_lo) += offset;
if (*r_lo < r1_lo)
(*r_hi) ++;
}
/* calculate a - b where a is a 64 bit number and b is a 32 bit number */
void
bcm_sub_64(uint32* r_hi, uint32* r_lo, uint32 offset)
{
uint32 r1_lo = *r_lo;
(*r_lo) -= offset;
if (*r_lo > r1_lo)
(*r_hi) --;
}
#ifdef DEBUG_COUNTER
#if (OSL_SYSUPTIME_SUPPORT == TRUE)
void counter_printlog(counter_tbl_t *ctr_tbl)
{
uint32 now;
if (!ctr_tbl->enabled)
return;
now = OSL_SYSUPTIME();
if (now - ctr_tbl->prev_log_print > ctr_tbl->log_print_interval) {
uint8 i = 0;
printf("counter_print(%s %d):", ctr_tbl->name, now - ctr_tbl->prev_log_print);
for (i = 0; i < ctr_tbl->needed_cnt; i++) {
printf(" %u", ctr_tbl->cnt[i]);
}
printf("\n");
ctr_tbl->prev_log_print = now;
bzero(ctr_tbl->cnt, CNTR_TBL_MAX * sizeof(uint));
}
}
#else
/* OSL_SYSUPTIME is not supported so no way to get time */
#define counter_printlog(a) do {} while (0)
#endif /* OSL_SYSUPTIME_SUPPORT == TRUE */
#endif /* DEBUG_COUNTER */
#ifdef BCMDRIVER
void
dll_pool_detach(void * osh, dll_pool_t * pool, uint16 elems_max, uint16 elem_size)
{
uint32 mem_size;
mem_size = sizeof(dll_pool_t) + (elems_max * elem_size);
if (pool)
MFREE(osh, pool, mem_size);
}
dll_pool_t *
dll_pool_init(void * osh, uint16 elems_max, uint16 elem_size)
{
uint32 mem_size, i;
dll_pool_t * dll_pool_p;
dll_t * elem_p;
ASSERT(elem_size > sizeof(dll_t));
mem_size = sizeof(dll_pool_t) + (elems_max * elem_size);
if ((dll_pool_p = (dll_pool_t *)MALLOC(osh, mem_size)) == NULL) {
printf("dll_pool_init: elems_max<%u> elem_size<%u> malloc failure\n",
elems_max, elem_size);
ASSERT(0);
return dll_pool_p;
}
bzero(dll_pool_p, mem_size);
dll_init(&dll_pool_p->free_list);
dll_pool_p->elems_max = elems_max;
dll_pool_p->elem_size = elem_size;
elem_p = dll_pool_p->elements;
for (i = 0; i < elems_max; i++) {
dll_append(&dll_pool_p->free_list, elem_p);
elem_p = (dll_t *)((uintptr)elem_p + elem_size);
}
dll_pool_p->free_count = elems_max;
return dll_pool_p;
}
void *
dll_pool_alloc(dll_pool_t * dll_pool_p)
{
dll_t * elem_p;
if (dll_pool_p->free_count == 0) {
ASSERT(dll_empty(&dll_pool_p->free_list));
return NULL;
}
elem_p = dll_head_p(&dll_pool_p->free_list);
dll_delete(elem_p);
dll_pool_p->free_count -= 1;
return (void *)elem_p;
}
void
dll_pool_free(dll_pool_t * dll_pool_p, void * elem_p)
{
dll_t * node_p = (dll_t *)elem_p;
dll_prepend(&dll_pool_p->free_list, node_p);
dll_pool_p->free_count += 1;
}
void
dll_pool_free_tail(dll_pool_t * dll_pool_p, void * elem_p)
{
dll_t * node_p = (dll_t *)elem_p;
dll_append(&dll_pool_p->free_list, node_p);
dll_pool_p->free_count += 1;
}
#endif /* BCMDRIVER */
| s20121035/rk3288_android5.1_repo | kernel/drivers/net/wireless/rockchip_wlan/rkwifi/bcmdhd/bcmutils.c | C | gpl-3.0 | 77,626 |
/*
Copyright (C) 2010,2012,2016 The ESPResSo project
Copyright (C) 2002,2003,2004,2005,2006,2007,2008,2009,2010
Max-Planck-Institute for Polymer Research, Theory Group
This file is part of ESPResSo.
ESPResSo 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.
ESPResSo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** \file lees_edwards.h
Data and methods for Lees-Edwards periodic boundary conditions. The gist of LE-PBCs is to impose shear flow
by constantly moving the PBC wrap such that: $x_{unfolded} == x_{folded} + x_{img} \times L + (y_{img} * \gamma * t)$,
and $vx_{unfolded} = vx_{folded} + (y_{img} * \gamma)$.
*/
#ifndef LEES_EDWARDS_H
#define LEES_EDWARDS_H
#include "config.hpp"
extern double lees_edwards_offset, lees_edwards_rate;
extern int lees_edwards_count;
#ifdef LEES_EDWARDS
void lees_edwards_step_boundaries();
#endif //LEES_EDWARDS
#endif //LEES_EDWARDS_H
| Smiljanic/espresso | src/core/lees_edwards.hpp | C++ | gpl-3.0 | 1,440 |
/* lzw.c -- compress files in LZW format.
* This is a dummy version avoiding patent problems.
*/
#include <config.h>
#include "tailor.h"
#include "gzip.h"
#include "lzw.h"
static int msg_done = 0;
/* Compress in to out with lzw method. */
int lzw(in, out)
int in, out;
{
if (msg_done) return ERROR;
msg_done = 1;
fprintf(stderr,"output in compress .Z format not supported\n");
if (in != out) { /* avoid warnings on unused variables */
exit_code = ERROR;
}
return ERROR;
}
| infoburp/gzip | lzw.c | C | gpl-3.0 | 513 |
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
package mod._streams.uno;
import com.sun.star.io.XActiveDataSink;
import com.sun.star.io.XActiveDataSource;
import com.sun.star.io.XDataOutputStream;
import com.sun.star.io.XInputStream;
import com.sun.star.io.XOutputStream;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
import java.io.PrintWriter;
import java.util.ArrayList;
import lib.TestCase;
import lib.TestEnvironment;
import lib.TestParameters;
/**
* Test for object which is represented by service
* <code>com.sun.star.io.DataInputStream</code>.
* <ul>
* <li> <code>com::sun::star::io::XInputStream</code></li>
* <li> <code>com::sun::star::io::XDataInputStream</code></li>
* <li> <code>com::sun::star::io::XConnectable</code></li>
* <li> <code>com::sun::star::io::XActiveDataSink</code></li>
* </ul>
* @see com.sun.star.io.DataInputStream
* @see com.sun.star.io.XInputStream
* @see com.sun.star.io.XDataInputStream
* @see com.sun.star.io.XConnectable
* @see com.sun.star.io.XActiveDataSink
* @see ifc.io._XInputStream
* @see ifc.io._XDataInputStream
* @see ifc.io._XConnectable
* @see ifc.io._XActiveDataSink
*/
public class DataInputStream extends TestCase {
/**
* Creates a TestEnvironment for the interfaces to be tested.
* Creates <code>com.sun.star.io.DataInputStream</code> object,
* connects it to <code>com.sun.star.io.DataOutputStream</code>
* through <code>com.sun.star.io.Pipe</code>. All of possible data
* types are written into <code>DataOutputStream</code>.
* Object relations created :
* <ul>
* <li> <code>'StreamData'</code> for
* {@link ifc.io._XDataInputStream}(the data that should be written into
* the stream) </li>
* <li> <code>'ByteData'</code> for
* {@link ifc.io._XInputStream}(the data that should be written into
* the stream) </li>
* <li> <code>'StreamWriter'</code> for
* {@link ifc.io._XDataInputStream}
* {@link ifc.io._XInputStream}(a stream to write data to) </li>
* <li> <code>'Connectable'</code> for
* {@link ifc.io._XConnectable}(another object that can be connected) </li>
* <li> <code>'InputStream'</code> for
* {@link ifc.io._XActiveDataSink}(an input stream to set and get) </li>
* </ul>
*/
@Override
protected TestEnvironment createTestEnvironment(TestParameters Param, PrintWriter log) throws Exception {
Object oInterface = null;
XMultiServiceFactory xMSF = Param.getMSF();
oInterface = xMSF.createInstance("com.sun.star.io.DataInputStream");
XInterface oObj = (XInterface) oInterface;
// creating and connecting DataOutputStream to the
// DataInputStream created through the Pipe
XActiveDataSink xDataSink = UnoRuntime.queryInterface(XActiveDataSink.class, oObj);
XInterface oPipe = (XInterface)
xMSF.createInstance("com.sun.star.io.Pipe");
XInputStream xPipeInput = UnoRuntime.queryInterface(XInputStream.class, oPipe);
XOutputStream xPipeOutput = UnoRuntime.queryInterface(XOutputStream.class, oPipe);
XInterface oDataOutput = (XInterface)
xMSF.createInstance("com.sun.star.io.DataOutputStream");
XDataOutputStream xDataOutput = UnoRuntime.queryInterface(XDataOutputStream.class, oDataOutput) ;
XActiveDataSource xDataSource = UnoRuntime.queryInterface(XActiveDataSource.class, oDataOutput) ;
xDataSource.setOutputStream(xPipeOutput) ;
xDataSink.setInputStream(xPipeInput) ;
// all data types for writing to an XDataInputStream
ArrayList<Object> data = new ArrayList<Object>() ;
data.add(Boolean.TRUE) ;
data.add(Byte.valueOf((byte)123)) ;
data.add(new Character((char)1234)) ;
data.add(Short.valueOf((short)1234)) ;
data.add(Integer.valueOf(123456)) ;
data.add(new Float(1.234)) ;
data.add(new Double(1.23456)) ;
data.add("DataInputStream") ;
// information for writing to the pipe
byte[] byteData = new byte[] {
1, 2, 3, 4, 5, 6, 7, 8 } ;
// creating a connectable object for XConnectable interface
XInterface xConnect = (XInterface)xMSF.createInstance(
"com.sun.star.io.DataInputStream") ;
// creating an input stream to set in XActiveDataSink
XInterface oDataInput = (XInterface) xMSF.createInstance(
"com.sun.star.io.Pipe" );
log.println("creating a new environment for object");
TestEnvironment tEnv = new TestEnvironment( oObj );
// adding sequence of data that must be read
// by XDataInputStream interface methods
tEnv.addObjRelation("StreamData", data) ;
// add a writer
tEnv.addObjRelation("StreamWriter", xDataOutput);
// add a connectable
tEnv.addObjRelation("Connectable", xConnect);
// add an inputStream
tEnv.addObjRelation("InputStream", oDataInput);
tEnv.addObjRelation("ByteData", byteData);
return tEnv;
} // finish method getTestEnvironment
}
| jvanz/core | qadevOOo/tests/java/mod/_streams/uno/DataInputStream.java | Java | gpl-3.0 | 6,006 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!--
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.
--><html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>Apache log4cxx: wlogstream Class Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.4.6 -->
<div class="tabs">
<ul>
<li><a href="main.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li id="current"><a href="classes.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul></div>
<div class="tabs">
<ul>
<li><a href="classes.html"><span>Alphabetical List</span></a></li>
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul></div>
<div class="nav">
<a class="el" href="namespacelog4cxx.html">log4cxx</a>::<a class="el" href="classlog4cxx_1_1wlogstream.html">wlogstream</a></div>
<h1>wlogstream Class Reference</h1><!-- doxytag: class="log4cxx::wlogstream" --><!-- doxytag: inherits="log4cxx::logstream_base" -->Inherits <a class="el" href="classlog4cxx_1_1logstream__base.html">logstream_base</a>.
<p>
<a href="classlog4cxx_1_1wlogstream-members.html">List of all members.</a><hr><a name="_details"></a><h2>Detailed Description</h2>
An STL-like stream API for <a class="el" href="namespacelog4cxx.html">log4cxx</a> using wchar_t as the character type.
<p>
. Instances of <a class="el" href="classlog4cxx_1_1logstream.html">log4cxx::logstream</a> are not designedfor use by multiple threads and in general should be short-lived function scoped objects. Using log4cxx::basic_logstream as a class member or static instance should be avoided in the same manner as you would avoid placing a std::ostringstream in those locations. Insertion operations are generally short-circuited if the level for the stream is not the same of higher that the level of the associated logger.
<p>
<table border="0" cellpadding="0" cellspacing="0">
<tr><td></td></tr>
<tr><td colspan="2"><br><h2>Public Member Functions</h2></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classlog4cxx_1_1wlogstream.html#a3cdaec14785accf92c18a7dbd9e42a7">wlogstream</a> (const <a class="el" href="classlog4cxx_1_1helpers_1_1_object_ptr_t.html">log4cxx::LoggerPtr</a> &logger, const <a class="el" href="classlog4cxx_1_1helpers_1_1_object_ptr_t.html">log4cxx::LevelPtr</a> &level)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Constructor. <a href="#a3cdaec14785accf92c18a7dbd9e42a7"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classlog4cxx_1_1wlogstream.html#779372ca1e7e9009082629772021426a">wlogstream</a> (const Ch *loggerName, const <a class="el" href="classlog4cxx_1_1helpers_1_1_object_ptr_t.html">log4cxx::LevelPtr</a> &level)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Constructor. <a href="#779372ca1e7e9009082629772021426a"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classlog4cxx_1_1wlogstream.html#56880c1923aef73fb47100c9cfee5bd3">wlogstream</a> (const std::basic_string< Ch > &loggerName, const <a class="el" href="classlog4cxx_1_1helpers_1_1_object_ptr_t.html">log4cxx::LevelPtr</a> &level)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Constructor. <a href="#56880c1923aef73fb47100c9cfee5bd3"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classlog4cxx_1_1wlogstream.html#d5d81ce1b5c7455eebd6277f916890ad">~wlogstream</a> ()</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="el" href="classlog4cxx_1_1wlogstream.html">wlogstream</a> & </td><td class="memItemRight" valign="bottom"><a class="el" href="classlog4cxx_1_1wlogstream.html#be12766bade075faa63f4f89a2d1074c">operator<<</a> (std::ios_base &(*manip)(std::ios_base &))</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Insertion operator for std::fixed and similar manipulators. <a href="#be12766bade075faa63f4f89a2d1074c"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="el" href="classlog4cxx_1_1wlogstream.html">wlogstream</a> & </td><td class="memItemRight" valign="bottom"><a class="el" href="classlog4cxx_1_1wlogstream.html#5876fc72f98cdeb290c2c435690b7312">operator<<</a> (<a class="el" href="namespacelog4cxx.html#fe0ea990a92d242b75f4d620dcd8e71f">logstream_manipulator</a> manip)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Insertion operator for <a class="el" href="classlog4cxx_1_1logstream__base.html#e95420093e23b645a275e115043684e9">logstream_base::endmsg</a>. <a href="#5876fc72f98cdeb290c2c435690b7312"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="el" href="classlog4cxx_1_1wlogstream.html">wlogstream</a> & </td><td class="memItemRight" valign="bottom"><a class="el" href="classlog4cxx_1_1wlogstream.html#75d9fda0ee55ffdf568b2d2ce2a5979d">operator<<</a> (const <a class="el" href="classlog4cxx_1_1helpers_1_1_object_ptr_t.html">log4cxx::LevelPtr</a> &level)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Insertion operator for level. <a href="#75d9fda0ee55ffdf568b2d2ce2a5979d"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="el" href="classlog4cxx_1_1wlogstream.html">wlogstream</a> & </td><td class="memItemRight" valign="bottom"><a class="el" href="classlog4cxx_1_1wlogstream.html#584ccffac9990f906a9e98f66d802292">operator<<</a> (const <a class="el" href="classlog4cxx_1_1spi_1_1_location_info.html">log4cxx::spi::LocationInfo</a> &location)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Insertion operator for location. <a href="#584ccffac9990f906a9e98f66d802292"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="el" href="classlog4cxx_1_1wlogstream.html">wlogstream</a> & </td><td class="memItemRight" valign="bottom"><a class="el" href="classlog4cxx_1_1wlogstream.html#123354515e7d457d3f01c1b59cfe6fac">operator>></a> (const <a class="el" href="classlog4cxx_1_1spi_1_1_location_info.html">log4cxx::spi::LocationInfo</a> &location)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Alias for insertion operator for location. <a href="#123354515e7d457d3f01c1b59cfe6fac"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classlog4cxx_1_1wlogstream.html#99359af16778cf382f92639bafe47bc4">operator std::basic_ostream</a> ()</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Cast operator to provide access to embedded std::basic_ostream. <a href="#99359af16778cf382f92639bafe47bc4"></a><br></td></tr>
<tr><td class="memTemplParams" nowrap colspan="2">template<class V> </td></tr>
<tr><td class="memTemplItemLeft" nowrap align="right" valign="top"><a class="el" href="classlog4cxx_1_1wlogstream.html">log4cxx::wlogstream</a> & </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="classlog4cxx_1_1wlogstream.html#383b42274701a53bff2060878dac0437">operator<<</a> (const V &val)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Template to allow any class with an std::basic_ostream inserter to be applied to this class. <a href="#383b42274701a53bff2060878dac0437"></a><br></td></tr>
<tr><td colspan="2"><br><h2>Protected Member Functions</h2></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="classlog4cxx_1_1wlogstream.html#3175ec78d6e1235ebd1ab3aad0e8e717">log</a> (<a class="el" href="classlog4cxx_1_1helpers_1_1_object_ptr_t.html">LoggerPtr</a> &logger, const <a class="el" href="classlog4cxx_1_1helpers_1_1_object_ptr_t.html">LevelPtr</a> &level, const <a class="el" href="classlog4cxx_1_1spi_1_1_location_info.html">log4cxx::spi::LocationInfo</a> &location)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Dispatches the pending log request. <a href="#3175ec78d6e1235ebd1ab3aad0e8e717"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="classlog4cxx_1_1wlogstream.html#cc248831fec96b660d813c565ffd93b7">erase</a> ()</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Erase any content in the message construction buffer. <a href="#cc248831fec96b660d813c565ffd93b7"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="classlog4cxx_1_1wlogstream.html#9e8c5ad843e0886f9e6c683e6888de77">get_stream_state</a> (std::ios_base &base, std::ios_base &mask, int &fill, bool &fillSet) const </td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Copy state of embedded stream (if any) to value and mask instances of std::ios_base and return fill character value. <a href="#9e8c5ad843e0886f9e6c683e6888de77"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="classlog4cxx_1_1wlogstream.html#979bc47725d6c28a371e71b4f45ed548">refresh_stream_state</a> ()</td></tr>
</table>
<hr><h2>Constructor & Destructor Documentation</h2>
<a class="anchor" name="a3cdaec14785accf92c18a7dbd9e42a7"></a><!-- doxytag: member="log4cxx::wlogstream::wlogstream" ref="a3cdaec14785accf92c18a7dbd9e42a7" args="(const log4cxx::LoggerPtr &logger, const log4cxx::LevelPtr &level)" --><p>
<table class="mdTable" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top"><a class="el" href="classlog4cxx_1_1wlogstream.html">wlogstream</a> </td>
<td class="md" valign="top">( </td>
<td class="md" nowrap valign="top">const <a class="el" href="classlog4cxx_1_1helpers_1_1_object_ptr_t.html">log4cxx::LoggerPtr</a> & </td>
<td class="mdname" nowrap> <em>logger</em>, </td>
</tr>
<tr>
<td class="md" nowrap align="right"></td>
<td class="md"></td>
<td class="md" nowrap>const <a class="el" href="classlog4cxx_1_1helpers_1_1_object_ptr_t.html">log4cxx::LevelPtr</a> & </td>
<td class="mdname" nowrap> <em>level</em></td>
</tr>
<tr>
<td class="md"></td>
<td class="md">) </td>
<td class="md" colspan="2"></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing="5" cellpadding="0" border="0">
<tr>
<td>
</td>
<td>
<p>
Constructor.
<p>
</td>
</tr>
</table>
<a class="anchor" name="779372ca1e7e9009082629772021426a"></a><!-- doxytag: member="log4cxx::wlogstream::wlogstream" ref="779372ca1e7e9009082629772021426a" args="(const Ch *loggerName, const log4cxx::LevelPtr &level)" --><p>
<table class="mdTable" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top"><a class="el" href="classlog4cxx_1_1wlogstream.html">wlogstream</a> </td>
<td class="md" valign="top">( </td>
<td class="md" nowrap valign="top">const Ch * </td>
<td class="mdname" nowrap> <em>loggerName</em>, </td>
</tr>
<tr>
<td class="md" nowrap align="right"></td>
<td class="md"></td>
<td class="md" nowrap>const <a class="el" href="classlog4cxx_1_1helpers_1_1_object_ptr_t.html">log4cxx::LevelPtr</a> & </td>
<td class="mdname" nowrap> <em>level</em></td>
</tr>
<tr>
<td class="md"></td>
<td class="md">) </td>
<td class="md" colspan="2"></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing="5" cellpadding="0" border="0">
<tr>
<td>
</td>
<td>
<p>
Constructor.
<p>
</td>
</tr>
</table>
<a class="anchor" name="56880c1923aef73fb47100c9cfee5bd3"></a><!-- doxytag: member="log4cxx::wlogstream::wlogstream" ref="56880c1923aef73fb47100c9cfee5bd3" args="(const std::basic_string< Ch > &loggerName, const log4cxx::LevelPtr &level)" --><p>
<table class="mdTable" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top"><a class="el" href="classlog4cxx_1_1wlogstream.html">wlogstream</a> </td>
<td class="md" valign="top">( </td>
<td class="md" nowrap valign="top">const std::basic_string< Ch > & </td>
<td class="mdname" nowrap> <em>loggerName</em>, </td>
</tr>
<tr>
<td class="md" nowrap align="right"></td>
<td class="md"></td>
<td class="md" nowrap>const <a class="el" href="classlog4cxx_1_1helpers_1_1_object_ptr_t.html">log4cxx::LevelPtr</a> & </td>
<td class="mdname" nowrap> <em>level</em></td>
</tr>
<tr>
<td class="md"></td>
<td class="md">) </td>
<td class="md" colspan="2"></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing="5" cellpadding="0" border="0">
<tr>
<td>
</td>
<td>
<p>
Constructor.
<p>
</td>
</tr>
</table>
<a class="anchor" name="d5d81ce1b5c7455eebd6277f916890ad"></a><!-- doxytag: member="log4cxx::wlogstream::~wlogstream" ref="d5d81ce1b5c7455eebd6277f916890ad" args="()" --><p>
<table class="mdTable" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top">~<a class="el" href="classlog4cxx_1_1wlogstream.html">wlogstream</a> </td>
<td class="md" valign="top">( </td>
<td class="mdname1" valign="top" nowrap> </td>
<td class="md" valign="top"> ) </td>
<td class="md" nowrap></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing="5" cellpadding="0" border="0">
<tr>
<td>
</td>
<td>
<p>
</td>
</tr>
</table>
<hr><h2>Member Function Documentation</h2>
<a class="anchor" name="cc248831fec96b660d813c565ffd93b7"></a><!-- doxytag: member="log4cxx::wlogstream::erase" ref="cc248831fec96b660d813c565ffd93b7" args="()" --><p>
<table class="mdTable" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top">virtual void erase </td>
<td class="md" valign="top">( </td>
<td class="mdname1" valign="top" nowrap> </td>
<td class="md" valign="top"> ) </td>
<td class="md" nowrap><code> [protected, virtual]</code></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing="5" cellpadding="0" border="0">
<tr>
<td>
</td>
<td>
<p>
Erase any content in the message construction buffer.
<p>
<p>
Implements <a class="el" href="classlog4cxx_1_1logstream__base.html#60b4d079ef9767fcbf6b3955aaaedf75">logstream_base</a>. </td>
</tr>
</table>
<a class="anchor" name="9e8c5ad843e0886f9e6c683e6888de77"></a><!-- doxytag: member="log4cxx::wlogstream::get_stream_state" ref="9e8c5ad843e0886f9e6c683e6888de77" args="(std::ios_base &base, std::ios_base &mask, int &fill, bool &fillSet) const " --><p>
<table class="mdTable" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top">virtual void get_stream_state </td>
<td class="md" valign="top">( </td>
<td class="md" nowrap valign="top">std::ios_base & </td>
<td class="mdname" nowrap> <em>base</em>, </td>
</tr>
<tr>
<td class="md" nowrap align="right"></td>
<td class="md"></td>
<td class="md" nowrap>std::ios_base & </td>
<td class="mdname" nowrap> <em>mask</em>, </td>
</tr>
<tr>
<td class="md" nowrap align="right"></td>
<td class="md"></td>
<td class="md" nowrap>int & </td>
<td class="mdname" nowrap> <em>fill</em>, </td>
</tr>
<tr>
<td class="md" nowrap align="right"></td>
<td class="md"></td>
<td class="md" nowrap>bool & </td>
<td class="mdname" nowrap> <em>fillSet</em></td>
</tr>
<tr>
<td class="md"></td>
<td class="md">) </td>
<td class="md" colspan="2"> const<code> [protected, virtual]</code></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing="5" cellpadding="0" border="0">
<tr>
<td>
</td>
<td>
<p>
Copy state of embedded stream (if any) to value and mask instances of std::ios_base and return fill character value.
<p>
<p>
Implements <a class="el" href="classlog4cxx_1_1logstream__base.html#f4354e248898842ab15baa421806671a">logstream_base</a>. </td>
</tr>
</table>
<a class="anchor" name="3175ec78d6e1235ebd1ab3aad0e8e717"></a><!-- doxytag: member="log4cxx::wlogstream::log" ref="3175ec78d6e1235ebd1ab3aad0e8e717" args="(LoggerPtr &logger, const LevelPtr &level, const log4cxx::spi::LocationInfo &location)" --><p>
<table class="mdTable" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top">virtual void log </td>
<td class="md" valign="top">( </td>
<td class="md" nowrap valign="top"><a class="el" href="classlog4cxx_1_1helpers_1_1_object_ptr_t.html">LoggerPtr</a> & </td>
<td class="mdname" nowrap> <em>logger</em>, </td>
</tr>
<tr>
<td class="md" nowrap align="right"></td>
<td class="md"></td>
<td class="md" nowrap>const <a class="el" href="classlog4cxx_1_1helpers_1_1_object_ptr_t.html">LevelPtr</a> & </td>
<td class="mdname" nowrap> <em>level</em>, </td>
</tr>
<tr>
<td class="md" nowrap align="right"></td>
<td class="md"></td>
<td class="md" nowrap>const <a class="el" href="classlog4cxx_1_1spi_1_1_location_info.html">log4cxx::spi::LocationInfo</a> & </td>
<td class="mdname" nowrap> <em>location</em></td>
</tr>
<tr>
<td class="md"></td>
<td class="md">) </td>
<td class="md" colspan="2"><code> [protected, virtual]</code></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing="5" cellpadding="0" border="0">
<tr>
<td>
</td>
<td>
<p>
Dispatches the pending log request.
<p>
<p>
Implements <a class="el" href="classlog4cxx_1_1logstream__base.html#7319c6c9b6eb2354fcef57fa77ad90c8">logstream_base</a>. </td>
</tr>
</table>
<a class="anchor" name="99359af16778cf382f92639bafe47bc4"></a><!-- doxytag: member="log4cxx::wlogstream::operator std::basic_ostream" ref="99359af16778cf382f92639bafe47bc4" args="()" --><p>
<table class="mdTable" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top">operator std::basic_ostream </td>
<td class="md" valign="top">( </td>
<td class="mdname1" valign="top" nowrap> </td>
<td class="md" valign="top"> ) </td>
<td class="md" nowrap></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing="5" cellpadding="0" border="0">
<tr>
<td>
</td>
<td>
<p>
Cast operator to provide access to embedded std::basic_ostream.
<p>
</td>
</tr>
</table>
<a class="anchor" name="383b42274701a53bff2060878dac0437"></a><!-- doxytag: member="log4cxx::wlogstream::operator<<" ref="383b42274701a53bff2060878dac0437" args="(const V &val)" --><p>
<table class="mdTable" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top"><a class="el" href="classlog4cxx_1_1wlogstream.html">log4cxx::wlogstream</a>& operator<< </td>
<td class="md" valign="top">( </td>
<td class="md" nowrap valign="top">const V & </td>
<td class="mdname1" valign="top" nowrap> <em>val</em> </td>
<td class="md" valign="top"> ) </td>
<td class="md" nowrap><code> [inline]</code></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing="5" cellpadding="0" border="0">
<tr>
<td>
</td>
<td>
<p>
Template to allow any class with an std::basic_ostream inserter to be applied to this class.
<p>
</td>
</tr>
</table>
<a class="anchor" name="584ccffac9990f906a9e98f66d802292"></a><!-- doxytag: member="log4cxx::wlogstream::operator<<" ref="584ccffac9990f906a9e98f66d802292" args="(const log4cxx::spi::LocationInfo &location)" --><p>
<table class="mdTable" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top"><a class="el" href="classlog4cxx_1_1wlogstream.html">wlogstream</a>& operator<< </td>
<td class="md" valign="top">( </td>
<td class="md" nowrap valign="top">const <a class="el" href="classlog4cxx_1_1spi_1_1_location_info.html">log4cxx::spi::LocationInfo</a> & </td>
<td class="mdname1" valign="top" nowrap> <em>location</em> </td>
<td class="md" valign="top"> ) </td>
<td class="md" nowrap></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing="5" cellpadding="0" border="0">
<tr>
<td>
</td>
<td>
<p>
Insertion operator for location.
<p>
</td>
</tr>
</table>
<a class="anchor" name="75d9fda0ee55ffdf568b2d2ce2a5979d"></a><!-- doxytag: member="log4cxx::wlogstream::operator<<" ref="75d9fda0ee55ffdf568b2d2ce2a5979d" args="(const log4cxx::LevelPtr &level)" --><p>
<table class="mdTable" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top"><a class="el" href="classlog4cxx_1_1wlogstream.html">wlogstream</a>& operator<< </td>
<td class="md" valign="top">( </td>
<td class="md" nowrap valign="top">const <a class="el" href="classlog4cxx_1_1helpers_1_1_object_ptr_t.html">log4cxx::LevelPtr</a> & </td>
<td class="mdname1" valign="top" nowrap> <em>level</em> </td>
<td class="md" valign="top"> ) </td>
<td class="md" nowrap></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing="5" cellpadding="0" border="0">
<tr>
<td>
</td>
<td>
<p>
Insertion operator for level.
<p>
</td>
</tr>
</table>
<a class="anchor" name="5876fc72f98cdeb290c2c435690b7312"></a><!-- doxytag: member="log4cxx::wlogstream::operator<<" ref="5876fc72f98cdeb290c2c435690b7312" args="(logstream_manipulator manip)" --><p>
<table class="mdTable" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top"><a class="el" href="classlog4cxx_1_1wlogstream.html">wlogstream</a>& operator<< </td>
<td class="md" valign="top">( </td>
<td class="md" nowrap valign="top"><a class="el" href="namespacelog4cxx.html#fe0ea990a92d242b75f4d620dcd8e71f">logstream_manipulator</a> </td>
<td class="mdname1" valign="top" nowrap> <em>manip</em> </td>
<td class="md" valign="top"> ) </td>
<td class="md" nowrap></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing="5" cellpadding="0" border="0">
<tr>
<td>
</td>
<td>
<p>
Insertion operator for <a class="el" href="classlog4cxx_1_1logstream__base.html#e95420093e23b645a275e115043684e9">logstream_base::endmsg</a>.
<p>
</td>
</tr>
</table>
<a class="anchor" name="be12766bade075faa63f4f89a2d1074c"></a><!-- doxytag: member="log4cxx::wlogstream::operator<<" ref="be12766bade075faa63f4f89a2d1074c" args="(std::ios_base &(*manip)(std::ios_base &))" --><p>
<table class="mdTable" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top"><a class="el" href="classlog4cxx_1_1wlogstream.html">wlogstream</a>& operator<< </td>
<td class="md" valign="top">( </td>
<td class="md" nowrap valign="top">std::ios_base &(*)(std::ios_base &) </td>
<td class="mdname1" valign="top" nowrap> <em>manip</em> </td>
<td class="md" valign="top"> ) </td>
<td class="md" nowrap></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing="5" cellpadding="0" border="0">
<tr>
<td>
</td>
<td>
<p>
Insertion operator for std::fixed and similar manipulators.
<p>
</td>
</tr>
</table>
<a class="anchor" name="123354515e7d457d3f01c1b59cfe6fac"></a><!-- doxytag: member="log4cxx::wlogstream::operator>>" ref="123354515e7d457d3f01c1b59cfe6fac" args="(const log4cxx::spi::LocationInfo &location)" --><p>
<table class="mdTable" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top"><a class="el" href="classlog4cxx_1_1wlogstream.html">wlogstream</a>& operator>> </td>
<td class="md" valign="top">( </td>
<td class="md" nowrap valign="top">const <a class="el" href="classlog4cxx_1_1spi_1_1_location_info.html">log4cxx::spi::LocationInfo</a> & </td>
<td class="mdname1" valign="top" nowrap> <em>location</em> </td>
<td class="md" valign="top"> ) </td>
<td class="md" nowrap></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing="5" cellpadding="0" border="0">
<tr>
<td>
</td>
<td>
<p>
Alias for insertion operator for location.
<p>
Kludge to avoid inappropriate compiler ambiguity. </td>
</tr>
</table>
<a class="anchor" name="979bc47725d6c28a371e71b4f45ed548"></a><!-- doxytag: member="log4cxx::wlogstream::refresh_stream_state" ref="979bc47725d6c28a371e71b4f45ed548" args="()" --><p>
<table class="mdTable" cellpadding="2" cellspacing="0">
<tr>
<td class="mdRow">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="md" nowrap valign="top">virtual void refresh_stream_state </td>
<td class="md" valign="top">( </td>
<td class="mdname1" valign="top" nowrap> </td>
<td class="md" valign="top"> ) </td>
<td class="md" nowrap><code> [protected, virtual]</code></td>
</tr>
</table>
</td>
</tr>
</table>
<table cellspacing="5" cellpadding="0" border="0">
<tr>
<td>
</td>
<td>
<p>
<p>
Implements <a class="el" href="classlog4cxx_1_1logstream__base.html#69058a0b06cd353e328325f4a8579790">logstream_base</a>. </td>
</tr>
</table>
<hr>The documentation for this class was generated from the following file:<ul>
<li><a class="el" href="stream_8h.html">stream.h</a></ul>
<!--
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.
-->
</BODY>
</HTML>
| Kiddinglife/gecoengine | thirdparty/log4cxx/site/apidocs/classlog4cxx_1_1wlogstream.html | HTML | gpl-3.0 | 31,499 |
<?php
/**
* @file
* @ingroup SpecialPage
*/
/**
* @todo document
* @ingroup SpecialPage
*/
class ProtectedPagesForm {
protected $IdLevel = 'level';
protected $IdType = 'type';
public function showList( $msg = '' ) {
global $wgOut, $wgRequest;
if( $msg != "" ) {
$wgOut->setSubtitle( $msg );
}
// Purge expired entries on one in every 10 queries
if( !mt_rand( 0, 10 ) ) {
Title::purgeExpiredRestrictions();
}
$type = $wgRequest->getVal( $this->IdType );
$level = $wgRequest->getVal( $this->IdLevel );
$sizetype = $wgRequest->getVal( 'sizetype' );
$size = $wgRequest->getIntOrNull( 'size' );
$NS = $wgRequest->getIntOrNull( 'namespace' );
$indefOnly = $wgRequest->getBool( 'indefonly' ) ? 1 : 0;
$cascadeOnly = $wgRequest->getBool('cascadeonly') ? 1 : 0;
$pager = new ProtectedPagesPager( $this, array(), $type, $level, $NS, $sizetype, $size, $indefOnly, $cascadeOnly );
$wgOut->addHTML( $this->showOptions( $NS, $type, $level, $sizetype, $size, $indefOnly, $cascadeOnly ) );
if( $pager->getNumRows() ) {
$s = $pager->getNavigationBar();
$s .= "<ul>" .
$pager->getBody() .
"</ul>";
$s .= $pager->getNavigationBar();
} else {
$s = '<p>' . wfMsgHtml( 'protectedpagesempty' ) . '</p>';
}
$wgOut->addHTML( $s );
}
/**
* Callback function to output a restriction
* @param $row object Protected title
* @return string Formatted <li> element
*/
public function formatRow( $row ) {
global $wgUser, $wgLang, $wgContLang;
wfProfileIn( __METHOD__ );
static $skin=null;
if( is_null( $skin ) )
$skin = $wgUser->getSkin();
$title = Title::makeTitleSafe( $row->page_namespace, $row->page_title );
$link = $skin->link( $title );
$description_items = array ();
$protType = wfMsgHtml( 'restriction-level-' . $row->pr_level );
$description_items[] = $protType;
if( $row->pr_cascade ) {
$description_items[] = wfMsg( 'protect-summary-cascade' );
}
$expiry_description = '';
$stxt = '';
if( $row->pr_expiry != 'infinity' && strlen($row->pr_expiry) ) {
$expiry = Block::decodeExpiry( $row->pr_expiry );
$expiry_description = wfMsg( 'protect-expiring' , $wgLang->timeanddate( $expiry ) ,
$wgLang->date( $expiry ) , $wgLang->time( $expiry ) );
$description_items[] = htmlspecialchars($expiry_description);
}
if(!is_null($size = $row->page_len)) {
$stxt = $wgContLang->getDirMark() . ' ' . $skin->formatRevisionSize( $size );
}
# Show a link to the change protection form for allowed users otherwise a link to the protection log
if( $wgUser->isAllowed( 'protect' ) ) {
$changeProtection = ' (' . $skin->linkKnown(
$title,
wfMsgHtml( 'protect_change' ),
array(),
array( 'action' => 'unprotect' )
) . ')';
} else {
$ltitle = SpecialPage::getTitleFor( 'Log' );
$changeProtection = ' (' . $skin->linkKnown(
$ltitle,
wfMsgHtml( 'protectlogpage' ),
array(),
array(
'type' => 'protect',
'page' => $title->getPrefixedText()
)
) . ')';
}
wfProfileOut( __METHOD__ );
return Html::rawElement(
'li',
array(),
wfSpecialList( $link . $stxt, $wgLang->commaList( $description_items ) ) . $changeProtection ) . "\n";
}
/**
* @param $namespace int
* @param $type string
* @param $level string
* @param $minsize int
* @param $indefOnly bool
* @param $cascadeOnly bool
* @return string Input form
* @private
*/
protected function showOptions( $namespace, $type='edit', $level, $sizetype, $size, $indefOnly, $cascadeOnly ) {
global $wgScript;
$title = SpecialPage::getTitleFor( 'Protectedpages' );
return Xml::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript ) ) .
Xml::openElement( 'fieldset' ) .
Xml::element( 'legend', array(), wfMsg( 'protectedpages' ) ) .
Xml::hidden( 'title', $title->getPrefixedDBkey() ) . "\n" .
$this->getNamespaceMenu( $namespace ) . " \n" .
$this->getTypeMenu( $type ) . " \n" .
$this->getLevelMenu( $level ) . " \n" .
"<br /><span style='white-space: nowrap'>" .
$this->getExpiryCheck( $indefOnly ) . " \n" .
$this->getCascadeCheck( $cascadeOnly ) . " \n" .
"</span><br /><span style='white-space: nowrap'>" .
$this->getSizeLimit( $sizetype, $size ) . " \n" .
"</span>" .
" " . Xml::submitButton( wfMsg( 'allpagessubmit' ) ) . "\n" .
Xml::closeElement( 'fieldset' ) .
Xml::closeElement( 'form' );
}
/**
* Prepare the namespace filter drop-down; standard namespace
* selector, sans the MediaWiki namespace
*
* @param mixed $namespace Pre-select namespace
* @return string
*/
protected function getNamespaceMenu( $namespace = null ) {
return "<span style='white-space: nowrap'>" .
Xml::label( wfMsg( 'namespace' ), 'namespace' ) . ' '
. Xml::namespaceSelector( $namespace, '' ) . "</span>";
}
/**
* @return string Formatted HTML
*/
protected function getExpiryCheck( $indefOnly ) {
return
Xml::checkLabel( wfMsg('protectedpages-indef'), 'indefonly', 'indefonly', $indefOnly ) . "\n";
}
/**
* @return string Formatted HTML
*/
protected function getCascadeCheck( $cascadeOnly ) {
return
Xml::checkLabel( wfMsg('protectedpages-cascade'), 'cascadeonly', 'cascadeonly', $cascadeOnly ) . "\n";
}
/**
* @return string Formatted HTML
*/
protected function getSizeLimit( $sizetype, $size ) {
$max = $sizetype === 'max';
return
Xml::radioLabel( wfMsg('minimum-size'), 'sizetype', 'min', 'wpmin', !$max ) .
' ' .
Xml::radioLabel( wfMsg('maximum-size'), 'sizetype', 'max', 'wpmax', $max ) .
' ' .
Xml::input( 'size', 9, $size, array( 'id' => 'wpsize' ) ) .
' ' .
Xml::label( wfMsg('pagesize'), 'wpsize' );
}
/**
* Creates the input label of the restriction type
* @param $pr_type string Protection type
* @return string Formatted HTML
*/
protected function getTypeMenu( $pr_type ) {
global $wgRestrictionTypes;
$m = array(); // Temporary array
$options = array();
// First pass to load the log names
foreach( $wgRestrictionTypes as $type ) {
$text = wfMsg("restriction-$type");
$m[$text] = $type;
}
// Third pass generates sorted XHTML content
foreach( $m as $text => $type ) {
$selected = ($type == $pr_type );
$options[] = Xml::option( $text, $type, $selected ) . "\n";
}
return "<span style='white-space: nowrap'>" .
Xml::label( wfMsg('restriction-type') , $this->IdType ) . ' ' .
Xml::tags( 'select',
array( 'id' => $this->IdType, 'name' => $this->IdType ),
implode( "\n", $options ) ) . "</span>";
}
/**
* Creates the input label of the restriction level
* @param $pr_level string Protection level
* @return string Formatted HTML
*/
protected function getLevelMenu( $pr_level ) {
global $wgRestrictionLevels;
$m = array( wfMsg('restriction-level-all') => 0 ); // Temporary array
$options = array();
// First pass to load the log names
foreach( $wgRestrictionLevels as $type ) {
// Messages used can be 'restriction-level-sysop' and 'restriction-level-autoconfirmed'
if( $type !='' && $type !='*') {
$text = wfMsg("restriction-level-$type");
$m[$text] = $type;
}
}
// Third pass generates sorted XHTML content
foreach( $m as $text => $type ) {
$selected = ($type == $pr_level );
$options[] = Xml::option( $text, $type, $selected );
}
return "<span style='white-space: nowrap'>" .
Xml::label( wfMsg( 'restriction-level' ) , $this->IdLevel ) . ' ' .
Xml::tags( 'select',
array( 'id' => $this->IdLevel, 'name' => $this->IdLevel ),
implode( "\n", $options ) ) . "</span>";
}
}
/**
* @todo document
* @ingroup Pager
*/
class ProtectedPagesPager extends AlphabeticPager {
public $mForm, $mConds;
private $type, $level, $namespace, $sizetype, $size, $indefonly;
function __construct( $form, $conds = array(), $type, $level, $namespace, $sizetype='', $size=0,
$indefonly = false, $cascadeonly = false )
{
$this->mForm = $form;
$this->mConds = $conds;
$this->type = ( $type ) ? $type : 'edit';
$this->level = $level;
$this->namespace = $namespace;
$this->sizetype = $sizetype;
$this->size = intval($size);
$this->indefonly = (bool)$indefonly;
$this->cascadeonly = (bool)$cascadeonly;
parent::__construct();
}
function getStartBody() {
# Do a link batch query
$lb = new LinkBatch;
while( $row = $this->mResult->fetchObject() ) {
$lb->add( $row->page_namespace, $row->page_title );
}
$lb->execute();
return '';
}
function formatRow( $row ) {
return $this->mForm->formatRow( $row );
}
function getQueryInfo() {
$conds = $this->mConds;
$conds[] = '(pr_expiry>' . $this->mDb->addQuotes( $this->mDb->timestamp() ) .
'OR pr_expiry IS NULL)';
$conds[] = 'page_id=pr_page';
$conds[] = 'pr_type=' . $this->mDb->addQuotes( $this->type );
if( $this->sizetype=='min' ) {
$conds[] = 'page_len>=' . $this->size;
} else if( $this->sizetype=='max' ) {
$conds[] = 'page_len<=' . $this->size;
}
if( $this->indefonly ) {
$conds[] = "pr_expiry = 'infinity' OR pr_expiry IS NULL";
}
if( $this->cascadeonly ) {
$conds[] = "pr_cascade = '1'";
}
if( $this->level )
$conds[] = 'pr_level=' . $this->mDb->addQuotes( $this->level );
if( !is_null($this->namespace) )
$conds[] = 'page_namespace=' . $this->mDb->addQuotes( $this->namespace );
return array(
'tables' => array( 'page_restrictions', 'page' ),
'fields' => 'pr_id,page_namespace,page_title,page_len,pr_type,pr_level,pr_expiry,pr_cascade',
'conds' => $conds
);
}
function getIndexField() {
return 'pr_id';
}
}
/**
* Constructor
*/
function wfSpecialProtectedpages() {
$ppForm = new ProtectedPagesForm();
$ppForm->showList();
}
| hendrysuwanda/101dev | tools/mediawiki/includes/specials/SpecialProtectedpages.php | PHP | gpl-3.0 | 9,777 |
#!/bin/bash
test_info()
{
cat <<EOF
Verify that the ctdb_transaction test succeeds.
Prerequisites:
* An active CTDB cluster with at least 2 active nodes.
Steps:
1. Verify that the status on all of the ctdb nodes is 'OK'.
2. Run two copies of ctdb_transaction on each node with a 30 second
timeout.
3. Ensure that all ctdb_transaction processes complete successfully.
Expected results:
* ctdb_transaction runs without error.
EOF
}
. "${TEST_SCRIPTS_DIR}/integration.bash"
ctdb_test_init "$@"
set -e
cluster_is_healthy
try_command_on_node 0 "$CTDB listnodes"
num_nodes=$(echo "$out" | wc -l)
if test "x${CTDB_TEST_TIMELIMIT}" == "x" ; then
CTDB_TEST_TIMELIMIT=30
fi
t="$CTDB_TEST_WRAPPER $VALGRIND ctdb_transaction --timelimit=${CTDB_TEST_TIMELIMIT}"
echo "Running ctdb_transaction on all $num_nodes nodes."
try_command_on_node -v -p all "$t & $t"
| SpectraLogic/samba | ctdb/tests/simple/53_ctdb_transaction.sh | Shell | gpl-3.0 | 869 |
package com.earth2me.essentials.antibuild;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class EssentialsAntiBuild extends JavaPlugin implements IAntiBuild
{
private final transient Map<AntiBuildConfig, Boolean> settingsBoolean = new EnumMap<AntiBuildConfig, Boolean>(AntiBuildConfig.class);
private final transient Map<AntiBuildConfig, List<Integer>> settingsList = new EnumMap<AntiBuildConfig, List<Integer>>(AntiBuildConfig.class);
private transient EssentialsConnect ess = null;
@Override
public void onEnable()
{
final PluginManager pm = this.getServer().getPluginManager();
final Plugin essPlugin = pm.getPlugin("Essentials");
if (essPlugin == null || !essPlugin.isEnabled())
{
return;
}
ess = new EssentialsConnect(essPlugin, this);
final EssentialsAntiBuildListener blockListener = new EssentialsAntiBuildListener(this);
pm.registerEvents(blockListener, this);
}
@Override
public boolean checkProtectionItems(final AntiBuildConfig list, final int id)
{
final List<Integer> itemList = settingsList.get(list);
return itemList != null && !itemList.isEmpty() && itemList.contains(id);
}
@Override
public EssentialsConnect getEssentialsConnect()
{
return ess;
}
@Override
public Map<AntiBuildConfig, Boolean> getSettingsBoolean()
{
return settingsBoolean;
}
@Override
public Map<AntiBuildConfig, List<Integer>> getSettingsList()
{
return settingsList;
}
@Override
public boolean getSettingBool(final AntiBuildConfig protectConfig)
{
final Boolean bool = settingsBoolean.get(protectConfig);
return bool == null ? protectConfig.getDefaultValueBoolean() : bool;
}
}
| walster001/Essentials | EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuild.java | Java | gpl-3.0 | 1,783 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!--
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.
--><html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>Apache log4cxx: Member List</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.4.6 -->
<div class="tabs">
<ul>
<li><a href="main.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li id="current"><a href="classes.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul></div>
<div class="tabs">
<ul>
<li><a href="classes.html"><span>Alphabetical List</span></a></li>
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul></div>
<h1>InterruptedIOException Member List</h1>This is the complete list of members for <a class="el" href="classlog4cxx_1_1helpers_1_1_interrupted_i_o_exception.html">InterruptedIOException</a>, including all inherited members.<p><table>
<tr class="memlist"><td><a class="el" href="classlog4cxx_1_1helpers_1_1_exception.html#e5e04df303590dff4f57f2da4e60d6d7">Exception</a>(const char *msg)</td><td><a class="el" href="classlog4cxx_1_1helpers_1_1_exception.html">Exception</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classlog4cxx_1_1helpers_1_1_exception.html#8dcca19ab4ce108db16e644fc687eeed">Exception</a>(const LogString &msg)</td><td><a class="el" href="classlog4cxx_1_1helpers_1_1_exception.html">Exception</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classlog4cxx_1_1helpers_1_1_exception.html#8dafee80c8d90301c465737c0c869a74">Exception</a>(const Exception &src)</td><td><a class="el" href="classlog4cxx_1_1helpers_1_1_exception.html">Exception</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classlog4cxx_1_1helpers_1_1_interrupted_i_o_exception.html#0f802c558c0be6f719187240756bf2c6">InterruptedIOException</a>(const LogString &msg)</td><td><a class="el" href="classlog4cxx_1_1helpers_1_1_interrupted_i_o_exception.html">InterruptedIOException</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classlog4cxx_1_1helpers_1_1_interrupted_i_o_exception.html#5305dcf7aed763b55b04c2886b2e21d4">InterruptedIOException</a>(const InterruptedIOException &)</td><td><a class="el" href="classlog4cxx_1_1helpers_1_1_interrupted_i_o_exception.html">InterruptedIOException</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classlog4cxx_1_1helpers_1_1_i_o_exception.html#af2d79761cb149ecc425c18743911a85">IOException</a>()</td><td><a class="el" href="classlog4cxx_1_1helpers_1_1_i_o_exception.html">IOException</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classlog4cxx_1_1helpers_1_1_i_o_exception.html#50e391afc3ba3e304f381f3003344b6d">IOException</a>(log4cxx_status_t stat)</td><td><a class="el" href="classlog4cxx_1_1helpers_1_1_i_o_exception.html">IOException</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classlog4cxx_1_1helpers_1_1_i_o_exception.html#66ed6afc1f66ea29949f58713a7bd214">IOException</a>(const LogString &msg)</td><td><a class="el" href="classlog4cxx_1_1helpers_1_1_i_o_exception.html">IOException</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classlog4cxx_1_1helpers_1_1_i_o_exception.html#e6ceb38f01c523cfa433c6705ff266e9">IOException</a>(const IOException &src)</td><td><a class="el" href="classlog4cxx_1_1helpers_1_1_i_o_exception.html">IOException</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classlog4cxx_1_1helpers_1_1_interrupted_i_o_exception.html#a408b663067146907af792a5354f38ac">operator=</a>(const InterruptedIOException &)</td><td><a class="el" href="classlog4cxx_1_1helpers_1_1_interrupted_i_o_exception.html">InterruptedIOException</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classlog4cxx_1_1helpers_1_1_i_o_exception.html#8f2d14cb76606091a996909f09d092a7">log4cxx::helpers::IOException::operator=</a>(const IOException &)</td><td><a class="el" href="classlog4cxx_1_1helpers_1_1_i_o_exception.html">IOException</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classlog4cxx_1_1helpers_1_1_exception.html#4c17b6fd950ef49bbf6adb7add4fe450">log4cxx::helpers::Exception::operator=</a>(const Exception &src)</td><td><a class="el" href="classlog4cxx_1_1helpers_1_1_exception.html">Exception</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classlog4cxx_1_1helpers_1_1_exception.html#586eee248fedb7de1b50219e14b99c7b">what</a>() const </td><td><a class="el" href="classlog4cxx_1_1helpers_1_1_exception.html">Exception</a></td><td></td></tr>
</table><!--
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.
-->
</BODY>
</HTML>
| Kiddinglife/gecoengine | thirdparty/log4cxx/site/apidocs/classlog4cxx_1_1helpers_1_1_interrupted_i_o_exception-members.html | HTML | gpl-3.0 | 6,660 |
// Copyright 2012 Mark Cavage, Inc. All rights reserved.
'use strict';
///--- Exports
/**
* JSONP formatter. like JSON, but with a callback invocation.
*
* Unicode escapes line and paragraph separators.
*
* @public
* @function formatJSONP
* @param {Object} req the request object
* @param {Object} res the response object
* @param {Object} body response body
* @returns {String}
*/
function formatJSONP(req, res, body) {
if (!body) {
res.setHeader('Content-Length', 0);
return (null);
}
if (Buffer.isBuffer(body)) {
body = body.toString('base64');
}
var _cb = req.query.callback || req.query.jsonp;
var data;
if (_cb) {
data = 'typeof ' + _cb + ' === \'function\' && ' +
_cb + '(' + JSON.stringify(body) + ');';
} else {
data = JSON.stringify(body);
}
data = data.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
res.setHeader('Content-Length', Buffer.byteLength(data));
return data;
}
module.exports = formatJSONP;
| eduardomrodrigues/atabey | ws-api/node_modules/restify/lib/formatters/jsonp.js | JavaScript | gpl-3.0 | 1,081 |
//===- BitCodes.h - Enum values for the bitcode format ----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This header Bitcode enum values.
//
// The enum values defined in this file should be considered permanent. If
// new features are added, they should have values added at the end of the
// respective lists.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_BITCODE_BITCODES_H
#define LLVM_BITCODE_BITCODES_H
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/DataTypes.h"
#include <cassert>
namespace llvm {
namespace bitc {
enum StandardWidths {
BlockIDWidth = 8, // We use VBR-8 for block IDs.
CodeLenWidth = 4, // Codelen are VBR-4.
BlockSizeWidth = 32 // BlockSize up to 2^32 32-bit words = 16GB per block.
};
// The standard abbrev namespace always has a way to exit a block, enter a
// nested block, define abbrevs, and define an unabbreviated record.
enum FixedAbbrevIDs {
END_BLOCK = 0, // Must be zero to guarantee termination for broken bitcode.
ENTER_SUBBLOCK = 1,
/// DEFINE_ABBREV - Defines an abbrev for the current block. It consists
/// of a vbr5 for # operand infos. Each operand info is emitted with a
/// single bit to indicate if it is a literal encoding. If so, the value is
/// emitted with a vbr8. If not, the encoding is emitted as 3 bits followed
/// by the info value as a vbr5 if needed.
DEFINE_ABBREV = 2,
// UNABBREV_RECORDs are emitted with a vbr6 for the record code, followed by
// a vbr6 for the # operands, followed by vbr6's for each operand.
UNABBREV_RECORD = 3,
// This is not a code, this is a marker for the first abbrev assignment.
FIRST_APPLICATION_ABBREV = 4
};
/// StandardBlockIDs - All bitcode files can optionally include a BLOCKINFO
/// block, which contains metadata about other blocks in the file.
enum StandardBlockIDs {
/// BLOCKINFO_BLOCK is used to define metadata about blocks, for example,
/// standard abbrevs that should be available to all blocks of a specified
/// ID.
BLOCKINFO_BLOCK_ID = 0,
// Block IDs 1-7 are reserved for future expansion.
FIRST_APPLICATION_BLOCKID = 8
};
/// BlockInfoCodes - The blockinfo block contains metadata about user-defined
/// blocks.
enum BlockInfoCodes {
// DEFINE_ABBREV has magic semantics here, applying to the current SETBID'd
// block, instead of the BlockInfo block.
BLOCKINFO_CODE_SETBID = 1, // SETBID: [blockid#]
BLOCKINFO_CODE_BLOCKNAME = 2, // BLOCKNAME: [name]
BLOCKINFO_CODE_SETRECORDNAME = 3 // BLOCKINFO_CODE_SETRECORDNAME: [id, name]
};
} // End bitc namespace
/// BitCodeAbbrevOp - This describes one or more operands in an abbreviation.
/// This is actually a union of two different things:
/// 1. It could be a literal integer value ("the operand is always 17").
/// 2. It could be an encoding specification ("this operand encoded like so").
///
class BitCodeAbbrevOp {
uint64_t Val; // A literal value or data for an encoding.
bool IsLiteral : 1; // Indicate whether this is a literal value or not.
unsigned Enc : 3; // The encoding to use.
public:
enum Encoding {
Fixed = 1, // A fixed width field, Val specifies number of bits.
VBR = 2, // A VBR field where Val specifies the width of each chunk.
Array = 3, // A sequence of fields, next field species elt encoding.
Char6 = 4, // A 6-bit fixed field which maps to [a-zA-Z0-9._].
Blob = 5 // 32-bit aligned array of 8-bit characters.
};
explicit BitCodeAbbrevOp(uint64_t V) : Val(V), IsLiteral(true) {}
explicit BitCodeAbbrevOp(Encoding E, uint64_t Data = 0)
: Val(Data), IsLiteral(false), Enc(E) {}
bool isLiteral() const { return IsLiteral; }
bool isEncoding() const { return !IsLiteral; }
// Accessors for literals.
uint64_t getLiteralValue() const { assert(isLiteral()); return Val; }
// Accessors for encoding info.
Encoding getEncoding() const { assert(isEncoding()); return (Encoding)Enc; }
uint64_t getEncodingData() const {
assert(isEncoding() && hasEncodingData());
return Val;
}
bool hasEncodingData() const { return hasEncodingData(getEncoding()); }
static bool hasEncodingData(Encoding E) {
switch (E) {
default: assert(0 && "Unknown encoding");
case Fixed:
case VBR:
return true;
case Array:
case Char6:
case Blob:
return false;
}
}
/// isChar6 - Return true if this character is legal in the Char6 encoding.
static bool isChar6(char C) {
if (C >= 'a' && C <= 'z') return true;
if (C >= 'A' && C <= 'Z') return true;
if (C >= '0' && C <= '9') return true;
if (C == '.' || C == '_') return true;
return false;
}
static unsigned EncodeChar6(char C) {
if (C >= 'a' && C <= 'z') return C-'a';
if (C >= 'A' && C <= 'Z') return C-'A'+26;
if (C >= '0' && C <= '9') return C-'0'+26+26;
if (C == '.') return 62;
if (C == '_') return 63;
assert(0 && "Not a value Char6 character!");
return 0;
}
static char DecodeChar6(unsigned V) {
assert((V & ~63) == 0 && "Not a Char6 encoded character!");
if (V < 26) return V+'a';
if (V < 26+26) return V-26+'A';
if (V < 26+26+10) return V-26-26+'0';
if (V == 62) return '.';
if (V == 63) return '_';
assert(0 && "Not a value Char6 character!");
return ' ';
}
};
/// BitCodeAbbrev - This class represents an abbreviation record. An
/// abbreviation allows a complex record that has redundancy to be stored in a
/// specialized format instead of the fully-general, fully-vbr, format.
class BitCodeAbbrev {
SmallVector<BitCodeAbbrevOp, 8> OperandList;
unsigned char RefCount; // Number of things using this.
~BitCodeAbbrev() {}
public:
BitCodeAbbrev() : RefCount(1) {}
void addRef() { ++RefCount; }
void dropRef() { if (--RefCount == 0) delete this; }
unsigned getNumOperandInfos() const {
return static_cast<unsigned>(OperandList.size());
}
const BitCodeAbbrevOp &getOperandInfo(unsigned N) const {
return OperandList[N];
}
void Add(const BitCodeAbbrevOp &OpInfo) {
OperandList.push_back(OpInfo);
}
};
} // End llvm namespace
#endif
| reinhrst/panda | usr/lib/llvm-3.0/include/llvm/Bitcode/BitCodes.h | C | gpl-3.0 | 6,500 |
-----------------------------------
--
-- Zone: RuAun_Gardens (130)
--
-----------------------------------
local ID = require("scripts/zones/RuAun_Gardens/IDs");
require("scripts/globals/missions");
require("scripts/globals/conquest");
require("scripts/globals/treasure")
require("scripts/globals/status");
require("scripts/globals/titles");
-----------------------------------
function onInitialize(zone)
for k, v in pairs(ID.npc.PORTALS) do
zone:registerRegion(k,unpack(v["coords"]));
end
dsp.treasure.initZone(zone)
dsp.conq.setRegionalConquestOverseers(zone:getRegionID())
end;
function onConquestUpdate(zone, updatetype)
dsp.conq.onConquestUpdate(zone, updatetype)
end;
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(333.017,-44.896,-458.35,164);
end
if (player:getCurrentMission(ZILART) == dsp.mission.id.zilart.THE_GATE_OF_THE_GODS and player:getCharVar("ZilartStatus") == 1) then
cs = 51;
end
return cs;
end;
function onRegionEnter(player,region)
local p = ID.npc.PORTALS[region:GetRegionID()];
if (p["green"] ~= nil) then -- green portal
if (player:getCharVar("skyShortcut") == 1) then
player:startEvent(42);
else
title = player:getTitle();
if (title == dsp.title.WARRIOR_OF_THE_CRYSTAL) then
player:startEvent(41,title);
else
player:startEvent(43,title);
end
end
elseif (p["portal"] ~= nil) then -- blue portal
if (GetNPCByID(p["portal"]):getAnimation() == dsp.anim.OPEN_DOOR) then
player:startEvent(p["event"]);
end
elseif (type(p["event"]) == "table") then -- portal with random destination
local events = p["event"];
player:startEvent(events[math.random(#events)]);
else -- portal with static destination
player:startEvent(p["event"]);
end
end;
function onRegionLeave(player,region)
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 41 and option ~= 0) then
player:setCharVar("skyShortcut",1);
elseif (csid == 51) then
player:setCharVar("ZilartStatus",0);
player:completeMission(ZILART,dsp.mission.id.zilart.THE_GATE_OF_THE_GODS);
player:addMission(ZILART,dsp.mission.id.zilart.ARK_ANGELS);
end
end;
| dacrybabysuck/darkstar | scripts/zones/RuAun_Gardens/Zone.lua | Lua | gpl-3.0 | 2,491 |
#!/bin/sh
echo "$1" | sbbic/core | shell/source/unix/exec/urltest.sh | Shell | gpl-3.0 | 19 |
/*
Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
(function(){CKEDITOR.on("dialogDefinition",function(a){var b;b=a.data.name;a=a.data.definition;"link"==b?(a.removeContents("target"),a.removeContents("upload"),a.removeContents("advanced"),b=a.getContents("info"),b.remove("emailSubject"),b.remove("emailBody")):"image"==b&&(a.removeContents("advanced"),b=a.getContents("Link"),b.remove("cmbTarget"),b=a.getContents("info"),b.remove("txtAlt"),b.remove("basic"))});var l={b:"strong",u:"u",i:"em",color:"span",size:"span",left:"div",right:"div",center:"div",
justify:"div",quote:"blockquote",code:"code",url:"a",email:"span",img:"span","*":"li",list:"ol"},x={strong:"b",b:"b",u:"u",em:"i",i:"i",code:"code",li:"*"},m={strong:"b",em:"i",u:"u",li:"*",ul:"list",ol:"list",code:"code",a:"link",img:"img",blockquote:"quote"},y={color:"color",size:"font-size",left:"text-align",center:"text-align",right:"text-align",justify:"text-align"},z={url:"href",email:"mailhref",quote:"cite",list:"listType"},n=CKEDITOR.dtd,A=CKEDITOR.tools.extend({table:1},n.$block,n.$listItem,
n.$tableContent,n.$list),C=/\s*(?:;\s*|$)/,q={smiley:":)",sad:":(",wink:";)",laugh:":D",cheeky:":P",blush:":*)",surprise:":-o",indecision:":|",angry:"\x3e:(",angel:"o:)",cool:"8-)",devil:"\x3e:-)",crying:";(",kiss:":-*"},B={},r=[],t;for(t in q)B[q[t]]=t,r.push(q[t].replace(/\(|\)|\:|\/|\*|\-|\|/g,function(a){return"\\"+a}));var r=new RegExp(r.join("|"),"g"),D=function(){var a=[],b={nbsp:" ",shy:""},c;for(c in b)a.push(c);a=new RegExp("\x26("+a.join("|")+");","g");return function(c){return c.replace(a,
function(e,a){return b[a]})}}();CKEDITOR.BBCodeParser=function(){this._={bbcPartsRegex:/(?:\[([^\/\]=]*?)(?:=([^\]]*?))?\])|(?:\[\/([a-z]{1,16})\])/ig}};CKEDITOR.BBCodeParser.prototype={parse:function(a){for(var b,c,k=0;b=this._.bbcPartsRegex.exec(a);)if(c=b.index,c>k&&(k=a.substring(k,c),this.onText(k,1)),k=this._.bbcPartsRegex.lastIndex,(c=(b[1]||b[3]||"").toLowerCase())&&!l[c])this.onText(b[0]);else if(b[1]){var e=l[c],g={},h={};b=b[2];if("left"==c||"right"==c||"center"==c||"justify"==c)b=c;if(b)if("list"==
c&&(isNaN(b)?/^[a-z]+$/.test(b)?b="lower-alpha":/^[A-Z]+$/.test(b)&&(b="upper-alpha"):b="decimal"),y[c]){"size"==c&&(b+="%");h[y[c]]=b;b=g;var f="",d=void 0;for(d in h)var u=(d+":"+h[d]).replace(C,";"),f=f+u;b.style=f}else z[c]&&(g[z[c]]=CKEDITOR.tools.htmlDecode(b));if("email"==c||"img"==c)g.bbcode=c;this.onTagOpen(e,g,CKEDITOR.dtd.$empty[e])}else if(b[3])this.onTagClose(l[c]);if(a.length>k)this.onText(a.substring(k,a.length),1)}};CKEDITOR.htmlParser.fragment.fromBBCode=function(a){function b(e){if(0<
h.length)for(var a=0;a<h.length;a++){var b=h[a],c=b.name,g=CKEDITOR.dtd[c],f=d.name&&CKEDITOR.dtd[d.name];f&&!f[c]||e&&g&&!g[e]&&CKEDITOR.dtd[e]||(b=b.clone(),b.parent=d,d=b,h.splice(a,1),a--)}}function c(a,e){var b=d.children.length,c=0<b&&d.children[b-1],b=!c&&v.getRule(m[d.name],"breakAfterOpen"),c=c&&c.type==CKEDITOR.NODE_ELEMENT&&v.getRule(m[c.name],"breakAfterClose"),g=a&&v.getRule(m[a],e?"breakBeforeClose":"breakBeforeOpen");f&&(b||c||g)&&f--;f&&a in A&&f++;for(;f&&f--;)d.children.push(new CKEDITOR.htmlParser.element("br"))}
function k(a,e){c(a.name,1);e=e||d||g;var b=e.children.length;a.previous=0<b&&e.children[b-1]||null;a.parent=e;e.children.push(a);a.returnPoint&&(d=a.returnPoint,delete a.returnPoint)}var e=new CKEDITOR.BBCodeParser,g=new CKEDITOR.htmlParser.fragment,h=[],f=0,d=g,u;e.onTagOpen=function(a,g){var f=new CKEDITOR.htmlParser.element(a,g);if(CKEDITOR.dtd.$removeEmpty[a])h.push(f);else{var w=d.name,p=w&&(CKEDITOR.dtd[w]||(d._.isBlockLike?CKEDITOR.dtd.div:CKEDITOR.dtd.span));if(p&&!p[a]){var p=!1,l;a==w?
k(d,d.parent):(a in CKEDITOR.dtd.$listItem?(e.onTagOpen("ul",{}),l=d):(k(d,d.parent),h.unshift(d)),p=!0);d=l?l:d.returnPoint||d.parent;if(p){e.onTagOpen.apply(this,arguments);return}}b(a);c(a);f.parent=d;f.returnPoint=u;u=0;f.isEmpty?k(f):d=f}};e.onTagClose=function(a){for(var e=h.length-1;0<=e;e--)if(a==h[e].name){h.splice(e,1);return}for(var b=[],c=[],g=d;g.type&&g.name!=a;)g._.isBlockLike||c.unshift(g),b.push(g),g=g.parent;if(g.type){for(e=0;e<b.length;e++)a=b[e],k(a,a.parent);d=g;k(g,g.parent);
g==d&&(d=d.parent);h=h.concat(c)}};e.onText=function(a){var e=CKEDITOR.dtd[d.name];if(!e||e["#"])c(),b(),a.replace(/(\r\n|[\r\n])|[^\r\n]*/g,function(a,e){if(void 0!==e&&e.length)f++;else if(a.length){var b=0;a.replace(r,function(e,c){k(new CKEDITOR.htmlParser.text(a.substring(b,c)),d);k(new CKEDITOR.htmlParser.element("smiley",{desc:B[e]}),d);b=c+e.length});b!=a.length&&k(new CKEDITOR.htmlParser.text(a.substring(b,a.length)),d)}})};for(e.parse(CKEDITOR.tools.htmlEncode(a));d.type!=CKEDITOR.NODE_DOCUMENT_FRAGMENT;)a=
d.parent,k(d,a),d=a;return g};var v=new (CKEDITOR.tools.createClass({$:function(){this._={output:[],rules:[]};this.setRules("list",{breakBeforeOpen:1,breakAfterOpen:1,breakBeforeClose:1,breakAfterClose:1});this.setRules("*",{breakBeforeOpen:1,breakAfterOpen:0,breakBeforeClose:1,breakAfterClose:0});this.setRules("quote",{breakBeforeOpen:1,breakAfterOpen:0,breakBeforeClose:0,breakAfterClose:1})},proto:{setRules:function(a,b){var c=this._.rules[a];c?CKEDITOR.tools.extend(c,b,!0):this._.rules[a]=b},getRule:function(a,
b){return this._.rules[a]&&this._.rules[a][b]},openTag:function(a){a in l&&(this.getRule(a,"breakBeforeOpen")&&this.lineBreak(1),this.write("[",a))},openTagClose:function(a){"br"==a?this._.output.push("\n"):a in l&&(this.write("]"),this.getRule(a,"breakAfterOpen")&&this.lineBreak(1))},attribute:function(a,b){"option"==a&&this.write("\x3d",b)},closeTag:function(a){a in l&&(this.getRule(a,"breakBeforeClose")&&this.lineBreak(1),"*"!=a&&this.write("[/",a,"]"),this.getRule(a,"breakAfterClose")&&this.lineBreak(1))},
text:function(a){this.write(a)},comment:function(){},lineBreak:function(){!this._.hasLineBreak&&this._.output.length&&(this.write("\n"),this._.hasLineBreak=1)},write:function(){this._.hasLineBreak=0;var a=Array.prototype.join.call(arguments,"");this._.output.push(a)},reset:function(){this._.output=[];this._.hasLineBreak=0},getHtml:function(a){var b=this._.output.join("");a&&this.reset();return D(b)}}}));CKEDITOR.plugins.add("bbcode",{requires:"entities",beforeInit:function(a){CKEDITOR.tools.extend(a.config,
{enterMode:CKEDITOR.ENTER_BR,basicEntities:!1,entities:!1,fillEmptyBlocks:!1},!0);a.filter.disable();a.activeEnterMode=a.enterMode=CKEDITOR.ENTER_BR},init:function(a){function b(a){var b=a.data;a=CKEDITOR.htmlParser.fragment.fromBBCode(a.data.dataValue);var c=new CKEDITOR.htmlParser.basicWriter;a.writeHtml(c,k);a=c.getHtml(!0);b.dataValue=a}var c=a.config,k=new CKEDITOR.htmlParser.filter;k.addRules({elements:{blockquote:function(a){var b=new CKEDITOR.htmlParser.element("div");b.children=a.children;
a.children=[b];if(b=a.attributes.cite){var c=new CKEDITOR.htmlParser.element("cite");c.add(new CKEDITOR.htmlParser.text(b.replace(/^"|"$/g,"")));delete a.attributes.cite;a.children.unshift(c)}},span:function(a){var b;if(b=a.attributes.bbcode)"img"==b?(a.name="img",a.attributes.src=a.children[0].value,a.children=[]):"email"==b&&(a.name="a",a.attributes.href="mailto:"+a.children[0].value),delete a.attributes.bbcode},ol:function(a){a.attributes.listType?"decimal"!=a.attributes.listType&&(a.attributes.style=
"list-style-type:"+a.attributes.listType):a.name="ul";delete a.attributes.listType},a:function(a){a.attributes.href||(a.attributes.href=a.children[0].value)},smiley:function(a){a.name="img";var b=a.attributes.desc,h=c.smiley_images[CKEDITOR.tools.indexOf(c.smiley_descriptions,b)],h=CKEDITOR.tools.htmlEncode(c.smiley_path+h);a.attributes={src:h,"data-cke-saved-src":h,title:b,alt:b}}}});a.dataProcessor.htmlFilter.addRules({elements:{$:function(b){var c=b.attributes,h=CKEDITOR.tools.parseCssText(c.style,
1),f,d=b.name;if(d in x)d=x[d];else if("span"==d)if(f=h.color)d="color",f=CKEDITOR.tools.convertRgbToHex(f);else{if(f=h["font-size"])if(c=f.match(/(\d+)%$/))f=c[1],d="size"}else if("ol"==d||"ul"==d){if(f=h["list-style-type"])switch(f){case "lower-alpha":f="a";break;case "upper-alpha":f="A"}else"ol"==d&&(f=1);d="list"}else if("blockquote"==d){try{var k=b.children[0],l=b.children[1],m="cite"==k.name&&k.children[0].value;m&&(f='"'+m+'"',b.children=l.children)}catch(n){}d="quote"}else if("a"==d){if(f=
c.href)-1!==f.indexOf("mailto:")?(d="email",b.children=[new CKEDITOR.htmlParser.text(f.replace("mailto:",""))],f=""):((d=1==b.children.length&&b.children[0])&&d.type==CKEDITOR.NODE_TEXT&&d.value==f&&(f=""),d="url")}else if("img"==d){b.isEmpty=0;h=c["data-cke-saved-src"]||c.src;c=c.alt;if(h&&-1!=h.indexOf(a.config.smiley_path)&&c)return new CKEDITOR.htmlParser.text(q[c]);b.children=[new CKEDITOR.htmlParser.text(h)]}b.name=d;f&&(b.attributes.option=f);return null},div:function(a){var b=CKEDITOR.tools.parseCssText(a.attributes.style,
1)["text-align"]||"";if(b)return a.name=b,null},br:function(a){if((a=a.next)&&a.name in A)return!1}}},1);a.dataProcessor.writer=v;if(a.elementMode==CKEDITOR.ELEMENT_MODE_INLINE)a.once("contentDom",function(){a.on("setData",b)});else a.on("setData",b)},afterInit:function(a){var b;a._.elementsPath&&(b=a._.elementsPath.filters)&&b.push(function(b){var k=b.getName(),e=m[k]||!1;"link"==e&&0===b.getAttribute("href").indexOf("mailto:")?e="email":"span"==k?b.getStyle("font-size")?e="size":b.getStyle("color")&&
(e="color"):"div"==k&&b.getStyle("text-align")?e=b.getStyle("text-align"):"img"==e&&(b=b.data("cke-saved-src")||b.getAttribute("src"))&&0===b.indexOf(a.config.smiley_path)&&(e="smiley");return e})}})})(); | cmos3511/cmos_linux | python/op/op_site/op_static/npm/node_modules/ckeditor/plugins/bbcode/plugin.js | JavaScript | gpl-3.0 | 9,603 |
-----------------------------------------------------------------------
-- DO NOT EDIT THIS FILE. IT IS AUTOGENERATED --
-- Edit the original file in the macroed_functions directory instead --
-----------------------------------------------------------------------
-- Generated by Ora2Pg, the Oracle database Schema converter, version 11.4
-- Copyright 2000-2013 Gilles DAROLD. All rights reserved.
-- DATASOURCE: dbi:Oracle:host=mydb.mydom.fr;sid=SIDNAME
CREATE OR REPLACE FUNCTION tm_cz.rwg_create_analysis_entry (
trialID text,
delete_flag text DEFAULT null,
currentJobID bigint DEFAULT null
)
RETURNS BIGINT AS $body$
DECLARE
--Audit variables
newJobFlag smallint;
databaseName varchar(100);
procedureName varchar(100);
jobID bigint;
stepCt bigint;
rowCt bigint;
errorNumber varchar;
errorMessage varchar;
Cdelete CURSOR FOR
SELECT
DISTINCT ( baa.bio_assay_analysis_id )
FROM
Biomart.bio_assay_analysis baa
WHERE
UPPER ( baa.etl_id ) LIKE ( UPPER ( trialID ) || ':%' );
cDeleteRow record;
BEGIN
--Set Audit Parameters
newJobFlag := 0; -- False (Default)
jobID := currentJobID;
SELECT current_user INTO databaseName; --(sic)
procedureName := 'RWG_CREATE_ANALYSIS_ENTRY';
--Audit JOB Initialization
--If Job ID does not exist, then this is a single procedure run and we need to create it
IF (coalesce(jobID::text, '') = '' OR jobID < 1)
THEN
newJobFlag := 1; -- True
SELECT cz_start_audit(procedureName, databaseName) INTO jobID;
END IF;
PERFORM cz_write_audit(jobId, databaseName, procedureName,
'Start FUNCTION', 0, stepCt, 'Done');
stepCt := 1;
-- If this flag is set to 'D', all study data from biomart.bio_assay_analysis and biomart.bio_assay_analysis_data
IF upper(delete_flag) = 'D' THEN
PERFORM cz_write_audit(jobId,databaseName,procedureName,'Start Delete bio_assay_analysis_data Loop',0,stepCt,'Done');
stepCt := stepCt + 1;
FOR Cdeleterow IN Cdelete LOOP
BEGIN
DELETE
FROM
biomart.bio_assay_analysis_data baad
WHERE
baad.bio_assay_analysis_id = cDeleteRow.bio_assay_analysis_id;
GET DIAGNOSTICS rowCt := ROW_COUNT;
PERFORM cz_write_audit(jobId, databaseName, procedureName,
'Delete records for analysis: ' || cDeleteRow.bio_assay_analysis_id, rowCt, stepCt, 'Done');
stepCt := stepCt + 1;
EXCEPTION
WHEN OTHERS THEN
errorNumber := SQLSTATE;
errorMessage := SQLERRM;
PERFORM cz_error_handler(jobID, procedureName, errorNumber, errorMessage);
PERFORM cz_end_audit (jobID, 'FAIL');
RETURN -16;
END;
END LOOP;
BEGIN
DELETE
FROM
Biomart.bio_assay_analysis baa
WHERE UPPER ( baa.etl_id ) LIKE ( UPPER ( trialID ) || ':%' );
GET DIAGNOSTICS rowCt := ROW_COUNT;
PERFORM cz_write_audit(jobId, databaseName, procedureName,
'Delete existing records from Biomart.bio_assay_analysis', rowCt, stepCt, 'Done');
stepCt := stepCt + 1;
EXCEPTION
WHEN OTHERS THEN
errorNumber := SQLSTATE;
errorMessage := SQLERRM;
PERFORM cz_error_handler(jobID, procedureName, errorNumber, errorMessage);
PERFORM cz_end_audit (jobID, 'FAIL');
RETURN -16;
END;
END IF;
BEGIN
INSERT INTO Biomart.Bio_Assay_Analysis (
ANALYSIS_NAME,
Short_Description,
Long_Description,
Fold_Change_Cutoff,
Pvalue_Cutoff,
lsmean_cutoff,
Analysis_Method_Cd,
Bio_Assay_Data_Type,
Etl_Id,
Qa_Criteria,
analysis_create_date,
analysis_update_date )
SELECT
rwg.analysis_id,
rwg.Short_Desc,
rwg.Long_Desc,
rwg.foldchange_cutoff,
pvalue_cutoff,
lsmean_cutoff,
--fold_change, pvalue, lsmean cutoffs
rwg.Analysis_Type,
rwg.Data_Type,
rwg.study_id || 'RWG',
'(Abs(fold Change) > ' || rwg.foldchange_cutoff || ' OR coalesce(fold_change::text, '') = '')' || ' AND pvalue < ' || pvalue_cutoff || ' AND Max(LSMean) >' || lsmean_cutoff,
now(),
now()
FROM
tm_lz.rwg_analysis rwg
WHERE
UPPER ( rwg.study_id ) = UPPER ( trialID );
GET DIAGNOSTICS rowCt := ROW_COUNT;
PERFORM cz_write_audit(jobId, databaseName, procedureName,
'Insert records into Biomart.Bio_Assay_Analysis', rowCt, stepCt, 'Done');
stepCt := stepCt + 1;
EXCEPTION
WHEN OTHERS THEN
errorNumber := SQLSTATE;
errorMessage := SQLERRM;
PERFORM cz_error_handler(jobID, procedureName, errorNumber, errorMessage);
PERFORM cz_end_audit (jobID, 'FAIL');
RETURN -16;
END;
/* Update tm_lz.Rwg_Analysis with the newly created bio_assay_analysis_Id */
BEGIN
UPDATE tm_lz.Rwg_Analysis rwg
SET
rwg.bio_assay_analysis_id = (
SELECT
baa.bio_assay_analysis_id
FROM
Biomart.Bio_Assay_Analysis baa
WHERE
baa.analysis_name = rwg.analysis_id
AND UPPER ( baa.etl_id ) LIKE UPPER ( trialID || ':%' )
AND UPPER ( rwg.study_id ) LIKE UPPER ( trialID ) )
WHERE
UPPER ( rwg.study_id ) LIKE UPPER ( trialID );
GET DIAGNOSTICS rowCt := ROW_COUNT;
PERFORM cz_write_audit(jobId, databaseName, procedureName,
'Update records in tm_lz.Rwg_Analysis with bio_assay_analysis_id ', rowCt, stepCt, 'Done');
stepCt := stepCt + 1;
EXCEPTION
WHEN OTHERS THEN
errorNumber := SQLSTATE;
errorMessage := SQLERRM;
PERFORM cz_error_handler(jobID, procedureName, errorNumber, errorMessage);
PERFORM cz_end_audit (jobID, 'FAIL');
RETURN -16;
END;
PERFORM cz_write_audit(jobId,databaseName,procedureName,'FUNCTION Complete',0,stepCt,'Done');
RETURN 0;
---Cleanup OVERALL JOB if this proc is being run standalone
IF newJobFlag = 1
THEN
PERFORM cz_end_audit (jobID, 'SUCCESS');
END IF;
EXCEPTION
WHEN OTHERS THEN
errorNumber := SQLSTATE;
errorMessage := SQLERRM;
PERFORM cz_error_handler(jobID, procedureName, errorNumber, errorMessage);
PERFORM cz_end_audit (jobID, 'FAIL');
RETURN -16;
END;
$body$
LANGUAGE PLPGSQL;
| tranSMART-Foundation/transmart-data | ddl/postgres/tm_cz/functions/rwg_create_analysis_entry.sql | SQL | gpl-3.0 | 5,727 |
declare module Virtex {
interface IOptions {
ambientLightColor: number;
cameraZ: number;
directionalLight1Color: number;
directionalLight1Intensity: number;
directionalLight2Color: number;
directionalLight2Intensity: number;
doubleSided: boolean;
element: string;
fadeSpeed: number;
far: number;
fov: number;
maxZoom: number;
minZoom: number;
near: number;
object: string;
shading: THREE.Shading;
shininess: number;
showStats: boolean;
zoomSpeed: number;
}
}
interface IVirtex {
create: (options: Virtex.IOptions) => Virtex.Viewport;
}
declare var Detector: any;
declare var Stats: any;
declare var requestAnimFrame: any;
declare module Virtex {
class Viewport {
options: IOptions;
private _$element;
private _$viewport;
private _$loading;
private _$loadingBar;
private _$oldie;
private _camera;
private _lightGroup;
private _modelGroup;
private _renderer;
private _scene;
private _stats;
private _viewportHalfX;
private _viewportHalfY;
private _isMouseDown;
private _mouseX;
private _mouseXOnMouseDown;
private _mouseY;
private _mouseYOnMouseDown;
private _pinchStart;
private _targetRotationOnMouseDownX;
private _targetRotationOnMouseDownY;
private _targetRotationX;
private _targetRotationY;
private _targetZoom;
constructor(options: IOptions);
private _init();
private _loadProgress(progress);
private _onMouseDown(event);
private _onMouseMove(event);
private _onMouseUp(event);
private _onMouseOut(event);
private _onMouseWheel(event);
private _onTouchStart(event);
private _onTouchMove(event);
private _onTouchEnd(event);
private _draw();
private _render();
private _getWidth();
private _getHeight();
zoomIn(): void;
zoomOut(): void;
private _resize();
}
}
| perryrothjohnson/artifact-database | pawtucket/assets/universalviewer/src/typings/virtex.d.ts | TypeScript | gpl-3.0 | 2,184 |
using System.Windows.Forms;
using GitUIPluginInterfaces;
using ResourceManager;
namespace ReleaseNotesGenerator
{
public class ReleaseNotesGeneratorPlugin : GitPluginBase
{
public ReleaseNotesGeneratorPlugin()
{
SetNameAndDescription("Release Notes Generator");
Translate();
}
public override bool Execute(GitUIBaseEventArgs gitUiCommands)
{
using (var form = new ReleaseNotesGeneratorForm(gitUiCommands))
{
if (form.ShowDialog(gitUiCommands.OwnerForm) == DialogResult.OK)
{
return true;
}
}
return false;
}
}
}
| ArsenShnurkov/gitextensions | Plugins/ReleaseNotesGenerator/ReleaseNotesGeneratorPlugin.cs | C# | gpl-3.0 | 718 |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""Implement standard (and unused) TCP protocols.
These protocols are either provided by inetd, or are not provided at all.
"""
from __future__ import absolute_import, division
import time
import struct
from zope.interface import implementer
from twisted.internet import protocol, interfaces
from twisted.python.compat import _PY3
class Echo(protocol.Protocol):
"""As soon as any data is received, write it back (RFC 862)"""
def dataReceived(self, data):
self.transport.write(data)
class Discard(protocol.Protocol):
"""Discard any received data (RFC 863)"""
def dataReceived(self, data):
# I'm ignoring you, nyah-nyah
pass
@implementer(interfaces.IProducer)
class Chargen(protocol.Protocol):
"""Generate repeating noise (RFC 864)"""
noise = r'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !"#$%&?'
def connectionMade(self):
self.transport.registerProducer(self, 0)
def resumeProducing(self):
self.transport.write(self.noise)
def pauseProducing(self):
pass
def stopProducing(self):
pass
class QOTD(protocol.Protocol):
"""Return a quote of the day (RFC 865)"""
def connectionMade(self):
self.transport.write(self.getQuote())
self.transport.loseConnection()
def getQuote(self):
"""Return a quote. May be overrriden in subclasses."""
return "An apple a day keeps the doctor away.\r\n"
class Who(protocol.Protocol):
"""Return list of active users (RFC 866)"""
def connectionMade(self):
self.transport.write(self.getUsers())
self.transport.loseConnection()
def getUsers(self):
"""Return active users. Override in subclasses."""
return "root\r\n"
class Daytime(protocol.Protocol):
"""Send back the daytime in ASCII form (RFC 867)"""
def connectionMade(self):
self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n')
self.transport.loseConnection()
class Time(protocol.Protocol):
"""Send back the time in machine readable form (RFC 868)"""
def connectionMade(self):
# is this correct only for 32-bit machines?
result = struct.pack("!i", int(time.time()))
self.transport.write(result)
self.transport.loseConnection()
__all__ = ["Echo", "Discard", "Chargen", "QOTD", "Who", "Daytime", "Time"]
if _PY3:
__all3__ = ["Echo"]
for name in __all__[:]:
if name not in __all3__:
__all__.remove(name)
del globals()[name]
del name, __all3__
| Architektor/PySnip | venv/lib/python2.7/site-packages/twisted/protocols/wire.py | Python | gpl-3.0 | 2,659 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The `MozMap` (open-ended dictionary) type.
use dom::bindings::conversions::jsid_to_string;
use dom::bindings::str::DOMString;
use js::conversions::{FromJSValConvertible, ToJSValConvertible, ConversionResult};
use js::jsapi::GetPropertyKeys;
use js::jsapi::HandleValue;
use js::jsapi::JSContext;
use js::jsapi::JSITER_OWNONLY;
use js::jsapi::JSPROP_ENUMERATE;
use js::jsapi::JS_DefineUCProperty2;
use js::jsapi::JS_GetPropertyById;
use js::jsapi::JS_NewPlainObject;
use js::jsapi::MutableHandleValue;
use js::jsval::ObjectValue;
use js::jsval::UndefinedValue;
use js::rust::IdVector;
use std::collections::HashMap;
use std::ops::Deref;
/// The `MozMap` (open-ended dictionary) type.
#[derive(Clone)]
pub struct MozMap<T> {
map: HashMap<DOMString, T>,
}
impl<T> MozMap<T> {
/// Create an empty `MozMap`.
pub fn new() -> Self {
MozMap {
map: HashMap::new(),
}
}
}
impl<T> Deref for MozMap<T> {
type Target = HashMap<DOMString, T>;
fn deref(&self) -> &HashMap<DOMString, T> {
&self.map
}
}
impl<T, C> FromJSValConvertible for MozMap<T>
where T: FromJSValConvertible<Config=C>,
C: Clone,
{
type Config = C;
unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, config: C)
-> Result<ConversionResult<Self>, ()> {
if !value.is_object() {
return Ok(ConversionResult::Failure("MozMap value was not an object".into()));
}
rooted!(in(cx) let object = value.to_object());
let ids = IdVector::new(cx);
assert!(GetPropertyKeys(cx, object.handle(), JSITER_OWNONLY, ids.get()));
let mut map = HashMap::new();
for id in &*ids {
rooted!(in(cx) let id = *id);
rooted!(in(cx) let mut property = UndefinedValue());
if !JS_GetPropertyById(cx, object.handle(), id.handle(), property.handle_mut()) {
return Err(());
}
let property = match try!(T::from_jsval(cx, property.handle(), config.clone())) {
ConversionResult::Success(property) => property,
ConversionResult::Failure(message) => return Ok(ConversionResult::Failure(message)),
};
let key = jsid_to_string(cx, id.handle()).unwrap();
map.insert(key, property);
}
Ok(ConversionResult::Success(MozMap {
map: map,
}))
}
}
impl<T: ToJSValConvertible> ToJSValConvertible for MozMap<T> {
#[inline]
unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
rooted!(in(cx) let js_object = JS_NewPlainObject(cx));
assert!(!js_object.handle().is_null());
rooted!(in(cx) let mut js_value = UndefinedValue());
for (key, value) in &self.map {
let key = key.encode_utf16().collect::<Vec<_>>();
value.to_jsval(cx, js_value.handle_mut());
assert!(JS_DefineUCProperty2(cx,
js_object.handle(),
key.as_ptr(),
key.len(),
js_value.handle(),
JSPROP_ENUMERATE,
None,
None));
}
rval.set(ObjectValue(&*js_object.handle().get()));
}
}
| bbansalWolfPack/servo | components/script/dom/bindings/mozmap.rs | Rust | mpl-2.0 | 3,635 |
/* Bitset vectors.
Copyright (C) 2002, 2004, 2009-2013 Free Software Foundation, Inc.
Contributed by Michael Hayes (m.hayes@elec.canterbury.ac.nz).
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/>. */
#ifndef _BITSETV_H
#define _BITSETV_H
#include "bitset.h"
typedef bitset * bitsetv;
/* Create a vector of N_VECS bitsets, each of N_BITS, and of
type TYPE. */
extern bitsetv bitsetv_alloc (bitset_bindex, bitset_bindex, enum bitset_type);
/* Create a vector of N_VECS bitsets, each of N_BITS, and with
attribute hints specified by ATTR. */
extern bitsetv bitsetv_create (bitset_bindex, bitset_bindex, unsigned int);
/* Free vector of bitsets. */
extern void bitsetv_free (bitsetv);
/* Zero vector of bitsets. */
extern void bitsetv_zero (bitsetv);
/* Set vector of bitsets. */
extern void bitsetv_ones (bitsetv);
/* Given a vector BSETV of N bitsets of size N, modify its contents to
be the transitive closure of what was given. */
extern void bitsetv_transitive_closure (bitsetv);
/* Given a vector BSETV of N bitsets of size N, modify its contents to
be the reflexive transitive closure of what was given. This is
the same as transitive closure but with all bits on the diagonal
of the bit matrix set. */
extern void bitsetv_reflexive_transitive_closure (bitsetv);
/* Dump vector of bitsets. */
extern void bitsetv_dump (FILE *, const char *, const char *, bitsetv);
/* Function to debug vector of bitsets from debugger. */
extern void debug_bitsetv (bitsetv);
#endif /* _BITSETV_H */
| evilmucedin/tomita-parser | src/contrib/tools/bison/gnulib/src/bitsetv.h | C | mpl-2.0 | 2,132 |
/**
* @file
* @copyright 2020 Aleksej Komarov
* @license MIT
*/
// Themes
import './styles/main.scss';
import './styles/themes/abductor.scss';
import './styles/themes/cardtable.scss';
import './styles/themes/hackerman.scss';
import './styles/themes/malfunction.scss';
import './styles/themes/neutral.scss';
import './styles/themes/ntos.scss';
import './styles/themes/paper.scss';
import './styles/themes/retro.scss';
import './styles/themes/syndicate.scss';
import './styles/themes/wizard.scss';
import { perf } from 'common/perf';
import { setupHotReloading } from 'tgui-dev-server/link/client';
import { setupHotKeys } from './hotkeys';
import { captureExternalLinks } from './links';
import { createRenderer } from './renderer';
import { configureStore, StoreProvider } from './store';
import { setupGlobalEvents } from './events';
perf.mark('inception', window.performance?.timing?.navigationStart);
perf.mark('init');
const store = configureStore();
const renderApp = createRenderer(() => {
const { getRoutedComponent } = require('./routes');
const Component = getRoutedComponent(store);
return (
<StoreProvider store={store}>
<Component />
</StoreProvider>
);
});
const setupApp = () => {
// Delay setup
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', setupApp);
return;
}
setupGlobalEvents();
setupHotKeys();
captureExternalLinks();
// Subscribe for state updates
store.subscribe(renderApp);
// Dispatch incoming messages
window.update = msg => store.dispatch(Byond.parseJson(msg));
// Process the early update queue
while (true) {
const msg = window.__updateQueue__.shift();
if (!msg) {
break;
}
window.update(msg);
}
// Enable hot module reloading
if (module.hot) {
setupHotReloading();
module.hot.accept([
'./components',
'./debug',
'./layouts',
'./routes',
], () => {
renderApp();
});
}
};
setupApp();
| optimumtact/-tg-station | tgui/packages/tgui/index.js | JavaScript | agpl-3.0 | 1,998 |
(function() {
'use strict';
Features.$inject = ['urls'];
function Features(urls) {
var self = this;
urls.links().then(function(links) {
angular.extend(self, links);
});
}
/**
* Provides info what features are available on server
*/
angular.module('superdesk.features', ['superdesk.api'])
.service('features', Features);
})();
| vladnicoara/superdesk-client-core | scripts/superdesk/features/features.js | JavaScript | agpl-3.0 | 355 |
/************************************************************************************
* arch/arm/src/sam34/sam4l_gpio.h
*
* Copyright (C) 2013 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* 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 NuttX nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
************************************************************************************/
#ifndef __ARCH_ARM_SRC_SAM34_SAM4L_GPIO_H
#define __ARCH_ARM_SRC_SAM34_SAM4L_GPIO_H
/************************************************************************************
* Included Files
************************************************************************************/
#include <nuttx/config.h>
/************************************************************************************
* Definitions
************************************************************************************/
/* Bit-encoded input to sam_configgpio() ********************************************/
/* 24-bit Encoding. This could be compacted into 16-bits by making the bit usage
* mode specific. However, by giving each bit field a unique position, we handle
* bad combinations of properties safely.
*
* MODE BITFIELDS
* ------------ -----------------------------
* 2222 1111 1111 1100 0000 0000
* 3210 9876 5432 1098 7654 3210
* ------------ -----------------------------
* GPIO Input: MMRR .... .... IIGT .PPB BBBB
* GPIO Output: MM.. .... DDSV .... .PPB BBBB
* Peripheral: MM.. FFFE .... IIG. .PPB BBBB
* ------------ -----------------------------
* MMRR FFFE DDSV IIGT .PPB BBBB
*/
/* Input/output/peripheral mode:
*
* MODE BITFIELDS
* ------------ -----------------------------
* 2222 1111 1111 1100 0000 0000
* 3210 9876 5432 1098 7654 3210
* ------------ -----------------------------
* GPIO Input: MM.. .... .... .... .... ....
* GPIO Output: MM.. .... .... .... .... ....
* Peripheral: MM.. .... .... .... .... ....
*/
#define GPIO_MODE_SHIFT (22) /* Bits 22-23: GPIO mode */
#define GPIO_MODE_MASK (3 << GPIO_MODE_SHIFT)
# define GPIO_INPUT (0 << GPIO_MODE_SHIFT) /* GPIO Input */
# define GPIO_OUTPUT (1 << GPIO_MODE_SHIFT) /* GPIO Output */
# define GPIO_PERIPHERAL (2 << GPIO_MODE_SHIFT) /* Controlled by peripheral */
# define GPIO_INTERRUPT (3 << GPIO_MODE_SHIFT) /* Interrupting input */
/* Pull-up/down resistor control for inputs
*
* MODE BITFIELDS
* ------------ -----------------------------
* 2222 1111 1111 1100 0000 0000
* 3210 9876 5432 1098 7654 3210
* ------------ -----------------------------
* GPIO Input: ..RR .... .... .... .... ....
* GPIO Output: .... .... .... .... .... ....
* Peripheral: .... .... .... .... .... ....
*/
#define GPIO_PULL_SHIFT (20) /* Bits 20-21: Pull-up/down resistor control */
#define GPIO_PULL_MASK (3 << GPIO_PULL_SHIFT)
# define GPIO_PULL_NONE (0 << GPIO_PULL_SHIFT)
# define GPIO_PULL_UP (1 << GPIO_PULL_SHIFT)
# define GPIO_PULL_DOWN (2 << GPIO_PULL_SHIFT)
# define GPIO_PULL_BUSKEEPER (3 << GPIO_PULL_SHIFT)
/* Peripheral Function
*
* MODE BITFIELDS
* ------------ -----------------------------
* 2222 1111 1111 1100 0000 0000
* 3210 9876 5432 1098 7654 3210
* ------------ -----------------------------
* GPIO Input: .... .... .... .... .... ....
* GPIO Output: .... .... .... .... .... ....
* Peripheral: .... FFF. .... .... .... ....
*/
#define GPIO_FUNC_SHIFT (17) /* Bits 17-19: Peripheral function */
#define GPIO_FUNC_MASK (7 << GPIO_FUNC_SHIFT)
# define _GPIO_FUNCA (0 << GPIO_FUNC_SHIFT) /* Function A */
# define _GPIO_FUNCB (1 << GPIO_FUNC_SHIFT) /* Function B */
# define _GPIO_FUNCC (2 << GPIO_FUNC_SHIFT) /* Function C */
# define _GPIO_FUNCD (3 << GPIO_FUNC_SHIFT) /* Function D */
# define _GPIO_FUNCE (4 << GPIO_FUNC_SHIFT) /* Function E */
# define _GPIO_FUNCF (5 << GPIO_FUNC_SHIFT) /* Function F */
# define _GPIO_FUNCG (6 << GPIO_FUNC_SHIFT) /* Function G */
# define _GPIO_FUNCH (7 << GPIO_FUNC_SHIFT) /* Function H */
/* Extended input/output/peripheral mode:
*
* MODE BITFIELDS
* ------------ -----------------------------
* 2222 1111 1111 1100 0000 0000
* 3210 9876 5432 1098 7654 3210
* ------------ -----------------------------
* GPIO Input: .... .... .... .... .... ....
* GPIO Output: .... .... .... .... .... ....
* Peripheral: MM.. FFF. .... .... .... ....
*/
#define GPIO_FUNCA (GPIO_PERIPHERAL | _GPIO_FUNCA) /* Function A */
#define GPIO_FUNCB (GPIO_PERIPHERAL | _GPIO_FUNCB) /* Function B */
#define GPIO_FUNCC (GPIO_PERIPHERAL | _GPIO_FUNCC) /* Function C */
#define GPIO_FUNCD (GPIO_PERIPHERAL | _GPIO_FUNCD) /* Function D */
#define GPIO_FUNCE (GPIO_PERIPHERAL | _GPIO_FUNCE) /* Function E */
#define GPIO_FUNCF (GPIO_PERIPHERAL | _GPIO_FUNCF) /* Function F */
#define GPIO_FUNCG (GPIO_PERIPHERAL | _GPIO_FUNCG) /* Function G */
#define GPIO_FUNCH (GPIO_PERIPHERAL | _GPIO_FUNCH) /* Function H */
/* Peripheral event control
*
* MODE BITFIELDS
* ------------ -----------------------------
* 2222 1111 1111 1100 0000 0000
* 3210 9876 5432 1098 7654 3210
* ------------ -----------------------------
* GPIO Input: .... .... .... .... .... ....
* GPIO Output: .... .... .... .... .... ....
* Peripheral: .... ...E .... .... .... ....
*/
#define GPIO_PERIPH_EVENTS (1 << 16) /* Bit 16: Enable peripheral events */
/* Output drive control
*
* MODE BITFIELDS
* ------------ -----------------------------
* 2222 1111 1111 1100 0000 0000
* 3210 9876 5432 1098 7654 3210
* ------------ -----------------------------
* GPIO Input: .... .... .... .... .... ....
* GPIO Output: .... .... DD.. .... .... ....
* Peripheral: .... .... .... .... .... ....
*/
#define GPIO_DRIVE_SHIFT (14) /* Bits 14-15: Interrupting input control */
#define GPIO_DRIVE_MASK (3 << GPIO_INT_SHIFT) /* Lowest drive strength*/
# define GPIO_DRIVE_LOW (0 << GPIO_INT_SHIFT)
# define GPIO_DRIVE_MEDLOW (1 << GPIO_INT_SHIFT)
# define GPIO_DRIVE_MEDHIGH (2 << GPIO_INT_SHIFT)
# define GPIO_DRIVE_HIGH (3 << GPIO_INT_SHIFT) /* Highest drive strength */
/* Output slew rate control
*
* MODE BITFIELDS
* ------------ -----------------------------
* 2222 1111 1111 1100 0000 0000
* 3210 9876 5432 1098 7654 3210
* ------------ -----------------------------
* GPIO Input: .... .... .... .... .... ....
* GPIO Output: .... .... ..S. .... .... ....
* Peripheral: .... .... .... .... .... ....
*/
#define GPIO_SLEW (1 << 13) /* Bit 13: Enable output slew control */
/* If the pin is an GPIO output, then this identifies the initial output value:
*
* MODE BITFIELDS
* ------------ -----------------------------
* 2222 1111 1111 1100 0000 0000
* 3210 9876 5432 1098 7654 3210
* ------------ -----------------------------
* GPIO Input: .... .... .... .... .... ....
* GPIO Output: .... .... ...V .... .... ....
* Peripheral: .... .... .... .... .... ....
*/
#define GPIO_OUTPUT_SET (1 << 12) /* Bit 12: Inital value of output */
#define GPIO_OUTPUT_CLEAR (0)
/* Selections for an interrupting input and peripheral events:
*
* MODE BITFIELDS
* ------------ -----------------------------
* 2222 1111 1111 1100 0000 0000
* 3210 9876 5432 1098 7654 3210
* ------------ -----------------------------
* GPIO Input: .... .... .... II.. .... ....
* GPIO Output: .... .... .... .... .... ....
* Peripheral: .... .... .... II.. .... ....
*/
#define GPIO_INT_SHIFT (10) /* Bits 10-11: Interrupting input control */
#define GPIO_INT_MASK (3 << GPIO_INT_SHIFT)
# define GPIO_INT_CHANGE (0 << GPIO_INT_SHIFT) /* Pin change */
# define GPIO_INT_RISING (1 << GPIO_INT_SHIFT) /* Rising edge */
# define GPIO_INT_FALLING (2 << GPIO_INT_SHIFT) /* Falling edge */
/* These combinations control events. These help to clean up pin definitions. */
#define GPIO_EVENT_CHANGE (GPIO_PERIPH_EVENTS | GPIO_INT_CHANGE) /* Pin change */
#define GPIO_EVENT_RISING (GPIO_PERIPH_EVENTS | GPIO_INT_RISING) /* Rising edge */
#define GPIO_EVENT_FALLING (GPIO_PERIPH_EVENTS | GPIO_INT_FALLING) /* Falling edge */
/* Enable input/periphal glitch filter
*
* MODE BITFIELDS
* ------------ -----------------------------
* 2222 1111 1111 1100 0000 0000
* 3210 9876 5432 1098 7654 3210
* ------------ -----------------------------
* GPIO Input: .... .... .... ..G. .... ....
* GPIO Output: .... .... .... .... .... ....
* Peripheral: .... .... .... ..G. .... ....
*/
#define GPIO_GLITCH_FILTER (1 << 9) /* Bit 9: Enable input/peripheral glitch filter */
/* Input Schmitt trigger
*
* MODE BITFIELDS
* ------------ -----------------------------
* 2222 1111 1111 1100 0000 0000
* 3210 9876 5432 1098 7654 3210
* ------------ -----------------------------
* GPIO Input: .... .... .... ...T .... ....
* GPIO Output: .... .... .... .... .... ....
* Peripheral: .... .... .... .... .... ....
*/
#define GPIO_SCHMITT_TRIGGER (1 << 8) /* Bit 8: Enable Input Schmitt trigger */
/* This identifies the GPIO port:
*
* MODE BITFIELDS
* ------------ -----------------------------
* 2222 1111 1111 1100 0000 0000
* 3210 9876 5432 1098 7654 3210
* ------------ -----------------------------
* GPIO Input: .... .... .... .... .PP. ....
* GPIO Output: .... .... .... .... .PP. ....
* Peripheral: .... .... .... .... .PP. ....
*/
#define GPIO_PORT_SHIFT (5) /* Bit 5-6: Port number */
#define GPIO_PORT_MASK (3 << GPIO_PORT_SHIFT)
# define GPIO_PORTA (0 << GPIO_PORT_SHIFT)
# define GPIO_PORTB (1 << GPIO_PORT_SHIFT)
# define GPIO_PORTC (2 << GPIO_PORT_SHIFT)
/* This identifies the bit in the port:
*
* MODE BITFIELDS
* ------------ -----------------------------
* 2222 1111 1111 1100 0000 0000
* 3210 9876 5432 1098 7654 3210
* ------------ -----------------------------
* GPIO Input: .... .... .... .... ...B BBBB
* GPIO Output: .... .... .... .... ...B BBBB
* Peripheral: .... .... .... .... ...B BBBB
*/
#define GPIO_PIN_SHIFT 0 /* Bits 0-4: GPIO number: 0-31 */
#define GPIO_PIN_MASK (31 << GPIO_PIN_SHIFT)
#define GPIO_PIN0 (0 << GPIO_PIN_SHIFT)
#define GPIO_PIN1 (1 << GPIO_PIN_SHIFT)
#define GPIO_PIN2 (2 << GPIO_PIN_SHIFT)
#define GPIO_PIN3 (3 << GPIO_PIN_SHIFT)
#define GPIO_PIN4 (4 << GPIO_PIN_SHIFT)
#define GPIO_PIN5 (5 << GPIO_PIN_SHIFT)
#define GPIO_PIN6 (6 << GPIO_PIN_SHIFT)
#define GPIO_PIN7 (7 << GPIO_PIN_SHIFT)
#define GPIO_PIN8 (8 << GPIO_PIN_SHIFT)
#define GPIO_PIN9 (9 << GPIO_PIN_SHIFT)
#define GPIO_PIN10 (10 << GPIO_PIN_SHIFT)
#define GPIO_PIN11 (11 << GPIO_PIN_SHIFT)
#define GPIO_PIN12 (12 << GPIO_PIN_SHIFT)
#define GPIO_PIN13 (13 << GPIO_PIN_SHIFT)
#define GPIO_PIN14 (14 << GPIO_PIN_SHIFT)
#define GPIO_PIN15 (15 << GPIO_PIN_SHIFT)
#define GPIO_PIN16 (16 << GPIO_PIN_SHIFT)
#define GPIO_PIN17 (17 << GPIO_PIN_SHIFT)
#define GPIO_PIN18 (18 << GPIO_PIN_SHIFT)
#define GPIO_PIN19 (19 << GPIO_PIN_SHIFT)
#define GPIO_PIN20 (20 << GPIO_PIN_SHIFT)
#define GPIO_PIN21 (21 << GPIO_PIN_SHIFT)
#define GPIO_PIN22 (22 << GPIO_PIN_SHIFT)
#define GPIO_PIN23 (23 << GPIO_PIN_SHIFT)
#define GPIO_PIN24 (24 << GPIO_PIN_SHIFT)
#define GPIO_PIN25 (25 << GPIO_PIN_SHIFT)
#define GPIO_PIN26 (26 << GPIO_PIN_SHIFT)
#define GPIO_PIN27 (27 << GPIO_PIN_SHIFT)
#define GPIO_PIN28 (28 << GPIO_PIN_SHIFT)
#define GPIO_PIN29 (29 << GPIO_PIN_SHIFT)
#define GPIO_PIN30 (30 << GPIO_PIN_SHIFT)
#define GPIO_PIN31 (31 << GPIO_PIN_SHIFT)
/************************************************************************************
* Public Types
************************************************************************************/
/* Must be big enough to hold the 24-bit encoding */
typedef uint32_t gpio_pinset_t;
/************************************************************************************
* Inline Functions
************************************************************************************/
#ifndef __ASSEMBLY__
/************************************************************************************
* Public Data
************************************************************************************/
#undef EXTERN
#if defined(__cplusplus)
#define EXTERN extern "C"
extern "C"
{
#else
#define EXTERN extern
#endif
/************************************************************************************
* Public Function Prototypes
************************************************************************************/
#undef EXTERN
#if defined(__cplusplus)
}
#endif
#endif /* __ASSEMBLY__ */
#endif /* __ARCH_ARM_SRC_SAM34_SAM4L_GPIO_H */
| BrewPi/firmware | platform/spark/firmware/hal/src/photon/wiced/RTOS/NuttX/ver7.8/arch/arm/src/sam34/sam4l_gpio.h | C | agpl-3.0 | 15,750 |
/*
Colorbox Core Style:
The following CSS is consistent between example themes and should not be altered.
*/
#colorbox, #cboxOverlay, #cboxWrapper {
position: absolute;
top: 0;
left: 0;
z-index: 9999;
overflow: hidden;
}
#cboxOverlay {
position: fixed;
width: 100%;
height: 100%;
}
#cboxMiddleLeft, #cboxBottomLeft {
clear: left;
}
#cboxContent {
position: relative;
}
#cboxLoadedContent {
overflow: auto;
-webkit-overflow-scrolling: touch;
}
#cboxTitle {
margin: 0;
}
#cboxLoadingOverlay, #cboxLoadingGraphic {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
#cboxPrevious, #cboxNext, #cboxClose, #cboxSlideshow {
cursor: pointer;
}
.cboxPhoto {
float: left;
margin: auto;
border: 0;
display: block;
max-width: none;
-ms-interpolation-mode: bicubic;
}
.cboxIframe {
width: 100%;
height: 100%;
display: block;
border: 0;
}
#colorbox, #cboxContent, #cboxLoadedContent {
box-sizing: content-box;
-moz-box-sizing: content-box;
-webkit-box-sizing: content-box;
}
/*
User Style:
Change the following styles to modify the appearance of Colorbox. They are
ordered & tabbed in a way that represents the nesting of the generated HTML.
*/
#cboxOverlay {
background: #000;
}
#colorbox {
outline: 0;
}
#cboxTopLeft {
width: 14px;
height: 14px;
background: url(images/controls.png) no-repeat 0 0;
}
#cboxTopCenter {
height: 14px;
background: url(images/border.png) repeat-x top left;
}
#cboxTopRight {
width: 14px;
height: 14px;
background: url(images/controls.png) no-repeat -36px 0;
}
#cboxBottomLeft {
width: 14px;
height: 43px;
background: url(images/controls.png) no-repeat 0 -32px;
}
#cboxBottomCenter {
height: 43px;
background: url(images/border.png) repeat-x bottom left;
}
#cboxBottomRight {
width: 14px;
height: 43px;
background: url(images/controls.png) no-repeat -36px -32px;
}
#cboxMiddleLeft {
width: 14px;
background: url(images/controls.png) repeat-y -175px 0;
}
#cboxMiddleRight {
width: 14px;
background: url(images/controls.png) repeat-y -211px 0;
}
#cboxContent {
background: #FFF;
overflow: visible;
}
.cboxIframe {
background: #FFF;
}
#cboxError {
padding: 50px;
border: 1px solid #CCC;
}
#cboxLoadedContent {
margin-bottom: 5px;
}
#cboxLoadingOverlay {
background: url(images/loading_background.png) no-repeat center center;
}
#cboxLoadingGraphic {
background: url(images/loading.gif) no-repeat center center;
}
#cboxTitle {
position: absolute;
bottom: -25px;
left: 0;
text-align: center;
width: 100%;
font-weight: bold;
color: #7C7C7C;
}
#cboxCurrent {
position: absolute;
bottom: -25px;
left: 58px;
font-weight: bold;
color: #7C7C7C;
}
/* these elements are buttons, and may need to have additional styles reset to avoid unwanted base styles */
#cboxPrevious, #cboxNext, #cboxSlideshow, #cboxClose {
border: 0;
padding: 0;
margin: 0;
overflow: visible;
position: absolute;
bottom: -29px;
background: url(images/controls.png) no-repeat 0px 0px;
width: 23px;
height: 23px;
text-indent: -9999px;
}
/* avoid outlines on :active (mouseclick), but preserve outlines on :focus (tabbed navigating) */
#cboxPrevious:active, #cboxNext:active, #cboxSlideshow:active, #cboxClose:active {
outline: 0;
}
#cboxPrevious {
left: 0px;
background-position: -51px -25px;
}
#cboxPrevious:hover {
background-position: -51px 0px;
}
#cboxNext {
left: 27px;
background-position: -75px -25px;
}
#cboxNext:hover {
background-position: -75px 0px;
}
#cboxClose {
right: 0;
background-position: -100px -25px;
}
#cboxClose:hover {
background-position: -100px 0px;
}
.cboxSlideshow_on #cboxSlideshow {
background-position: -125px 0px;
right: 27px;
}
.cboxSlideshow_on #cboxSlideshow:hover {
background-position: -150px 0px;
}
.cboxSlideshow_off #cboxSlideshow {
background-position: -150px -25px;
right: 27px;
}
.cboxSlideshow_off #cboxSlideshow:hover {
background-position: -125px 0px;
}
| Sina30/PHP-Fusion-9.00 | includes/jquery/colorbox/colorbox.css | CSS | agpl-3.0 | 4,250 |
require File.dirname(__FILE__)+"/env"
module Actors
# /actors/worker
class Worker
include Magent::Actor
expose :echo
def echo(payload)
puts payload.inspect
end
end
Magent.register(Worker.new)
end
if $0 == __FILE__
Magent::Processor.new(Magent.current_actor).run!
end
| binarycode/shapado | app/actors/worker.rb | Ruby | agpl-3.0 | 303 |
UPDATE `version` SET `app_ver` = '1.4.0', `XmdsVersion` = 3;
UPDATE `setting` SET `value` = 0 WHERE `setting` = 'PHONE_HOME_DATE';
UPDATE `version` SET `DBVersion` = '50'; | jbirdkerr/xibo-cms | install/database/50.sql | SQL | agpl-3.0 | 172 |
# -*- coding: utf-8 -*-
# Copyright(C) 2014 Laurent Bachelier
#
# This file is part of weboob.
#
# weboob 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.
#
# weboob 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 weboob. If not, see <http://www.gnu.org/licenses/>.
import requests.cookies
try:
import cookielib
except ImportError:
import http.cookiejar as cookielib
__all__ = ['WeboobCookieJar']
class WeboobCookieJar(requests.cookies.RequestsCookieJar):
@classmethod
def from_cookiejar(klass, cj):
"""
Create a WeboobCookieJar from another CookieJar instance.
"""
return requests.cookies.merge_cookies(klass(), cj)
def export(self, filename):
"""
Export all cookies to a file, regardless of expiration, etc.
"""
cj = requests.cookies.merge_cookies(cookielib.LWPCookieJar(), self)
cj.save(filename, ignore_discard=True, ignore_expires=True)
def _cookies_from_attrs_set(self, attrs_set, request):
for tup in self._normalized_cookie_tuples(attrs_set):
cookie = self._cookie_from_cookie_tuple(tup, request)
if cookie:
yield cookie
def make_cookies(self, response, request):
"""Return sequence of Cookie objects extracted from response object."""
# get cookie-attributes for RFC 2965 and Netscape protocols
headers = response.info()
rfc2965_hdrs = headers.getheaders("Set-Cookie2")
ns_hdrs = headers.getheaders("Set-Cookie")
rfc2965 = self._policy.rfc2965
netscape = self._policy.netscape
if netscape:
for cookie in self._cookies_from_attrs_set(cookielib.parse_ns_headers(ns_hdrs), request):
self._process_rfc2109_cookies([cookie])
yield cookie
if rfc2965:
for cookie in self._cookies_from_attrs_set(cookielib.split_header_words(rfc2965_hdrs), request):
yield cookie
def copy(self):
new_cj = type(self)()
new_cj.update(self)
return new_cj
| Boussadia/weboob | weboob/tools/browser2/cookies.py | Python | agpl-3.0 | 2,534 |
<?php
/**
* @package Core
* @subpackage system
* @deprecated
*/
require_once ( __DIR__ . "/kalturaSystemAction.class.php" );
/**
* @package Core
* @subpackage system
* @deprecated
*/
class executeCommandAction extends kalturaSystemAction
{
// TODO - read from the entryWrapper
private static $allowed_names = array ( "conversionQuality" );
/**
* Will anipulate a single entry
*/
public function execute()
{
$this->forceSystemAuthentication();
myDbHelper::$use_alternative_con = null;
$command = $this->getP ( "command" );
if ( $command == "updateEntry" )
{
$id = $this->getP ( "id" );
$entry = entryPeer::retrieveByPK( $id );
if ( $entry )
{
$name = $this->getP ( "name" );
$value = $this->getP ( "value" );
$obj_wrapper = objectWrapperBase::getWrapperClass( $entry , 0 );
$updateable_fields = $obj_wrapper->getUpdateableFields( "2" );
if ( ! in_array ( $name , $updateable_fields ) ) die();
if ( $name )
{
$setter = "set" . $name;
call_user_func( array ( $entry , $setter ) , $value );
$entry->save();
}
}
}
die();
}
}
?> | ratliff/server | alpha/apps/kaltura/modules/system/actions/executeCommandAction.class.php | PHP | agpl-3.0 | 1,152 |
//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#pragma once
#include "MooseObjectAction.h"
/**
* Action that sets up BCs for porous flow module
*/
class PorousFlowAddBCAction : public MooseObjectAction
{
public:
static InputParameters validParams();
PorousFlowAddBCAction(const InputParameters & parameters);
virtual void act() override;
protected:
/**
* Setup a BC corresponding to hot/cold fluid injection
*/
void setupPorousFlowEnthalpySink();
};
| harterj/moose | modules/porous_flow/include/actions/PorousFlowAddBCAction.h | C | lgpl-2.1 | 743 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package org.jboss.as.test.manualmode.secman;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.manualmode.deployment.AbstractDeploymentScannerBasedTestCase;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.as.test.shared.TimeoutUtil;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.wildfly.core.testrunner.ServerControl;
import org.wildfly.core.testrunner.ServerController;
import org.wildfly.core.testrunner.WildflyTestRunner;
import javax.inject.Inject;
import java.io.File;
/**
* Tests the processing of {@code permissions.xml} in deployments
*
* @author Jaikiran Pai
*/
@RunWith(WildflyTestRunner.class)
@ServerControl(manual = true)
public class PermissionsDeploymentTestCase extends AbstractDeploymentScannerBasedTestCase {
private static final String SYS_PROP_SERVER_BOOTSTRAP_MAX_THREADS = "-Dorg.jboss.server.bootstrap.maxThreads=1";
@Rule
public TemporaryFolder tempDir = new TemporaryFolder();
@Inject
private ServerController container;
private ModelControllerClient modelControllerClient;
@Before
public void before() throws Exception {
modelControllerClient = TestSuiteEnvironment.getModelControllerClient();
}
@After
public void after() throws Exception {
modelControllerClient.close();
}
@Override
protected File getDeployDir() {
return this.tempDir.getRoot();
}
/**
* Tests that when the server is booted with {@code org.jboss.server.bootstrap.maxThreads} system property
* set (to whatever value), the deployment unit processors relevant for dealing with processing of {@code permissions.xml},
* in deployments, do run and process the deployment
* <p>
* NOTE: This test just tests that the deployment unit processor(s) process the deployment unit for the {@code permissions.xml}
* and it's not in the scope of this test to verify that the permissions configured in that file are indeed applied correctly
* to the deployment unit
*
* @throws Exception
* @see <a href="https://issues.jboss.org/browse/WFLY-6657">WFLY-6657</a>
*/
@Test
public void testWithConfiguredMaxBootThreads() throws Exception {
// Test-runner's ServerController/Server uses prop jvm.args to control what args are passed
// to the server process VM. So, we add the system property controlling the max boot threads,
// here
final String existingJvmArgs = System.getProperty("jvm.args");
if (existingJvmArgs == null) {
System.setProperty("jvm.args", SYS_PROP_SERVER_BOOTSTRAP_MAX_THREADS);
} else {
System.setProperty("jvm.args", existingJvmArgs + " " + SYS_PROP_SERVER_BOOTSTRAP_MAX_THREADS);
}
// start the container
container.start();
try {
addDeploymentScanner(modelControllerClient,1000, false, true);
this.testInvalidPermissionsXmlDeployment("test-permissions-xml-with-configured-max-boot-threads.jar");
} finally {
removeDeploymentScanner(modelControllerClient);
container.stop();
if (existingJvmArgs == null) {
System.clearProperty("jvm.args");
} else {
System.setProperty("jvm.args", existingJvmArgs);
}
}
}
/**
* Tests that when the server is booted *without* the {@code org.jboss.server.bootstrap.maxThreads} system property
* set, the deployment unit processors relevant for dealing with processing of {@code permissions.xml},
* in deployments, do run and process the deployment
* <p>
* NOTE: This test just tests that the deployment unit processor(s) process the deployment unit for the {@code permissions.xml}
* and it's not in the scope of this test to verify that the permissions configured in that file are indeed applied correctly
* to the deployment unit
*
* @throws Exception
* @see <a href="https://issues.jboss.org/browse/WFLY-6657">WFLY-6657</a>
*/
@Test
public void testWithoutConfiguredMaxBootThreads() throws Exception {
container.start();
try {
addDeploymentScanner(modelControllerClient,1000, false, true);
this.testInvalidPermissionsXmlDeployment("test-permissions-xml-without-max-boot-threads.jar");
} finally {
removeDeploymentScanner(modelControllerClient);
container.stop();
}
}
private void testInvalidPermissionsXmlDeployment(final String deploymentName) throws Exception {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class);
// add an empty (a.k.a invalid content) in permissions.xml
jar.addAsManifestResource(new StringAsset(""), "permissions.xml");
// "deploy" it by placing it in the deployment directory
jar.as(ZipExporter.class).exportTo(new File(getDeployDir(), deploymentName));
final PathAddress deploymentPathAddr = PathAddress.pathAddress(ModelDescriptionConstants.DEPLOYMENT, deploymentName);
// wait for the deployment to be picked up and completed (either with success or failure)
waitForDeploymentToFinish(deploymentPathAddr);
// the deployment is expected to fail due to a parsing error in the permissions.xml
Assert.assertEquals("Deployment was expected to fail", "FAILED", deploymentState(modelControllerClient, deploymentPathAddr));
}
private void waitForDeploymentToFinish(final PathAddress deploymentPathAddr) throws Exception {
// Wait until deployed ...
long timeout = System.currentTimeMillis() + TimeoutUtil.adjust(30000);
while (!exists(modelControllerClient, deploymentPathAddr) && System.currentTimeMillis() < timeout) {
Thread.sleep(100);
}
Assert.assertTrue(exists(modelControllerClient, deploymentPathAddr));
}
}
| aloubyansky/wildfly-core | testsuite/manualmode/src/test/java/org/jboss/as/test/manualmode/secman/PermissionsDeploymentTestCase.java | Java | lgpl-2.1 | 7,442 |
/**
*
* Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
**/
package lucee.runtime.type.comparator;
import java.util.Comparator;
import lucee.commons.lang.ComparatorUtil;
import lucee.runtime.PageContext;
import lucee.runtime.engine.ThreadLocalPageContext;
import lucee.runtime.exp.PageException;
import lucee.runtime.op.Caster;
/**
* Implementation of a Comparator, compares to Softregister Objects
*/
public final class SortRegisterComparator implements ExceptionComparator {
private boolean isAsc;
private PageException pageException=null;
private boolean ignoreCase;
private final Comparator comparator;
/**
* constructor of the class
* @param isAsc is ascending or descending
* @param ignoreCase do ignore case
*/
public SortRegisterComparator(PageContext pc,boolean isAsc, boolean ignoreCase, boolean localeSensitive) {
this.isAsc=isAsc;
this.ignoreCase=ignoreCase;
comparator = ComparatorUtil.toComparator(
ignoreCase?ComparatorUtil.SORT_TYPE_TEXT_NO_CASE:ComparatorUtil.SORT_TYPE_TEXT
, isAsc, localeSensitive?ThreadLocalPageContext.getLocale(pc):null, null);
}
/**
* @return Returns the expressionException.
*/
public PageException getPageException() {
return pageException;
}
@Override
public int compare(Object oLeft, Object oRight) {
try {
if(pageException!=null) return 0;
else if(isAsc) return compareObjects(oLeft, oRight);
else return compareObjects(oRight, oLeft);
} catch (PageException e) {
pageException=e;
return 0;
}
}
private int compareObjects(Object oLeft, Object oRight) throws PageException {
String strLeft=Caster.toString(((SortRegister)oLeft).getValue());
String strRight=Caster.toString(((SortRegister)oRight).getValue());
return comparator.compare(strLeft, strRight);
}
} | lucee/unoffical-Lucee-no-jre | source/java/core/src/lucee/runtime/type/comparator/SortRegisterComparator.java | Java | lgpl-2.1 | 2,517 |
/*
* Copyright (C) 2008-2014 The QXmpp developers
*
* Author:
* Manjeet Dahiya
*
* Source:
* https://github.com/qxmpp-project/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include "QXmppClient.h"
#include "QXmppConstants.h"
#include "QXmppUtils.h"
#include "QXmppVCardIq.h"
#include "QXmppVCardManager.h"
class QXmppVCardManagerPrivate
{
public:
QXmppVCardIq clientVCard;
bool isClientVCardReceived;
};
QXmppVCardManager::QXmppVCardManager()
: d(new QXmppVCardManagerPrivate)
{
d->isClientVCardReceived = false;
}
QXmppVCardManager::~QXmppVCardManager()
{
delete d;
}
/// This function requests the server for vCard of the specified jid.
/// Once received the signal vCardReceived() is emitted.
///
/// \param jid Jid of the specific entry in the roster
///
QString QXmppVCardManager::requestVCard(const QString& jid)
{
QXmppVCardIq request(jid);
if(client()->sendPacket(request))
return request.id();
else
return QString();
}
/// Returns the vCard of the connected client.
///
/// \return QXmppVCard
///
const QXmppVCardIq& QXmppVCardManager::clientVCard() const
{
return d->clientVCard;
}
/// Sets the vCard of the connected client.
///
/// \param clientVCard QXmppVCard
///
void QXmppVCardManager::setClientVCard(const QXmppVCardIq& clientVCard)
{
d->clientVCard = clientVCard;
d->clientVCard.setTo("");
d->clientVCard.setFrom("");
d->clientVCard.setType(QXmppIq::Set);
client()->sendPacket(d->clientVCard);
}
/// This function requests the server for vCard of the connected user itself.
/// Once received the signal clientVCardReceived() is emitted. Received vCard
/// can be get using clientVCard().
QString QXmppVCardManager::requestClientVCard()
{
return requestVCard();
}
/// Returns true if vCard of the connected client has been
/// received else false.
///
/// \return bool
///
bool QXmppVCardManager::isClientVCardReceived() const
{
return d->isClientVCardReceived;
}
/// \cond
QStringList QXmppVCardManager::discoveryFeatures() const
{
// XEP-0054: vcard-temp
return QStringList() << ns_vcard;
}
bool QXmppVCardManager::handleStanza(const QDomElement &element)
{
if(element.tagName() == "iq" && QXmppVCardIq::isVCard(element))
{
QXmppVCardIq vCardIq;
vCardIq.parse(element);
if (vCardIq.from().isEmpty()) {
d->clientVCard = vCardIq;
d->isClientVCardReceived = true;
emit clientVCardReceived();
}
emit vCardReceived(vCardIq);
return true;
}
return false;
}
/// \endcond
| gamenet/qxmpp | src/client/QXmppVCardManager.cpp | C++ | lgpl-2.1 | 3,127 |
using Nop.Web.Framework.Mvc;
namespace Nop.Admin.Models.Common
{
public partial class SystemWarningModel : BaseNopModel
{
public SystemWarningLevel Level { get; set; }
public string Text { get; set; }
}
public enum SystemWarningLevel
{
Pass,
Warning,
Fail
}
} | jornfilho/nopCommerce | source/Presentation/Nop.Web/Administration/Models/Common/SystemWarningModel.cs | C# | apache-2.0 | 329 |
/*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.services.backend.compiler;
import java.io.File;
import java.io.Serializable;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.kie.workbench.common.services.backend.compiler.impl.WorkspaceCompilationInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uberfire.java.nio.file.Files;
import org.uberfire.java.nio.file.Path;
import org.uberfire.java.nio.file.Paths;
public class BaseCompilerTest implements Serializable {
protected static Path tmpRoot;
protected String mavenRepoPath;
protected static Logger logger = LoggerFactory.getLogger(BaseCompilerTest.class);
protected String alternateSettingsAbsPath;
protected WorkspaceCompilationInfo info;
protected AFCompiler compiler;
@BeforeClass
public static void setup() {
System.setProperty("org.uberfire.nio.git.daemon.enabled", "false");
System.setProperty("org.uberfire.nio.git.ssh.enabled", "false");
}
public BaseCompilerTest(String prjName) {
try {
mavenRepoPath = TestUtilMaven.getMavenRepo();
tmpRoot = Files.createTempDirectory("repo");
alternateSettingsAbsPath = new File("src/test/settings.xml").getAbsolutePath();
Path tmp = Files.createDirectories(Paths.get(tmpRoot.toString(), "dummy"));
TestUtil.copyTree(Paths.get(prjName), tmp);
info = new WorkspaceCompilationInfo(Paths.get(tmp.toUri()));
} catch (Exception e) {
logger.error(e.getMessage());
}
}
@AfterClass
public static void tearDown() {
System.clearProperty("org.uberfire.nio.git.daemon.enabled");
System.clearProperty("org.uberfire.nio.git.ssh.enabled");
if (tmpRoot != null) {
TestUtil.rm(tmpRoot.toFile());
}
}
}
| jomarko/kie-wb-common | kie-wb-common-services/kie-wb-common-compiler/kie-wb-common-compiler-service/src/test/java/org/kie/workbench/common/services/backend/compiler/BaseCompilerTest.java | Java | apache-2.0 | 2,464 |
/*
* 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.ode.ql.tree.nodes;
public class Equality extends IdentifierToValueCMP {
private static final long serialVersionUID = 8151616227509392901L;
/**
* @param identifier
* @param value
*/
public Equality(Identifier identifier, Value value) {
super(identifier, value);
}
}
| Subasinghe/ode | bpel-ql/src/main/java/org/apache/ode/ql/tree/nodes/Equality.java | Java | apache-2.0 | 1,136 |
---
Module Name: AzureRM.ApiManagement
Module Guid: f875725d-8ce4-423f-a6af-ea880bc63f13
Download Help Link: None
Help Version: 4.0.0.0
Locale: en-US
ms.assetid: B24D0651-01BA-4DD6-9816-EC960880A605
---
# AzureRM.ApiManagement Module
## Description
This topic displays help topics for the Azure API Management Cmdlets.
## AzureRM.ApiManagement Cmdlets
### [Add-AzureRmApiManagementApiToProduct](Add-AzureRmApiManagementApiToProduct.md)
Adds an API to a product.
### [Add-AzureRmApiManagementProductToGroup](Add-AzureRmApiManagementProductToGroup.md)
Adds a product to a group.
### [Add-AzureRmApiManagementRegion](Add-AzureRmApiManagementRegion.md)
Adds new deployment regions to a PsApiManagement instance.
### [Add-AzureRmApiManagementUserToGroup](Add-AzureRmApiManagementUserToGroup.md)
Adds a user to a group.
### [Backup-AzureRmApiManagement](Backup-AzureRmApiManagement.md)
Backs up an API Management service.
### [Export-AzureRmApiManagementApi](Export-AzureRmApiManagementApi.md)
Exports an API to a file.
### [Get-AzureRmApiManagement](Get-AzureRmApiManagement.md)
Gets a list or a particular API Management Service description.
### [Get-AzureRmApiManagementApi](Get-AzureRmApiManagementApi.md)
Gets an API.
### [Get-AzureRmApiManagementAuthorizationServer](Get-AzureRmApiManagementAuthorizationServer.md)
Gets an API Management authorization server.
### [Get-AzureRmApiManagementCertificate](Get-AzureRmApiManagementCertificate.md)
Gets API Management certificates.
### [Get-AzureRmApiManagementGroup](Get-AzureRmApiManagementGroup.md)
Gets all or specific API management groups.
### [Get-AzureRmApiManagementLogger](Get-AzureRmApiManagementLogger.md)
Gets API Management Logger objects.
### [Get-AzureRmApiManagementOpenIdConnectProvider](Get-AzureRmApiManagementOpenIdConnectProvider.md)
Gets OpenID Connect providers.
### [Get-AzureRmApiManagementOperation](Get-AzureRmApiManagementOperation.md)
Gets a list or a specified API Operation.
### [Get-AzureRmApiManagementPolicy](Get-AzureRmApiManagementPolicy.md)
Gets the specified scope policy.
### [Get-AzureRmApiManagementProduct](Get-AzureRmApiManagementProduct.md)
Gets a list or a particular product.
### [Get-AzureRmApiManagementProperty](Get-AzureRmApiManagementProperty.md)
### [Get-AzureRmApiManagementSsoToken](Get-AzureRmApiManagementSsoToken.md)
Gets a link with an SSO token to a deployed management portal of an API Management service.
### [Get-AzureRmApiManagementSubscription](Get-AzureRmApiManagementSubscription.md)
Gets subscriptions.
### [Get-AzureRmApiManagementTenantAccess](Get-AzureRmApiManagementTenantAccess.md)
Gets the access configuration for a tenant.
### [Get-AzureRmApiManagementTenantGitAccess](Get-AzureRmApiManagementTenantGitAccess.md)
Gets the Git access configuration for a tenant.
### [Get-AzureRmApiManagementTenantSyncState](Get-AzureRmApiManagementTenantSyncState.md)
Gets the status of the most recent synchronization between the configuration database and the Git repository.
### [Get-AzureRmApiManagementUser](Get-AzureRmApiManagementUser.md)
Gets a user or users.
### [Get-AzureRmApiManagementUserSsoUrl](Get-AzureRmApiManagementUserSsoUrl.md)
Generates an SSO URL for a user.
### [Import-AzureRmApiManagementApi](Import-AzureRmApiManagementApi.md)
Imports an API from a file or a URL.
### [Import-AzureRmApiManagementHostnameCertificate](Import-AzureRmApiManagementHostnameCertificate.md)
Imports a certificate in a PFX format for an API Management Service.
### [New-AzureRmApiManagement](New-AzureRmApiManagement.md)
Creates an API Management deployment.
### [New-AzureRmApiManagementApi](New-AzureRmApiManagementApi.md)
Creates an API.
### [New-AzureRmApiManagementAuthorizationServer](New-AzureRmApiManagementAuthorizationServer.md)
Creates an authorization server.
### [New-AzureRmApiManagementCertificate](New-AzureRmApiManagementCertificate.md)
Creates an API Management certificate.
### [New-AzureRmApiManagementContext](New-AzureRmApiManagementContext.md)
Creates an instance of PsAzureApiManagementContext.
### [New-AzureRmApiManagementGroup](New-AzureRmApiManagementGroup.md)
Creates an API management group.
### [New-AzureRmApiManagementHostnameConfiguration](New-AzureRmApiManagementHostnameConfiguration.md)
Creates an instance of PsApiManagementHostnameConfiguration.
### [New-AzureRmApiManagementLogger](New-AzureRmApiManagementLogger.md)
Creates an API Management Logger.
### [New-AzureRmApiManagementOpenIdConnectProvider](New-AzureRmApiManagementOpenIdConnectProvider.md)
Creates an OpenID Connect provider.
### [New-AzureRmApiManagementOperation](New-AzureRmApiManagementOperation.md)
Creates an API management operation.
### [New-AzureRmApiManagementProduct](New-AzureRmApiManagementProduct.md)
Creates an API Management product.
### [New-AzureRmApiManagementProperty](New-AzureRmApiManagementProperty.md)
Creates a new Property.
### [New-AzureRmApiManagementRegion](New-AzureRmApiManagementRegion.md)
Creates an instance of PsApiManagementRegion.
### [New-AzureRmApiManagementSubscription](New-AzureRmApiManagementSubscription.md)
Creates a subscription.
### [New-AzureRmApiManagementUser](New-AzureRmApiManagementUser.md)
Registers a new user.
### [New-AzureRmApiManagementVirtualNetwork](New-AzureRmApiManagementVirtualNetwork.md)
Creates an instance of PsApiManagementVirtualNetwork.
### [Publish-AzureRmApiManagementTenantGitConfiguration](Publish-AzureRmApiManagementTenantGitConfiguration.md)
Publishes changes from a Git branch to the configuration database.
### [Remove-AzureRmApiManagement](Remove-AzureRmApiManagement.md)
Removes an API Management service.
### [Remove-AzureRmApiManagementApi](Remove-AzureRmApiManagementApi.md)
Removes an API.
### [Remove-AzureRmApiManagementApiFromProduct](Remove-AzureRmApiManagementApiFromProduct.md)
Removes an API from a product.
### [Remove-AzureRmApiManagementAuthorizationServer](Remove-AzureRmApiManagementAuthorizationServer.md)
Removes an authorization server.
### [Remove-AzureRmApiManagementCertificate](Remove-AzureRmApiManagementCertificate.md)
Removes an API Management certificate.
### [Remove-AzureRmApiManagementGroup](Remove-AzureRmApiManagementGroup.md)
Removes an existing API management group.
### [Remove-AzureRmApiManagementLogger](Remove-AzureRmApiManagementLogger.md)
Removes an API Management Logger.
### [Remove-AzureRmApiManagementOpenIdConnectProvider](Remove-AzureRmApiManagementOpenIdConnectProvider.md)
Removes an OpenID Connect provider.
### [Remove-AzureRmApiManagementOperation](Remove-AzureRmApiManagementOperation.md)
Removes an existing operation.
### [Remove-AzureRmApiManagementPolicy](Remove-AzureRmApiManagementPolicy.md)
Removes the API Management policy from a specified scope.
### [Remove-AzureRmApiManagementProduct](Remove-AzureRmApiManagementProduct.md)
Removes an existing API Management product.
### [Remove-AzureRmApiManagementProductFromGroup](Remove-AzureRmApiManagementProductFromGroup.md)
Removes a product from a group.
### [Remove-AzureRmApiManagementProperty](Remove-AzureRmApiManagementProperty.md)
Removes an API Management Property.
### [Remove-AzureRmApiManagementRegion](Remove-AzureRmApiManagementRegion.md)
Removes an existing deployment region from PsApiManagement instance.
### [Remove-AzureRmApiManagementSubscription](Remove-AzureRmApiManagementSubscription.md)
Deletes an existing subscription.
### [Remove-AzureRmApiManagementUser](Remove-AzureRmApiManagementUser.md)
Deletes an existing user.
### [Remove-AzureRmApiManagementUserFromGroup](Remove-AzureRmApiManagementUserFromGroup.md)
Removes a user from a group.
### [Restore-AzureRmApiManagement](Restore-AzureRmApiManagement.md)
Restores an API Management Service from the specified Azure storage blob.
### [Save-AzureRmApiManagementTenantGitConfiguration](Save-AzureRmApiManagementTenantGitConfiguration.md)
Saves changes by creating a commit for current configuration.
### [Set-AzureRmApiManagementApi](Set-AzureRmApiManagementApi.md)
Modifies an API.
### [Set-AzureRmApiManagementAuthorizationServer](Set-AzureRmApiManagementAuthorizationServer.md)
Modifies an authorization server.
### [Set-AzureRmApiManagementCertificate](Set-AzureRmApiManagementCertificate.md)
Modifies an API Management certificate.
### [Set-AzureRmApiManagementGroup](Set-AzureRmApiManagementGroup.md)
Configures an API management group.
### [Set-AzureRmApiManagementHostnames](Set-AzureRmApiManagementHostnames.md)
Sets a custom hostname configuration for an API Management service proxy or portal.
### [Set-AzureRmApiManagementLogger](Set-AzureRmApiManagementLogger.md)
Modifies an API Management Logger.
### [Set-AzureRmApiManagementOpenIdConnectProvider](Set-AzureRmApiManagementOpenIdConnectProvider.md)
Modifies an OpenID Connect provider.
### [Set-AzureRmApiManagementOperation](Set-AzureRmApiManagementOperation.md)
Sets API operation details.
### [Set-AzureRmApiManagementPolicy](Set-AzureRmApiManagementPolicy.md)
Sets the specified scope policy for API Management.
### [Set-AzureRmApiManagementProduct](Set-AzureRmApiManagementProduct.md)
Sets the API Management product details.
### [Set-AzureRmApiManagementProperty](Set-AzureRmApiManagementProperty.md)
Modifies an API Management Property.
### [Set-AzureRmApiManagementSubscription](Set-AzureRmApiManagementSubscription.md)
Sets existing subscription details.
### [Set-AzureRmApiManagementTenantAccess](Set-AzureRmApiManagementTenantAccess.md)
Enables or disables tenant access.
### [Set-AzureRmApiManagementUser](Set-AzureRmApiManagementUser.md)
Sets user details.
### [Update-AzureRmApiManagementDeployment](Update-AzureRmApiManagementDeployment.md)
Updates deployment of an API Management Service.
### [Update-AzureRmApiManagementRegion](Update-AzureRmApiManagementRegion.md)
Updates existing deployment region in PsApiManagement instance.
| zhencui/azure-powershell | src/ResourceManager/ApiManagement/Commands.ApiManagement/help/AzureRM.ApiManagement.md | Markdown | apache-2.0 | 9,865 |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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.intellij.packageDependencies;
import com.intellij.analysis.AnalysisScope;
import com.intellij.analysis.AnalysisScopeBundle;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class ForwardDependenciesBuilder extends DependenciesBuilder {
private final Map<PsiFile, Set<PsiFile>> myDirectDependencies = new HashMap<PsiFile, Set<PsiFile>>();
public ForwardDependenciesBuilder(@NotNull Project project, @NotNull AnalysisScope scope) {
super(project, scope);
}
public ForwardDependenciesBuilder(final Project project, final AnalysisScope scope, final AnalysisScope scopeOfInterest) {
super(project, scope, scopeOfInterest);
}
public ForwardDependenciesBuilder(final Project project, final AnalysisScope scope, final int transitive) {
super(project, scope);
myTransitive = transitive;
}
@Override
public String getRootNodeNameInUsageView(){
return AnalysisScopeBundle.message("forward.dependencies.usage.view.root.node.text");
}
@Override
public String getInitialUsagesPosition(){
return AnalysisScopeBundle.message("forward.dependencies.usage.view.initial.text");
}
@Override
public boolean isBackward(){
return false;
}
@Override
public void analyze() {
final PsiManager psiManager = PsiManager.getInstance(getProject());
psiManager.startBatchFilesProcessingMode();
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(getProject()).getFileIndex();
try {
getScope().accept(new PsiRecursiveElementVisitor() {
@Override public void visitFile(final PsiFile file) {
visit(file, fileIndex, psiManager, 0);
}
});
}
finally {
psiManager.finishBatchFilesProcessingMode();
}
}
private void visit(final PsiFile file, final ProjectFileIndex fileIndex, final PsiManager psiManager, int depth) {
final FileViewProvider viewProvider = file.getViewProvider();
if (viewProvider.getBaseLanguage() != file.getLanguage()) return;
if (getScopeOfInterest() != null && !getScopeOfInterest().contains(file)) return;
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
final VirtualFile virtualFile = file.getVirtualFile();
if (indicator != null) {
if (indicator.isCanceled()) {
throw new ProcessCanceledException();
}
indicator.setText(AnalysisScopeBundle.message("package.dependencies.progress.text"));
if (virtualFile != null) {
indicator.setText2(getRelativeToProjectPath(virtualFile));
}
if ( myTotalFileCount > 0) {
indicator.setFraction(((double)++ myFileCount) / myTotalFileCount);
}
}
final boolean isInLibrary = virtualFile == null || fileIndex.isInLibrarySource(virtualFile) || fileIndex.isInLibraryClasses(virtualFile);
final Set<PsiFile> collectedDeps = new HashSet<PsiFile>();
final HashSet<PsiFile> processed = new HashSet<PsiFile>();
collectedDeps.add(file);
do {
if (depth++ > getTransitiveBorder()) return;
for (PsiFile psiFile : new HashSet<PsiFile>(collectedDeps)) {
final VirtualFile vFile = psiFile.getVirtualFile();
if (vFile != null) {
if (indicator != null) {
indicator.setText2(getRelativeToProjectPath(vFile));
}
if (!isInLibrary && (fileIndex.isInLibraryClasses(vFile) || fileIndex.isInLibrarySource(vFile))) {
processed.add(psiFile);
}
}
final Set<PsiFile> found = new HashSet<PsiFile>();
if (!processed.contains(psiFile)) {
processed.add(psiFile);
analyzeFileDependencies(psiFile, new DependencyProcessor() {
@Override
public void process(PsiElement place, PsiElement dependency) {
PsiFile dependencyFile = dependency.getContainingFile();
if (dependencyFile != null) {
if (viewProvider == dependencyFile.getViewProvider()) return;
if (dependencyFile.isPhysical()) {
final VirtualFile virtualFile = dependencyFile.getVirtualFile();
if (virtualFile != null &&
(fileIndex.isInContent(virtualFile) ||
fileIndex.isInLibraryClasses(virtualFile) ||
fileIndex.isInLibrarySource(virtualFile))) {
found.add(dependencyFile);
}
}
}
}
});
Set<PsiFile> deps = getDependencies().get(file);
if (deps == null) {
deps = new HashSet<PsiFile>();
getDependencies().put(file, deps);
}
deps.addAll(found);
getDirectDependencies().put(psiFile, new HashSet<PsiFile>(found));
collectedDeps.addAll(found);
psiManager.dropResolveCaches();
InjectedLanguageManager.getInstance(file.getProject()).dropFileCaches(file);
}
}
collectedDeps.removeAll(processed);
}
while (isTransitive() && !collectedDeps.isEmpty());
}
@Override
public Map<PsiFile, Set<PsiFile>> getDirectDependencies() {
return myDirectDependencies;
}
}
| romankagan/DDBWorkbench | platform/analysis-impl/src/com/intellij/packageDependencies/ForwardDependenciesBuilder.java | Java | apache-2.0 | 6,335 |
/**
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.jboss.pnc.common.util;
/**
* Simple wrapper class which contains a result and an exception.
* This can be useful for example when performing asynchronous operations
* which do not immediately return, but could throw an exception.
*
* @param <R> The result of the operation
* @param <E> The exception (if any) thrown during the operation.
*/
public class ResultWrapper<R, E extends Exception> {
private E exception;
private R result;
public ResultWrapper(R result) {
this.result = result;
}
public ResultWrapper(R result, E exception) {
this.result = result;
this.exception = exception;
}
/** Returns null if no exception was thrown */
/**
* @return
*/
public E getException() {
return exception;
}
public R getResult() {
return result;
}
} | ruhan1/pnc | common/src/main/java/org/jboss/pnc/common/util/ResultWrapper.java | Java | apache-2.0 | 1,569 |
/*
* Copyright 2015 JBoss by Red Hat.
*
* 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.widgets.common.client.colorpicker.dialog;
import com.google.gwt.event.shared.EventHandler;
public interface DialogClosedHandler extends EventHandler {
void dialogClosed(DialogClosedEvent event);
}
| wmedvede/uberfire-extensions | uberfire-widgets/uberfire-widgets-commons/src/main/java/org/uberfire/ext/widgets/common/client/colorpicker/dialog/DialogClosedHandler.java | Java | apache-2.0 | 849 |
// Tests for the JavaScriptMVC compatibility layer. Will be removed eventually
steal('funcunit/qunit', 'jquerypp/controller/view/test/qunit'
, 'jquerypp/class/class_test.js'
, 'jquerypp/model/test/qunit'
, 'jquerypp/controller/controller_test.js'
, 'jquerypp/view/test/qunit'
, 'jquerypp/dom/route/route_test.js'
, './integration.js'); | willametteuniversity/webcirc2 | static/jquerypp/test/qunit/jmvc.js | JavaScript | apache-2.0 | 341 |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.wso2.developerstudio.eclipse.gmf.esb.provider;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
/**
* This is the item provider adapter for a {@link org.wso2.developerstudio.eclipse.gmf.esb.LogMediatorInputConnector} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class LogMediatorInputConnectorItemProvider
extends InputConnectorItemProvider {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LogMediatorInputConnectorItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
}
return itemPropertyDescriptors;
}
/**
* This returns LogMediatorInputConnector.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/LogMediatorInputConnector"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
return getString("_UI_LogMediatorInputConnector_type");
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
| nwnpallewela/devstudio-tooling-esb | plugins/org.wso2.developerstudio.eclipse.gmf.esb.edit/src/org/wso2/developerstudio/eclipse/gmf/esb/provider/LogMediatorInputConnectorItemProvider.java | Java | apache-2.0 | 2,890 |
/* Copyright 2016 The TensorFlow Authors. 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.
==============================================================================*/
#ifndef TENSORFLOW_CORE_PLATFORM_RETRYING_FILE_SYSTEM_H_
#define TENSORFLOW_CORE_PLATFORM_RETRYING_FILE_SYSTEM_H_
#include <string>
#include <vector>
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/file_system.h"
namespace tensorflow {
/// A wrapper to add retry logic to another file system.
class RetryingFileSystem : public FileSystem {
public:
RetryingFileSystem(std::unique_ptr<FileSystem> base_file_system,
int64 delay_microseconds = 1000000)
: base_file_system_(std::move(base_file_system)),
initial_delay_microseconds_(delay_microseconds) {}
Status NewRandomAccessFile(
const string& filename,
std::unique_ptr<RandomAccessFile>* result) override;
Status NewWritableFile(const string& fname,
std::unique_ptr<WritableFile>* result) override;
Status NewAppendableFile(const string& fname,
std::unique_ptr<WritableFile>* result) override;
Status NewReadOnlyMemoryRegionFromFile(
const string& filename,
std::unique_ptr<ReadOnlyMemoryRegion>* result) override;
Status FileExists(const string& fname) override;
Status GetChildren(const string& dir, std::vector<string>* result) override;
Status GetMatchingPaths(const string& dir,
std::vector<string>* result) override;
Status Stat(const string& fname, FileStatistics* stat) override;
Status DeleteFile(const string& fname) override;
Status CreateDir(const string& dirname) override;
Status DeleteDir(const string& dirname) override;
Status GetFileSize(const string& fname, uint64* file_size) override;
Status RenameFile(const string& src, const string& target) override;
Status IsDirectory(const string& dir) override;
Status DeleteRecursively(const string& dirname, int64* undeleted_files,
int64* undeleted_dirs) override;
void FlushCaches() override;
private:
std::unique_ptr<FileSystem> base_file_system_;
const int64 initial_delay_microseconds_;
TF_DISALLOW_COPY_AND_ASSIGN(RetryingFileSystem);
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_PLATFORM_RETRYING_FILE_SYSTEM_H_
| Xeralux/tensorflow | tensorflow/core/platform/cloud/retrying_file_system.h | C | apache-2.0 | 2,873 |
/**
* 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.hadoop.yarn.server.api.protocolrecords.impl.pb;
import org.apache.hadoop.thirdparty.protobuf.TextFormat;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.impl.pb.ApplicationIdPBImpl;
import org.apache.hadoop.yarn.proto.YarnProtos;
import org.apache.hadoop.yarn.proto.YarnServerCommonServiceProtos.GetTimelineCollectorContextRequestProtoOrBuilder;
import org.apache.hadoop.yarn.proto.YarnServerCommonServiceProtos.GetTimelineCollectorContextRequestProto;
import org.apache.hadoop.yarn.server.api.protocolrecords.GetTimelineCollectorContextRequest;
public class GetTimelineCollectorContextRequestPBImpl extends
GetTimelineCollectorContextRequest {
private GetTimelineCollectorContextRequestProto
proto = GetTimelineCollectorContextRequestProto.getDefaultInstance();
private GetTimelineCollectorContextRequestProto.Builder builder = null;
private boolean viaProto = false;
private ApplicationId appId = null;
public GetTimelineCollectorContextRequestPBImpl() {
builder = GetTimelineCollectorContextRequestProto.newBuilder();
}
public GetTimelineCollectorContextRequestPBImpl(
GetTimelineCollectorContextRequestProto proto) {
this.proto = proto;
viaProto = true;
}
public GetTimelineCollectorContextRequestProto getProto() {
mergeLocalToProto();
proto = viaProto ? proto : builder.build();
viaProto = true;
return proto;
}
@Override
public int hashCode() {
return getProto().hashCode();
}
@Override
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (other.getClass().isAssignableFrom(this.getClass())) {
return this.getProto().equals(this.getClass().cast(other).getProto());
}
return false;
}
@Override
public String toString() {
return TextFormat.shortDebugString(getProto());
}
private void mergeLocalToBuilder() {
if (appId != null) {
builder.setAppId(convertToProtoFormat(this.appId));
}
}
private void mergeLocalToProto() {
if (viaProto) {
maybeInitBuilder();
}
mergeLocalToBuilder();
proto = builder.build();
viaProto = true;
}
private void maybeInitBuilder() {
if (viaProto || builder == null) {
builder = GetTimelineCollectorContextRequestProto.newBuilder(proto);
}
viaProto = false;
}
@Override
public ApplicationId getApplicationId() {
if (this.appId != null) {
return this.appId;
}
GetTimelineCollectorContextRequestProtoOrBuilder p =
viaProto ? proto : builder;
if (!p.hasAppId()) {
return null;
}
this.appId = convertFromProtoFormat(p.getAppId());
return this.appId;
}
@Override
public void setApplicationId(ApplicationId id) {
maybeInitBuilder();
if (id == null) {
builder.clearAppId();
}
this.appId = id;
}
private ApplicationIdPBImpl convertFromProtoFormat(
YarnProtos.ApplicationIdProto p) {
return new ApplicationIdPBImpl(p);
}
private YarnProtos.ApplicationIdProto convertToProtoFormat(ApplicationId t) {
return ((ApplicationIdPBImpl)t).getProto();
}
}
| steveloughran/hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/impl/pb/GetTimelineCollectorContextRequestPBImpl.java | Java | apache-2.0 | 3,988 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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.intellij.codeInsight.template.impl;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.containers.hash.LinkedHashMap;
/**
* @author Maxim.Mossienko
*/
public class TemplateImplUtil {
public static LinkedHashMap<String, Variable> parseVariables(CharSequence text) {
LinkedHashMap<String, Variable> variables = new LinkedHashMap<String, Variable>();
TemplateTextLexer lexer = new TemplateTextLexer();
lexer.start(text);
while (true) {
IElementType tokenType = lexer.getTokenType();
if (tokenType == null) break;
int start = lexer.getTokenStart();
int end = lexer.getTokenEnd();
String token = text.subSequence(start, end).toString();
if (tokenType == TemplateTokenType.VARIABLE) {
String name = token.substring(1, token.length() - 1);
if (!variables.containsKey(name)) {
variables.put(name, new Variable(name, "", "", true));
}
}
lexer.advance();
}
return variables;
}
public static boolean isValidVariableName(String varName) {
return parseVariables("$" + varName + "$").containsKey(varName);
}
}
| kdwink/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateImplUtil.java | Java | apache-2.0 | 1,752 |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['el'] =
{
appTitle : 'CKFinder', // MISSING
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING
ok : 'OK', // MISSING
cancel : 'Cancel', // MISSING
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Undo', // MISSING
redo : 'Redo', // MISSING
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
dir : 'ltr', // MISSING
HelpLang : 'en',
LangCode : 'el',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy HH:MM',
DateAmPm : ['ΜΜ', 'ΠΜ'],
// Folders
FoldersTitle : 'Φάκελοι',
FolderLoading : 'Φόρτωση...',
FolderNew : 'Παρακαλούμε πληκτρολογήστε την ονομασία του νέου φακέλου: ',
FolderRename : 'Παρακαλούμε πληκτρολογήστε την νέα ονομασία του φακέλου: ',
FolderDelete : 'Είστε σίγουροι ότι θέλετε να διαγράψετε το φάκελο "%1";',
FolderRenaming : ' (Μετονομασία...)',
FolderDeleting : ' (Διαγραφή...)',
// Files
FileRename : 'Παρακαλούμε πληκτρολογήστε την νέα ονομασία του αρχείου: ',
FileRenameExt : 'Είστε σίγουροι ότι θέλετε να αλλάξετε την επέκταση του αρχείου; Μετά από αυτή την ενέργεια το αρχείο μπορεί να μην μπορεί να χρησιμοποιηθεί',
FileRenaming : 'Μετονομασία...',
FileDelete : 'Είστε σίγουροι ότι θέλετε να διαγράψετε το αρχείο "%1"?',
FilesLoading : 'Loading...', // MISSING
FilesEmpty : 'Empty folder', // MISSING
FilesMoved : 'File %1 moved into %2:%3', // MISSING
FilesCopied : 'File %1 copied into %2:%3', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from basket', // MISSING
BasketOpenFolder : 'Open parent folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag\'n\'drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Μεταφόρτωση',
UploadTip : 'Μεταφόρτωση Νέου Αρχείου',
Refresh : 'Ανανέωση',
Settings : 'Ρυθμίσεις',
Help : 'Βοήθεια',
HelpTip : 'Βοήθεια',
// Context Menus
Select : 'Επιλογή',
SelectThumbnail : 'Επιλογή Μικρογραφίας',
View : 'Προβολή',
Download : 'Λήψη Αρχείου',
NewSubFolder : 'Νέος Υποφάκελος',
Rename : 'Μετονομασία',
Delete : 'Διαγραφή',
CopyDragDrop : 'Copy file here', // MISSING
MoveDragDrop : 'Move file here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New name', // MISSING
FileExistsDlgTitle : 'File already exists', // MISSING
SysErrorDlgTitle : 'System error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Ακύρωση',
CloseBtn : 'Κλείσιμο',
// Upload Panel
UploadTitle : 'Μεταφόρτωση Νέου Αρχείου',
UploadSelectLbl : 'επιλέξτε το αρχείο που θέλετε να μεταφερθεί κάνοντας κλίκ στο κουμπί',
UploadProgressLbl : '(Η μεταφόρτωση εκτελείται, παρακαλούμε περιμένετε...)',
UploadBtn : 'Μεταφόρτωση Επιλεγμένου Αρχείου',
UploadBtnCancel : 'Cancel', // MISSING
UploadNoFileMsg : 'Παρακαλούμε επιλέξτε ένα αρχείο από τον υπολογιστή σας',
UploadNoFolder : 'Please select folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Settings Panel
SetTitle : 'Ρυθμίσεις',
SetView : 'Προβολή:',
SetViewThumb : 'Μικρογραφίες',
SetViewList : 'Λίστα',
SetDisplay : 'Εμφάνιση:',
SetDisplayName : 'Όνομα Αρχείου',
SetDisplayDate : 'Ημερομηνία',
SetDisplaySize : 'Μέγεθος Αρχείου',
SetSort : 'Ταξινόμηση:',
SetSortName : 'βάσει Όνοματος Αρχείου',
SetSortDate : 'βάσει Ημερομήνιας',
SetSortSize : 'βάσει Μεγέθους',
// Status Bar
FilesCountEmpty : '<Κενός Φάκελος>',
FilesCountOne : '1 αρχείο',
FilesCountMany : '%1 αρχεία',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Η ενέργεια δεν ήταν δυνατόν να εκτελεστεί. (Σφάλμα %1)',
Errors :
{
10 : 'Λανθασμένη Εντολή.',
11 : 'Το resource type δεν ήταν δυνατόν να προσδιορίστεί.',
12 : 'Το resource type δεν είναι έγκυρο.',
102 : 'Το όνομα αρχείου ή φακέλου δεν είναι έγκυρο.',
103 : 'Δεν ήταν δυνατή η εκτέλεση της ενέργειας λόγω έλλειψης δικαιωμάτων ασφαλείας.',
104 : 'Δεν ήταν δυνατή η εκτέλεση της ενέργειας λόγω περιορισμών του συστήματος αρχείων.',
105 : 'Λανθασμένη Επέκταση Αρχείου.',
109 : 'Λανθασμένη Ενέργεια.',
110 : 'Άγνωστο Λάθος.',
115 : 'Το αρχείο ή φάκελος υπάρχει ήδη.',
116 : 'Ο φάκελος δεν βρέθηκε. Παρακαλούμε ανανεώστε τη σελίδα και προσπαθήστε ξανά.',
117 : 'Το αρχείο δεν βρέθηκε. Παρακαλούμε ανανεώστε τη σελίδα και προσπαθήστε ξανά.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Ένα αρχείο με την ίδια ονομασία υπάρχει ήδη. Το μεταφορτωμένο αρχείο μετονομάστηκε σε "%1"',
202 : 'Λανθασμένο Αρχείο',
203 : 'Λανθασμένο Αρχείο. Το μέγεθος του αρχείου είναι πολύ μεγάλο.',
204 : 'Το μεταφορτωμένο αρχείο είναι χαλασμένο.',
205 : 'Δεν υπάρχει προσωρινός φάκελος για να χρησιμοποιηθεί για τις μεταφορτώσεις των αρχείων.',
206 : 'Η μεταφόρτωση ακυρώθηκε για λόγους ασφαλείας. Το αρχείο περιέχει δεδομένα μορφής HTML.',
207 : 'Το μεταφορτωμένο αρχείο μετονομάστηκε σε "%1"',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'Ο πλοηγός αρχείων έχει απενεργοποιηθεί για λόγους ασφαλείας. Παρακαλούμε επικοινωνήστε με τον διαχειριστή της ιστοσελίδας και ελέγξτε το αρχείο ρυθμίσεων του πλοηγού (CKFinder).',
501 : 'Η υποστήριξη των μικρογραφιών έχει απενεργοποιηθεί.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Η ονομασία του αρχείου δεν μπορεί να είναι κενή',
FileExists : 'File %s already exists', // MISSING
FolderEmpty : 'Η ονομασία του φακέλου δεν μπορεί να είναι κενή',
FileInvChar : 'Η ονομασία του αρχείου δεν μπορεί να περιέχει τους ακόλουθους χαρακτήρες: \n\\ / : * ? " < > |',
FolderInvChar : 'Η ονομασία του φακέλου δεν μπορεί να περιέχει τους ακόλουθους χαρακτήρες: \n\\ / : * ? " < > |',
PopupBlockView : 'Δεν ήταν εφικτό να ανοίξει το αρχείο σε νέο παράθυρο. Παρακαλώ, ελέγξτε τις ρυθμίσεις τους πλοηγού σας και απενεργοποιήστε όλους τους popup blockers για αυτή την ιστοσελίδα.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set new size', // MISSING
width : 'Width', // MISSING
height : 'Height', // MISSING
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create new image', // MISSING
noExtensionChange : 'The file extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small', // MISSING
contextMenuName : 'Resize' // MISSING
},
// Fileeditor plugin
Fileeditor :
{
save : 'Save', // MISSING
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
}
};
| vikigroup/cbuilk | web/skin/temp12/scripts/ckfinder/lang/el.js | JavaScript | apache-2.0 | 11,785 |
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
' Rewriting for select case statement.
'
' Select case statements can be rewritten as: Switch Table or an If list.
' There are certain restrictions and heuristics for determining which approach
' is being chosen for each select case statement. This determination
' is done in Binder.RecommendSwitchTable method and the result is stored in
' BoundSelectStatement.RecommendSwitchTable flag.
' For switch table based approach we have an option of completely rewriting the switch header
' and switch sections into simpler constructs, i.e. we can rewrite the select header
' using bound conditional goto statements and the rewrite the case blocks into
' bound labeled statements.
' However, all the logic for emitting the switch jump tables is language agnostic
' and includes IL optimizations. Hence we delay the switch jump table generation
' till the emit phase. This way we also get additional benefit of sharing this code
' between both VB and C# compilers.
' For integral type switch table based statements, we delay almost all the work
' to the emit phase.
' For string type switch table based statements, we need to determine if we are generating a hash
' table based jump table or a non hash jump table, i.e. linear string comparisons
' with each case clause string constant. We use the Dev10 C# compiler's heuristic to determine this
' (see SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch() for details).
' If we are generating a hash table based jump table, we use a simple customizable
' hash function to hash the string constants corresponding to the case labels.
' See SwitchStringJumpTableEmitter.ComputeStringHash().
' We need to emit this function to compute the hash value into the compiler generated
' <PrivateImplementationDetails> class.
' If we have at least one string type select case statement in a module that needs a
' hash table based jump table, we generate a single public string hash synthesized method (SynthesizedStringSwitchHashMethod)
' that is shared across the module.
' CONSIDER: Ideally generating the SynthesizedStringSwitchHashMethod in <PrivateImplementationDetails>
' CONSIDER: class must be done during code generation, as the lowering does not mention or use
' CONSIDER: the hash function in any way.
' CONSIDER: However this would mean that <PrivateImplementationDetails> class can have
' CONSIDER: different sets of methods during the code generation phase,
' CONSIDER: which might be problematic if we want to make the emitter multithreaded?
Partial Friend NotInheritable Class LocalRewriter
Public Overrides Function VisitSelectStatement(node As BoundSelectStatement) As BoundNode
Return RewriteSelectStatement(node, node.Syntax, node.ExpressionStatement, node.ExprPlaceholderOpt, node.CaseBlocks, node.RecommendSwitchTable, node.ExitLabel)
End Function
Protected Function RewriteSelectStatement(
node As BoundSelectStatement,
syntaxNode As SyntaxNode,
selectExpressionStmt As BoundExpressionStatement,
exprPlaceholderOpt As BoundRValuePlaceholder,
caseBlocks As ImmutableArray(Of BoundCaseBlock),
recommendSwitchTable As Boolean,
exitLabel As LabelSymbol
) As BoundNode
Dim statementBuilder = ArrayBuilder(Of BoundStatement).GetInstance()
Dim instrument = Me.Instrument(node)
If instrument Then
' Add select case begin sequence point
Dim prologue As BoundStatement = _instrumenterOpt.CreateSelectStatementPrologue(node)
If prologue IsNot Nothing Then
statementBuilder.Add(prologue)
End If
End If
' Rewrite select expression
Dim rewrittenSelectExpression As BoundExpression = Nothing
Dim tempLocals As ImmutableArray(Of LocalSymbol) = Nothing
Dim endSelectResumeLabel As BoundLabelStatement = Nothing
Dim generateUnstructuredExceptionHandlingResumeCode As Boolean = ShouldGenerateUnstructuredExceptionHandlingResumeCode(node)
Dim rewrittenSelectExprStmt = RewriteSelectExpression(generateUnstructuredExceptionHandlingResumeCode,
selectExpressionStmt,
rewrittenSelectExpression,
tempLocals,
statementBuilder,
caseBlocks,
recommendSwitchTable,
endSelectResumeLabel)
' Add the select expression placeholder to placeholderReplacementMap
If exprPlaceholderOpt IsNot Nothing Then
AddPlaceholderReplacement(exprPlaceholderOpt, rewrittenSelectExpression)
Else
Debug.Assert(node.WasCompilerGenerated)
End If
' Rewrite select statement
If Not caseBlocks.Any() Then
' Add rewritten select expression statement.
statementBuilder.Add(rewrittenSelectExprStmt)
ElseIf recommendSwitchTable Then
If rewrittenSelectExpression.Type.IsStringType Then
' If we are emitting a hash table based string switch, then we need to create a
' SynthesizedStringSwitchHashMethod and add it to the compiler generated <PrivateImplementationDetails> class.
EnsureStringHashFunction(node)
End If
statementBuilder.Add(node.Update(rewrittenSelectExprStmt, exprPlaceholderOpt, VisitList(caseBlocks), recommendSwitchTable:=True, exitLabel:=exitLabel))
Else
' Rewrite select statement case blocks as IF List
Dim lazyConditionalBranchLocal As LocalSymbol = Nothing
statementBuilder.Add(RewriteCaseBlocksRecursive(node,
generateUnstructuredExceptionHandlingResumeCode,
caseBlocks,
startFrom:=0,
lazyConditionalBranchLocal:=lazyConditionalBranchLocal))
If lazyConditionalBranchLocal IsNot Nothing Then
tempLocals = tempLocals.Add(lazyConditionalBranchLocal)
End If
' Add label statement for exit label
statementBuilder.Add(New BoundLabelStatement(syntaxNode, exitLabel))
End If
If exprPlaceholderOpt IsNot Nothing Then
RemovePlaceholderReplacement(exprPlaceholderOpt)
End If
Dim epilogue As BoundStatement = endSelectResumeLabel
If instrument Then
' Add End Select sequence point
epilogue = _instrumenterOpt.InstrumentSelectStatementEpilogue(node, epilogue)
End If
If epilogue IsNot Nothing Then
statementBuilder.Add(epilogue)
End If
Return New BoundBlock(syntaxNode, Nothing, tempLocals, statementBuilder.ToImmutableAndFree()).MakeCompilerGenerated()
End Function
Private Sub EnsureStringHashFunction(node As BoundSelectStatement)
Dim selectCaseExpr = node.ExpressionStatement.Expression
' Prefer embedded version of the member if present
Dim embeddedOperatorsType As NamedTypeSymbol = Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators)
Dim compareStringMember As WellKnownMember =
If(embeddedOperatorsType.IsErrorType AndAlso TypeOf embeddedOperatorsType Is MissingMetadataTypeSymbol,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean)
Dim compareStringMethod = DirectCast(Compilation.GetWellKnownTypeMember(compareStringMember), MethodSymbol)
Me.ReportMissingOrBadRuntimeHelper(selectCaseExpr, compareStringMember, compareStringMethod)
Const stringCharsMember As SpecialMember = SpecialMember.System_String__Chars
Dim stringCharsMethod = DirectCast(ContainingAssembly.GetSpecialTypeMember(stringCharsMember), MethodSymbol)
Me.ReportMissingOrBadRuntimeHelper(selectCaseExpr, stringCharsMember, stringCharsMethod)
Me.ReportBadType(selectCaseExpr, Compilation.GetSpecialType(SpecialType.System_Int32))
Me.ReportBadType(selectCaseExpr, Compilation.GetSpecialType(SpecialType.System_UInt32))
Me.ReportBadType(selectCaseExpr, Compilation.GetSpecialType(SpecialType.System_String))
If _emitModule Is Nothing Then
Return
End If
If Not ShouldGenerateHashTableSwitch(_emitModule, node) Then
Return
End If
' If we have already generated this helper method, possibly for another select case
' or on another thread, we don't need to regenerate it.
Dim privateImplClass = _emitModule.GetPrivateImplClass(node.Syntax, _diagnostics)
If privateImplClass.GetMethod(PrivateImplementationDetails.SynthesizedStringHashFunctionName) IsNot Nothing Then
Return
End If
Dim method = New SynthesizedStringSwitchHashMethod(_emitModule.SourceModule, privateImplClass)
privateImplClass.TryAddSynthesizedMethod(method)
End Sub
Private Function RewriteSelectExpression(
generateUnstructuredExceptionHandlingResumeCode As Boolean,
selectExpressionStmt As BoundExpressionStatement,
<Out()> ByRef rewrittenSelectExpression As BoundExpression,
<Out()> ByRef tempLocals As ImmutableArray(Of LocalSymbol),
statementBuilder As ArrayBuilder(Of BoundStatement),
caseBlocks As ImmutableArray(Of BoundCaseBlock),
recommendSwitchTable As Boolean,
<Out()> ByRef endSelectResumeLabel As BoundLabelStatement
) As BoundExpressionStatement
Debug.Assert(statementBuilder IsNot Nothing)
Debug.Assert(Not caseBlocks.IsDefault)
Dim selectExprStmtSyntax = selectExpressionStmt.Syntax
If generateUnstructuredExceptionHandlingResumeCode Then
RegisterUnstructuredExceptionHandlingResumeTarget(selectExprStmtSyntax, canThrow:=True, statements:=statementBuilder)
' If the Select throws, a Resume Next should branch to the End Select.
endSelectResumeLabel = RegisterUnstructuredExceptionHandlingNonThrowingResumeTarget(selectExprStmtSyntax)
Else
endSelectResumeLabel = Nothing
End If
' Rewrite select expression
rewrittenSelectExpression = VisitExpressionNode(selectExpressionStmt.Expression)
' We will need to store the select case expression into a temporary local if we have at least one case block
' and one of the following is true:
' (1) We are generating If list based code.
' (2) We are generating switch table based code and the select expression is not a bound local expression.
' We need a local for this case because during codeGen we are going to perform a binary search with
' select expression result as the key and might need to load the key multiple times.
Dim needTempLocal = caseBlocks.Any() AndAlso (Not recommendSwitchTable OrElse rewrittenSelectExpression.Kind <> BoundKind.Local)
If needTempLocal Then
Dim selectExprType = rewrittenSelectExpression.Type
' Store the select expression result in a temp
Dim selectStatementSyntax = DirectCast(selectExprStmtSyntax.Parent, SelectBlockSyntax).SelectStatement
Dim tempLocal = New SynthesizedLocal(Me._currentMethodOrLambda, selectExprType, SynthesizedLocalKind.SelectCaseValue, selectStatementSyntax)
tempLocals = ImmutableArray.Create(Of LocalSymbol)(tempLocal)
Dim boundTemp = New BoundLocal(rewrittenSelectExpression.Syntax, tempLocal, selectExprType)
statementBuilder.Add(New BoundAssignmentOperator(syntax:=selectExprStmtSyntax,
left:=boundTemp,
right:=rewrittenSelectExpression,
suppressObjectClone:=True,
type:=selectExprType).ToStatement().MakeCompilerGenerated())
rewrittenSelectExpression = boundTemp.MakeRValue()
Else
tempLocals = ImmutableArray(Of LocalSymbol).Empty
End If
Return selectExpressionStmt.Update(rewrittenSelectExpression)
End Function
' Rewrite select statement case blocks as IF List
Private Function RewriteCaseBlocksRecursive(
selectStatement As BoundSelectStatement,
generateUnstructuredExceptionHandlingResumeCode As Boolean,
caseBlocks As ImmutableArray(Of BoundCaseBlock),
startFrom As Integer,
ByRef lazyConditionalBranchLocal As LocalSymbol
) As BoundStatement
Debug.Assert(startFrom <= caseBlocks.Length)
If startFrom = caseBlocks.Length Then
Return Nothing
End If
Dim rewrittenStatement As BoundStatement
Dim curCaseBlock = caseBlocks(startFrom)
Debug.Assert(generateUnstructuredExceptionHandlingResumeCode = ShouldGenerateUnstructuredExceptionHandlingResumeCode(curCaseBlock))
Dim unstructuredExceptionHandlingResumeTarget As ImmutableArray(Of BoundStatement) = Nothing
Dim rewrittenCaseCondition As BoundExpression = RewriteCaseStatement(generateUnstructuredExceptionHandlingResumeCode, curCaseBlock.CaseStatement, unstructuredExceptionHandlingResumeTarget)
Dim rewrittenBody = DirectCast(VisitBlock(curCaseBlock.Body), BoundBlock)
If generateUnstructuredExceptionHandlingResumeCode AndAlso startFrom < caseBlocks.Length - 1 Then
' Add a Resume entry to protect against fall-through to the next Case block.
rewrittenBody = AppendToBlock(rewrittenBody, RegisterUnstructuredExceptionHandlingNonThrowingResumeTarget(curCaseBlock.Syntax))
End If
Dim instrument = Me.Instrument(selectStatement)
If rewrittenCaseCondition Is Nothing Then
' This must be a Case Else Block
Debug.Assert(curCaseBlock.Syntax.Kind = SyntaxKind.CaseElseBlock)
Debug.Assert(Not curCaseBlock.CaseStatement.CaseClauses.Any())
' Only the last block can be a Case Else block
Debug.Assert(startFrom = caseBlocks.Length - 1)
' Case Else statement needs a sequence point
If instrument Then
rewrittenStatement = _instrumenterOpt.InstrumentCaseElseBlock(curCaseBlock, rewrittenBody)
Else
rewrittenStatement = rewrittenBody
End If
Else
Debug.Assert(curCaseBlock.Syntax.Kind = SyntaxKind.CaseBlock)
If instrument Then
rewrittenCaseCondition = _instrumenterOpt.InstrumentSelectStatementCaseCondition(selectStatement, rewrittenCaseCondition, _currentMethodOrLambda, lazyConditionalBranchLocal)
End If
' EnC: We need to insert a hidden sequence point to handle function remapping in case
' the containing method is edited while methods invoked in the condition are being executed.
rewrittenStatement = RewriteIfStatement(
syntaxNode:=curCaseBlock.Syntax,
rewrittenCondition:=rewrittenCaseCondition,
rewrittenConsequence:=rewrittenBody,
rewrittenAlternative:=RewriteCaseBlocksRecursive(selectStatement, generateUnstructuredExceptionHandlingResumeCode, caseBlocks, startFrom + 1, lazyConditionalBranchLocal),
unstructuredExceptionHandlingResumeTarget:=unstructuredExceptionHandlingResumeTarget,
instrumentationTargetOpt:=If(instrument, curCaseBlock, Nothing))
End If
Return rewrittenStatement
End Function
' Rewrite case statement as conditional expression
Private Function RewriteCaseStatement(
generateUnstructuredExceptionHandlingResumeCode As Boolean,
node As BoundCaseStatement,
<Out()> ByRef unstructuredExceptionHandlingResumeTarget As ImmutableArray(Of BoundStatement)
) As BoundExpression
If node.CaseClauses.Any() Then
' Case block
Debug.Assert(node.Syntax.Kind = SyntaxKind.CaseStatement)
Debug.Assert(node.ConditionOpt IsNot Nothing)
unstructuredExceptionHandlingResumeTarget = If(generateUnstructuredExceptionHandlingResumeCode,
RegisterUnstructuredExceptionHandlingResumeTarget(node.Syntax, canThrow:=True),
Nothing)
Return VisitExpressionNode(node.ConditionOpt)
Else
' Case Else block
Debug.Assert(node.Syntax.Kind = SyntaxKind.CaseElseStatement)
unstructuredExceptionHandlingResumeTarget = Nothing
Return Nothing
End If
End Function
' Checks whether we are generating a hash table based string switch
Private Shared Function ShouldGenerateHashTableSwitch([module] As Microsoft.CodeAnalysis.VisualBasic.Emit.PEModuleBuilder, node As BoundSelectStatement) As Boolean
Debug.Assert(Not node.HasErrors)
Debug.Assert(node.ExpressionStatement.Expression.Type.IsStringType)
Debug.Assert(node.RecommendSwitchTable)
If Not [module].SupportsPrivateImplClass Then
Return False
End If
' compute unique string constants from select clauses.
Dim uniqueStringConstants = New HashSet(Of ConstantValue)
For Each caseBlock In node.CaseBlocks
For Each caseClause In caseBlock.CaseStatement.CaseClauses
Dim constant As ConstantValue = Nothing
Select Case caseClause.Kind
Case BoundKind.SimpleCaseClause
Dim simpleCaseClause = DirectCast(caseClause, BoundSimpleCaseClause)
Debug.Assert(simpleCaseClause.ValueOpt IsNot Nothing)
Debug.Assert(simpleCaseClause.ConditionOpt Is Nothing)
constant = simpleCaseClause.ValueOpt.ConstantValueOpt
Case BoundKind.RelationalCaseClause
Dim relationalCaseClause = DirectCast(caseClause, BoundRelationalCaseClause)
Debug.Assert(relationalCaseClause.OperatorKind = BinaryOperatorKind.Equals)
Debug.Assert(relationalCaseClause.ValueOpt IsNot Nothing)
Debug.Assert(relationalCaseClause.ConditionOpt Is Nothing)
constant = relationalCaseClause.ValueOpt.ConstantValueOpt
Case Else
Throw ExceptionUtilities.UnexpectedValue(caseClause.Kind)
End Select
Debug.Assert(constant IsNot Nothing)
uniqueStringConstants.Add(constant)
Next
Next
Return SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch([module], uniqueStringConstants.Count)
End Function
Public Overrides Function VisitCaseBlock(node As BoundCaseBlock) As BoundNode
Dim rewritten = DirectCast(MyBase.VisitCaseBlock(node), BoundCaseBlock)
Dim rewrittenBody = rewritten.Body
' Add a Resume entry to protect against fall-through to the next Case block.
If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then
rewrittenBody = AppendToBlock(rewrittenBody, RegisterUnstructuredExceptionHandlingNonThrowingResumeTarget(node.Syntax))
End If
Return rewritten.Update(rewritten.CaseStatement, rewrittenBody)
End Function
End Class
End Namespace
| davkean/roslyn | src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_SelectCase.vb | Visual Basic | apache-2.0 | 22,052 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.