text stringlengths 2 99k | meta dict |
|---|---|
/*********************************************
作者:曹旭升
QQ:279060597
访问博客了解详细介绍及更多内容:
http://blog.shengxunwei.com
**********************************************/
using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners
{
public class MsmqSendInterfaceFactory : IMsmqSendInterfaceFactory
{
public IMsmqSendInterface CreateMsmqInterface(string queuePath)
{
return new MsmqSendInterface(queuePath);
}
}
}
| {
"pile_set_name": "Github"
} |
# Copyright 2018 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
FROM ubuntu:18.04 as base_build
ARG TF_SERVING_VERSION_GIT_BRANCH=master
ARG TF_SERVING_VERSION_GIT_COMMIT=head
LABEL maintainer=gvasudevan@google.com
LABEL tensorflow_serving_github_branchtag=${TF_SERVING_VERSION_GIT_BRANCH}
LABEL tensorflow_serving_github_commit=${TF_SERVING_VERSION_GIT_COMMIT}
RUN apt-get update && apt-get install -y --no-install-recommends \
automake \
build-essential \
ca-certificates \
curl \
git \
libcurl3-dev \
libfreetype6-dev \
libpng-dev \
libtool \
libzmq3-dev \
mlocate \
openjdk-8-jdk\
openjdk-8-jre-headless \
pkg-config \
python-dev \
software-properties-common \
swig \
unzip \
wget \
zip \
zlib1g-dev \
python3-distutils \
&& \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
RUN curl -fSsL -O https://bootstrap.pypa.io/get-pip.py && \
python3 get-pip.py && \
rm get-pip.py
# Install python 3.6.
RUN add-apt-repository ppa:deadsnakes/ppa && \
apt-get update && apt-get install -y \
python3.6 python3.6-dev python3-pip python3.6-venv && \
rm -rf /var/lib/apt/lists/* && \
python3.6 -m pip install pip --upgrade && \
update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 0
# Make python3.6 the default python version
RUN update-alternatives --install /usr/bin/python python /usr/bin/python3.6 0
RUN pip3 --no-cache-dir install \
future>=0.17.1 \
grpcio \
h5py \
keras_applications>=1.0.8 \
keras_preprocessing>=1.1.0 \
mock \
numpy \
requests \
--ignore-installed setuptools \
--ignore-installed six>=1.12.0
# Set up Bazel
ENV BAZEL_VERSION 3.0.0
WORKDIR /
RUN mkdir /bazel && \
cd /bazel && \
curl -H "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36" -fSsL -O https://github.com/bazelbuild/bazel/releases/download/$BAZEL_VERSION/bazel-$BAZEL_VERSION-installer-linux-x86_64.sh && \
curl -H "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36" -fSsL -o /bazel/LICENSE.txt https://raw.githubusercontent.com/bazelbuild/bazel/master/LICENSE && \
chmod +x bazel-*.sh && \
./bazel-$BAZEL_VERSION-installer-linux-x86_64.sh && \
cd / && \
rm -f /bazel/bazel-$BAZEL_VERSION-installer-linux-x86_64.sh
# Download TF Serving sources (optionally at specific commit).
WORKDIR /tensorflow-serving
RUN git clone --branch=${TF_SERVING_VERSION_GIT_BRANCH} https://github.com/tensorflow/serving . && \
git remote add upstream https://github.com/tensorflow/serving.git && \
if [ "${TF_SERVING_VERSION_GIT_COMMIT}" != "head" ]; then git checkout ${TF_SERVING_VERSION_GIT_COMMIT} ; fi
FROM base_build as binary_build
# Build, and install TensorFlow Serving
ARG TF_SERVING_BUILD_OPTIONS="--config=release"
RUN echo "Building with build options: ${TF_SERVING_BUILD_OPTIONS}"
ARG TF_SERVING_BAZEL_OPTIONS=""
RUN echo "Building with Bazel options: ${TF_SERVING_BAZEL_OPTIONS}"
RUN bazel build --color=yes --curses=yes \
${TF_SERVING_BAZEL_OPTIONS} \
--verbose_failures \
--output_filter=DONT_MATCH_ANYTHING \
${TF_SERVING_BUILD_OPTIONS} \
tensorflow_serving/model_servers:tensorflow_model_server && \
cp bazel-bin/tensorflow_serving/model_servers/tensorflow_model_server \
/usr/local/bin/
# Build and install TensorFlow Serving API
RUN bazel build --color=yes --curses=yes \
${TF_SERVING_BAZEL_OPTIONS} \
--verbose_failures \
--output_filter=DONT_MATCH_ANYTHING \
${TF_SERVING_BUILD_OPTIONS} \
tensorflow_serving/tools/pip_package:build_pip_package && \
bazel-bin/tensorflow_serving/tools/pip_package/build_pip_package \
/tmp/pip && \
pip --no-cache-dir install --upgrade \
/tmp/pip/tensorflow_serving_api-*.whl && \
rm -rf /tmp/pip
FROM binary_build as clean_build
# Clean up Bazel cache when done.
RUN bazel clean --expunge --color=yes && \
rm -rf /root/.cache
CMD ["/bin/bash"]
| {
"pile_set_name": "Github"
} |
/**
* Copyright 2008 - 2012
*
* 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.
*
* @project loon
* @author cping
* @email:javachenpeng@yahoo.com
* @version 0.3.3
*/
package loon.action.sprite.node;
import loon.core.geom.Vector2f;
import loon.utils.MathUtils;
public class LNJumpBy extends LNAction {
LNJumpBy(){
}
protected Vector2f _delta;
protected float _height;
protected int _jumps;
protected Vector2f _orgPos;
public static LNJumpBy Action(float duration, float d, float height,
int jumps) {
return Action(duration, new Vector2f(d, d), height, jumps);
}
public static LNJumpBy Action(float duration, Vector2f delta, float height,
int jumps) {
LNJumpBy by = new LNJumpBy();
by._duration = duration;
by._delta = delta;
by._height = height;
by._jumps = jumps;
return by;
}
@Override
public void setTarget(LNNode node) {
super._firstTick = true;
super._isEnd = false;
super._target = node;
this._orgPos = node.getPosition();
}
@Override
public void update(float t) {
if (t == 1f) {
super._isEnd = true;
super._target.setPosition(this._delta.x + this._orgPos.x,
this._delta.y + this._orgPos.y);
} else {
float num = this._height
* MathUtils.abs(MathUtils
.sin(((t * 3.141593f) * this._jumps)));
num += this._delta.y * t;
float num2 = this._delta.x * t;
super._target.setPosition(num2 + this._orgPos.x, num
+ this._orgPos.y);
}
}
@Override
public LNAction copy() {
return Action(_duration, _delta, _height, _jumps);
}
public LNJumpBy reverse() {
return Action(_duration, _delta.negate(), _height, _jumps);
}
}
| {
"pile_set_name": "Github"
} |
---
title: Mapping eShopOnContainers to Azure Services
description: Mapping eShopOnContainers to Azure Services like Azure Kubernetes Service, API Gateway, and Azure Service Bus.
ms.date: 05/13/2020
---
# Mapping eShopOnContainers to Azure Services
Although not required, Azure is well-suited to supporting the eShopOnContainers because the project was built to be a cloud-native application. The application is built with .NET Core, so it can run on Linux or Windows containers depending on the Docker host. The application is made up of multiple autonomous microservices, each with its own data. The different microservices showcase different approaches, ranging from simple CRUD operations to more complex DDD and CQRS patterns. Microservices communicate with clients over HTTP and with one another via message-based communication. The application supports multiple platforms for clients as well, since it adopts HTTP as a standard communication protocol and includes ASP.NET Core and Xamarin mobile apps that run on Android, iOS, and Windows platforms.
The application's architecture is shown in Figure 2-5. On the left are the client apps, broken up into mobile, traditional Web, and Web Single Page Application (SPA) flavors. On the right are the server-side components that make up the system, each of which can be hosted in Docker containers and Kubernetes clusters. The traditional web app is powered by the ASP.NET Core MVC application shown in yellow. This app and the mobile and web SPA applications communicate with the individual microservices through one or more API gateways. The API gateways follow the "backends for front ends" (BFF) pattern, meaning that each gateway is designed to support a given front-end client. The individual microservices are listed to the right of the API gateways and include both business logic and some kind of persistence store. The different services make use of SQL Server databases, Redis cache instances, and MongoDB/CosmosDB stores. On the far right is the system's Event Bus, which is used for communication between the microservices.

**Figure 2-5**. The eShopOnContainers Architecture.
The server-side components of this architecture all map easily to Azure services.
## Container orchestration and clustering
The application's container-hosted services, from ASP.NET Core MVC apps to individual Catalog and Ordering microservices, can be hosted and managed in Azure Kubernetes Service (AKS). The application can run locally on Docker and Kubernetes, and the same containers can then be deployed to staging and production environments hosted in AKS. This process can be automated as we'll see in the next section.
AKS provides management services for individual clusters of containers. The application will deploy separate AKS clusters for each microservice shown in the architecture diagram above. This approach allows each individual service to scale independently according to its resource demands. Each microservice can also be deployed independently, and ideally such deployments should incur zero system downtime.
## API Gateway
The eShopOnContainers application has multiple front-end clients and multiple different back-end services. There's no one-to-one correspondence between the client applications and the microservices that support them. In such a scenario, there may be a great deal of complexity when writing client software to interface with the various back-end services in a secure manner. Each client would need to address this complexity on its own, resulting in duplication and many places in which to make updates as services change or new policies are implemented.
Azure API Management (APIM) helps organizations publish APIs in a consistent, manageable fashion. APIM consists of three components: the API Gateway, and administration portal (the Azure portal), and a developer portal.
The API Gateway accepts API calls and routes them to the appropriate back-end API. It can also provide additional services like verification of API keys or JWT tokens and API transformation on the fly without code modifications (for instance, to accommodate clients expecting an older interface).
The Azure portal is where you define the API schema and package different APIs into products. You also configure user access, view reports, and configure policies for quotas or transformations.
The developer portal serves as the main resource for developers. It provides developers with API documentation, an interactive test console, and reports on their own usage. Developers also use the portal to create and manage their own accounts, including subscription and API key support.
Using APIM, applications can expose several different groups of services, each providing a back end for a particular front-end client. APIM is recommended for complex scenarios. For simpler needs, the lightweight API Gateway Ocelot can be used. The eShopOnContainers app uses Ocelot because of its simplicity and because it can be deployed into the same application environment as the application itself. [Learn more about eShopOnContainers, APIM, and Ocelot.](../microservices/architect-microservice-container-applications/direct-client-to-microservice-communication-versus-the-api-gateway-pattern.md#azure-api-management)
Another option if your application is using AKS is to deploy the Azure Gateway Ingress Controller as a pod within your AKS cluster. This allows your cluster to integrate with an Azure Application Gateway, allowing the gateway to load-balance traffic to the AKS pods. [Learn more about the Azure Gateway Ingress Controller for AKS](https://github.com/Azure/application-gateway-kubernetes-ingress).
## Data
The various back-end services used by eShopOnContainers have different storage requirements. Several microservices use SQL Server databases. The Basket microservice leverages a Redis cache for its persistence. The Locations microservice expects a MongoDB API for its data. Azure supports each of these data formats.
For SQL Server database support, Azure has products for everything from single databases up to highly scalable SQL Database elastic pools. Individual microservices can be configured to communicate with their own individual SQL Server databases quickly and easily. These databases can be scaled as needed to support each separate microservice according to its needs.
The eShopOnContainers application stores the user's current shopping basket between requests. This is managed by the Basket microservice that stores the data in a Redis cache. In development, this cache can be deployed in a container, while in production it can utilize Azure Cache for Redis. Azure Cache for Redis is a fully managed service offering high performance and reliability without the need to deploy and manage Redis instances or containers on your own.
The Locations microservice uses a MongoDB NoSQL database for its persistence. During development, the database can be deployed in its own container, while in production the service can leverage [Azure Cosmos DB's API for MongoDB](/azure/cosmos-db/mongodb-introduction). One of the benefits of Azure Cosmos DB is its ability to leverage multiple different communication protocols, including a SQL API and common NoSQL APIs including MongoDB, Cassandra, Gremlin, and Azure Table Storage. Azure Cosmos DB offers a fully managed and globally distributed database as a service that can scale to meet the needs of the services that use it.
Distributed data in cloud-native applications is covered in more detail in [chapter 5](distributed-data.md).
## Event Bus
The application uses events to communicate changes between different services. This functionality can be implemented with a variety of implementations, and locally the eShopOnContainers application uses [RabbitMQ](https://www.rabbitmq.com/). When hosted in Azure, the application would leverage [Azure Service Bus](/azure/service-bus/) for its messaging. Azure Service Bus is a fully managed integration message broker that allows applications and services to communicate with one another in a decoupled, reliable, asynchronous manner. Azure Service Bus supports individual queues as well as separate *topics* to support publisher-subscriber scenarios. The eShopOnContainers application would leverage topics with Azure Service Bus to support distributing messages from one microservice to any other microservice that needed to react to a given message.
## Resiliency
Once deployed to production, the eShopOnContainers application would be able to take advantage of several Azure services available to improve its resiliency. The application publishes health checks, which can be integrated with Application Insights to provide reporting and alerts based on the app's availability. Azure resources also provide diagnostic logs that can be used to identify and correct bugs and performance issues. Resource logs provide detailed information on when and how different Azure resources are used by the application. You'll learn more about cloud-native resiliency features in [chapter 6](resiliency.md).
>[!div class="step-by-step"]
>[Previous](introduce-eshoponcontainers-reference-app.md)
>[Next](deploy-eshoponcontainers-azure.md)
| {
"pile_set_name": "Github"
} |
/*
* SPDX-License-Identifier: ISC
*
* Copyright (c) 2010-2013, 2015-2017 Todd C. Miller <Todd.Miller@sudo.ws>
*
* Permission to use, copy, modify, and 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.
*/
#ifndef SUDOERS_PWUTIL_H
#define SUDOERS_PWUTIL_H
#define ptr_to_item(p) ((struct cache_item *)((char *)p - offsetof(struct cache_item_##p, p)))
/*
* Generic cache element.
*/
struct cache_item {
unsigned int refcnt;
unsigned int type; /* only used for gidlist */
char registry[16]; /* AIX-specific, empty otherwise */
/* key */
union {
uid_t uid;
gid_t gid;
char *name;
} k;
/* datum */
union {
struct passwd *pw;
struct group *gr;
struct group_list *grlist;
struct gid_list *gidlist;
} d;
};
/*
* Container structs to simpify size and offset calculations and guarantee
* proper alignment of struct passwd, group, gid_list and group_list.
*/
struct cache_item_pw {
struct cache_item cache;
struct passwd pw;
};
struct cache_item_gr {
struct cache_item cache;
struct group gr;
};
struct cache_item_grlist {
struct cache_item cache;
struct group_list grlist;
/* actually bigger */
};
struct cache_item_gidlist {
struct cache_item cache;
struct gid_list gidlist;
/* actually bigger */
};
struct cache_item *sudo_make_gritem(gid_t gid, const char *group);
struct cache_item *sudo_make_grlist_item(const struct passwd *pw, char * const *groups);
struct cache_item *sudo_make_gidlist_item(const struct passwd *pw, char * const *gids, unsigned int type);
struct cache_item *sudo_make_pwitem(uid_t uid, const char *user);
#endif /* SUDOERS_PWUTIL_H */
| {
"pile_set_name": "Github"
} |
/*
* arch/arm/include/asm/assembler.h
*
* Copyright (C) 1996-2000 Russell King
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This file contains arm architecture specific defines
* for the different processors.
*
* Do not include any C declarations in this file - it is included by
* assembler source.
*/
#ifndef __ASM_ASSEMBLER_H__
#define __ASM_ASSEMBLER_H__
#ifndef __ASSEMBLY__
#error "Only include this from assembly code"
#endif
#include <asm/ptrace.h>
#include <asm/domain.h>
#define IOMEM(x) (x)
/*
* Endian independent macros for shifting bytes within registers.
*/
#ifndef __ARMEB__
#define pull lsr
#define push lsl
#define get_byte_0 lsl #0
#define get_byte_1 lsr #8
#define get_byte_2 lsr #16
#define get_byte_3 lsr #24
#define put_byte_0 lsl #0
#define put_byte_1 lsl #8
#define put_byte_2 lsl #16
#define put_byte_3 lsl #24
#else
#define pull lsl
#define push lsr
#define get_byte_0 lsr #24
#define get_byte_1 lsr #16
#define get_byte_2 lsr #8
#define get_byte_3 lsl #0
#define put_byte_0 lsl #24
#define put_byte_1 lsl #16
#define put_byte_2 lsl #8
#define put_byte_3 lsl #0
#endif
/*
* Data preload for architectures that support it
*/
#if __LINUX_ARM_ARCH__ >= 5
#define PLD(code...) code
#else
#define PLD(code...)
#endif
/*
* This can be used to enable code to cacheline align the destination
* pointer when bulk writing to memory. Experiments on StrongARM and
* XScale didn't show this a worthwhile thing to do when the cache is not
* set to write-allocate (this would need further testing on XScale when WA
* is used).
*
* On Feroceon there is much to gain however, regardless of cache mode.
*/
#ifdef CONFIG_CPU_FEROCEON
#define CALGN(code...) code
#else
#define CALGN(code...)
#endif
/*
* Enable and disable interrupts
*/
#if __LINUX_ARM_ARCH__ >= 6
.macro disable_irq_notrace
cpsid i
.endm
.macro enable_irq_notrace
cpsie i
.endm
#else
.macro disable_irq_notrace
msr cpsr_c, #PSR_I_BIT | SVC_MODE
.endm
.macro enable_irq_notrace
msr cpsr_c, #SVC_MODE
.endm
#endif
.macro asm_trace_hardirqs_off
#if defined(CONFIG_TRACE_IRQFLAGS)
stmdb sp!, {r0-r3, ip, lr}
bl trace_hardirqs_off
ldmia sp!, {r0-r3, ip, lr}
#endif
.endm
.macro asm_trace_hardirqs_on_cond, cond
#if defined(CONFIG_TRACE_IRQFLAGS)
/*
* actually the registers should be pushed and pop'd conditionally, but
* after bl the flags are certainly clobbered
*/
stmdb sp!, {r0-r3, ip, lr}
bl\cond trace_hardirqs_on
ldmia sp!, {r0-r3, ip, lr}
#endif
.endm
.macro asm_trace_hardirqs_on
asm_trace_hardirqs_on_cond al
.endm
.macro disable_irq
disable_irq_notrace
asm_trace_hardirqs_off
.endm
.macro enable_irq
asm_trace_hardirqs_on
enable_irq_notrace
.endm
/*
* Save the current IRQ state and disable IRQs. Note that this macro
* assumes FIQs are enabled, and that the processor is in SVC mode.
*/
.macro save_and_disable_irqs, oldcpsr
mrs \oldcpsr, cpsr
disable_irq
.endm
.macro save_and_disable_irqs_notrace, oldcpsr
mrs \oldcpsr, cpsr
disable_irq_notrace
.endm
/*
* Restore interrupt state previously stored in a register. We don't
* guarantee that this will preserve the flags.
*/
.macro restore_irqs_notrace, oldcpsr
msr cpsr_c, \oldcpsr
.endm
.macro restore_irqs, oldcpsr
tst \oldcpsr, #PSR_I_BIT
asm_trace_hardirqs_on_cond eq
restore_irqs_notrace \oldcpsr
.endm
#define USER(x...) \
9999: x; \
.pushsection __ex_table,"a"; \
.align 3; \
.long 9999b,9001f; \
.popsection
#ifdef CONFIG_SMP
#define ALT_SMP(instr...) \
9998: instr
/*
* Note: if you get assembler errors from ALT_UP() when building with
* CONFIG_THUMB2_KERNEL, you almost certainly need to use
* ALT_SMP( W(instr) ... )
*/
#define ALT_UP(instr...) \
.pushsection ".alt.smp.init", "a" ;\
.long 9998b ;\
9997: instr ;\
.if . - 9997b != 4 ;\
.error "ALT_UP() content must assemble to exactly 4 bytes";\
.endif ;\
.popsection
#define ALT_UP_B(label) \
.equ up_b_offset, label - 9998b ;\
.pushsection ".alt.smp.init", "a" ;\
.long 9998b ;\
W(b) . + up_b_offset ;\
.popsection
#else
#define ALT_SMP(instr...)
#define ALT_UP(instr...) instr
#define ALT_UP_B(label) b label
#endif
/*
* Instruction barrier
*/
.macro instr_sync
#if __LINUX_ARM_ARCH__ >= 7
isb
#elif __LINUX_ARM_ARCH__ == 6
mcr p15, 0, r0, c7, c5, 4
#endif
.endm
/*
* SMP data memory barrier
*/
.macro smp_dmb mode
#ifdef CONFIG_SMP
#if __LINUX_ARM_ARCH__ >= 7
.ifeqs "\mode","arm"
ALT_SMP(dmb)
.else
ALT_SMP(W(dmb))
.endif
#elif __LINUX_ARM_ARCH__ == 6
ALT_SMP(mcr p15, 0, r0, c7, c10, 5) @ dmb
#else
#error Incompatible SMP platform
#endif
.ifeqs "\mode","arm"
ALT_UP(nop)
.else
ALT_UP(W(nop))
.endif
#endif
.endm
#ifdef CONFIG_THUMB2_KERNEL
.macro setmode, mode, reg
mov \reg, #\mode
msr cpsr_c, \reg
.endm
#else
.macro setmode, mode, reg
msr cpsr_c, #\mode
.endm
#endif
/*
* STRT/LDRT access macros with ARM and Thumb-2 variants
*/
#ifdef CONFIG_THUMB2_KERNEL
.macro usraccoff, instr, reg, ptr, inc, off, cond, abort, t=TUSER()
9999:
.if \inc == 1
\instr\cond\()b\()\t\().w \reg, [\ptr, #\off]
.elseif \inc == 4
\instr\cond\()\t\().w \reg, [\ptr, #\off]
.else
.error "Unsupported inc macro argument"
.endif
.pushsection __ex_table,"a"
.align 3
.long 9999b, \abort
.popsection
.endm
.macro usracc, instr, reg, ptr, inc, cond, rept, abort
@ explicit IT instruction needed because of the label
@ introduced by the USER macro
.ifnc \cond,al
.if \rept == 1
itt \cond
.elseif \rept == 2
ittt \cond
.else
.error "Unsupported rept macro argument"
.endif
.endif
@ Slightly optimised to avoid incrementing the pointer twice
usraccoff \instr, \reg, \ptr, \inc, 0, \cond, \abort
.if \rept == 2
usraccoff \instr, \reg, \ptr, \inc, \inc, \cond, \abort
.endif
add\cond \ptr, #\rept * \inc
.endm
#else /* !CONFIG_THUMB2_KERNEL */
.macro usracc, instr, reg, ptr, inc, cond, rept, abort, t=TUSER()
.rept \rept
9999:
.if \inc == 1
\instr\cond\()b\()\t \reg, [\ptr], #\inc
.elseif \inc == 4
\instr\cond\()\t \reg, [\ptr], #\inc
.else
.error "Unsupported inc macro argument"
.endif
.pushsection __ex_table,"a"
.align 3
.long 9999b, \abort
.popsection
.endr
.endm
#endif /* CONFIG_THUMB2_KERNEL */
.macro strusr, reg, ptr, inc, cond=al, rept=1, abort=9001f
usracc str, \reg, \ptr, \inc, \cond, \rept, \abort
.endm
.macro ldrusr, reg, ptr, inc, cond=al, rept=1, abort=9001f
usracc ldr, \reg, \ptr, \inc, \cond, \rept, \abort
.endm
/* Utility macro for declaring string literals */
.macro string name:req, string
.type \name , #object
\name:
.asciz "\string"
.size \name , . - \name
.endm
.macro check_uaccess, addr:req, size:req, limit:req, tmp:req, bad:req
#ifndef CONFIG_CPU_USE_DOMAINS
adds \tmp, \addr, #\size - 1
sbcccs \tmp, \tmp, \limit
bcs \bad
#endif
.endm
#endif /* __ASM_ASSEMBLER_H__ */
| {
"pile_set_name": "Github"
} |
.. highlight:: bash
.. _started-solr:
Solr
====
First you need to install Solr itself. There are several ways to do so:
Using Hosted-solr.com
---------------------
If you want to start simple and just create a solr core with a click. You can use hosted-solr.com. For a small fee you get your own solr core in seconds, configured to be used with EXT:solr.
Shipped install script
----------------------
With the extension we ship and install script that can be used for a **development** context. It creates a solr server with a core for all languages.
This script is located in "Resources/Private/Install" an it installs a configured solr server that is useable with EXT:solr.
By default this script is not executable and you need to add the execute permissions to your user to run it.
The example below shows how to install a solr server to /home/developer
.. code-block:: bash
chmod u+x ./Resources/Private/Install/install-solr.sh
./Resources/Private/Install/install-solr.sh -d /home/developer
After running the script you are able to open a solr server with over the loopback address. Which means, when you want to access it from outside, you need to create an ssh tunnel.
Docker
------
You can use our official docker image to start and maintain solr server with a small effort.
To pull the TYPO3 Solr image from docker hub, simply type the following in command line:
.. code-block:: bash
docker pull typo3solr/ext-solr:<EXT:Solr_Version>
.. tip::
To find out available image versions refer to https://hub.docker.com/r/typo3solr/ext-solr/tags
Persistent Data
^^^^^^^^^^^^^^^
Our docker image is based on `official Apache Solr image <https://github.com/docker-solr/docker-solr>`_.
.. important::
Our and official Apache Solr image exports a volume ``/var/solr`` for persistent data.
This volume will be mounted to persist the index and other resources from Apache Solr server.
Following paths inside the exported volume are relevant for backups.
+---------------------------------------------------------------------------------------------------------+----------------------------------------------------------------+
| Path | Contents |
+=========================================================================================================+================================================================+
| data/data/<language> | the index data of corresponding core |
+---------------------------------------------------------------------------------------------------------+----------------------------------------------------------------+
| data/configsets/ext_solr_<EXT:Solr_Version>/conf/_schema_analysis_(stopwords\|synonyms)_<language>.json | the managed stop words and synonyms of corresponding core |
+---------------------------------------------------------------------------------------------------------+----------------------------------------------------------------+
.. tip::
To be save for other scenarios(e.g. SVC of modified Solr Schemas and managed resources), simply backup the whole "data/" folder.
Start container with anonymous volume
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
To run the container with anonymous volume, simply type the following in command line:
.. code-block:: bash
docker run --name=typo3s-solr-server -d -p 8983:8983 typo3solr/ext-solr
This will create a docker anonymous volume and store the data inside of it.
To find out the path of used anonymous volume, simply type the following in command line:
.. code-block:: bash
docker inspect -f '{{ .Mounts }}' typo3s-solr-server
Start container with volume on hosts path
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
There are few steps required to be able to run the container with volume on hosts path.
Following commands will create the named volume "typo3s-solr-server-data" on hosts path and start the container with this volume.
.. code-block:: bash
mkdir .solrdata
docker volume create --name typo3s-solr-server-data --opt type=none --opt device=$PWD/.solrdata --opt o=bind
docker run --name=typo3s-solr-server --mount source=typo3s-solr-server-data,target=/var/solr -d -p 8983:8983 typo3solr/ext-solr
.. important::
The folder for solr data MUST exist on the host machine.
.. important::
The data is owned by containers solr UNIX-User/Group with id 8983, and MUST NOT be changed(re-owned) to different UNIX-Users.
.. tip::
Following is equivalent docker-compose.yaml definition with ".solrdata" folder next to docker-compose.yaml file.
.. code-block:: yaml
version: '3.6'
services:
solr:
container_name: typo3s-solr-server
image: typo3solr/ext-solr:<EXT:Solr_Version>
ports:
- 8983:8983
volumes:
- typo3s-solr-server-data:/var/solr
volumes:
typo3s-solr-server-data:
driver: local
driver_opts:
type: none
device: $PWD/.solrdata
o: bind
Check if Solr is up and running
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
To check whether Solr is up and running head over to:
``http://<ip>:8983/solr/#/core_en/query``.
You should see the web interface of Solr to run queries:
.. figure:: ../Images/GettingStarted/solr-query-webinterface.png
**Important**: The image ships a default cores for all languages. The data of the cores is stored on an exported volume. When you want to update the container, you can just start a new container using the data volume of the old container. But at the same time this has the limitation, that you should only use this image with the default cores! If you want to create custom cores with a different configuration please read the section "Advanced Docker Usage"
Please note: The steps above show how to build the image from the Dockerfile. You can also download and use our compiled images from dockerhub:
https://hub.docker.com/r/typo3solr/ext-solr/
Advanced Docker Usage
---------------------
Our image has the intension to create running cores out of the box. This implies, that the schema is inside the container.
The intension in our integration was to stay as close as possible to the official Apache Solr docker images. Sometimes it might make
sence that you use the official image directly instead of our image. An example could be when you want to have the solrconfig, schema and data outside of the container.
The following example shows how you can run our configuration with the official Apache Solr docker container by mounting the configuration and data from a volume (When using Docker on macOS make sure you've added the volume folder to "Preferences -> File Sharing").
.. code-block:: bash
mkdir -p ~/mysolr
cp -r Resources/Private/Solr/* ~/mysolr/.
mkdir ~/mysolr/data
sudo chown -R 8983:8983 ~/mysolr
docker run -d -p 8983:8983 -v ~/mysolr:/var/solr/data solr:8.5
Other Setup
-----------
Beside the install script and Docker there are various possibilities to setup solr. All of these possibilities are not
officially supported, but the simplify the setup i want to mention them shortly here and summarize the needed steps.
Known Installers
^^^^^^^^^^^^^^^^
All of these installers can be used to setup a plain, reboot save solr server:
* Use the installer shipped with solr itself (bin/install_solr_service.sh):
Allows to install solr on many distributions including init scripts (At the time of development ubuntu 16.04 was not supported and therefore it was no option for us to use it).
* Use chef / ansible / whatever dev ops tool:
Allows you to setup a solr server with your DevOps tool.
e.g. https://galaxy.ansible.com/geerlingguy/solr/ (ansible) or https://supermarket.chef.io/cookbooks/solr (chef)
Deployment of EXT:solr configuration into Apache Solr
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Since EXT:solr 6.0.0 the configuration and all jar files are shipped in one "configSet". The goal of this approach is to make the deployment much easier.
All you need to do is, you need to copy the configSet directory into your prepared solr installation and replace the solr.xml file. In the installer we do it like this:
.. code-block:: bash
cp -r ${EXTENSION_ROOTPATH}/Resources/Private/Solr/configsets ${SOLR_INSTALL_DIR}/server/solr
cp ${EXTENSION_ROOTPATH}/Resources/Private/Solr/solr.xml ${SOLR_INSTALL_DIR}/server/solr/solr.xml
After this, you can decide if you want to create the default cores by copying the default core.properties files or if you want to create a core with the solr rest api.
Copy the default cores:
.. code-block:: bash
cp -r ${EXTENSION_ROOTPATH}/Resources/Private/Solr/cores ${SOLR_INSTALL_DIR}/server/solr
Create a core with the rest api:
.. code-block:: bash
curl "http://localhost:8983/solr/admin/cores?action=CREATE&name=core_de&configSet=ext_solr_8_0_0&schema=german/schema.xml&dataDir=../../data/german"
After installing the solr server and deploying all schemata, the TYPO3 reports module helps you to verify if your setup fits to the requirements of EXT:solr
You now have a fully working, pre configured Solr running to start with
No you can continue with installing the extension :ref:`started-install-extension`.
| {
"pile_set_name": "Github"
} |
//
// DAModularTableViewController.h
// DAModularTableView
//
// Created by Daniel Amitay on 8/5/12.
// Copyright (c) 2012 Daniel Amitay. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "DAModularTableView.h"
@interface DAModularTableViewController : UITableViewController
@property (nonatomic, strong) DAModularTableView *tableView;
@property (nonatomic, assign) CGRect frame;
@property (nonatomic, copy) void(^viewDidLoadBlock)();
- (id)initWithFrame:(CGRect)aFrame style:(UITableViewStyle)aStyle;
@end
| {
"pile_set_name": "Github"
} |
package com.godcheese.nimrod.system.controller;
import com.godcheese.nimrod.common.others.Common;
import com.godcheese.nimrod.system.System;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import static com.godcheese.nimrod.common.security.SimpleUserDetailsServiceImpl.SYSTEM_ADMIN;
/**
* @author godcheese [godcheese@outlook.com]
* @date 2018-02-22
*/
@Controller
@RequestMapping(System.Page.OPERATION_LOG)
public class OperationLogController {
@PreAuthorize("hasRole('" + SYSTEM_ADMIN + "') OR hasAuthority('/SYSTEM/OPERATION_LOG/LIST')")
@RequestMapping("/list")
public String list() {
return Common.trimSlash(System.Page.OPERATION_LOG + "/list");
}
@PreAuthorize("isAuthenticated()")
@RequestMapping("/view_dialog")
public String viewDialog() {
return Common.trimSlash(System.Page.OPERATION_LOG + "/view_dialog");
}
}
| {
"pile_set_name": "Github"
} |
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<meta name="description" content="An app for producing linguistics syntax trees from labelled bracket notation." />
<link rel="canonical" href="http://mshang.ca/syntree" />
<title>Syntax Tree Generator</title>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-25344866-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<a href="https://github.com/mshang/syntree"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_orange_ff7600.png" alt="Fork me on GitHub"></a>
<div id="accordion">
<h3><a href="#">Syntax Tree Generator</a></h3><div style="text-align:left">
<textarea id="i" rows="4">[S [NP This] [VP [V is] [^NP a wug]]]</textarea>
(C) 2011 by <a href="http://mshang.ca/">Miles Shang</a>, see <a href="LICENSE.txt">license</a>.
</div>
<h3><a href="#">Options</a></h3><div>
<table>
<col width="1*">
<col width="1*">
<tr>
<td colspan="2" align="center"><div id="font-style-radio" class="nobr">
<input type="radio" name="font-style" id="serif" value="serif" class="redraw" /><label for="serif">Serif</label>
<input type="radio" name="font-style" id="sans-serif" value="sans-serif" class="redraw" checked /><label for="sans-serif">Sans-Serif</label>
<input type="radio" name="font-style" id="monospace" value="monospace" class="redraw" /><label for="monospace">Monospace</label>
</div></td>
</tr>
<tr>
<td align="center">Terminals:</td>
<td align="center">Non-terminals:</td>
</tr>
<tr>
<td align="center"><div id="term-font-check" class="nobr">
<input type="checkbox" id="term-bold" class="redraw" /><label for="term-bold">Bold</label>
<input type="checkbox" id="term-ital" class="redraw" /><label for="term-ital">Italic</label>
</span></td>
<td align="center"><div id="nonterm-font-check" class="nobr">
<input type="checkbox" id="nonterm-bold" class="redraw" /><label for="nonterm-bold">Bold</label>
<input type="checkbox" id="nonterm-ital" class="redraw" /><label for="nonterm-ital">Italic</label>
</span></td>
</tr>
<tr>
<td align="left">Font size:</td>
<td><div id="font-size-slider"></div></td>
</tr>
<tr>
<td align="left">Height:</td>
<td><div id="vert-space-slider"></div></td>
</tr>
<tr>
<td align="left">Width:</td>
<td><div id="hor-space-slider"></div></td>
</tr>
<tr>
<td align="center" colspan="2"><div class="nobr">
<input type="checkbox" id="color-check" class="redraw" checked /><label for="color-check">Color</label>
<input type="checkbox" id="term-lines" class="redraw" checked /><label for="term-lines">Terminal lines</label>
<a href="#" id="make-link">Link</a>
</div></td>
</tr>
</table>
</div>
<h3><a href="#">Help</a></h3><div class="help">
<p>Use labelled bracket notation. This app will build the tree as you type and will attempt to close any brackets that you may be missing. Save the image to your computer by right-clicking on it and selecting "Save image as". For more information, including on how to draw movement lines, visit the <a href="https://github.com/mshang/syntree/wiki">wiki</a>.</p>
<h3>Examples</h3>
<a class="example" href="?i=[NP^ Alice]">[NP^ Alice]</a><br />
<a class="example" href="?i=[NP [N Alice] and [N Bob]]">[NP [N Alice] and [N Bob]]</a><br />
<a class="example" href="?i=[S[NP[N Alice]][VP[V is][NP[N'[N a student][PP^ of physics">[S[NP[N Alice]][VP[V is][NP[N'[N a student][PP^ of physics</a><br />
<a class="example" href="?i=[S [X_a Movement] [Y example <a>]]">[S [X_a Movement] [Y example <a>]]</a>
</div>
</div>
<br />
<div id="image-goes-here"></div>
<style type="text/css">
body { font-size: small !important; font-family: sans-serif; margin: 20px; background-color: #ffffff}
#accordion { margin: 0px auto; width: 500px; text-align: center; }
table { margin: 0px auto; }
//.ui-widget { font-size:small !important; }
td {font-size:small !important;}
textarea {resize: vertical; width: 100%}
a.example { text-decoration: none; color: #4183C4!important; }
.help {text-align: left;}
#image-goes-here { text-align: center; }
img { border: 1px solid #bbbbbb; }
.nobr { white-space: nowrap; }
</style>
<link type="text/css" href="css/cupertino/jquery-ui-1.8.18.custom.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.18.custom.min.js"></script>
<script type="text/javascript" src="js/base64.js"></script>
<script type="text/javascript" src="js/canvas2image.js"></script>
<script type="text/javascript" src="js/syntree.js"></script>
<script type="text/javascript">
function handler(font_size_update, vert_space_update, hor_space_update) {
try {
// Initialize the various options.
var term_font = "";
var nonterm_font = "";
var color = false;
var term_lines = false;
if (document.getElementById("term-ital").checked)
term_font = term_font + "italic ";
if (document.getElementById("term-bold").checked)
term_font = term_font + "bold ";
if (document.getElementById("nonterm-ital").checked)
nonterm_font = nonterm_font + "italic ";
if (document.getElementById("nonterm-bold").checked)
nonterm_font = nonterm_font + "bold ";
if (document.getElementById("color-check").checked)
color = true;
if (document.getElementById("term-lines").checked)
term_lines = true;
font_size = $("#font-size-slider").slider( "option", "value" );
vert_space = $("#vert-space-slider").slider( "option", "value" );
hor_space = $("#hor-space-slider").slider( "option", "value" );
if (font_size_update) font_size = font_size_update;
if (vert_space_update) vert_space = vert_space_update;
if (hor_space_update) hor_space = hor_space_update;
term_font = term_font + font_size + "pt ";
nonterm_font = nonterm_font + font_size + "pt ";
term_font = term_font + $('input:radio[name=font-style]:checked').val();
nonterm_font = nonterm_font + $('input:radio[name=font-style]:checked').val();
// Get the string.
var str = document.getElementById("i").value;
/*$("#image-goes-here").text(str + ", " + font_size + ", " +
term_font + ", " + nonterm_font + ", " + vert_space + ", " + hor_space);*/
var img = go(str, font_size, term_font, nonterm_font, vert_space, hor_space, color, term_lines);
$("#image-goes-here").empty();
$("#image-goes-here").append(img);
} catch (err) {
if (debug) {
throw(err);
} else {
if (err == "canvas")
$("#image-goes-here").text("Browser not supported.");
}
} // try-catch
return false;
} // handler()
$(function() {
// UI
$("#make-link, #color-check, #term-lines").button();
$("#font-size-slider").slider({value: 12, min: 8, max: 16, step: 1});
$("#vert-space-slider").slider({value: 35, min: 35, max: 70, step: 5});
$("#hor-space-slider").slider({value: 10, min: 10, max: 50, step: 5});
$("#font-style-radio, #term-font-check, #nonterm-font-check").buttonset();
$("#accordion").accordion({collapsible: true, icons: false, autoHeight: false});
try {
var qs = decodeURIComponent(window.location.search.slice(1));
qs = qs.replace(/^i=/,"");
qs = qs.replace(/\+/g," ");
if (qs == "") throw "";
document.getElementById("i").value = qs;
} catch (err) {}
handler();
// Events
$("#i").keypress(function() {handler(); return true;});
$("#i").keyup(function() {handler(); return true;});
$("#i").keydown(function() {handler(); return true;});
$("#i").change(function() {handler(); return true;});
$(".redraw").change(function() {return handler()});
$("#make-link").click(function() {
var loc = window.location.href;
loc = loc.replace(window.location.search, "");
window.prompt ("Link for this tree:", loc + "?i=" +
encodeURIComponent(document.getElementById("i").value));
return false;
});
$("#font-size-slider").bind("slide", function (event, ui) {
handler(ui.value, null, null); return true;
});
$("#vert-space-slider").bind("slide", function (event, ui) {
handler(null, ui.value, null); return true;
});
$("#hor-space-slider").bind("slide", function (event, ui) {
handler(null, null, ui.value); return true;
});
});
</script>
</body>
</html> | {
"pile_set_name": "Github"
} |
#appModules/loudtalks.py
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2010 Peter Vagner <peter.v@datagate.sk>
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
import appModuleHandler
from NVDAObjects.IAccessible import IAccessible
import oleacc
from NVDAObjects.IAccessible.sysListView32 import ListItem
import controlTypes
from NVDAObjects.window import Window
class loudTalksLink(Window):
value = None
role = controlTypes.ROLE_LINK
class loudTalksContactListItem(ListItem):
shouldAllowIAccessibleFocusEvent = True
def _get_keyboardShortcut(self):
keyboardShortcut = super(loudTalksContactListItem,self).keyboardShortcut
if keyboardShortcut == "None":
return None
return keyboardShortcut
class AppModule(appModuleHandler.AppModule):
def chooseNVDAObjectOverlayClasses(self, obj, clsList):
if obj.role == controlTypes.ROLE_WINDOW:
return
if obj.windowClassName == "UrlStaticWndClass":
clsList.insert(0, loudTalksLink)
elif obj.windowControlID == 1009 and isinstance(obj, IAccessible) and obj.IAccessibleRole == oleacc.ROLE_SYSTEM_LISTITEM:
clsList.insert(0, loudTalksContactListItem)
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2002-2020 Gargoyle Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gargoylesoftware.htmlunit.svg;
import java.util.Map;
import com.gargoylesoftware.htmlunit.SgmlPage;
import com.gargoylesoftware.htmlunit.html.DomAttr;
/**
* Wrapper for the SVG element "font-face-name".
*
* @author Frank Danek
*/
public class SvgFontFaceName extends SvgElement {
/** The tag represented by this element. */
public static final String TAG_NAME = "font-face-name";
/**
* Creates a new instance.
*
* @param namespaceURI the URI that identifies an XML namespace
* @param qualifiedName the qualified name of the element type to instantiate
* @param page the page that contains this element
* @param attributes the initial attributes
*/
SvgFontFaceName(final String namespaceURI, final String qualifiedName, final SgmlPage page,
final Map<String, DomAttr> attributes) {
super(namespaceURI, qualifiedName, page, attributes);
}
}
| {
"pile_set_name": "Github"
} |
import fs from 'fs';
import util from 'util';
import path from 'path';
import child_process from 'child_process';
import Worker from 'jest-worker';
import chalk from 'chalk';
import {table, createStream} from 'table';
import corejs2 from './data/corejs2';
import corejs3 from './data/corejs3';
const corejsVersions = {
2: corejs2,
3: corejs3,
};
import {getRC} from "./rc";
import {esmBaseline} from "./data/esmBaseline";
import {inTime, fileSize, isBelow, getSize} from "./utils";
export const scan = async (dist, out, _options = getRC()) => {
console.log(chalk.bold.underline.green("devolution"), "🦎 -> 🦖");
const options = await _options;
const corejsVersion = +(options.corejs || 2);
const corejs = corejsVersions[corejsVersion];
if (!corejs) {
throw new Error('invalid core-js version:' + corejsVersion);
}
if (options.useSWC) {
try {
require("@swc/core");
} catch (e) {
throw new Error('to use SWC please install `@swc/core`');
}
}
const {builtIns, definitions} = corejs;
const {targets, proposals, addPolyfills} = options;
const mainBundleReg = new RegExp(options.rootBundles);
const dontPolyfill = (options.dontPolyfill || []).map(x => new RegExp(x));
const firstTarget = targets[Object.keys(targets)[0]];
// find all required files
const allFiles = Array.isArray(options.files) ? options.files : await util.promisify(fs.readdir)(dist);
const jsFiles = allFiles.filter(file => file.match(options.match));
if (!jsFiles.length) {
console.log(chalk.bold.underline.ref("no files to process"));
return false;
}
const otherFiles = allFiles.filter(file => (
!jsFiles.includes(file) &&
!fs.lstatSync(path.join(dist, file)).isDirectory()
));
const mainBundle = jsFiles.find(name => name === mainBundleReg || name.match(mainBundleReg));
// prepare polyfill target
const polyfills = {};
let basePolyfills = [];
const polyCache = {};
const devolutionRoot = path.resolve(path.join(out, '.devolution'));
const polyfillDir = path.resolve(path.join(devolutionRoot, '.polyfills'));
const outDir = path.resolve(out);
if (!fs.existsSync(out)) {
fs.mkdirSync(out);
}
if (!fs.existsSync(devolutionRoot)) {
fs.mkdirSync(devolutionRoot);
}
if (!fs.existsSync(polyfillDir)) {
fs.mkdirSync(polyfillDir);
}
console.log({
dist,
out,
mainBundle,
bundledPolyfills: options.includesPolyfills,
'core-js': corejsVersion,
proposals
});
const processPolyfills = (fills) => (
proposals
? fills
: fills.filter(name => !name.startsWith('esnext.'))
);
console.log(" -> 🦎 -> ", chalk.bold.underline.green("scanning files"));
console.group();
await inTime(async () => {
const tableStream = createStream({
columnDefault: {
width: 50
},
columns: {
0: {
width: 70,
},
1: {
alignment: 'right'
}
},
columnCount: 2
});
tableStream.write(['file', 'polyfills required']);
const worker = new Worker(require.resolve('./workers/detect'));
const polyfillsLeft = x => basePolyfills.indexOf(x) < 0;
if (mainBundle && mainBundle !== '.') {
basePolyfills = polyfills[mainBundle] = processPolyfills(
await worker.extractPolyfills(dist, mainBundle, options.babelScan, definitions)
);
tableStream.write([mainBundle, basePolyfills.length]);
}
if (addPolyfills && !mainBundle) {
throw new Error("devolution: in order to use `addPolyfills` define `rootBundles` condition.")
}
await Promise.all(
jsFiles.map(async file => {
if (file !== mainBundle) {
polyfills[file] = processPolyfills(
await worker.extractPolyfills(dist, file, options.babelScan, definitions)
).filter(polyfillsLeft);
tableStream.write([file, polyfills[file].length]);
}
})
);
worker.end();
});
console.groupEnd();
const targetPolyfills = {};
console.log(" -> 🦎 -> 🥚", chalk.bold.underline.green("composing polyfills"));
console.group();
await inTime(async () => {
const worker = new Worker(require.resolve('./workers/composePolyfill'));
const tableStream = createStream({
columnDefault: {
width: 50
},
columns: {
0: {
width: 6
},
1: {
width: 40
},
2: {
width: 15,
wrapWord: true,
alignment: 'right'
},
3: {
width: 6,
alignment: 'right'
},
4: {
width: 50,
wrapWord: true,
}
},
columnCount: 6
});
tableStream.write(['target', 'file', 'missing polyfills', 'size', 'names', 'extra']);
const usedInMain = new Set();
const writePromises = [];
Object
.keys(targets)
.forEach(target => {
targetPolyfills[target] = [];
Object
.keys(polyfills)
.forEach(key => {
let extraCode = '';
const localPolyfills = polyfills[key]
.filter(
rule => (
// would not be included in a base image
(rule==='@regenerator' || !(options.includesPolyfills && isBelow(rule, builtIns[rule], firstTarget))) &&
// and not used in the main bundle
(!usedInMain.has(rule) || key===mainBundle) &&
// not ignored in config
!options.ignorePolyfills.includes(rule)
)
);
if (key === mainBundle) {
if(addPolyfills) {
localPolyfills.push(...(addPolyfills[target] || []));
}
localPolyfills.forEach(name => usedInMain.add(name));
}
// uses regenerator
if (localPolyfills.includes('@regenerator')) {
if (isBelow('regenerator', esmBaseline, targets[target])) {
extraCode += "import 'regenerator-runtime';"
}
}
const list = localPolyfills
.filter(rule => (
// and required for the target
isBelow(rule, builtIns[rule], targets[target])
)
);
list.forEach(p => {
if (!targetPolyfills[target].includes(p)) {
targetPolyfills[target].push(p)
}
});
const chunkPolyfills = list.map(x => `import 'core-js/modules/${x}'`);
const fileIn = path.join(polyfillDir, `${target}-${key}.mjs`);
fs.writeFileSync(fileIn, extraCode + chunkPolyfills.join('\n'));
writePromises.push((async () => {
let composedResult = polyCache[`${target}-${key}`] = '';
if (!dontPolyfill.some(mask => key.match(mask))) {
if (fileSize(fileIn) > 0) {
composedResult = await worker.composePolyfill(fileIn);
const {error} = composedResult;
if (error) {
console.log('');
console.error(`failed to compose polyfill from ${fileIn}. Error: ${error}`);
throw new Error(error);
}
polyCache[`${target}-${key}`] = composedResult;
}
}
tableStream.write([target, key, list.length ? list.length : '-', composedResult.length,list, extraCode]);
})());
});
});
await Promise.all(writePromises);
worker.end();
});
console.groupEnd();
console.log(" -> 🦎 -> 🦖", chalk.bold.underline.green("devoluting targets..."));
console.group();
await inTime(async () => {
const worker = new Worker(require.resolve('./workers/transpile'));
const writePromises = [];
const tableStream = createStream({
columnDefault: {
width: 50
},
columns: {
0: {
width: 6,
},
1: {
width: 70,
},
2: {
width: 10,
alignment: 'right'
},
4: {
width: 10
}
},
columnCount: 4
});
tableStream.write(['target', 'file', 'time, ms', 'delta']);
Object
.keys(targets)
.forEach(target => {
const bundleDir = path.join(outDir, target);
if (!fs.existsSync(bundleDir)) {
fs.mkdirSync(bundleDir);
}
writePromises.push(...Object
.keys(polyfills)
.map(async file => {
const fileOut = path.join(bundleDir, file);
const now = Date.now();
const useTerser = target === 'esm' ? options.useTerserForBaseline : options.useTerser;
const code = await worker.compileAndWrite(
dist, file, target,
fileOut, polyCache[`${target}-${file}`],
{
targets: targets[target],
plugins: options.babelTransform,
useSWC: options.useSWC,
useTerser: useTerser,
}
);
const delta = fileSize(fileOut) - fileSize(path.join(dist, file));
tableStream.write([target, file, Date.now() - now, (delta > 0 ? '+' : '-') + Math.abs(delta)]);
}))
});
await Promise.all(writePromises);
worker.end();
});
console.groupEnd();
console.group();
await inTime(async () => {
console.log(" -> 🥚 -> 🥚", chalk.bold.underline.green("linking...."), otherFiles.length, 'files');
const copyCommand = options.copyFiles ? 'cp' : 'ln -s';
if (otherFiles.length) {
Object
.keys(targets)
.forEach(target => {
try {
child_process.execSync(
otherFiles
.map(file => `${copyCommand} ${path.join(dist, file)} ${path.join(outDir, target, file)}`)
.join(' && ')
)
} catch (e) {
// nope
}
})
}
});
console.groupEnd();
{
console.log(" -> 🦖", chalk.bold.underline.green("you have been de-evoluted"));
console.group();
const base = getSize(dist, jsFiles);
const report = [
['target', 'size', 'delta', 'polyfills', 'added']
];
report.push(['base', base, 0, '(base)' + basePolyfills.length, '']);
Object
.keys(targets)
.forEach(target => {
const size = getSize(path.join(outDir, target), jsFiles);
const delta = size - base;
report.push([
target,
size,
(delta > 0 ? '+' : '-') + Math.abs(delta),
targetPolyfills[target].length,
targetPolyfills[target].join(',')
]);
});
console.log(table(report, {
columns: {
1: {
alignment: 'right'
},
2: {
alignment: 'right'
},
3: {
alignment: 'right'
},
4: {
width: 60,
wrapWord: true,
}
}
}));
console.groupEnd();
}
return true;
}; | {
"pile_set_name": "Github"
} |
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
load('sort.js');
new BenchmarkSuite('SortCustomCompareFnIntTypes', [1000],
CreateBenchmarks(typedArrayIntConstructors,
[cmp_smaller, cmp_greater]));
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef MODULES_RTP_RTCP_SOURCE_RTP_GENERIC_FRAME_DESCRIPTOR_H_
#define MODULES_RTP_RTCP_SOURCE_RTP_GENERIC_FRAME_DESCRIPTOR_H_
#include <stddef.h>
#include <stdint.h>
#include <vector>
#include "absl/types/optional.h"
#include "api/array_view.h"
namespace webrtc {
class RtpGenericFrameDescriptorExtension;
// Data to put on the wire for FrameDescriptor rtp header extension.
class RtpGenericFrameDescriptor {
public:
static constexpr int kMaxNumFrameDependencies = 8;
static constexpr int kMaxTemporalLayers = 8;
static constexpr int kMaxSpatialLayers = 8;
RtpGenericFrameDescriptor();
RtpGenericFrameDescriptor(const RtpGenericFrameDescriptor&);
~RtpGenericFrameDescriptor();
bool FirstPacketInSubFrame() const { return beginning_of_subframe_; }
void SetFirstPacketInSubFrame(bool first) { beginning_of_subframe_ = first; }
bool LastPacketInSubFrame() const { return end_of_subframe_; }
void SetLastPacketInSubFrame(bool last) { end_of_subframe_ = last; }
// Properties below undefined if !FirstPacketInSubFrame()
// Valid range for temporal layer: [0, 7]
int TemporalLayer() const;
void SetTemporalLayer(int temporal_layer);
// Frame might by used, possible indirectly, for spatial layer sid iff
// (bitmask & (1 << sid)) != 0
int SpatialLayer() const;
uint8_t SpatialLayersBitmask() const;
void SetSpatialLayersBitmask(uint8_t spatial_layers);
int Width() const { return width_; }
int Height() const { return height_; }
void SetResolution(int width, int height);
uint16_t FrameId() const;
void SetFrameId(uint16_t frame_id);
rtc::ArrayView<const uint16_t> FrameDependenciesDiffs() const;
void ClearFrameDependencies() { num_frame_deps_ = 0; }
// Returns false on failure, i.e. number of dependencies is too large.
bool AddFrameDependencyDiff(uint16_t fdiff);
private:
bool beginning_of_subframe_ = false;
bool end_of_subframe_ = false;
uint16_t frame_id_ = 0;
uint8_t spatial_layers_ = 1;
uint8_t temporal_layer_ = 0;
size_t num_frame_deps_ = 0;
uint16_t frame_deps_id_diffs_[kMaxNumFrameDependencies];
int width_ = 0;
int height_ = 0;
};
} // namespace webrtc
#endif // MODULES_RTP_RTCP_SOURCE_RTP_GENERIC_FRAME_DESCRIPTOR_H_
| {
"pile_set_name": "Github"
} |
/**
Core script to handle the entire theme and core functions
**/
var Layout = function() {
var layoutImgPath = 'admin/layout2/img/';
var layoutCssPath = 'admin/layout2/css/';
var resBreakpointMd = Metronic.getResponsiveBreakpoint('md');
//* BEGIN:CORE HANDLERS *//
// this function handles responsive layout on screen size resize or mobile device rotate.
// Set proper height for sidebar and content. The content and sidebar height must be synced always.
var handleSidebarAndContentHeight = function() {
var content = $('.page-content');
var sidebar = $('.page-sidebar');
var body = $('body');
var height;
if (body.hasClass("page-footer-fixed") === true && body.hasClass("page-sidebar-fixed") === false) {
var available_height = Metronic.getViewPort().height - $('.page-footer').outerHeight() - $('.page-header').outerHeight();
if (content.height() < available_height) {
content.attr('style', 'min-height:' + available_height + 'px');
}
} else {
if (body.hasClass('page-sidebar-fixed')) {
height = _calculateFixedSidebarViewportHeight();
if (body.hasClass('page-footer-fixed') === false) {
height = height - $('.page-footer').outerHeight();
}
} else {
var headerHeight = $('.page-header').outerHeight();
var footerHeight = $('.page-footer').outerHeight();
if (Metronic.getViewPort().width < resBreakpointMd) {
height = Metronic.getViewPort().height - headerHeight - footerHeight;
} else {
height = sidebar.outerHeight() + 10;
}
if ((height + headerHeight + footerHeight) <= Metronic.getViewPort().height) {
height = Metronic.getViewPort().height - headerHeight - footerHeight;
}
}
content.attr('style', 'min-height:' + height + 'px');
}
};
// Handle sidebar menu links
var handleSidebarMenuActiveLink = function(mode, el) {
var url = location.hash.toLowerCase();
var menu = $('.page-sidebar-menu');
if (mode === 'click' || mode === 'set') {
el = $(el);
} else if (mode === 'match') {
menu.find("li > a").each(function() {
var path = $(this).attr("href").toLowerCase();
// url match condition
if (path.length > 1 && url.substr(1, path.length - 1) == path.substr(1)) {
el = $(this);
return;
}
});
}
if (!el || el.size() == 0) {
return;
}
if (el.attr('href').toLowerCase() === 'javascript:;' || el.attr('href').toLowerCase() === '#') {
return;
}
var slideSpeed = parseInt(menu.data("slide-speed"));
var keepExpand = menu.data("keep-expanded");
// disable active states
menu.find('li.active').removeClass('active');
menu.find('li > a > .selected').remove();
if (menu.hasClass('page-sidebar-menu-hover-submenu') === false) {
menu.find('li.open').each(function(){
if ($(this).children('.sub-menu').size() === 0) {
$(this).removeClass('open');
$(this).find('> a > .arrow.open').removeClass('open');
}
});
} else {
menu.find('li.open').removeClass('open');
}
el.parents('li').each(function () {
$(this).addClass('active');
$(this).find('> a > span.arrow').addClass('open');
if ($(this).parent('ul.page-sidebar-menu').size() === 1) {
$(this).find('> a').append('<span class="selected"></span>');
}
if ($(this).children('ul.sub-menu').size() === 1) {
$(this).addClass('open');
}
});
if (mode === 'click') {
if (Metronic.getViewPort().width < resBreakpointMd && $('.page-sidebar').hasClass("in")) { // close the menu on mobile view while laoding a page
$('.page-header .responsive-toggler').click();
}
}
};
// Handle sidebar menu
var handleSidebarMenu = function() {
$('.page-sidebar').on('click', 'li > a', function(e) {
if (Metronic.getViewPort().width >= resBreakpointMd && $(this).parents('.page-sidebar-menu-hover-submenu').size() === 1) { // exit of hover sidebar menu
return;
}
if ($(this).next().hasClass('sub-menu') === false) {
if (Metronic.getViewPort().width < resBreakpointMd && $('.page-sidebar').hasClass("in")) { // close the menu on mobile view while laoding a page
$('.page-header .responsive-toggler').click();
}
return;
}
if ($(this).next().hasClass('sub-menu always-open')) {
return;
}
var parent = $(this).parent().parent();
var the = $(this);
var menu = $('.page-sidebar-menu');
var sub = $(this).next();
var autoScroll = menu.data("auto-scroll");
var slideSpeed = parseInt(menu.data("slide-speed"));
var keepExpand = menu.data("keep-expanded");
if (keepExpand !== true) {
parent.children('li.open').children('a').children('.arrow').removeClass('open');
parent.children('li.open').children('.sub-menu:not(.always-open)').slideUp(slideSpeed);
parent.children('li.open').removeClass('open');
}
var slideOffeset = -200;
if (sub.is(":visible")) {
$('.arrow', $(this)).removeClass("open");
$(this).parent().removeClass("open");
sub.slideUp(slideSpeed, function() {
if (autoScroll === true && $('body').hasClass('page-sidebar-closed') === false) {
if ($('body').hasClass('page-sidebar-fixed')) {
menu.slimScroll({
'scrollTo': (the.position()).top
});
} else {
Metronic.scrollTo(the, slideOffeset);
}
}
handleSidebarAndContentHeight();
});
} else {
$('.arrow', $(this)).addClass("open");
$(this).parent().addClass("open");
sub.slideDown(slideSpeed, function() {
if (autoScroll === true && $('body').hasClass('page-sidebar-closed') === false) {
if ($('body').hasClass('page-sidebar-fixed')) {
menu.slimScroll({
'scrollTo': (the.position()).top
});
} else {
Metronic.scrollTo(the, slideOffeset);
}
}
handleSidebarAndContentHeight();
});
}
e.preventDefault();
});
// handle ajax links within sidebar menu
$('.page-sidebar').on('click', ' li > a.ajaxify', function(e) {
e.preventDefault();
Metronic.scrollTop();
var url = $(this).attr("href");
var menuContainer = $('.page-sidebar ul');
var pageContent = $('.page-content');
var pageContentBody = $('.page-content .page-content-body');
menuContainer.children('li.active').removeClass('active');
menuContainer.children('arrow.open').removeClass('open');
$(this).parents('li').each(function() {
$(this).addClass('active');
$(this).children('a > span.arrow').addClass('open');
});
$(this).parents('li').addClass('active');
if (Metronic.getViewPort().width < resBreakpointMd && $('.page-sidebar').hasClass("in")) { // close the menu on mobile view while laoding a page
$('.page-header .responsive-toggler').click();
}
Metronic.startPageLoading();
var the = $(this);
$.ajax({
type: "GET",
cache: false,
url: url,
dataType: "html",
success: function(res) {
if (the.parents('li.open').size() === 0) {
$('.page-sidebar-menu > li.open > a').click();
}
Metronic.stopPageLoading();
pageContentBody.html(res);
Layout.fixContentHeight(); // fix content height
Metronic.initAjax(); // initialize core stuff
},
error: function(xhr, ajaxOptions, thrownError) {
Metronic.stopPageLoading();
pageContentBody.html('<h4>Could not load the requested content.</h4>');
}
});
});
// handle ajax link within main content
$('.page-content').on('click', '.ajaxify', function(e) {
e.preventDefault();
Metronic.scrollTop();
var url = $(this).attr("href");
var pageContent = $('.page-content');
var pageContentBody = $('.page-content .page-content-body');
Metronic.startPageLoading();
if (Metronic.getViewPort().width < resBreakpointMd && $('.page-sidebar').hasClass("in")) { // close the menu on mobile view while laoding a page
$('.page-header .responsive-toggler').click();
}
$.ajax({
type: "GET",
cache: false,
url: url,
dataType: "html",
success: function(res) {
Metronic.stopPageLoading();
pageContentBody.html(res);
Layout.fixContentHeight(); // fix content height
Metronic.initAjax(); // initialize core stuff
},
error: function(xhr, ajaxOptions, thrownError) {
pageContentBody.html('<h4>Could not load the requested content.</h4>');
Metronic.stopPageLoading();
}
});
});
// handle scrolling to top on responsive menu toggler click when header is fixed for mobile view
$(document).on('click', '.page-header-fixed-mobile .page-header .responsive-toggler', function(){
Metronic.scrollTop();
});
};
// Helper function to calculate sidebar height for fixed sidebar layout.
var _calculateFixedSidebarViewportHeight = function() {
var sidebarHeight = Metronic.getViewPort().height - $('.page-header').outerHeight();
if ($('body').hasClass("page-footer-fixed")) {
sidebarHeight = sidebarHeight - $('.page-footer').outerHeight();
}
return sidebarHeight;
};
// Handles fixed sidebar
var handleFixedSidebar = function() {
var menu = $('.page-sidebar-menu');
Metronic.destroySlimScroll(menu);
if ($('.page-sidebar-fixed').size() === 0) {
handleSidebarAndContentHeight();
return;
}
if (Metronic.getViewPort().width >= resBreakpointMd) {
menu.attr("data-height", _calculateFixedSidebarViewportHeight());
Metronic.initSlimScroll(menu);
handleSidebarAndContentHeight();
}
};
// Handles sidebar toggler to close/hide the sidebar.
var handleFixedSidebarHoverEffect = function () {
var body = $('body');
if (body.hasClass('page-sidebar-fixed')) {
$('.page-sidebar').on('mouseenter', function () {
if (body.hasClass('page-sidebar-closed')) {
$(this).find('.page-sidebar-menu').removeClass('page-sidebar-menu-closed');
}
}).on('mouseleave', function () {
if (body.hasClass('page-sidebar-closed')) {
$(this).find('.page-sidebar-menu').addClass('page-sidebar-menu-closed');
}
});
}
};
// Hanles sidebar toggler
var handleSidebarToggler = function() {
var body = $('body');
if ($.cookie && $.cookie('sidebar_closed') === '1' && Metronic.getViewPort().width >= resBreakpointMd) {
$('body').addClass('page-sidebar-closed');
$('.page-sidebar-menu').addClass('page-sidebar-menu-closed');
}
// handle sidebar show/hide
$('body').on('click', '.sidebar-toggler', function(e) {
var sidebar = $('.page-sidebar');
var sidebarMenu = $('.page-sidebar-menu');
$(".sidebar-search", sidebar).removeClass("open");
if (body.hasClass("page-sidebar-closed")) {
body.removeClass("page-sidebar-closed");
sidebarMenu.removeClass("page-sidebar-menu-closed");
if ($.cookie) {
$.cookie('sidebar_closed', '0');
}
} else {
body.addClass("page-sidebar-closed");
sidebarMenu.addClass("page-sidebar-menu-closed");
if (body.hasClass("page-sidebar-fixed")) {
sidebarMenu.trigger("mouseleave");
}
if ($.cookie) {
$.cookie('sidebar_closed', '1');
}
}
$(window).trigger('resize');
});
handleFixedSidebarHoverEffect();
// handle the search bar close
$('.page-sidebar').on('click', '.sidebar-search .remove', function(e) {
e.preventDefault();
$('.sidebar-search').removeClass("open");
});
// handle the search query submit on enter press
$('.page-sidebar .sidebar-search').on('keypress', 'input.form-control', function(e) {
if (e.which == 13) {
$('.sidebar-search').submit();
return false; //<---- Add this line
}
});
// handle the search submit(for sidebar search and responsive mode of the header search)
$('.sidebar-search .submit').on('click', function(e) {
e.preventDefault();
if ($('body').hasClass("page-sidebar-closed")) {
if ($('.sidebar-search').hasClass('open') === false) {
if ($('.page-sidebar-fixed').size() === 1) {
$('.page-sidebar .sidebar-toggler').click(); //trigger sidebar toggle button
}
$('.sidebar-search').addClass("open");
} else {
$('.sidebar-search').submit();
}
} else {
$('.sidebar-search').submit();
}
});
// handle close on body click
if ($('.sidebar-search').size() !== 0) {
$('.sidebar-search .input-group').on('click', function(e) {
e.stopPropagation();
});
$('body').on('click', function() {
if ($('.sidebar-search').hasClass('open')) {
$('.sidebar-search').removeClass("open");
}
});
}
};
// Handles the horizontal menu
var handleHeader = function() {
// handle search box expand/collapse
$('.page-header').on('click', '.search-form', function(e) {
$(this).addClass("open");
$(this).find('.form-control').focus();
$('.page-header .search-form .form-control').on('blur', function(e) {
$(this).closest('.search-form').removeClass("open");
$(this).unbind("blur");
});
});
// handle hor menu search form on enter press
$('.page-header').on('keypress', '.hor-menu .search-form .form-control', function(e) {
if (e.which == 13) {
$(this).closest('.search-form').submit();
return false;
}
});
// handle header search button click
$('.page-header').on('mousedown', '.search-form.open .submit', function(e) {
e.preventDefault();
e.stopPropagation();
$(this).closest('.search-form').submit();
});
};
// Handles Bootstrap Tabs.
var handleTabs = function() {
// fix content height on tab click
$('body').on('shown.bs.tab', 'a[data-toggle="tab"]', function() {
handleSidebarAndContentHeight();
});
};
// Handles the go to top button at the footer
var handleGoTop = function() {
var offset = 300;
var duration = 500;
if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) { // ios supported
$(window).bind("touchend touchcancel touchleave", function(e) {
if ($(this).scrollTop() > offset) {
$('.scroll-to-top').fadeIn(duration);
} else {
$('.scroll-to-top').fadeOut(duration);
}
});
} else { // general
$(window).scroll(function() {
if ($(this).scrollTop() > offset) {
$('.scroll-to-top').fadeIn(duration);
} else {
$('.scroll-to-top').fadeOut(duration);
}
});
}
$('.scroll-to-top').click(function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: 0
}, duration);
return false;
});
};
// Hanlde 100% height elements(block, portlet, etc)
var handle100HeightContent = function() {
var target = $('.full-height-content');
var height;
if (!target.hasClass('portlet')) {
return;
}
height = Metronic.getViewPort().height -
$('.page-header').outerHeight(true) -
$('.page-footer').outerHeight(true) -
$('.page-title').outerHeight(true) -
$('.page-bar').outerHeight(true);
if ($('body').hasClass('page-header-fixed')) {
height = height - $('.page-header').outerHeight(true);
}
var portletBody = target.find('.portlet-body');
if (Metronic.getViewPort().width < resBreakpointMd) {
Metronic.destroySlimScroll(portletBody.find('.full-height-content-body')); // destroy slimscroll
return;
}
if (target.find('.portlet-title')) {
height = height - target.find('.portlet-title').outerHeight(true);
}
height = height - parseInt(portletBody.css("padding-top"));
height = height - parseInt(portletBody.css("padding-bottom"));
if (target.hasClass("full-height-content-scrollable")) {
portletBody.find('.full-height-content-body').css('height', height);
Metronic.initSlimScroll(portletBody.find('.full-height-content-body'));
} else {
portletBody.css('min-height', height);
}
};
//* END:CORE HANDLERS *//
return {
// Main init methods to initialize the layout
// IMPORTANT!!!: Do not modify the core handlers call order.
initHeader: function() {
handleHeader(); // handles horizontal menu
},
setSidebarMenuActiveLink: function(mode, el) {
handleSidebarMenuActiveLink(mode, el);
},
initSidebar: function() {
//layout handlers
handleFixedSidebar(); // handles fixed sidebar menu
handleSidebarMenu(); // handles main menu
handleSidebarToggler(); // handles sidebar hide/show
if (Metronic.isAngularJsApp()) {
handleSidebarMenuActiveLink('match'); // init sidebar active links
}
Metronic.addResizeHandler(handleFixedSidebar); // reinitialize fixed sidebar on window resize
},
initContent: function() {
handle100HeightContent(); // handles 100% height elements(block, portlet, etc)
handleTabs(); // handle bootstrah tabs
Metronic.addResizeHandler(handleSidebarAndContentHeight); // recalculate sidebar & content height on window resize
Metronic.addResizeHandler(handle100HeightContent); // reinitialize content height on window resize
},
initFooter: function() {
handleGoTop(); //handles scroll to top functionality in the footer
},
init: function () {
this.initHeader();
this.initSidebar();
this.initContent();
this.initFooter();
},
//public function to fix the sidebar and content height accordingly
fixContentHeight: function() {
handleSidebarAndContentHeight();
},
initFixedSidebarHoverEffect: function() {
handleFixedSidebarHoverEffect();
},
initFixedSidebar: function() {
handleFixedSidebar();
},
getLayoutImgPath: function() {
return Metronic.getAssetsPath() + layoutImgPath;
},
getLayoutCssPath: function() {
return Metronic.getAssetsPath() + layoutCssPath;
}
};
}(); | {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 1cff5f9620f5c6147af68780a5da2952
timeCreated: 1498584916
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
/*
*
* (C) Copyright IBM Corp. and others 1998-2014 - All Rights Reserved
*
*/
#ifndef __SEGMENTARRAYPROCESSOR_H
#define __SEGMENTARRAYPROCESSOR_H
/**
* \file
* \internal
*/
#include "LETypes.h"
#include "MorphTables.h"
#include "SubtableProcessor2.h"
#include "NonContextualGlyphSubst.h"
#include "NonContextualGlyphSubstProc2.h"
U_NAMESPACE_BEGIN
class LEGlyphStorage;
class SegmentArrayProcessor2 : public NonContextualGlyphSubstitutionProcessor2
{
public:
virtual void process(LEGlyphStorage &glyphStorage, LEErrorCode &success);
SegmentArrayProcessor2(const LEReferenceTo<MorphSubtableHeader2> &morphSubtableHeader, LEErrorCode &success);
virtual ~SegmentArrayProcessor2();
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @deprecated ICU 54. See {@link icu::LayoutEngine}
*/
virtual UClassID getDynamicClassID() const;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @deprecated ICU 54. See {@link icu::LayoutEngine}
*/
static UClassID getStaticClassID();
private:
SegmentArrayProcessor2();
protected:
LEReferenceTo<SegmentArrayLookupTable> segmentArrayLookupTable;
};
U_NAMESPACE_END
#endif
| {
"pile_set_name": "Github"
} |
use em::*;
// this will fail because of incorrect data types
#[gpu_use]
fn main() {
let data = vec![0.0f64; 1000];
gpu_do!(load(data));
gpu_do!(launch());
for i in 0..1000 {
data[i] = data[i];
}
gpu_do!(read(data));
} | {
"pile_set_name": "Github"
} |
/*******************************************************************************
* @license
* Copyright (c) 2012 VMware, Inc. All Rights Reserved.
* THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
* ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
* CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
* You can obtain a current copy of the Eclipse Public License from
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* Contributors:
* Andrew Eisenberg
* Andrew Clement
* Kris De Volder
* Christopher Johnson
******************************************************************************/
/*global requirejs $ console window require XMLHttpRequest*/
requirejs.config({
packages: [{ name: 'dojo', location: 'dojo', main:'lib/main-browser', lib:'.'},
{ name: 'dijit',location: 'dijit',main:'lib/main',lib: '.'}],
paths: {
i18n: 'requirejs/i18n',
text: 'requirejs/text',
fileapi: 'orion/editor/fileapi',
jquery: 'lib/jquery-1.7.2.min',
jquery_ui: 'lib/jquery-ui-custom',
jsbeautify: 'orion/editor/jsbeautify',
jsrender: 'lib/jsrender'
}
});
require(["editor", "scripted/utils/", "orion/explorer-table", "fileapi", "jquery"],
function(mEditor, mExplorerTable, mFileApi, mJquery) {
function loadScriptedConfig(scriptedconfig) {
// Load the configuration file
try {
var contents = mFileApi.getContentsSync(scriptedconfig);
console.log("Loading scripted configuration: "+scriptedconfig);
if (contents.length!==0) {
var endBlockCommentIndex = contents.indexOf('*/');
if (endBlockCommentIndex!==-1) {
contents = contents.substr(endBlockCommentIndex+2);
}
window.scripted.config = JSON.parse(contents);
}
} catch (e) {
console.error("Unable to parse JSON config block: "+e);
}
if (window.scripted.config && window.scripted.config.ui && window.scripted.config.ui.navigator===false) {
window.scripted.navigator=false; // default is true
}
}
mEditor.editor.setInput("Content",null,'Loading...');
window.editor = mEditor.editor;
// Load editor contents - asynchronous activity
mEditor.loadContents();
// Create new FileExplorer
var explorer = new mExplorerTable.FileExplorer({
//serviceRegistry: serviceRegistry, treeRoot: treeRoot, selection: selection,
//searcher: searcher, fileClient: fileClient, commandService: commandService,
//contentTypeService: contentTypeService,
parentId: "explorer-tree"
//breadcrumbId: "location", toolbarId: "pageActions",
//selectionToolsId: "selectionTools", preferences: preferences
});
require(["orion/explorer-table"],function(mExplorerTable) {
// From orion table.js
if (!window.scripted) {
window.scripted = {};
}
var filetoedit = window.location.search.substr(1);
// need to find the nearest .project/.scripted/.git file or at most 5 dirs up
var projectRootContext = null;
var dir = filetoedit.substr(0,filetoedit.lastIndexOf("/"));
var count = 0;
var scriptedconfig;
try {
while (projectRootContext === null && dir.length!==0) {
// does it contain a .project or .scripted?
var xhrobj = new XMLHttpRequest();
var url = 'http://localhost:7261/fs_list/'+dir;
//console.log("url is "+url);
xhrobj.open("GET",url,false); // TODO naughty? synchronous xhr
xhrobj.send();
var kids = JSON.parse(xhrobj.responseText).children;
if (kids) {
// Check if this is where to stop
for (var i=0;i<kids.length;i++) {
var n = kids[i].name;
if (n === ".scripted" || n === ".project" || n === ".git") {
if (n === ".scripted") {
scriptedconfig = dir+"/"+n;
}
projectRootContext = dir;
}
}
}
if (projectRootContext===null) {
dir = dir.substr(0,dir.lastIndexOf("/"));
count++;
if (count===5) {
projectRootContext = dir;
}
}
}
} catch (e2) {
console.log("xhr failed "+e2);
}
if (projectRootContext===null) {
projectRootContext = filetoedit.substr(0,filetoedit.lastIndexOf("/"));
}
// Was there a .scripted file?
if (scriptedconfig) {
loadScriptedConfig(scriptedconfig);
}
if(window.scripted.navigator === false){
$('#editor').css('margin-left', 0);
}
// Set to the root for the navigator
window.fsroot=projectRootContext;
if (window.scripted.navigator === undefined || window.scripted.navigator === true) {
explorer.loadResourceList(projectRootContext/*pageParams.resource*/, false, function() {
// mGlobalCommands.setPageTarget(explorer.treeRoot, serviceRegistry, commandService, null, /* favorites target */explorer.treeRoot);
// highlight the row we are using
explorer.highlight(filetoedit);
});
} else {
$('#editor').css("left","0px");
$('#explorer-tree').remove();
}
});
// Ugh...CSS sucks so we have to dynamically resize #main with javascript. There has to be a CSS solution for this but most involve absolute/fixed position which breaks #editor.
var footer_height = $('footer').height();
var header_height = $('header').height();
$('#main').height(
$(window).height() -
footer_height -
header_height
);
$(window).resize(function(){
$('#main').height(
$(window).height() -
footer_height -
header_height
);
window.editor.getTextView()._update();
});
require(['jquery_ui'], function(mJqueryUI){
var navigator_width = $('#navigator-container').width();
$('#navigator-wrapper').resizable({
handles: "e",
resize: function(event, ui){
$('#editor').css('margin-left', ui.size.width);
$('#pageToolbar').css('left', ui.size.width);
window.editor.getTextView()._update();
}
});
require(['jsrender'], function(mJsRender){
var keyCodes = {};
$.each($.ui.keyCode, function(key, value){
keyCodes[value] = key;
});
$.views.converters({
toChar: function(val){
if (keyCodes[val] != null) return keyCodes[val];
else if (val === 191) return "/";
else if (val === 220) return "\\";
else return String.fromCharCode(val);
}
});
$.views.helpers({
isMac: function(){
return (window.navigator.platform.indexOf("Mac") !== -1);
}
});
var command_file = "../templates/_command.tmpl.html";
var keyBindings = window.editor.getTextView()._keyBindings;
$.get(command_file, null, function(template){
var tmpl = $.templates(template);
$('#command_list').append(tmpl.render(keyBindings));
});
window.editor.getTextView()._update();
});
});
var the_box = $('.hoverbox:first').show().clone();
$('.hoverbox').remove();
$('#the_button').on('click', function(){
$('#hoverbox_panel').append(the_box);
the_box = the_box.clone();
});
$('#hoverbox_panel').on('click', '.hoverbox_close', function(element){
$(element.currentTarget.parentElement.parentElement).remove();
});
var help_panel_width = $('#help_panel').width();
var hoverbox_panel_right = parseInt($('#hoverbox_panel').css('right'), 10);
var help_close;
var help_open = function(){
$('#editor').css('margin-right', help_panel_width);
window.editor.getTextView()._update();
$('#hoverbox_panel').css('right', hoverbox_panel_right + help_panel_width);
$('#help_panel').show();
$('#help_open').off('click');
$('#help_open').on('click', help_close);
};
help_close = function(){
$('#editor').css('margin-right', '0');
window.editor.getTextView()._update();
$('#hoverbox_panel').css('right', hoverbox_panel_right);
$('#help_panel').hide();
$('#help_open').off('click');
$('#help_open').on('click', help_open);
};
$('#help_open').click(help_open);
//this little bit fixes the cursor disappearing problem in firefox. probably the hackiest workaround i've come up with, but it works.
//if we ever add an anchor tag anywhere, we can use that instead of this fix.
$('header').append('<a href="#" id="cursor_fix">.</a>');
$('#cursor_fix').focus().remove();
});
| {
"pile_set_name": "Github"
} |
UPDATE `sys_options` SET `desc` = 'Maximum size of one file (in Megabytes)' WHERE `Name` = 'bx_videos_max_file_size';
DELETE FROM `sys_objects_actions` WHERE `Type` = 'bx_videos' AND `Caption` = '{repostCpt}';
INSERT INTO `sys_objects_actions` (`Type`, `Caption`, `Icon`, `Url`, `Script`, `Eval`, `Order`) VALUES
('bx_videos', '{repostCpt}', 'repeat', '', '{repostScript}', '', 10);
-- update module version
UPDATE `sys_modules` SET `version` = '1.3.0' WHERE `uri` = 'videos' AND `version` = '1.2.1';
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!-- Documenting T:NAnt.Contrib.Tasks.VersionTask.RevisionNumberAlgorithm-->
<head>
<meta http-equiv="Content-Language" content="en-ca" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="../style.css" />
<title>VersionTask.RevisionNumberAlgorithm enum</title>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="2" class="NavBar">
<tr>
<td class="NavBar-Cell">
<a href="">
<b>NAntContrib</b>
</a>
<img alt="->" src="../images/arrow.gif" />
<a href="../index.html">Help</a>
<img alt="->" src="../images/arrow.gif" />
<span>Enum Reference</span>
<img alt="->" src="../images/arrow.gif" /> VersionTask.RevisionNumberAlgorithm</td>
<td class="NavBar-Cell" align="right">
v0.85</td>
</tr>
</table>
<h1>VersionTask.RevisionNumberAlgorithm</h1>
<p> Defines possible algorithms to generate the revision number. </p>
<h3>Fields</h3>
<div class="table">
<table>
<tr>
<th>Field</th>
<th>Description</th>
</tr>
<tr>
<td valign="top">Automatic</td>
<td> Use the number of seconds since the start of today / 10. </td>
</tr>
<tr>
<td valign="top">Increment</td>
<td> Increment an existing revision number. </td>
</tr>
</table>
</div>
<h3>Requirements</h3>
<div style="margin-left: 20px;">
<b>Assembly:</b> NAnt.Contrib.Tasks (0.85.2479.0)
</div>
</body>
</html> | {
"pile_set_name": "Github"
} |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders 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.
*/
package jdk.internal.org.objectweb.asm.util;
import java.io.PrintWriter;
import jdk.internal.org.objectweb.asm.AnnotationVisitor;
import jdk.internal.org.objectweb.asm.Attribute;
import jdk.internal.org.objectweb.asm.ClassVisitor;
import jdk.internal.org.objectweb.asm.FieldVisitor;
import jdk.internal.org.objectweb.asm.MethodVisitor;
import jdk.internal.org.objectweb.asm.ModuleVisitor;
import jdk.internal.org.objectweb.asm.Opcodes;
import jdk.internal.org.objectweb.asm.RecordComponentVisitor;
import jdk.internal.org.objectweb.asm.TypePath;
/**
* A {@link ClassVisitor} that prints the classes it visits with a {@link Printer}. This class
* visitor can be used in the middle of a class visitor chain to trace the class that is visited at
* a given point in this chain. This may be useful for debugging purposes.
*
* <p>When used with a {@link Textifier}, the trace printed when visiting the {@code Hello} class is
* the following:
*
* <pre>
* // class version 49.0 (49) // access flags 0x21 public class Hello {
*
* // compiled from: Hello.java
*
* // access flags 0x1
* public <init> ()V
* ALOAD 0
* INVOKESPECIAL java/lang/Object <init> ()V
* RETURN
* MAXSTACK = 1 MAXLOCALS = 1
*
* // access flags 0x9
* public static main ([Ljava/lang/String;)V
* GETSTATIC java/lang/System out Ljava/io/PrintStream;
* LDC "hello"
* INVOKEVIRTUAL java/io/PrintStream println (Ljava/lang/String;)V
* RETURN
* MAXSTACK = 2 MAXLOCALS = 1
* }
* </pre>
*
* <p>where {@code Hello} is defined by:
*
* <pre>
* public class Hello {
*
* public static void main(String[] args) {
* System.out.println("hello");
* }
* }
* </pre>
*
* @author Eric Bruneton
* @author Eugene Kuleshov
*/
public final class TraceClassVisitor extends ClassVisitor {
/** The print writer to be used to print the class. May be {@literal null}. */
private final PrintWriter printWriter;
/** The printer to convert the visited class into text. */
// DontCheck(MemberName): can't be renamed (for backward binary compatibility).
public final Printer p;
/**
* Constructs a new {@link TraceClassVisitor}.
*
* @param printWriter the print writer to be used to print the class. May be {@literal null}.
*/
public TraceClassVisitor(final PrintWriter printWriter) {
this(null, printWriter);
}
/**
* Constructs a new {@link TraceClassVisitor}.
*
* @param classVisitor the class visitor to which to delegate calls. May be {@literal null}.
* @param printWriter the print writer to be used to print the class. May be {@literal null}.
*/
public TraceClassVisitor(final ClassVisitor classVisitor, final PrintWriter printWriter) {
this(classVisitor, new Textifier(), printWriter);
}
/**
* Constructs a new {@link TraceClassVisitor}.
*
* @param classVisitor the class visitor to which to delegate calls. May be {@literal null}.
* @param printer the printer to convert the visited class into text.
* @param printWriter the print writer to be used to print the class. May be {@literal null}.
*/
@SuppressWarnings("deprecation")
public TraceClassVisitor(
final ClassVisitor classVisitor, final Printer printer, final PrintWriter printWriter) {
super(/* latest api = */ Opcodes.ASM9_EXPERIMENTAL, classVisitor);
this.printWriter = printWriter;
this.p = printer;
}
@Override
public void visit(
final int version,
final int access,
final String name,
final String signature,
final String superName,
final String[] interfaces) {
p.visit(version, access, name, signature, superName, interfaces);
super.visit(version, access, name, signature, superName, interfaces);
}
@Override
public void visitSource(final String file, final String debug) {
p.visitSource(file, debug);
super.visitSource(file, debug);
}
@Override
public ModuleVisitor visitModule(final String name, final int flags, final String version) {
Printer modulePrinter = p.visitModule(name, flags, version);
return new TraceModuleVisitor(super.visitModule(name, flags, version), modulePrinter);
}
@Override
public void visitNestHost(final String nestHost) {
p.visitNestHost(nestHost);
super.visitNestHost(nestHost);
}
@Override
public void visitOuterClass(final String owner, final String name, final String descriptor) {
p.visitOuterClass(owner, name, descriptor);
super.visitOuterClass(owner, name, descriptor);
}
@Override
public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) {
Printer annotationPrinter = p.visitClassAnnotation(descriptor, visible);
return new TraceAnnotationVisitor(
super.visitAnnotation(descriptor, visible), annotationPrinter);
}
@Override
public AnnotationVisitor visitTypeAnnotation(
final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {
Printer annotationPrinter = p.visitClassTypeAnnotation(typeRef, typePath, descriptor, visible);
return new TraceAnnotationVisitor(
super.visitTypeAnnotation(typeRef, typePath, descriptor, visible), annotationPrinter);
}
@Override
public void visitAttribute(final Attribute attribute) {
p.visitClassAttribute(attribute);
super.visitAttribute(attribute);
}
@Override
public void visitNestMember(final String nestMember) {
p.visitNestMember(nestMember);
super.visitNestMember(nestMember);
}
/**
* <b>Experimental, use at your own risk.</b>.
*
* @param permittedSubclass the internal name of a permitted subclass.
* @deprecated this API is experimental.
*/
@Override
@Deprecated
public void visitPermittedSubclassExperimental(final String permittedSubclass) {
p.visitPermittedSubclassExperimental(permittedSubclass);
super.visitPermittedSubclassExperimental(permittedSubclass);
}
@Override
public void visitInnerClass(
final String name, final String outerName, final String innerName, final int access) {
p.visitInnerClass(name, outerName, innerName, access);
super.visitInnerClass(name, outerName, innerName, access);
}
@Override
public RecordComponentVisitor visitRecordComponent(
final String name, final String descriptor, final String signature) {
Printer recordComponentPrinter = p.visitRecordComponent(name, descriptor, signature);
return new TraceRecordComponentVisitor(
super.visitRecordComponent(name, descriptor, signature), recordComponentPrinter);
}
@Override
public FieldVisitor visitField(
final int access,
final String name,
final String descriptor,
final String signature,
final Object value) {
Printer fieldPrinter = p.visitField(access, name, descriptor, signature, value);
return new TraceFieldVisitor(
super.visitField(access, name, descriptor, signature, value), fieldPrinter);
}
@Override
public MethodVisitor visitMethod(
final int access,
final String name,
final String descriptor,
final String signature,
final String[] exceptions) {
Printer methodPrinter = p.visitMethod(access, name, descriptor, signature, exceptions);
return new TraceMethodVisitor(
super.visitMethod(access, name, descriptor, signature, exceptions), methodPrinter);
}
@Override
public void visitEnd() {
p.visitClassEnd();
if (printWriter != null) {
p.print(printWriter);
printWriter.flush();
}
super.visitEnd();
}
}
| {
"pile_set_name": "Github"
} |
/* Difference Highlighting and Strike-through
------------------------------------------------ */
ins {
color: #333333;
background-color: #eaffea;
text-decoration: none;
}
del {
color: #AA3333;
background-color: #ffeaea;
text-decoration: line-through;
}
/* Image Diffing
------------------------------------------------ */
del.diffimg.diffsrc {
display: inline-block;
position: relative;
}
del.diffimg.diffsrc:before {
position: absolute;
content: "";
left: 0;
top: 0;
width: 100%;
height: 100%;
background: repeating-linear-gradient(
to left top,
rgba(255, 0, 0, 0),
rgba(255, 0, 0, 0) 49.5%,
rgba(255, 0, 0, 1) 49.5%,
rgba(255, 0, 0, 1) 50.5%
), repeating-linear-gradient(
to left bottom,
rgba(255, 0, 0, 0),
rgba(255, 0, 0, 0) 49.5%,
rgba(255, 0, 0, 1) 49.5%,
rgba(255, 0, 0, 1) 50.5%
);
}
/* List Diffing
------------------------------------------------ */
/* List Styles */
.diff-list {
list-style: none;
counter-reset: section;
display: table;
}
.diff-list > li.normal,
.diff-list > li.removed,
.diff-list > li.replacement {
display: table-row;
}
.diff-list > li > div{
display: inline;
}
.diff-list > li.replacement:before,
.diff-list > li.new:before {
color: #333333;
background-color: #eaffea;
text-decoration: none;
}
.diff-list > li.removed:before{
counter-increment: section;
color: #AA3333;
background-color: #ffeaea;
text-decoration: line-through;
}
/* List Counters / Numbering */
.diff-list > li.normal:before,
.diff-list > li.removed:before,
.diff-list > li.replacement:before {
width: 15px;
overflow: hidden;
content: counters(section,".") ". ";
display: table-cell;
text-indent: -1em;
padding-left: 1em;
}
.diff-list > li.normal:before,
li.replacement + li.replacement:before,
.diff-list > li.replacement:first-child:before{
counter-increment: section;
}
ol.diff-list li.removed + li.replacement {
counter-increment: none;
}
ol.diff-list li.removed + li.removed + li.replacement {
counter-increment: section -1;
}
ol.diff-list li.removed + li.removed + li.removed + li.replacement {
counter-increment: section -2;
}
ol.diff-list li.removed + li.removed + li.removed + li.removed + li.replacement {
counter-increment: section -3;
}
ol.diff-list li.removed + li.removed + li.removed + li.removed + li.removed + li.replacement {
counter-increment: section -4;
}
ol.diff-list li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.replacement {
counter-increment: section -5;
}
ol.diff-list li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.replacement {
counter-increment: section -6;
}
ol.diff-list li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.replacement {
counter-increment: section -7;
}
ol.diff-list li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.replacement {
counter-increment: section -8;
}
ol.diff-list li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.replacement {
counter-increment: section -9;
}
ol.diff-list li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.replacement{
counter-increment: section -10;
}
ol.diff-list li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.removed + li.replacement {
counter-increment: section -11;
}
/* Exception Lists */
ul.exception,
ul.exception li:before {
list-style: none;
content: none;
}
.diff-list ul.exception ol {
list-style: none;
counter-reset: exception-section;
/* Creates a new instance of the section counter with each ol element */
}
.diff-list ul.exception ol > li:before {
counter-increment: exception-section;
content:counters(exception-section, ".") ".";
}
| {
"pile_set_name": "Github"
} |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2014 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// 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/.
#ifndef EIGEN_SPARSEREDUX_H
#define EIGEN_SPARSEREDUX_H
namespace Eigen {
template<typename Derived>
typename internal::traits<Derived>::Scalar
SparseMatrixBase<Derived>::sum() const
{
eigen_assert(rows()>0 && cols()>0 && "you are using a non initialized matrix");
Scalar res(0);
internal::evaluator<Derived> thisEval(derived());
for (Index j=0; j<outerSize(); ++j)
for (typename internal::evaluator<Derived>::InnerIterator iter(thisEval,j); iter; ++iter)
res += iter.value();
return res;
}
template<typename _Scalar, int _Options, typename _Index>
typename internal::traits<SparseMatrix<_Scalar,_Options,_Index> >::Scalar
SparseMatrix<_Scalar,_Options,_Index>::sum() const
{
eigen_assert(rows()>0 && cols()>0 && "you are using a non initialized matrix");
if(this->isCompressed())
return Matrix<Scalar,1,Dynamic>::Map(m_data.valuePtr(), m_data.size()).sum();
else
return Base::sum();
}
template<typename _Scalar, int _Options, typename _Index>
typename internal::traits<SparseVector<_Scalar,_Options, _Index> >::Scalar
SparseVector<_Scalar,_Options,_Index>::sum() const
{
eigen_assert(rows()>0 && cols()>0 && "you are using a non initialized matrix");
return Matrix<Scalar,1,Dynamic>::Map(m_data.valuePtr(), m_data.size()).sum();
}
} // end namespace Eigen
#endif // EIGEN_SPARSEREDUX_H
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of JSR-310 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.
*/
package java.time.chrono;
import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH;
import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR;
import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_MONTH;
import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR;
import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.DAY_OF_WEEK;
import static java.time.temporal.ChronoField.DAY_OF_YEAR;
import static java.time.temporal.ChronoField.EPOCH_DAY;
import static java.time.temporal.ChronoField.ERA;
import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
import static java.time.temporal.ChronoField.PROLEPTIC_MONTH;
import static java.time.temporal.ChronoField.YEAR;
import static java.time.temporal.ChronoField.YEAR_OF_ERA;
import static java.time.temporal.ChronoUnit.DAYS;
import static java.time.temporal.ChronoUnit.MONTHS;
import static java.time.temporal.ChronoUnit.WEEKS;
import static java.time.temporal.TemporalAdjusters.nextOrSame;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.time.DateTimeException;
import java.time.DayOfWeek;
import java.time.format.ResolverStyle;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.TemporalField;
import java.time.temporal.ValueRange;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import sun.util.logging.PlatformLogger;
/**
* An abstract implementation of a calendar system, used to organize and identify dates.
* <p>
* The main date and time API is built on the ISO calendar system.
* The chronology operates behind the scenes to represent the general concept of a calendar system.
* <p>
* See {@link Chronology} for more details.
*
* @implSpec
* This class is separated from the {@code Chronology} interface so that the static methods
* are not inherited. While {@code Chronology} can be implemented directly, it is strongly
* recommended to extend this abstract class instead.
* <p>
* This class must be implemented with care to ensure other classes operate correctly.
* All implementations that can be instantiated must be final, immutable and thread-safe.
* Subclasses should be Serializable wherever possible.
*
* @since 1.8
*/
public abstract class AbstractChronology implements Chronology {
/**
* ChronoLocalDate order constant.
*/
static final Comparator<ChronoLocalDate> DATE_ORDER =
(Comparator<ChronoLocalDate> & Serializable) (date1, date2) -> {
return Long.compare(date1.toEpochDay(), date2.toEpochDay());
};
/**
* ChronoLocalDateTime order constant.
*/
static final Comparator<ChronoLocalDateTime<? extends ChronoLocalDate>> DATE_TIME_ORDER =
(Comparator<ChronoLocalDateTime<? extends ChronoLocalDate>> & Serializable) (dateTime1, dateTime2) -> {
int cmp = Long.compare(dateTime1.toLocalDate().toEpochDay(), dateTime2.toLocalDate().toEpochDay());
if (cmp == 0) {
cmp = Long.compare(dateTime1.toLocalTime().toNanoOfDay(), dateTime2.toLocalTime().toNanoOfDay());
}
return cmp;
};
/**
* ChronoZonedDateTime order constant.
*/
static final Comparator<ChronoZonedDateTime<?>> INSTANT_ORDER =
(Comparator<ChronoZonedDateTime<?>> & Serializable) (dateTime1, dateTime2) -> {
int cmp = Long.compare(dateTime1.toEpochSecond(), dateTime2.toEpochSecond());
if (cmp == 0) {
cmp = Long.compare(dateTime1.toLocalTime().getNano(), dateTime2.toLocalTime().getNano());
}
return cmp;
};
/**
* Map of available calendars by ID.
*/
private static final ConcurrentHashMap<String, Chronology> CHRONOS_BY_ID = new ConcurrentHashMap<>();
/**
* Map of available calendars by calendar type.
*/
private static final ConcurrentHashMap<String, Chronology> CHRONOS_BY_TYPE = new ConcurrentHashMap<>();
/**
* Register a Chronology by its ID and type for lookup by {@link #of(String)}.
* Chronologies must not be registered until they are completely constructed.
* Specifically, not in the constructor of Chronology.
*
* @param chrono the chronology to register; not null
* @return the already registered Chronology if any, may be null
*/
static Chronology registerChrono(Chronology chrono) {
return registerChrono(chrono, chrono.getId());
}
/**
* Register a Chronology by ID and type for lookup by {@link #of(String)}.
* Chronos must not be registered until they are completely constructed.
* Specifically, not in the constructor of Chronology.
*
* @param chrono the chronology to register; not null
* @param id the ID to register the chronology; not null
* @return the already registered Chronology if any, may be null
*/
static Chronology registerChrono(Chronology chrono, String id) {
Chronology prev = CHRONOS_BY_ID.putIfAbsent(id, chrono);
if (prev == null) {
String type = chrono.getCalendarType();
if (type != null) {
CHRONOS_BY_TYPE.putIfAbsent(type, chrono);
}
}
return prev;
}
/**
* Initialization of the maps from id and type to Chronology.
* The ServiceLoader is used to find and register any implementations
* of {@link java.time.chrono.AbstractChronology} found in the bootclass loader.
* The built-in chronologies are registered explicitly.
* Calendars configured via the Thread's context classloader are local
* to that thread and are ignored.
* <p>
* The initialization is done only once using the registration
* of the IsoChronology as the test and the final step.
* Multiple threads may perform the initialization concurrently.
* Only the first registration of each Chronology is retained by the
* ConcurrentHashMap.
* @return true if the cache was initialized
*/
private static boolean initCache() {
if (CHRONOS_BY_ID.get("ISO") == null) {
// Initialization is incomplete
// Register built-in Chronologies
registerChrono(HijrahChronology.INSTANCE);
registerChrono(JapaneseChronology.INSTANCE);
registerChrono(MinguoChronology.INSTANCE);
registerChrono(ThaiBuddhistChronology.INSTANCE);
// Register Chronologies from the ServiceLoader
@SuppressWarnings("rawtypes")
ServiceLoader<AbstractChronology> loader = ServiceLoader.load(AbstractChronology.class, null);
for (AbstractChronology chrono : loader) {
String id = chrono.getId();
if (id.equals("ISO") || registerChrono(chrono) != null) {
// Log the attempt to replace an existing Chronology
PlatformLogger logger = PlatformLogger.getLogger("java.time.chrono");
logger.warning("Ignoring duplicate Chronology, from ServiceLoader configuration " + id);
}
}
// finally, register IsoChronology to mark initialization is complete
registerChrono(IsoChronology.INSTANCE);
return true;
}
return false;
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Chronology} from a locale.
* <p>
* See {@link Chronology#ofLocale(Locale)}.
*
* @param locale the locale to use to obtain the calendar system, not null
* @return the calendar system associated with the locale, not null
* @throws java.time.DateTimeException if the locale-specified calendar cannot be found
*/
static Chronology ofLocale(Locale locale) {
Objects.requireNonNull(locale, "locale");
String type = locale.getUnicodeLocaleType("ca");
if (type == null || "iso".equals(type) || "iso8601".equals(type)) {
return IsoChronology.INSTANCE;
}
// Not pre-defined; lookup by the type
do {
Chronology chrono = CHRONOS_BY_TYPE.get(type);
if (chrono != null) {
return chrono;
}
// If not found, do the initialization (once) and repeat the lookup
} while (initCache());
// Look for a Chronology using ServiceLoader of the Thread's ContextClassLoader
// Application provided Chronologies must not be cached
@SuppressWarnings("rawtypes")
ServiceLoader<Chronology> loader = ServiceLoader.load(Chronology.class);
for (Chronology chrono : loader) {
if (type.equals(chrono.getCalendarType())) {
return chrono;
}
}
throw new DateTimeException("Unknown calendar system: " + type);
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Chronology} from a chronology ID or
* calendar system type.
* <p>
* See {@link Chronology#of(String)}.
*
* @param id the chronology ID or calendar system type, not null
* @return the chronology with the identifier requested, not null
* @throws java.time.DateTimeException if the chronology cannot be found
*/
static Chronology of(String id) {
Objects.requireNonNull(id, "id");
do {
Chronology chrono = of0(id);
if (chrono != null) {
return chrono;
}
// If not found, do the initialization (once) and repeat the lookup
} while (initCache());
// Look for a Chronology using ServiceLoader of the Thread's ContextClassLoader
// Application provided Chronologies must not be cached
@SuppressWarnings("rawtypes")
ServiceLoader<Chronology> loader = ServiceLoader.load(Chronology.class);
for (Chronology chrono : loader) {
if (id.equals(chrono.getId()) || id.equals(chrono.getCalendarType())) {
return chrono;
}
}
throw new DateTimeException("Unknown chronology: " + id);
}
/**
* Obtains an instance of {@code Chronology} from a chronology ID or
* calendar system type.
*
* @param id the chronology ID or calendar system type, not null
* @return the chronology with the identifier requested, or {@code null} if not found
*/
private static Chronology of0(String id) {
Chronology chrono = CHRONOS_BY_ID.get(id);
if (chrono == null) {
chrono = CHRONOS_BY_TYPE.get(id);
}
return chrono;
}
/**
* Returns the available chronologies.
* <p>
* Each returned {@code Chronology} is available for use in the system.
* The set of chronologies includes the system chronologies and
* any chronologies provided by the application via ServiceLoader
* configuration.
*
* @return the independent, modifiable set of the available chronology IDs, not null
*/
static Set<Chronology> getAvailableChronologies() {
initCache(); // force initialization
HashSet<Chronology> chronos = new HashSet<>(CHRONOS_BY_ID.values());
/// Add in Chronologies from the ServiceLoader configuration
@SuppressWarnings("rawtypes")
ServiceLoader<Chronology> loader = ServiceLoader.load(Chronology.class);
for (Chronology chrono : loader) {
chronos.add(chrono);
}
return chronos;
}
//-----------------------------------------------------------------------
/**
* Creates an instance.
*/
protected AbstractChronology() {
}
//-----------------------------------------------------------------------
/**
* Resolves parsed {@code ChronoField} values into a date during parsing.
* <p>
* Most {@code TemporalField} implementations are resolved using the
* resolve method on the field. By contrast, the {@code ChronoField} class
* defines fields that only have meaning relative to the chronology.
* As such, {@code ChronoField} date fields are resolved here in the
* context of a specific chronology.
* <p>
* {@code ChronoField} instances are resolved by this method, which may
* be overridden in subclasses.
* <ul>
* <li>{@code EPOCH_DAY} - If present, this is converted to a date and
* all other date fields are then cross-checked against the date.
* <li>{@code PROLEPTIC_MONTH} - If present, then it is split into the
* {@code YEAR} and {@code MONTH_OF_YEAR}. If the mode is strict or smart
* then the field is validated.
* <li>{@code YEAR_OF_ERA} and {@code ERA} - If both are present, then they
* are combined to form a {@code YEAR}. In lenient mode, the {@code YEAR_OF_ERA}
* range is not validated, in smart and strict mode it is. The {@code ERA} is
* validated for range in all three modes. If only the {@code YEAR_OF_ERA} is
* present, and the mode is smart or lenient, then the last available era
* is assumed. In strict mode, no era is assumed and the {@code YEAR_OF_ERA} is
* left untouched. If only the {@code ERA} is present, then it is left untouched.
* <li>{@code YEAR}, {@code MONTH_OF_YEAR} and {@code DAY_OF_MONTH} -
* If all three are present, then they are combined to form a date.
* In all three modes, the {@code YEAR} is validated.
* If the mode is smart or strict, then the month and day are validated.
* If the mode is lenient, then the date is combined in a manner equivalent to
* creating a date on the first day of the first month in the requested year,
* then adding the difference in months, then the difference in days.
* If the mode is smart, and the day-of-month is greater than the maximum for
* the year-month, then the day-of-month is adjusted to the last day-of-month.
* If the mode is strict, then the three fields must form a valid date.
* <li>{@code YEAR} and {@code DAY_OF_YEAR} -
* If both are present, then they are combined to form a date.
* In all three modes, the {@code YEAR} is validated.
* If the mode is lenient, then the date is combined in a manner equivalent to
* creating a date on the first day of the requested year, then adding
* the difference in days.
* If the mode is smart or strict, then the two fields must form a valid date.
* <li>{@code YEAR}, {@code MONTH_OF_YEAR}, {@code ALIGNED_WEEK_OF_MONTH} and
* {@code ALIGNED_DAY_OF_WEEK_IN_MONTH} -
* If all four are present, then they are combined to form a date.
* In all three modes, the {@code YEAR} is validated.
* If the mode is lenient, then the date is combined in a manner equivalent to
* creating a date on the first day of the first month in the requested year, then adding
* the difference in months, then the difference in weeks, then in days.
* If the mode is smart or strict, then the all four fields are validated to
* their outer ranges. The date is then combined in a manner equivalent to
* creating a date on the first day of the requested year and month, then adding
* the amount in weeks and days to reach their values. If the mode is strict,
* the date is additionally validated to check that the day and week adjustment
* did not change the month.
* <li>{@code YEAR}, {@code MONTH_OF_YEAR}, {@code ALIGNED_WEEK_OF_MONTH} and
* {@code DAY_OF_WEEK} - If all four are present, then they are combined to
* form a date. The approach is the same as described above for
* years, months and weeks in {@code ALIGNED_DAY_OF_WEEK_IN_MONTH}.
* The day-of-week is adjusted as the next or same matching day-of-week once
* the years, months and weeks have been handled.
* <li>{@code YEAR}, {@code ALIGNED_WEEK_OF_YEAR} and {@code ALIGNED_DAY_OF_WEEK_IN_YEAR} -
* If all three are present, then they are combined to form a date.
* In all three modes, the {@code YEAR} is validated.
* If the mode is lenient, then the date is combined in a manner equivalent to
* creating a date on the first day of the requested year, then adding
* the difference in weeks, then in days.
* If the mode is smart or strict, then the all three fields are validated to
* their outer ranges. The date is then combined in a manner equivalent to
* creating a date on the first day of the requested year, then adding
* the amount in weeks and days to reach their values. If the mode is strict,
* the date is additionally validated to check that the day and week adjustment
* did not change the year.
* <li>{@code YEAR}, {@code ALIGNED_WEEK_OF_YEAR} and {@code DAY_OF_WEEK} -
* If all three are present, then they are combined to form a date.
* The approach is the same as described above for years and weeks in
* {@code ALIGNED_DAY_OF_WEEK_IN_YEAR}. The day-of-week is adjusted as the
* next or same matching day-of-week once the years and weeks have been handled.
* </ul>
* <p>
* The default implementation is suitable for most calendar systems.
* If {@link java.time.temporal.ChronoField#YEAR_OF_ERA} is found without an {@link java.time.temporal.ChronoField#ERA}
* then the last era in {@link #eras()} is used.
* The implementation assumes a 7 day week, that the first day-of-month
* has the value 1, that first day-of-year has the value 1, and that the
* first of the month and year always exists.
*
* @param fieldValues the map of fields to values, which can be updated, not null
* @param resolverStyle the requested type of resolve, not null
* @return the resolved date, null if insufficient information to create a date
* @throws java.time.DateTimeException if the date cannot be resolved, typically
* because of a conflict in the input data
*/
@Override
public ChronoLocalDate resolveDate(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
// check epoch-day before inventing era
if (fieldValues.containsKey(EPOCH_DAY)) {
return dateEpochDay(fieldValues.remove(EPOCH_DAY));
}
// fix proleptic month before inventing era
resolveProlepticMonth(fieldValues, resolverStyle);
// invent era if necessary to resolve year-of-era
ChronoLocalDate resolved = resolveYearOfEra(fieldValues, resolverStyle);
if (resolved != null) {
return resolved;
}
// build date
if (fieldValues.containsKey(YEAR)) {
if (fieldValues.containsKey(MONTH_OF_YEAR)) {
if (fieldValues.containsKey(DAY_OF_MONTH)) {
return resolveYMD(fieldValues, resolverStyle);
}
if (fieldValues.containsKey(ALIGNED_WEEK_OF_MONTH)) {
if (fieldValues.containsKey(ALIGNED_DAY_OF_WEEK_IN_MONTH)) {
return resolveYMAA(fieldValues, resolverStyle);
}
if (fieldValues.containsKey(DAY_OF_WEEK)) {
return resolveYMAD(fieldValues, resolverStyle);
}
}
}
if (fieldValues.containsKey(DAY_OF_YEAR)) {
return resolveYD(fieldValues, resolverStyle);
}
if (fieldValues.containsKey(ALIGNED_WEEK_OF_YEAR)) {
if (fieldValues.containsKey(ALIGNED_DAY_OF_WEEK_IN_YEAR)) {
return resolveYAA(fieldValues, resolverStyle);
}
if (fieldValues.containsKey(DAY_OF_WEEK)) {
return resolveYAD(fieldValues, resolverStyle);
}
}
}
return null;
}
void resolveProlepticMonth(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
Long pMonth = fieldValues.remove(PROLEPTIC_MONTH);
if (pMonth != null) {
if (resolverStyle != ResolverStyle.LENIENT) {
PROLEPTIC_MONTH.checkValidValue(pMonth);
}
// first day-of-month is likely to be safest for setting proleptic-month
// cannot add to year zero, as not all chronologies have a year zero
ChronoLocalDate chronoDate = dateNow()
.with(DAY_OF_MONTH, 1).with(PROLEPTIC_MONTH, pMonth);
addFieldValue(fieldValues, MONTH_OF_YEAR, chronoDate.get(MONTH_OF_YEAR));
addFieldValue(fieldValues, YEAR, chronoDate.get(YEAR));
}
}
ChronoLocalDate resolveYearOfEra(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
Long yoeLong = fieldValues.remove(YEAR_OF_ERA);
if (yoeLong != null) {
Long eraLong = fieldValues.remove(ERA);
int yoe;
if (resolverStyle != ResolverStyle.LENIENT) {
yoe = range(YEAR_OF_ERA).checkValidIntValue(yoeLong, YEAR_OF_ERA);
} else {
yoe = Math.toIntExact(yoeLong);
}
if (eraLong != null) {
Era eraObj = eraOf(range(ERA).checkValidIntValue(eraLong, ERA));
addFieldValue(fieldValues, YEAR, prolepticYear(eraObj, yoe));
} else {
if (fieldValues.containsKey(YEAR)) {
int year = range(YEAR).checkValidIntValue(fieldValues.get(YEAR), YEAR);
ChronoLocalDate chronoDate = dateYearDay(year, 1);
addFieldValue(fieldValues, YEAR, prolepticYear(chronoDate.getEra(), yoe));
} else if (resolverStyle == ResolverStyle.STRICT) {
// do not invent era if strict
// reinstate the field removed earlier, no cross-check issues
fieldValues.put(YEAR_OF_ERA, yoeLong);
} else {
List<Era> eras = eras();
if (eras.isEmpty()) {
addFieldValue(fieldValues, YEAR, yoe);
} else {
Era eraObj = eras.get(eras.size() - 1);
addFieldValue(fieldValues, YEAR, prolepticYear(eraObj, yoe));
}
}
}
} else if (fieldValues.containsKey(ERA)) {
range(ERA).checkValidValue(fieldValues.get(ERA), ERA); // always validated
}
return null;
}
ChronoLocalDate resolveYMD(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
int y = range(YEAR).checkValidIntValue(fieldValues.remove(YEAR), YEAR);
if (resolverStyle == ResolverStyle.LENIENT) {
long months = Math.subtractExact(fieldValues.remove(MONTH_OF_YEAR), 1);
long days = Math.subtractExact(fieldValues.remove(DAY_OF_MONTH), 1);
return date(y, 1, 1).plus(months, MONTHS).plus(days, DAYS);
}
int moy = range(MONTH_OF_YEAR).checkValidIntValue(fieldValues.remove(MONTH_OF_YEAR), MONTH_OF_YEAR);
ValueRange domRange = range(DAY_OF_MONTH);
int dom = domRange.checkValidIntValue(fieldValues.remove(DAY_OF_MONTH), DAY_OF_MONTH);
if (resolverStyle == ResolverStyle.SMART) { // previous valid
try {
return date(y, moy, dom);
} catch (DateTimeException ex) {
return date(y, moy, 1).with(TemporalAdjusters.lastDayOfMonth());
}
}
return date(y, moy, dom);
}
ChronoLocalDate resolveYD(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
int y = range(YEAR).checkValidIntValue(fieldValues.remove(YEAR), YEAR);
if (resolverStyle == ResolverStyle.LENIENT) {
long days = Math.subtractExact(fieldValues.remove(DAY_OF_YEAR), 1);
return dateYearDay(y, 1).plus(days, DAYS);
}
int doy = range(DAY_OF_YEAR).checkValidIntValue(fieldValues.remove(DAY_OF_YEAR), DAY_OF_YEAR);
return dateYearDay(y, doy); // smart is same as strict
}
ChronoLocalDate resolveYMAA(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
int y = range(YEAR).checkValidIntValue(fieldValues.remove(YEAR), YEAR);
if (resolverStyle == ResolverStyle.LENIENT) {
long months = Math.subtractExact(fieldValues.remove(MONTH_OF_YEAR), 1);
long weeks = Math.subtractExact(fieldValues.remove(ALIGNED_WEEK_OF_MONTH), 1);
long days = Math.subtractExact(fieldValues.remove(ALIGNED_DAY_OF_WEEK_IN_MONTH), 1);
return date(y, 1, 1).plus(months, MONTHS).plus(weeks, WEEKS).plus(days, DAYS);
}
int moy = range(MONTH_OF_YEAR).checkValidIntValue(fieldValues.remove(MONTH_OF_YEAR), MONTH_OF_YEAR);
int aw = range(ALIGNED_WEEK_OF_MONTH).checkValidIntValue(fieldValues.remove(ALIGNED_WEEK_OF_MONTH), ALIGNED_WEEK_OF_MONTH);
int ad = range(ALIGNED_DAY_OF_WEEK_IN_MONTH).checkValidIntValue(fieldValues.remove(ALIGNED_DAY_OF_WEEK_IN_MONTH), ALIGNED_DAY_OF_WEEK_IN_MONTH);
ChronoLocalDate date = date(y, moy, 1).plus((aw - 1) * 7 + (ad - 1), DAYS);
if (resolverStyle == ResolverStyle.STRICT && date.get(MONTH_OF_YEAR) != moy) {
throw new DateTimeException("Strict mode rejected resolved date as it is in a different month");
}
return date;
}
ChronoLocalDate resolveYMAD(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
int y = range(YEAR).checkValidIntValue(fieldValues.remove(YEAR), YEAR);
if (resolverStyle == ResolverStyle.LENIENT) {
long months = Math.subtractExact(fieldValues.remove(MONTH_OF_YEAR), 1);
long weeks = Math.subtractExact(fieldValues.remove(ALIGNED_WEEK_OF_MONTH), 1);
long dow = Math.subtractExact(fieldValues.remove(DAY_OF_WEEK), 1);
return resolveAligned(date(y, 1, 1), months, weeks, dow);
}
int moy = range(MONTH_OF_YEAR).checkValidIntValue(fieldValues.remove(MONTH_OF_YEAR), MONTH_OF_YEAR);
int aw = range(ALIGNED_WEEK_OF_MONTH).checkValidIntValue(fieldValues.remove(ALIGNED_WEEK_OF_MONTH), ALIGNED_WEEK_OF_MONTH);
int dow = range(DAY_OF_WEEK).checkValidIntValue(fieldValues.remove(DAY_OF_WEEK), DAY_OF_WEEK);
ChronoLocalDate date = date(y, moy, 1).plus((aw - 1) * 7, DAYS).with(nextOrSame(DayOfWeek.of(dow)));
if (resolverStyle == ResolverStyle.STRICT && date.get(MONTH_OF_YEAR) != moy) {
throw new DateTimeException("Strict mode rejected resolved date as it is in a different month");
}
return date;
}
ChronoLocalDate resolveYAA(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
int y = range(YEAR).checkValidIntValue(fieldValues.remove(YEAR), YEAR);
if (resolverStyle == ResolverStyle.LENIENT) {
long weeks = Math.subtractExact(fieldValues.remove(ALIGNED_WEEK_OF_YEAR), 1);
long days = Math.subtractExact(fieldValues.remove(ALIGNED_DAY_OF_WEEK_IN_YEAR), 1);
return dateYearDay(y, 1).plus(weeks, WEEKS).plus(days, DAYS);
}
int aw = range(ALIGNED_WEEK_OF_YEAR).checkValidIntValue(fieldValues.remove(ALIGNED_WEEK_OF_YEAR), ALIGNED_WEEK_OF_YEAR);
int ad = range(ALIGNED_DAY_OF_WEEK_IN_YEAR).checkValidIntValue(fieldValues.remove(ALIGNED_DAY_OF_WEEK_IN_YEAR), ALIGNED_DAY_OF_WEEK_IN_YEAR);
ChronoLocalDate date = dateYearDay(y, 1).plus((aw - 1) * 7 + (ad - 1), DAYS);
if (resolverStyle == ResolverStyle.STRICT && date.get(YEAR) != y) {
throw new DateTimeException("Strict mode rejected resolved date as it is in a different year");
}
return date;
}
ChronoLocalDate resolveYAD(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
int y = range(YEAR).checkValidIntValue(fieldValues.remove(YEAR), YEAR);
if (resolverStyle == ResolverStyle.LENIENT) {
long weeks = Math.subtractExact(fieldValues.remove(ALIGNED_WEEK_OF_YEAR), 1);
long dow = Math.subtractExact(fieldValues.remove(DAY_OF_WEEK), 1);
return resolveAligned(dateYearDay(y, 1), 0, weeks, dow);
}
int aw = range(ALIGNED_WEEK_OF_YEAR).checkValidIntValue(fieldValues.remove(ALIGNED_WEEK_OF_YEAR), ALIGNED_WEEK_OF_YEAR);
int dow = range(DAY_OF_WEEK).checkValidIntValue(fieldValues.remove(DAY_OF_WEEK), DAY_OF_WEEK);
ChronoLocalDate date = dateYearDay(y, 1).plus((aw - 1) * 7, DAYS).with(nextOrSame(DayOfWeek.of(dow)));
if (resolverStyle == ResolverStyle.STRICT && date.get(YEAR) != y) {
throw new DateTimeException("Strict mode rejected resolved date as it is in a different year");
}
return date;
}
ChronoLocalDate resolveAligned(ChronoLocalDate base, long months, long weeks, long dow) {
ChronoLocalDate date = base.plus(months, MONTHS).plus(weeks, WEEKS);
if (dow > 7) {
date = date.plus((dow - 1) / 7, WEEKS);
dow = ((dow - 1) % 7) + 1;
} else if (dow < 1) {
date = date.plus(Math.subtractExact(dow, 7) / 7, WEEKS);
dow = ((dow + 6) % 7) + 1;
}
return date.with(nextOrSame(DayOfWeek.of((int) dow)));
}
/**
* Adds a field-value pair to the map, checking for conflicts.
* <p>
* If the field is not already present, then the field-value pair is added to the map.
* If the field is already present and it has the same value as that specified, no action occurs.
* If the field is already present and it has a different value to that specified, then
* an exception is thrown.
*
* @param field the field to add, not null
* @param value the value to add, not null
* @throws java.time.DateTimeException if the field is already present with a different value
*/
void addFieldValue(Map<TemporalField, Long> fieldValues, ChronoField field, long value) {
Long old = fieldValues.get(field); // check first for better error message
if (old != null && old.longValue() != value) {
throw new DateTimeException("Conflict found: " + field + " " + old + " differs from " + field + " " + value);
}
fieldValues.put(field, value);
}
//-----------------------------------------------------------------------
/**
* Compares this chronology to another chronology.
* <p>
* The comparison order first by the chronology ID string, then by any
* additional information specific to the subclass.
* It is "consistent with equals", as defined by {@link Comparable}.
*
* @implSpec
* This implementation compares the chronology ID.
* Subclasses must compare any additional state that they store.
*
* @param other the other chronology to compare to, not null
* @return the comparator value, negative if less, positive if greater
*/
@Override
public int compareTo(Chronology other) {
return getId().compareTo(other.getId());
}
/**
* Checks if this chronology is equal to another chronology.
* <p>
* The comparison is based on the entire state of the object.
*
* @implSpec
* This implementation checks the type and calls
* {@link #compareTo(java.time.chrono.Chronology)}.
*
* @param obj the object to check, null returns false
* @return true if this is equal to the other chronology
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof AbstractChronology) {
return compareTo((AbstractChronology) obj) == 0;
}
return false;
}
/**
* A hash code for this chronology.
* <p>
* The hash code should be based on the entire state of the object.
*
* @implSpec
* This implementation is based on the chronology ID and class.
* Subclasses should add any additional state that they store.
*
* @return a suitable hash code
*/
@Override
public int hashCode() {
return getClass().hashCode() ^ getId().hashCode();
}
//-----------------------------------------------------------------------
/**
* Outputs this chronology as a {@code String}, using the chronology ID.
*
* @return a string representation of this chronology, not null
*/
@Override
public String toString() {
return getId();
}
//-----------------------------------------------------------------------
/**
* Writes the Chronology using a
* <a href="../../../serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.
* <pre>
* out.writeByte(1); // identifies this as a Chronology
* out.writeUTF(getId());
* </pre>
*
* @return the instance of {@code Ser}, not null
*/
Object writeReplace() {
return new Ser(Ser.CHRONO_TYPE, this);
}
/**
* Defend against malicious streams.
*
* @param s the stream to read
* @throws java.io.InvalidObjectException always
*/
private void readObject(ObjectInputStream s) throws ObjectStreamException {
throw new InvalidObjectException("Deserialization via serialization delegate");
}
void writeExternal(DataOutput out) throws IOException {
out.writeUTF(getId());
}
static Chronology readExternal(DataInput in) throws IOException {
String id = in.readUTF();
return Chronology.of(id);
}
}
| {
"pile_set_name": "Github"
} |
package com.infinityraider.agricraft.utility;
import com.infinityraider.agricraft.reference.AgriNBT;
import javax.annotation.Nullable;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
public final class NBTHelper {
public static final void addCoordsToNBT(int[] coords, NBTTagCompound tag) {
if (coords != null && coords.length == 3) {
addCoordsToNBT(coords[0], coords[1], coords[2], tag);
}
}
public static final void addCoordsToNBT(int x, int y, int z, NBTTagCompound tag) {
tag.setInteger(AgriNBT.X, x);
tag.setInteger(AgriNBT.Y, y);
tag.setInteger(AgriNBT.Z, z);
}
public static final int[] getCoordsFromNBT(NBTTagCompound tag) {
int[] coords = null;
if (tag.hasKey(AgriNBT.X) && tag.hasKey(AgriNBT.Y) && tag.hasKey(AgriNBT.Z)) {
coords = new int[]{tag.getInteger(AgriNBT.X), tag.getInteger(AgriNBT.Y), tag.getInteger(AgriNBT.Z)};
}
return coords;
}
public static final boolean hasKey(NBTTagCompound tag, String... keys) {
if (tag == null) {
return false;
}
for (String key : keys) {
if (!tag.hasKey(key)) {
return false;
}
}
return true;
}
@Nullable
public static final NBTTagCompound asTag(Object obj) {
if (obj instanceof ItemStack) {
return ((ItemStack) obj).getTagCompound();
} else if (obj instanceof NBTTagCompound) {
return (NBTTagCompound) obj;
} else {
return null;
}
}
/**
* Private constructor to prevent utility class initialization.
*/
private NBTHelper() {
// Nothing to see here.
}
}
| {
"pile_set_name": "Github"
} |
# lodash.tail v4.1.1
The [lodash](https://lodash.com/) method `_.tail` exported as a [Node.js](https://nodejs.org/) module.
## Installation
Using npm:
```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash.tail
```
In Node.js:
```js
var tail = require('lodash.tail');
```
See the [documentation](https://lodash.com/docs#tail) or [package source](https://github.com/lodash/lodash/blob/4.1.1-npm-packages/lodash.tail) for more details.
| {
"pile_set_name": "Github"
} |
[
{
"type": "LIST_ADDRESS",
"listAddress": {
"ipv4": {
"type": "IPV4",
"ipv4": "1.2.3.4/32"
},
"ipv6": {
"type": "IPV6",
"ipv6": "1111:2222:3333:4444:5555:6666:7777:8886/128"
}
}
},
{
"type": "SEGMENT_ADDRESS",
"segmentAddress": {
"instanceId": 1,
"address": {
"type": "IPV4",
"ipv4": "1.2.3.4/32"
}
}
},
{
"type": "AS_ADDRESS",
"asAddress": {
"asNumber": 1,
"address": {
"type": "IPV4",
"ipv4": "1.2.3.4/32"
}
}
},
{
"type": "APPLICATION_DATA_ADDRESS",
"applicationDataAddress": {
"protocol": 1,
"ipTos": 1,
"localPortLow": 1,
"localPortHigh": 1,
"remotePortLow": 1,
"remotePortHigh": 1,
"address": {
"type": "IPV4",
"ipv4": "1.2.3.4/32"
}
}
},
{
"type": "GEO_COORDINATE_ADDRESS",
"geoCoordinateAddress": {
"north": true,
"latitudeDegree": 1,
"latitudeMinute": 1,
"latitudeSecond": 1,
"east": true,
"longitudeDegree": 1,
"longitudeMinute": 1,
"longitudeSecond": 1,
"altitude": 1,
"address": {
"type": "IPV4",
"ipv4": "1.2.3.4/32"
}
}
},
{
"type": "NAT_ADDRESS",
"natAddress": {
"msUdpPortNumber": 1,
"etrUdpPortNumber": 1,
"globalEtrRlocAddress": {
"type": "IPV4",
"ipv4": "1.2.3.4/32"
},
"msRlocAddress": {
"type": "IPV4",
"ipv4": "1.2.3.4/32"
},
"privateEtrRlocAddress": {
"type": "IPV4",
"ipv4": "1.2.3.4/32"
},
"rtrRlocAddresses": [
{
"type": "IPV4",
"ipv4": "1.2.3.4/32"
},
{
"type": "IPV6",
"ipv6": "1111:2222:3333:4444:5555:6666:7777:8886/128"
}
]
}
},
{
"type": "NONCE_ADDRESS",
"nonceAddress": {
"nonce": 1,
"address": {
"type": "IPV4",
"ipv4": "1.2.3.4/32"
}
}
},
{
"type": "MULTICAST_ADDRESS",
"multicastAddress": {
"instanceId": 1,
"srcMaskLength": 1,
"grpMaskLength": 1,
"srcAddress": {
"type": "IPV4",
"ipv4": "1.2.3.4/32"
},
"grpAddress": {
"type": "IPV4",
"ipv4": "1.2.3.4/32"
}
}
},
{
"type": "TRAFFIC_ENGINEERING_ADDRESS",
"trafficEngineeringAddress": {
"records": [
{
"lookup": true,
"rlocProbe": true,
"strict": true,
"address": {
"type": "IPV4",
"ipv4": "1.2.3.4/32"
}
}
]
}
},
{
"type": "SOURCE_DEST_ADDRESS",
"sourceDestAddress": {
"srcMaskLength": 1,
"dstMaskLength": 1,
"srcPrefix": {
"type": "IPV4",
"ipv4": "1.2.3.4/32"
},
"dstPrefix": {
"type": "IPV4",
"ipv4": "1.2.3.4/32"
}
}
}
] | {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 13aad83772f2645078c9cf9262faba2a
timeCreated: 1459498231
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
package org.rts.impl;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* Smarty Internal Plugin Compile Config Load
* Compiles the {config load} tag
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Config Load Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Config_Load extends Smarty_Internal_CompileBase
{
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $required_attributes = array('file');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $shorttag_order = array('file', 'section');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $optional_attributes = array('section', 'scope');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $option_flags = array('nocache', 'noscope');
/**
* Valid scope names
*
* @var array
*/
public $valid_scopes = array('local' => Smarty::SCOPE_LOCAL, 'parent' => Smarty::SCOPE_PARENT,
'root' => Smarty::SCOPE_ROOT, 'tpl_root' => Smarty::SCOPE_TPL_ROOT,
'smarty' => Smarty::SCOPE_SMARTY);
/**
* Compiles code for the {config_load} tag
*
* @param array $args array with attributes from parser
* @param \Smarty_Internal_TemplateCompilerBase $compiler compiler object
*
* @return string compiled code
* @throws \SmartyCompilerException
*/
public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
if ($_attr[ 'nocache' ] === true) {
$compiler->trigger_template_error('nocache option not allowed', null, true);
}
// save possible attributes
$conf_file = $_attr[ 'file' ];
if (isset($_attr[ 'section' ])) {
$section = $_attr[ 'section' ];
} else {
$section = 'null';
}
// scope setup
if ($_attr[ 'noscope' ]) {
$_scope = - 1;
} else {
$_scope = $compiler->convertScope($_attr, $this->valid_scopes);
}
// create config object
$_output =
"<?php\n\$_smarty_tpl->smarty->ext->configLoad->_loadConfigFile(\$_smarty_tpl, {$conf_file}, {$section}, {$_scope});\n?>\n";
return $_output;
}
}
| {
"pile_set_name": "Github"
} |
/*!
* # Semantic UI 2.0.7 - Modal
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
/*******************************
Modal
*******************************/
.ui.modal {
display: none;
position: fixed;
z-index: 1001;
top: 50%;
left: 50%;
text-align: left;
background: #ffffff;
border: none;
box-shadow: 1px 3px 3px 0px rgba(0, 0, 0, 0.2), 1px 3px 15px 2px rgba(0, 0, 0, 0.2);
-webkit-transform-origin: 50% 25%;
-ms-transform-origin: 50% 25%;
transform-origin: 50% 25%;
border-radius: 0.28571429rem;
-webkit-user-select: text;
-moz-user-select: text;
-ms-user-select: text;
user-select: text;
will-change: top, left, margin, transform, opacity;
}
.ui.modal > :first-child:not(.icon),
.ui.modal > .icon:first-child + * {
border-top-left-radius: 0.28571429rem;
border-top-right-radius: 0.28571429rem;
}
.ui.modal > :last-child {
border-bottom-left-radius: 0.28571429rem;
border-bottom-right-radius: 0.28571429rem;
}
/*******************************
Content
*******************************/
/*--------------
Close
---------------*/
.ui.modal > .close {
cursor: pointer;
position: absolute;
top: -2.5rem;
right: -2.5rem;
z-index: 1;
opacity: 0.8;
font-size: 1.25em;
color: #ffffff;
width: 2.25rem;
height: 2.25rem;
padding: 0.625rem 0rem 0rem 0rem;
}
.ui.modal > .close:hover {
opacity: 1;
}
/*--------------
Header
---------------*/
.ui.modal > .header {
display: block;
font-family: 'Lato', 'Helvetica Neue', Arial, Helvetica, sans-serif;
background: #ffffff;
margin: 0em;
padding: 1.25rem 1.5rem;
box-shadow: none;
color: rgba(0, 0, 0, 0.85);
border-bottom: 1px solid rgba(34, 36, 38, 0.15);
}
.ui.modal > .header:not(.ui) {
font-size: 1.42857143rem;
line-height: 1.2857em;
font-weight: bold;
}
/*--------------
Content
---------------*/
.ui.modal > .content {
display: block;
width: 100%;
font-size: 1em;
line-height: 1.4;
padding: 1.5rem;
background: #ffffff;
}
.ui.modal > .image.content {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
}
/* Image */
.ui.modal > .content > .image {
display: block;
-webkit-box-flex: 0;
-webkit-flex: 0 1 auto;
-ms-flex: 0 1 auto;
flex: 0 1 auto;
width: '';
-webkit-align-self: top;
-ms-flex-item-align: top;
align-self: top;
}
.ui.modal > [class*="top aligned"] {
-webkit-align-self: top;
-ms-flex-item-align: top;
align-self: top;
}
.ui.modal > [class*="middle aligned"] {
-webkit-align-self: middle;
-ms-flex-item-align: middle;
align-self: middle;
}
.ui.modal > [class*="stretched"] {
-webkit-align-self: stretch;
-ms-flex-item-align: stretch;
align-self: stretch;
}
/* Description */
.ui.modal > .content > .description {
display: block;
-webkit-box-flex: 1;
-webkit-flex: 1 0 auto;
-ms-flex: 1 0 auto;
flex: 1 0 auto;
min-width: 0px;
-webkit-align-self: top;
-ms-flex-item-align: top;
align-self: top;
}
.ui.modal > .content > .icon + .description,
.ui.modal > .content > .image + .description {
-webkit-box-flex: 0;
-webkit-flex: 0 1 auto;
-ms-flex: 0 1 auto;
flex: 0 1 auto;
min-width: '';
width: auto;
padding-left: 2em;
}
/*rtl:ignore*/
.ui.modal > .content > .image > i.icon {
margin: 0em;
opacity: 1;
width: auto;
line-height: 1;
font-size: 8rem;
}
/*--------------
Actions
---------------*/
.ui.modal > .actions {
background: #f9fafb;
padding: 1rem 1rem;
border-top: 1px solid rgba(34, 36, 38, 0.15);
text-align: right;
}
.ui.modal .actions > .button {
margin-left: 0.75em;
}
/*-------------------
Responsive
--------------------*/
/* Modal Width */
@media only screen and (max-width: 767px) {
.ui.modal {
width: 95%;
margin: 0em 0em 0em -47.5%;
}
}
@media only screen and (min-width: 768px) {
.ui.modal {
width: 88%;
margin: 0em 0em 0em -44%;
}
}
@media only screen and (min-width: 992px) {
.ui.modal {
width: 850px;
margin: 0em 0em 0em -425px;
}
}
@media only screen and (min-width: 1200px) {
.ui.modal {
width: 900px;
margin: 0em 0em 0em -450px;
}
}
@media only screen and (min-width: 1920px) {
.ui.modal {
width: 950px;
margin: 0em 0em 0em -475px;
}
}
/* Tablet and Mobile */
@media only screen and (max-width: 992px) {
.ui.modal > .header {
padding-right: 2.25rem;
}
.ui.modal > .close {
top: 1.0535rem;
right: 1rem;
color: rgba(0, 0, 0, 0.87);
}
}
/* Mobile */
@media only screen and (max-width: 767px) {
.ui.modal > .header {
padding: 0.75rem 1rem !important;
padding-right: 2.25rem !important;
}
.ui.modal > .content {
display: block;
padding: 1rem !important;
}
.ui.modal > .close {
top: 0.5rem !important;
right: 0.5rem !important;
}
/*rtl:ignore*/
.ui.modal .image.content {
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.ui.modal .content > .image {
display: block;
max-width: 100%;
margin: 0em auto !important;
text-align: center;
padding: 0rem 0rem 1rem !important;
}
.ui.modal > .content > .image > i.icon {
font-size: 5rem;
text-align: center;
}
/*rtl:ignore*/
.ui.modal .content > .description {
display: block;
width: 100% !important;
margin: 0em !important;
padding: 1rem 0rem !important;
box-shadow: none;
}
/* Let Buttons Stack */
.ui.modal > .actions {
padding: 1rem 1rem 0rem !important;
}
.ui.modal .actions > .buttons,
.ui.modal .actions > .button {
margin-bottom: 1rem;
}
}
/*--------------
Coupling
---------------*/
.ui.inverted.dimmer > .ui.modal {
box-shadow: 1px 3px 10px 2px rgba(0, 0, 0, 0.2);
}
/*******************************
Types
*******************************/
.ui.basic.modal {
background-color: transparent;
border: none;
border-radius: 0em;
box-shadow: none !important;
color: #ffffff;
}
.ui.basic.modal > .header,
.ui.basic.modal > .content,
.ui.basic.modal > .actions {
background-color: transparent;
}
.ui.basic.modal > .header {
color: #ffffff;
}
.ui.basic.modal > .close {
top: 1rem;
right: 1.5rem;
}
.ui.inverted.dimmer > .basic.modal {
color: rgba(0, 0, 0, 0.87);
}
.ui.inverted.dimmer > .ui.basic.modal > .header {
color: rgba(0, 0, 0, 0.85);
}
/* Tablet and Mobile */
@media only screen and (max-width: 992px) {
.ui.basic.modal > .close {
color: #ffffff;
}
}
/*******************************
States
*******************************/
.ui.active.modal {
display: block;
}
/*******************************
Variations
*******************************/
/*--------------
Scrolling
---------------*/
/* A modal that cannot fit on the page */
.scrolling.dimmable.dimmed {
overflow: hidden;
}
.scrolling.dimmable.dimmed > .dimmer {
overflow: auto;
-webkit-overflow-scrolling: touch;
}
.scrolling.dimmable > .dimmer {
position: fixed;
}
.modals.dimmer .ui.scrolling.modal {
position: static !important;
margin: 3.5rem auto !important;
}
/* undetached scrolling */
.scrolling.undetached.dimmable.dimmed {
overflow: auto;
-webkit-overflow-scrolling: touch;
}
.scrolling.undetached.dimmable.dimmed > .dimmer {
overflow: hidden;
}
.scrolling.undetached.dimmable .ui.scrolling.modal {
position: absolute;
left: 50%;
margin-top: 3.5rem !important;
}
/* Coupling with Sidebar */
.undetached.dimmable.dimmed > .pusher {
z-index: auto;
}
@media only screen and (max-width: 992px) {
.modals.dimmer .ui.scrolling.modal {
margin-top: 1rem !important;
margin-bottom: 1rem !important;
}
}
/*--------------
Full Screen
---------------*/
.ui.fullscreen.modal {
width: 95% !important;
left: 2.5% !important;
margin: 1em auto;
}
.ui.fullscreen.scrolling.modal {
left: 0em !important;
}
.ui.fullscreen.modal > .header {
padding-right: 2.25rem;
}
.ui.fullscreen.modal > .close {
top: 1.0535rem;
right: 1rem;
color: rgba(0, 0, 0, 0.87);
}
/*--------------
Size
---------------*/
.ui.modal {
font-size: 1rem;
}
/* Small */
.ui.small.modal > .header:not(.ui) {
font-size: 1.3em;
}
/* Small Modal Width */
@media only screen and (max-width: 767px) {
.ui.small.modal {
width: 95%;
margin: 0em 0em 0em -47.5%;
}
}
@media only screen and (min-width: 768px) {
.ui.small.modal {
width: 70.4%;
margin: 0em 0em 0em -35.2%;
}
}
@media only screen and (min-width: 992px) {
.ui.small.modal {
width: 680px;
margin: 0em 0em 0em -340px;
}
}
@media only screen and (min-width: 1200px) {
.ui.small.modal {
width: 720px;
margin: 0em 0em 0em -360px;
}
}
@media only screen and (min-width: 1920px) {
.ui.small.modal {
width: 760px;
margin: 0em 0em 0em -380px;
}
}
/* Large Modal Width */
.ui.large.modal > .header {
font-size: 1.6em;
}
@media only screen and (max-width: 767px) {
.ui.large.modal {
width: 95%;
margin: 0em 0em 0em -47.5%;
}
}
@media only screen and (min-width: 768px) {
.ui.large.modal {
width: 88%;
margin: 0em 0em 0em -44%;
}
}
@media only screen and (min-width: 992px) {
.ui.large.modal {
width: 1020px;
margin: 0em 0em 0em -510px;
}
}
@media only screen and (min-width: 1200px) {
.ui.large.modal {
width: 1080px;
margin: 0em 0em 0em -540px;
}
}
@media only screen and (min-width: 1920px) {
.ui.large.modal {
width: 1140px;
margin: 0em 0em 0em -570px;
}
}
/*******************************
Theme Overrides
*******************************/
/*******************************
Site Overrides
*******************************/
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="8dp"
android:textColor="?attr/textColorPrimary"
android:text="@string/onedrive_account_type"/>
<LinearLayout
android:id="@+id/onedrive_personal_account_view"
android:layout_width="match_parent"
android:layout_height="48dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:background="?selectableItemBackground" >
<RadioButton
android:id="@+id/rb_onedrive_personal_account"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="?attr/textColorPrimary"
android:text="@string/personal_account_type"/>
</LinearLayout>
<LinearLayout
android:id="@+id/onedrive_business_account_view"
android:layout_width="match_parent"
android:layout_height="48dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:background="?selectableItemBackground" >
<RadioButton
android:id="@+id/rb_onedrive_business_account"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="?attr/textColorPrimary"
android:text="@string/business_account_type"/>
</LinearLayout>
</LinearLayout> | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
-
- $Id$
-
- This file is part of the OpenLink Software Virtuoso Open-Source (VOS)
- project.
-
- Copyright (C) 1998-2020 OpenLink Software
-
- This project 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; only version 2 of the License, dated June 1991.
-
- 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
-
-->
<v:page name="foaf-import-page"
xmlns:vm="http://www.openlinksw.com/vspx/ods/"
xmlns:v="http://www.openlinksw.com/vspx/"
style="index.xsl"
doctype="-//W3C//DTD XHTML 1.0 Transitional//EN"
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<v:variable name="ol_mode" type="varchar" default="'OL/browse'"/>
<v:variable name="ol_id" type="any" default="null" />
<v:variable name="ol_type" type="varchar" default="'1'" />
<v:variable name="ol_properties" type="any" default="null" />
<v:variable name="ol_newProperties" type="any" default="null" />
<v:form name="usr_personal_054" type="simple" method="POST" xhtml_enctype="multipart/form-data">
<h3>My Offers</h3>
<vm:if test="self.ol_mode = 'OL/browse'">
<?vsp
if (0)
{
?>
<v:button name="ol_dButton" action="simple" value="Delete">
<v:on-post>
<![CDATA[
delete from DB.DBA.WA_USER_OFFERLIST where WUOL_ID = get_keyword ('ol_id', self.vc_page.vc_event.ve_params) and WUOL_U_ID = self.u_id;
self.vc_data_bind(e);
]]>
</v:on-post>
</v:button>
<?vsp
}
?>
<input type="hidden" name="ol_id" id="ol_id" value="" />
<div style="padding: 0 0 0.5em 0;">
<v:button name="ol_aButton" action="simple" style="url" value="''" xhtml_class="img_button">
<v:before-render>
<![CDATA[
control.ufl_value := '<img src="images/icons/add_16.png" border="0" /> Add';
]]>
</v:before-render>
<v:on-post>
<![CDATA[
self.ol_mode := 'OL/add';
self.ol_flag.ufl_value := null;
self.ol_offer.ufl_value := null;
self.ol_comment.ufl_value := null;
self.ol_properties := ODS..jsonObject ();
self.ol_newProperties := vector (vector_concat (ODS..jsonObject (), vector ('id', '0', 'ontology', 'http://purl.org/goodrelations/v1#', 'items', vector ())));
self.vc_data_bind(e);
]]>
</v:on-post>
</v:button>
</div>
<v:data-set name="ol_ds"
sql="select WUOL_ID, WUOL_OFFER, WUOL_COMMENT from DB.DBA.WA_USER_OFFERLIST where WUOL_U_ID = :self.u_id and WUOL_TYPE = :self.ol_type"
scrollable="1"
editable="1"
nrows="0">
<v:template name="ol_ds_header" type="simple" name-to-remove="table" set-to-remove="bottom">
<table class="listing" rules="groups">
<tr class="listing_header_row">
<th>Offer</th>
<th width="50px">Action</th>
</tr>
</table>
</v:template>
<v:template name="ol_ds_repeat" type="repeat" name-to-remove="" set-to-remove="">
<v:template name="ol_ds_empty" type="if-not-exists" name-to-remove="table" set-to-remove="both">
<table>
<tr align="center">
<td colspan="2">No Offers</td>
</tr>
</table>
</v:template>
<v:template name="ol_ds_browse" type="browse" name-to-remove="table" set-to-remove="both">
<table>
<tr class="<?V case when mod(control.te_ctr, 2) then 'listing_row_odd' else 'listing_row_even' end ?>">
<td nowrap="nowrap" width="100%">
<v:label value="--(control.vc_parent as vspx_row_template).te_column_value('WUOL_OFFER')" format="%s" name="ol_ds_browse_1_label"/>
</td>
<td nowrap="nowrap">
<v:button name="ol_eButton" action="simple" style="url" value="''" xhtml_class="img_button">
<v:before-render>
<![CDATA[
control.ufl_value := '<img src="images/icons/edit_16.png" border="0" alt="Edit Offer" title="Edit Offer"/> Edit';
]]>
</v:before-render>
<v:on-post>
<![CDATA[
self.ol_mode := 'OL/edit';
self.ol_id := (control.vc_parent as vspx_row_template).te_column_value('WUOL_ID');
self.ol_newProperties := vector (vector_concat (ODS..jsonObject (), vector ('id', '0', 'ontology', 'http://purl.org/goodrelations/v1#', 'items', vector ())));
select WUOL_FLAG,
WUOL_OFFER,
WUOL_COMMENT,
deserialize (WUOL_PROPERTIES)
into self.ol_flag.ufl_value,
self.ol_offer.ufl_value,
self.ol_comment.ufl_value,
self.ol_properties
from DB.DBA.WA_USER_OFFERLIST
where WUOL_ID = self.ol_id;
if (get_keyword ('version', self.ol_properties) = '1.0')
self.ol_newProperties := vector (vector_concat (ODS..jsonObject (), vector ('id', '0', 'ontology', 'http://purl.org/goodrelations/v1#', 'items', get_keyword ('products', self.ol_properties, vector ()))));
if (get_keyword ('version', self.ol_properties) = '2.0')
self.ol_newProperties := get_keyword ('ontologies', self.ol_properties, vector ());
self.vc_data_bind(e);
]]>
</v:on-post>
</v:button>
<span class="button pointer" onclick="javascript: if (confirm('Are you sure you want to delete this record?')) {$('ol_id').value = <?V (control as vspx_row_template).te_column_value('WUOL_ID') ?>; doPost('page_form', 'ol_dButton');}">
<img class="button" src="/ods/images/icons/trash_16.png"/> Delete
</span>
</td>
</tr>
</table>
</v:template>
</v:template>
<v:template name="ol_ds_footer" type="simple" name-to-remove="table" set-to-remove="top">
<table>
</table>
</v:template>
</v:data-set>
</vm:if>
<vm:if test="self.ol_mode <> 'OL/browse'">
<div class="fm">
<table>
<tr>
<th width="100px">
Access
</th>
<td>
<v:select-list name="ol_flag" xhtml_id="ol_flag">
<v:item name="public" value="1" />
<v:item name="acl" value="2" />
<v:item name="private" value="3" />
</v:select-list>
</td>
</tr>
<tr>
<th>
Offer Name
</th>
<td>
<v:text name="ol_offer" value="" xhtml_id="ol_offer" xhtml_size="50" xhtml_class="_validate_" />
</td>
</tr>
<tr>
<th valign="top">
Comment
</th>
<td>
<v:textarea name="ol_comment" value="" xhtml_id="ol_comment" xhtml_rows="5" xhtml_cols="50"/>
</td>
</tr>
<tr>
<th valign="top">
Products
</th>
<td width="800px">
<table class="ctl_grp">
<tr>
<td width="800px">
<table id="ol_tbl" class="listing">
<thead>
<tr class="listing_header_row">
<th>
<div style="width: 16px;"><![CDATA[ ]]></div>
</th>
<th width="100%">
Ontology
</th>
<th width="80px">
Action
</th>
</tr>
</thead>
<tbody id="ol_tbody" class="colorize">
<tr id="ol_tr_no"><td colspan="3"><b>No Attached Ontologies</b></td></tr>
</tbody>
</table>
</td>
<td valign="top" nowrap="nowrap">
<span class="button pointer" onclick="TBL.createRow('ol', null, {fld_1: {mode: 40, cssText: 'display: none;'}, fld_2: {mode: 41, labelValue: 'Ontology: ', cssText: 'width: 95%;'}, btn_1: {mode: 40}, btn_2: {mode: 41, title: 'Attach'}});"><img class="button" src="/ods/images/icons/add_16.png" border="0" alt="Add Ontology" title="Add Ontology" /> Add</span>
<br /><br />
<span class="button pointer" onclick="RDF.showRDF('ol', 'RDF');"><img class="button" src="/ods/images/icons/rdf_11.png" border="0" alt="Show RDF Data" title="Show RDF Data" /> RDF</span>
<br /><br />
<span class="button pointer" onclick="RDF.showRDF('ol', 'TTL');"><img class="button" src="/ods/images/icons/rdf_11.png" border="0" alt="Show RDF Data" title="Show RDF Data" /> TTL</span>
</td>
</tr>
</table>
<input type="hidden" id="ol_no" name="ol_no" value="1" />
<script type="text/javascript">
<![CDATA[
ODSInitArray.push ( function () {
OAT.Loader.load(["ajax", "json", "combolist"], function(){
RDF.tablePrefix = 'ol';
RDF.tableOptions = {itemType: {fld_1: {cssText: "display: none;"}, btn_1: {cssText: "display: none;"}}};
RDF.itemTypes = <?vsp http (replace (ODS..obj2json (self.ol_newProperties, 10), 'class:', 'className:')); ?>;
RDF.showItemTypes();
});
});
]]>
</script>
</td>
</tr>
<tr>
<td></td>
<td>
<br />
<v:button name="user_c_personal_054" value="Cancel" action="simple">
<v:on-post>
self.ol_mode := 'OL/browse';
self.vc_data_bind (e);
</v:on-post>
</v:button>
<v:button name="user_s_personal_054" value="--case when self.ol_mode = 'OL/add' then 'Add' else 'Update' end" action="simple" xhtml_onclick="return validateInputs(this);">
<v:on-post><![CDATA[
if (self.vc_is_valid = 0)
return;
declare ontologies, IDs any;
IDs := vector ();
ontologies := vector ();
self.getItems ('ol', 'gr', ontologies, IDs);
self.ol_properties := vector_concat (ODS..jsonObject (), vector ('version', '2.0', 'ontologies', ontologies));
if (self.ol_mode = 'OL/add')
{
if (exists (select 1 from DB.DBA.WA_USER_OFFERLIST where WUOL_U_ID = self.u_id and WUOL_TYPE = self.ol_type and WUOL_OFFER = self.ol_offer.ufl_value))
{
self.vc_error_message := 'An offer with same name already exists, please specify unique name.';
self.vc_is_valid := 0;
return;
}
insert into DB.DBA.WA_USER_OFFERLIST (WUOL_U_ID, WUOL_TYPE, WUOL_FLAG, WUOL_OFFER, WUOL_COMMENT, WUOL_PROPERTIES)
values (self.u_id, self.ol_type, self.ol_flag.ufl_value, self.ol_offer.ufl_value, self.ol_comment.ufl_value, serialize (self.ol_properties));
}
else
{
update DB.DBA.WA_USER_OFFERLIST
set WUOL_FLAG = self.ol_flag.ufl_value,
WUOL_OFFER = self.ol_offer.ufl_value,
WUOL_COMMENT = self.ol_comment.ufl_value,
WUOL_PROPERTIES = serialize (self.ol_properties)
where WUOL_ID = self.ol_id;
}
self.ol_mode := 'OL/browse';
self.vc_data_bind (e);
]]></v:on-post>
</v:button>
</td>
</tr>
</table>
</div>
<div id="rdfDiv" style="display: none;">
<pre id="rdfData">
</pre>
</div>
</vm:if>
</v:form>
</v:page>
| {
"pile_set_name": "Github"
} |
/********************************************************************
** Copyright (c) 2018-2020 Guan Wenliang
** This file is part of the Berry default interpreter.
** skiars@qq.com, https://github.com/Skiars/berry
** See Copyright Notice in the LICENSE file or at
** https://github.com/Skiars/berry/blob/master/LICENSE
********************************************************************/
#include "be_vm.h"
#include "be_func.h"
#include "be_class.h"
#include "be_string.h"
#include "be_vector.h"
#include "be_var.h"
#include "be_list.h"
#include "be_map.h"
#include "be_parser.h"
#include "be_debug.h"
#include "be_exec.h"
#include "be_strlib.h"
#include "be_module.h"
#include "be_gc.h"
#include <string.h>
#define retreg(vm) ((vm)->cf->func)
static void class_init(bvm *vm, bclass *c, const bnfuncinfo *lib)
{
if (lib) {
while (lib->name) {
bstring *s = be_newstr(vm, lib->name);
if (lib->function) { /* method */
be_prim_method_bind(vm, c, s, lib->function);
} else {
be_member_bind(vm, c, s); /* member */
}
++lib;
}
be_map_release(vm, c->members); /* clear space */
}
}
static bclass* class_auto_make(bvm *vm, bstring *name, const bnfuncinfo *lib)
{
bvalue key, *res;
var_setobj(&key, BE_COMPTR, (void*)lib);
if (vm->ntvclass == NULL) {
vm->ntvclass = be_map_new(vm);
}
res = be_map_find(vm, vm->ntvclass, &key);
if (res == NULL || !var_isclass(res)) {
bclass *c;
/* insert class to native class table */
res = be_map_insert(vm, vm->ntvclass, &key, NULL);
var_setnil(res); /* must be initialized to ensure correct GC */
c = be_newclass(vm, name, NULL);
var_setclass(res, c);
class_init(vm, c, lib); /* bind members */
return c;
}
return var_toobj(res);
}
BERRY_API void be_regfunc(bvm *vm, const char *name, bntvfunc f)
{
bvalue *var;
bstring *s = be_newstr(vm, name);
#if !BE_USE_PRECOMPILED_OBJECT
int idx = be_builtin_find(vm, s);
be_assert(idx == -1);
if (idx == -1) { /* new function */
idx = be_builtin_new(vm, s);
#else
int idx = be_global_find(vm, s);
be_assert(idx < be_builtin_count(vm));
if (idx < be_builtin_count(vm)) { /* new function */
idx = be_global_new(vm, s);
#endif
var = be_global_var(vm, idx);
var_setntvfunc(var, f);
} /* error case, do nothing */
}
BERRY_API void be_regclass(bvm *vm, const char *name, const bnfuncinfo *lib)
{
bvalue *var;
bstring *s = be_newstr(vm, name);
#if !BE_USE_PRECOMPILED_OBJECT
int idx = be_builtin_find(vm, s);
be_assert(idx == -1);
if (idx == -1) { /* new function */
idx = be_builtin_new(vm, s);
#else
int idx = be_global_find(vm, s);
be_assert(idx < be_builtin_count(vm));
if (idx < be_builtin_count(vm)) { /* new function */
idx = be_global_new(vm, s);
#endif
var = be_global_var(vm, idx);
var_setclass(var, class_auto_make(vm, s, lib));
} /* error case, do nothing */
}
BERRY_API int be_top(bvm *vm)
{
return cast_int(vm->top - vm->reg);
}
BERRY_API void be_pop(bvm *vm, int n)
{
be_assert(n <= vm->top - vm->reg);
be_stackpop(vm, n);
}
BERRY_API int be_absindex(bvm *vm, int index)
{
if (index > 0) {
return index;
}
be_assert(vm->reg <= vm->top + index);
return cast_int(vm->top + index - vm->reg + 1);
}
BERRY_API bbool be_isnil(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return var_isnil(v);
}
BERRY_API bbool be_isbool(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return var_isbool(v);
}
BERRY_API bbool be_isint(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return var_isint(v);
}
BERRY_API bbool be_isreal(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return var_isreal(v);
}
BERRY_API bbool be_isnumber(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return var_isnumber(v);
}
BERRY_API bbool be_isstring(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return var_isstr(v);
}
BERRY_API bbool be_isclosure(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return var_isclosure(v);
}
BERRY_API bbool be_isntvclos(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return var_isntvclos(v);
}
BERRY_API bbool be_isfunction(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return var_isfunction(v);
}
BERRY_API bbool be_isproto(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return var_isproto(v);
}
BERRY_API bbool be_isclass(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return var_isclass(v);
}
BERRY_API bbool be_isinstance(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return var_isinstance(v);
}
BERRY_API bbool be_islist(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return var_islist(v);
}
BERRY_API bbool be_ismap(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return var_ismap(v);
}
BERRY_API bbool be_iscomptr(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return var_istype(v, BE_COMPTR);
}
BERRY_API bbool be_iscomobj(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return var_istype(v, BE_COMOBJ);
}
BERRY_API bint be_toint(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return var_toint(v);
}
BERRY_API breal be_toreal(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
if (var_isreal(v)) {
return var_toreal(v);
}
if (var_isint(v)) {
return cast(breal, var_toint(v));
}
return cast(breal, 0.0);
}
BERRY_API int be_toindex(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return var_toidx(v);
}
BERRY_API bbool be_tobool(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return be_value2bool(vm, v);
}
BERRY_API const char* be_tostring(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
if (!var_isstr(v)) {
be_val2str(vm, index);
v = be_indexof(vm, index);
}
return str(var_tostr(v));
}
BERRY_API void* be_tocomptr(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
if (var_istype(v, BE_COMPTR)) {
return var_toobj(v);
}
if (var_istype(v, BE_COMOBJ)) {
bcommomobj *obj = var_toobj(v);
return obj->data;
}
return NULL;
}
BERRY_API void be_moveto(bvm *vm, int from, int to)
{
bvalue *src = be_indexof(vm, from);
bvalue *dst = be_indexof(vm, to);
var_setval(dst, src);
}
BERRY_API void be_pushnil(bvm *vm)
{
bvalue *reg = be_incrtop(vm);
var_setnil(reg);
}
BERRY_API void be_pushbool(bvm *vm, int b)
{
bvalue *reg = be_incrtop(vm);
var_setbool(reg, b != bfalse);
}
BERRY_API void be_pushint(bvm *vm, bint i)
{
bvalue *reg = be_incrtop(vm);
var_setint(reg, i);
}
BERRY_API void be_pushreal(bvm *vm, breal r)
{
bvalue *reg = be_incrtop(vm);
var_setreal(reg, r);
}
BERRY_API void be_pushstring(bvm *vm, const char *str)
{
/* to create a string and then push the top registor,
* otherwise the GC may crash due to uninitialized values.
**/
bstring *s = be_newstr(vm, str);
bvalue *reg = be_incrtop(vm);
be_assert(reg < vm->stacktop);
var_setstr(reg, s);
}
BERRY_API void be_pushnstring(bvm *vm, const char *str, size_t n)
{
/* to create a string and then push the top registor,
* otherwise the GC may crash due to uninitialized values.
**/
bstring *s = be_newstrn(vm, str, n);
bvalue *reg = be_incrtop(vm);
var_setstr(reg, s);
}
BERRY_API const char* be_pushfstring(bvm *vm, const char *format, ...)
{
const char* s;
va_list arg_ptr;
va_start(arg_ptr, format);
s = be_pushvfstr(vm, format, arg_ptr);
va_end(arg_ptr);
return s;
}
BERRY_API void* be_pushbuffer(bvm *vm, size_t size)
{
bstring *s = be_newlongstr(vm, NULL, size);
bvalue *reg = be_incrtop(vm);
var_setstr(reg, s);
return (void*)str(s);
}
BERRY_API void be_pushvalue(bvm *vm, int index)
{
bvalue *reg = vm->top;
var_setval(reg, be_indexof(vm, index));
be_incrtop(vm);
}
BERRY_API void be_pushntvclosure(bvm *vm, bntvfunc f, int nupvals)
{
/* to create a native closure and then push the top registor,
* otherwise the GC may crash due to uninitialized values.
**/
bntvclos *cl = be_newntvclosure(vm, f, nupvals);
bvalue *top = be_incrtop(vm);
var_setntvclos(top, cl);
}
BERRY_API void be_pushntvfunction(bvm *vm, bntvfunc f)
{
bvalue *top = be_incrtop(vm);
var_setntvfunc(top, f);
}
BERRY_API void be_pushclass(bvm *vm, const char *name, const bnfuncinfo *lib)
{
bclass *c;
bstring *s = be_newstr(vm, name);
bvalue *dst = be_incrtop(vm);
var_setstr(dst, s);
c = class_auto_make(vm, s, lib);
var_setclass(vm->top - 1, c);
}
BERRY_API void be_pushcomptr(bvm *vm, void *ptr)
{
bvalue *top = be_incrtop(vm);
var_setobj(top, BE_COMPTR, ptr);
}
BERRY_API void be_remove(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
bvalue *top = --vm->top;
while (v < top) {
*v = v[1];
++v;
}
}
BERRY_API void be_strconcat(bvm *vm, int index)
{
bstring *s;
bvalue *dst = be_indexof(vm, index);
bvalue *src = be_indexof(vm, -1);
be_assert(var_isstr(src) && var_isstr(dst));
s = be_strcat(vm, var_tostr(dst), var_tostr(src));
var_setstr(dst, s);
}
BERRY_API bbool be_setsuper(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
bvalue *top = be_indexof(vm, -1);
if (var_isclass(v) && var_isclass(top)) {
bclass *c = var_toobj(v);
if (!gc_isconst(c)) {
bclass *super = var_toobj(top);
be_class_setsuper(c, super);
return btrue;
}
}
return bfalse;
}
BERRY_API void be_getsuper(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
bvalue *top = be_incrtop(vm);
if (var_isclass(v)) {
bclass *c = var_toobj(v);
c = be_class_super(c);
if (c) {
var_setclass(top, c);
return;
}
} else if (var_isinstance(v)) {
binstance *o = var_toobj(v);
o = be_instance_super(o);
if (o) {
var_setinstance(top, o);
return;
}
}
var_setnil(top);
}
static bclass* _getclass(bvalue *v)
{
if (var_isinstance(v)) {
binstance *ins = var_toobj(v);
return be_instance_class(ins);
}
return var_isclass(v) ? var_toobj(v) : NULL;
}
BERRY_API bbool be_isderived(bvm *vm, int index)
{
bclass *sup = _getclass(be_indexof(vm, -1));
if (sup) {
bclass *c = _getclass(be_indexof(vm, index));
while (c && c != sup)
c = be_class_super(c);
return c != NULL;
}
return bfalse;
}
BERRY_API const char *be_typename(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
return be_vtype2str(v);
}
BERRY_API const char *be_classname(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
if (var_isclass(v)) {
bclass *c = var_toobj(v);
return str(be_class_name(c));
}
if (var_isinstance(v)) {
binstance *i = var_toobj(v);
return str(be_instance_name(i));
}
return NULL;
}
BERRY_API bbool be_classof(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
if (var_isinstance(v)) {
bvalue *top = be_incrtop(vm);
binstance *ins = var_toobj(v);
var_setclass(top, be_instance_class(ins));
return btrue;
}
return bfalse;
}
BERRY_API int be_strlen(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
if (var_isstr(v)) {
return str_len(var_tostr(v));
}
return 0;
}
BERRY_API void be_newlist(bvm *vm)
{
blist *list = be_list_new(vm);
bvalue *top = be_incrtop(vm);
var_setlist(top, list);
}
BERRY_API void be_newmap(bvm *vm)
{
bmap *map = be_map_new(vm);
bvalue *top = be_incrtop(vm);
var_setobj(top, BE_MAP, map);
}
BERRY_API void be_newmodule(bvm *vm)
{
bmodule *mod = be_module_new(vm);
bvalue *top = be_incrtop(vm);
var_setobj(top, BE_MODULE, mod);
}
BERRY_API void be_newobject(bvm *vm, const char *name)
{
be_getbuiltin(vm, name);
be_call(vm, 0);
be_getmember(vm, -1, ".p");
}
BERRY_API bbool be_setname(bvm *vm, int index, const char *name)
{
bvalue *v = be_indexof(vm, index);
if (var_ismodule(v)) {
bmodule *module = var_toobj(v);
return be_module_setname(module, be_newstr(vm, name));
}
return bfalse;
}
BERRY_API bbool be_getglobal(bvm *vm, const char *name)
{
int idx = be_global_find(vm, be_newstr(vm, name));
bvalue *top = be_incrtop(vm);
if (idx > -1) {
*top = *be_global_var(vm, idx);
return btrue;
}
var_setnil(top);
return bfalse;
}
BERRY_API void be_setglobal(bvm *vm, const char *name)
{
int idx;
bstring *s = be_newstr(vm, name);
bvalue *v = be_incrtop(vm);
var_setstr(v, s);
idx = be_global_new(vm, s);
v = be_global_var(vm, idx);
*v = *be_indexof(vm, -2);
be_stackpop(vm, 1);
}
BERRY_API bbool be_getbuiltin(bvm *vm, const char *name)
{
int idx = be_builtin_find(vm, be_newstr(vm, name));
bvalue *top = be_incrtop(vm);
if (idx > -1) {
*top = *be_global_var(vm, idx);
return btrue;
}
var_setnil(top);
return bfalse;
}
BERRY_API bbool be_setmember(bvm *vm, int index, const char *k)
{
int res = BE_NIL;
bvalue *o = be_indexof(vm, index);
if (var_isinstance(o)) {
bstring *key = be_newstr(vm, k);
bvalue *v = be_indexof(vm, -1);
binstance *obj = var_toobj(o);
res = be_instance_setmember(vm, obj, key, v);
} else if (var_ismodule(o)) {
bstring *key = be_newstr(vm, k);
bmodule *mod = var_toobj(o);
bvalue *v = be_module_bind(vm, mod, key);
if (v) {
*v = *be_indexof(vm, -1);
return btrue;
}
}
return res != BE_NIL;
}
BERRY_API bbool be_copy(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
bvalue *top = be_incrtop(vm);
if (var_type(v) == BE_LIST) {
blist *list = be_list_copy(vm, var_toobj(v));
var_setlist(top, list)
return btrue;
}
var_setnil(top);
return bfalse;
}
static int ins_member(bvm *vm, int index, const char *k)
{
int type = BE_NIL;
bvalue *o = be_indexof(vm, index);
bvalue *top = be_incrtop(vm);
var_setnil(top);
if (var_isinstance(o)) {
binstance *obj = var_toobj(o);
type = be_instance_member(vm, obj, be_newstr(vm, k), top);
}
return type;
}
BERRY_API bbool be_getmember(bvm *vm, int index, const char *k)
{
return ins_member(vm, index, k) != BE_NIL;
}
BERRY_API bbool be_getmethod(bvm *vm, int index, const char *k)
{
return basetype(ins_member(vm, index, k)) == BE_FUNCTION;
}
BERRY_API bbool be_getindex(bvm *vm, int index)
{
bvalue *o = be_indexof(vm, index);
bvalue *k = be_indexof(vm, -1);
bvalue *dst = be_incrtop(vm);
switch (var_type(o)) {
case BE_LIST:
if (var_isint(k)) {
blist *list = cast(blist*, var_toobj(o));
int idx = var_toidx(k);
bvalue *src = be_list_index(list, idx);
if (src) {
var_setval(dst, src);
return btrue;
}
}
break;
case BE_MAP:
if (!var_isnil(k)) {
bmap *map = cast(bmap*, var_toobj(o));
bvalue *src = be_map_find(vm, map, k);
if (src) {
var_setval(dst, src);
return btrue;
}
}
break;
default:
break;
}
var_setnil(dst);
return bfalse;
}
static bvalue* list_setindex(blist *list, bvalue *key)
{
int idx = var_toidx(key);
if (idx < be_list_count(list)) {
return be_list_at(list, idx);
}
return NULL;
}
BERRY_API bbool be_setindex(bvm *vm, int index)
{
bvalue *dst = NULL;
bvalue *o = be_indexof(vm, index);
bvalue *k = be_indexof(vm, -2);
bvalue *v = be_indexof(vm, -1);
switch (var_type(o)) {
case BE_LIST:
if (var_isint(k)) {
blist *list = var_toobj(o);
dst = list_setindex(list, k);
}
break;
case BE_MAP:
if (!var_isnil(k)) {
bmap *map = var_toobj(o);
dst = be_map_insert(vm, map, k, NULL);
}
break;
default:
break;
}
if (dst) {
var_setval(dst, v);
return btrue;
}
return bfalse;
}
BERRY_API void be_getupval(bvm *vm, int index, int pos)
{
bvalue *f = index ? be_indexof(vm, index) : vm->cf->func;
bvalue *uv, *top = be_incrtop(vm);
be_assert(var_istype(f, BE_NTVCLOS));
if (var_istype(f, BE_NTVCLOS)) {
bntvclos *nf = var_toobj(f);
be_assert(pos >= 0 && pos < nf->nupvals);
uv = be_ntvclos_upval(nf, pos)->value;
var_setval(top, uv);
} else {
var_setnil(top);
}
}
BERRY_API bbool be_setupval(bvm *vm, int index, int pos)
{
bvalue *f = index ? be_indexof(vm, index) : vm->cf->func;
bvalue *uv, *v = be_indexof(vm, -1);
be_assert(var_istype(f, BE_NTVCLOS));
if (var_istype(f, BE_NTVCLOS)) {
bntvclos *nf = var_toobj(f);
be_assert(pos >= 0 && pos < nf->nupvals);
uv = be_ntvclos_upval(nf, pos)->value;
var_setval(uv, v);
return btrue;
}
return bfalse;
}
BERRY_API int be_data_size(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
if (var_islist(v)) {
blist *list = var_toobj(v);
return be_list_count(list);
} else if (var_ismap(v)) {
bmap *map = cast(bmap*, var_toobj(v));
return be_map_count(map);
}
return -1;
}
BERRY_API void be_data_push(bvm *vm, int index)
{
bvalue *o = be_indexof(vm, index);
bvalue *v = be_indexof(vm, -1);
if (var_islist(o)) {
blist *list = var_toobj(o);
be_list_push(vm, list, v);
}
}
BERRY_API bbool be_data_insert(bvm *vm, int index)
{
bvalue *o = be_indexof(vm, index);
bvalue *k = be_indexof(vm, -2);
bvalue *v = be_indexof(vm, -1);
switch (var_type(o)) {
case BE_MAP:
if (!var_isnil(k)) {
bmap *map = cast(bmap*, var_toobj(o));
bvalue *dst = be_map_find(vm, map, k);
if (dst == NULL) {
return be_map_insert(vm, map, k, v) != NULL;
}
}
break;
case BE_LIST:
if (var_isint(k)) {
blist *list = cast(blist*, var_toobj(o));
return be_list_insert(vm, list, var_toidx(k), v) != NULL;
}
break;
default:
break;
}
return bfalse;
}
BERRY_API bbool be_data_remove(bvm *vm, int index)
{
bvalue *o = be_indexof(vm, index);
bvalue *k = be_indexof(vm, -1);
switch (var_type(o)) {
case BE_MAP:
if (!var_isnil(k)) {
bmap *map = cast(bmap*, var_toobj(o));
return be_map_remove(vm, map, k);
}
break;
case BE_LIST:
if (var_isint(k)) {
blist *list = cast(blist*, var_toobj(o));
return be_list_remove(vm, list, var_toidx(k));
}
break;
default:
break;
}
return bfalse;
}
BERRY_API bbool be_data_merge(bvm *vm, int index)
{
bvalue *a = be_indexof(vm, index);
bvalue *b = be_indexof(vm, -1);
if (var_islist(a) && var_islist(b)) {
blist *dst = var_toobj(a), *src = var_toobj(b);
be_list_merge(vm, dst, src);
return btrue;
}
return bfalse;
}
BERRY_API void be_data_resize(bvm *vm, int index)
{
bvalue *o = be_indexof(vm, index);
bvalue *v = be_indexof(vm, -1);
if (var_islist(o)) {
blist *list = var_toobj(o);
if (var_isint(v)) {
be_list_resize(vm, list, var_toidx(v));
}
}
}
BERRY_API void be_data_reverse(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
if (var_type(v) == BE_LIST) {
be_list_reverse(var_toobj(v));
}
}
BERRY_API bbool be_pushiter(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
if (var_ismap(v)) {
bvalue *iter = be_incrtop(vm);
var_setobj(iter, BE_COMPTR, NULL);
return btrue;
} else if (var_islist(v)) {
blist *list = var_toobj(v);
bvalue *iter = be_incrtop(vm);
var_setobj(iter, BE_COMPTR, be_list_data(list) - 1);
return btrue;
}
return bfalse;
}
static int list_next(bvm *vm)
{
bvalue *iter = be_indexof(vm, -1);
bvalue *next, *dst = be_incrtop(vm);
next = cast(bvalue*, var_toobj(iter)) + 1;
var_setobj(iter, BE_COMPTR, next);
var_setval(dst, next);
return 1;
}
static bbool list_hasnext(bvm *vm, bvalue *v)
{
bvalue *next;
bvalue *iter = be_indexof(vm, -1);
blist *obj = var_toobj(v);
next = cast(bvalue*, var_toobj(iter)) + 1;
return next >= be_list_data(obj) && next < be_list_end(obj);
}
static int map_next(bvm *vm, bvalue *v)
{
bmapiter iter;
bmapnode *entry;
bvalue *dst = vm->top;
bvalue *itvar = be_indexof(vm, -1);
iter = var_toobj(itvar);
entry = be_map_next(var_toobj(v), &iter);
var_setobj(itvar, BE_COMPTR, iter);
if (entry) {
bvalue vk = be_map_key2value(entry);
var_setval(dst, &vk);
var_setval(dst + 1, &entry->value);
vm->top += 2;
return 2;
}
return 0;
}
static bbool map_hasnext(bvm *vm, bvalue *v)
{
bvalue *node = be_indexof(vm, -1);
bmapiter iter = var_toobj(node);
return be_map_next(var_toobj(v), &iter) != NULL;
}
BERRY_API int be_iter_next(bvm *vm, int index)
{
bvalue *o = be_indexof(vm, index);
if (var_islist(o)) {
return list_next(vm);
} else if (var_ismap(o)) {
return map_next(vm, o);
}
return 0;
}
BERRY_API bbool be_iter_hasnext(bvm *vm, int index)
{
bvalue *o = be_indexof(vm, index);
if (var_islist(o)) {
return list_hasnext(vm, o);
} else if (var_ismap(o)) {
return map_hasnext(vm, o);
}
return bfalse;
}
BERRY_API bbool be_refcontains(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
binstance **ref = be_stack_base(&vm->refstack);
binstance **top = be_stack_top(&vm->refstack);
binstance *ins = var_toobj(v);
be_assert(var_isinstance(v));
if (ref) {
while (ref <= top && *ref != ins) {
++ref;
}
return ref <= top;
}
return bfalse;
}
BERRY_API void be_refpush(bvm *vm, int index)
{
bvalue *v = be_indexof(vm, index);
binstance *ins = var_toobj(v);
be_assert(var_isinstance(v));
be_stack_push(vm, &vm->refstack, &ins);
}
BERRY_API void be_refpop(bvm *vm)
{
be_stack_pop(&vm->refstack);
if (be_stack_isempty(&vm->refstack)) {
be_vector_release(vm, &vm->refstack);
}
}
BERRY_API int be_returnvalue(bvm *vm)
{
bvalue *src = vm->top - 1;
bvalue *ret = retreg(vm);
var_setval(ret, src);
return 0;
}
BERRY_API int be_returnnilvalue(bvm *vm)
{
bvalue *ret = retreg(vm);
var_setnil(ret);
return 0;
}
BERRY_API void be_call(bvm *vm, int argc)
{
bvalue *fval = vm->top - argc - 1;
be_dofunc(vm, fval, argc);
}
BERRY_API int be_pcall(bvm *vm, int argc)
{
bvalue *f = vm->top - argc - 1;
return be_protectedcall(vm, f, argc);
}
BERRY_API void be_raise(bvm *vm, const char *except, const char *msg)
{
be_pushstring(vm, except);
if (msg) {
be_pushstring(vm, msg);
} else {
be_pushnil(vm);
}
be_pop(vm, 2);
be_save_stacktrace(vm);
be_throw(vm, BE_EXCEPTION);
}
BERRY_API void be_stop_iteration(bvm *vm)
{
be_raise(vm, "stop_iteration", NULL);
}
BERRY_API int be_getexcept(bvm *vm, int code)
{
if (code == BE_EXCEPTION) {
if (be_isstring(vm, -2)) {
const char *except = be_tostring(vm, -2);
if (!strcmp(except, "syntax_error")) {
return BE_SYNTAX_ERROR;
}
if (!strcmp(except, "io_error")) {
return BE_IO_ERROR;
}
}
return BE_EXEC_ERROR;
}
return code;
}
static int _dvfunc(bvm *vm, bbool esc)
{
const char* s = esc ?
be_toescape(vm, 1, 'x') : be_tostring(vm, 1);
be_writestring(s);
be_return_nil(vm);
}
static int _dumpesc(bvm *vm)
{
return _dvfunc(vm, btrue);
}
static int _dumpdir(bvm *vm)
{
return _dvfunc(vm, bfalse);
}
static int dump_value(bvm *vm, int index, bbool esc)
{
int res, top = be_top(vm) + 1;
index = be_absindex(vm, index);
be_pushntvfunction(vm, esc ? _dumpesc : _dumpdir);
be_pushvalue(vm, index);
res = be_pcall(vm, 1); /* using index to store result */
be_remove(vm, top); /* remove '_dumpvalue' function */
be_remove(vm, top); /* remove the value */
if (res == BE_EXCEPTION) {
be_dumpexcept(vm);
}
return res;
}
BERRY_API void be_dumpvalue(bvm *vm, int index)
{
if (dump_value(vm, index, btrue) == BE_OK) {
be_writenewline();
}
}
BERRY_API void be_dumpexcept(bvm *vm)
{
do {
/* print exception value */
if (dump_value(vm, -2, bfalse)) break;
be_writestring(": ");
/* print exception argument */
if (dump_value(vm, -1, bfalse)) break;
be_writenewline();
/* print stack traceback */
be_tracestack(vm);
} while (0);
be_pop(vm, 2); /* pop the exception value & argument */
}
BERRY_API bbool be_iseq(bvm *vm)
{
be_assert(vm->reg + 2 <= vm->top);
return be_vm_iseq(vm, vm->top - 2, vm->top - 1);
}
BERRY_API bbool be_isneq(bvm *vm)
{
be_assert(vm->reg + 2 <= vm->top);
return be_vm_isneq(vm, vm->top - 2, vm->top - 1);
}
BERRY_API bbool be_islt(bvm *vm)
{
be_assert(vm->reg + 2 <= vm->top);
return be_vm_islt(vm, vm->top - 2, vm->top - 1);
}
BERRY_API bbool be_isle(bvm *vm)
{
be_assert(vm->reg + 2 <= vm->top);
return be_vm_isle(vm, vm->top - 2, vm->top - 1);
}
BERRY_API bbool be_isgt(bvm *vm)
{
be_assert(vm->reg + 2 <= vm->top);
return be_vm_isgt(vm, vm->top - 2, vm->top - 1);
}
BERRY_API bbool be_isge(bvm *vm)
{
be_assert(vm->reg + 2 <= vm->top);
return be_vm_isge(vm, vm->top - 2, vm->top - 1);
}
BERRY_API int be_register(bvm *vm, int index)
{
bvalue *v;
if (!vm->registry) {
vm->registry = be_list_new(vm);
be_list_pool_init(vm, vm->registry);
}
be_assert(vm->registry != NULL);
v = be_indexof(vm, index);
return be_list_pool_alloc(vm, vm->registry, v);
}
BERRY_API void be_unregister(bvm *vm, int id)
{
be_assert(vm->registry != NULL);
be_list_pool_free(vm->registry, id);
}
BERRY_API void be_getregister(bvm *vm, int id)
{
blist *reg = vm->registry;
be_assert(reg && id > 0 && id < be_list_count(reg));
var_setval(vm->top, be_list_at(reg, id));
be_incrtop(vm);
}
| {
"pile_set_name": "Github"
} |
print("Hello World!")
counter = 0
bSmooth = false
----------------------------------------------------
function setup()
of.setWindowTitle("graphics example")
print("script setup")
of.setCircleResolution(50)
of.background(255, 255, 255, 255)
of.setWindowTitle("graphics example")
of.setFrameRate(60) -- if vertical sync is off, we can go a bit fast... this caps the framerate at 60fps
of.disableSmoothing()
end
----------------------------------------------------
function update()
counter = counter + 0.033
end
----------------------------------------------------
function draw()
-- CIRCLES
-- let's draw a circle
of.setColor(255, 130, 0)
local radius = 50 + 10 * math.sin(counter)
of.fill()
of.drawCircle(100, 400, radius)
-- now just an outline
of.noFill()
of.setHexColor(0xCCCCCC)
of.drawCircle(100, 400, 80)
-- label
of.setHexColor(0x000000)
of.drawBitmapString("circle", 75, 500)
-- RECTANGLES
of.fill()
for i=0,200 do
of.setColor(of.random(0, 255), of.random(0, 255), of.random(0, 255))
of.drawRectangle(of.random(250, 350), of.random(350, 450),
of.random(10, 20), of.random(10, 20))
end
of.setHexColor(0x000000)
of.drawBitmapString("rectangles", 275, 500)
-- TRANSPARENCY
of.setHexColor(0x00FF33)
of.drawRectangle(400, 350, 100, 100)
-- alpha is usually turned off - for speed puposes. let's turn it on!
of.enableAlphaBlending()
of.setColor(255, 0, 0, 127) -- red, 50% transparent
of.drawRectangle(450, 430, 100, 33)
of.setColor(255, 0, 0, math.fmod(counter*10, 255)) -- red, variable transparent
of.drawRectangle(450, 370, 100, 33)
of.disableAlphaBlending()
of.setHexColor(0x000000)
of.drawBitmapString("transparency", 410, 500)
-- LINES
-- a bunch of red lines, make them smooth if the flag is set
if bSmooth then
of.enableSmoothing()
end
of.setHexColor(0xFF0000)
for i=0,20 do
of.drawLine(600, 300 + (i*5), 800, 250 + (i*10))
end
if bSmooth then
of.disableSmoothing()
end
of.setHexColor(0x000000)
of.drawBitmapString("lines\npress 's' to toggle smoothness", 600, 500)
end
----------------------------------------------------
function exit()
print("script finished")
end
-- input callbacks
----------------------------------------------------
function keyPressed(key)
-- print out key as ascii val & char (keep within ascii 0-127 range)
print("script keyPressed: "..tostring(key)
.." \'"..string.char(math.max(math.min(key, 127), 0)).."\'")
if key == string.byte("s") then
bSmooth = not bSmooth
end
end
| {
"pile_set_name": "Github"
} |
import * as React from 'react';
import createSvgIcon from '../utils/createSvgIcon';
const ChevronLeftIcon = createSvgIcon({
svg: ({ classes }) => (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2048 2048" className={classes.svg}>
<path d="M1443 2045L421 1024 1443 3l90 90-930 931 930 931-90 90z" />
</svg>
),
displayName: 'ChevronLeftIcon',
});
export default ChevronLeftIcon;
| {
"pile_set_name": "Github"
} |
//
// ASTraitCollection.h
// Texture
//
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the /ASDK-Licenses directory of this source tree. An additional
// grant of patent rights can be found in the PATENTS file in the same directory.
//
// Modifications to this file made after 4/13/2017 are: Copyright (c) 2017-present,
// Pinterest, Inc. Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
#import <UIKit/UIKit.h>
#import <AsyncDisplayKit/ASBaseDefines.h>
@class ASTraitCollection;
@protocol ASLayoutElement;
@protocol ASTraitEnvironment;
NS_ASSUME_NONNULL_BEGIN
ASDISPLAYNODE_EXTERN_C_BEGIN
#pragma mark - ASPrimitiveTraitCollection
typedef struct ASPrimitiveTraitCollection {
CGFloat displayScale;
UIUserInterfaceSizeClass horizontalSizeClass;
UIUserInterfaceIdiom userInterfaceIdiom;
UIUserInterfaceSizeClass verticalSizeClass;
UIForceTouchCapability forceTouchCapability;
CGSize containerSize;
} ASPrimitiveTraitCollection;
/**
* Creates ASPrimitiveTraitCollection with default values.
*/
extern ASPrimitiveTraitCollection ASPrimitiveTraitCollectionMakeDefault();
/**
* Creates a ASPrimitiveTraitCollection from a given UITraitCollection.
*/
extern ASPrimitiveTraitCollection ASPrimitiveTraitCollectionFromUITraitCollection(UITraitCollection *traitCollection);
/**
* Compares two ASPrimitiveTraitCollection to determine if they are the same.
*/
extern BOOL ASPrimitiveTraitCollectionIsEqualToASPrimitiveTraitCollection(ASPrimitiveTraitCollection lhs, ASPrimitiveTraitCollection rhs);
/**
* Returns a string representation of a ASPrimitiveTraitCollection.
*/
extern NSString *NSStringFromASPrimitiveTraitCollection(ASPrimitiveTraitCollection traits);
/**
* This function will walk the layout element hierarchy and updates the layout element trait collection for every
* layout element within the hierarchy.
*/
extern void ASTraitCollectionPropagateDown(id<ASLayoutElement> element, ASPrimitiveTraitCollection traitCollection);
ASDISPLAYNODE_EXTERN_C_END
/**
* Abstraction on top of UITraitCollection for propagation within AsyncDisplayKit-Layout
*/
@protocol ASTraitEnvironment <NSObject>
/**
* Returns a struct-representation of the environment's ASEnvironmentDisplayTraits. This only exists as a internal
* convenience method. Users should access the trait collections through the NSObject based asyncTraitCollection API
*/
- (ASPrimitiveTraitCollection)primitiveTraitCollection;
/**
* Sets a trait collection on this environment state.
*/
- (void)setPrimitiveTraitCollection:(ASPrimitiveTraitCollection)traitCollection;
/**
*/
- (ASTraitCollection *)asyncTraitCollection;
@end
#define ASPrimitiveTraitCollectionDefaults \
- (ASPrimitiveTraitCollection)primitiveTraitCollection\
{\
return _primitiveTraitCollection.load();\
}\
- (void)setPrimitiveTraitCollection:(ASPrimitiveTraitCollection)traitCollection\
{\
_primitiveTraitCollection = traitCollection;\
}\
#define ASLayoutElementCollectionTableSetTraitCollection(lock) \
- (void)setPrimitiveTraitCollection:(ASPrimitiveTraitCollection)traitCollection\
{\
ASDN::MutexLocker l(lock);\
\
ASPrimitiveTraitCollection oldTraits = self.primitiveTraitCollection;\
[super setPrimitiveTraitCollection:traitCollection];\
\
/* Extra Trait Collection Handling */\
\
/* If the node is not loaded yet don't do anything as otherwise the access of the view will trigger a load */\
if (! self.isNodeLoaded) { return; }\
\
ASPrimitiveTraitCollection currentTraits = self.primitiveTraitCollection;\
if (ASPrimitiveTraitCollectionIsEqualToASPrimitiveTraitCollection(currentTraits, oldTraits) == NO) {\
[self.dataController environmentDidChange];\
}\
}\
#pragma mark - ASTraitCollection
AS_SUBCLASSING_RESTRICTED
@interface ASTraitCollection : NSObject
@property (nonatomic, assign, readonly) CGFloat displayScale;
@property (nonatomic, assign, readonly) UIUserInterfaceSizeClass horizontalSizeClass;
@property (nonatomic, assign, readonly) UIUserInterfaceIdiom userInterfaceIdiom;
@property (nonatomic, assign, readonly) UIUserInterfaceSizeClass verticalSizeClass;
@property (nonatomic, assign, readonly) UIForceTouchCapability forceTouchCapability;
@property (nonatomic, assign, readonly) CGSize containerSize;
+ (ASTraitCollection *)traitCollectionWithASPrimitiveTraitCollection:(ASPrimitiveTraitCollection)traits;
+ (ASTraitCollection *)traitCollectionWithUITraitCollection:(UITraitCollection *)traitCollection
containerSize:(CGSize)windowSize;
+ (ASTraitCollection *)traitCollectionWithDisplayScale:(CGFloat)displayScale
userInterfaceIdiom:(UIUserInterfaceIdiom)userInterfaceIdiom
horizontalSizeClass:(UIUserInterfaceSizeClass)horizontalSizeClass
verticalSizeClass:(UIUserInterfaceSizeClass)verticalSizeClass
forceTouchCapability:(UIForceTouchCapability)forceTouchCapability
containerSize:(CGSize)windowSize;
- (ASPrimitiveTraitCollection)primitiveTraitCollection;
- (BOOL)isEqualToTraitCollection:(ASTraitCollection *)traitCollection;
@end
NS_ASSUME_NONNULL_END
| {
"pile_set_name": "Github"
} |
/*
Copyright (C) 2014-2019 de4dot@gmail.com
This file is part of dnSpy
dnSpy 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.
dnSpy 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 dnSpy. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using dnlib.DotNet.Resources;
using dnSpy.Contracts.DnSpy.Properties;
namespace dnSpy.Contracts.Documents.TreeView.Resources {
/// <summary>
/// Serialization utilities
/// </summary>
public static class SerializationUtilities {
/// <summary>
/// Creates a serialized image
/// </summary>
/// <param name="filename">Filename of image</param>
/// <returns></returns>
public static ResourceElement CreateSerializedImage(string filename) {
using (var stream = File.OpenRead(filename))
return CreateSerializedImage(stream, filename);
}
static ResourceElement CreateSerializedImage(Stream stream, string filename) {
object obj;
string typeName;
if (filename.EndsWith(".ico", StringComparison.OrdinalIgnoreCase)) {
obj = new System.Drawing.Icon(stream);
typeName = SerializedImageUtilities.SystemDrawingIcon.AssemblyQualifiedName;
}
else {
obj = new System.Drawing.Bitmap(stream);
typeName = SerializedImageUtilities.SystemDrawingBitmap.AssemblyQualifiedName;
}
var serializedData = Serialize(obj);
var userType = new UserResourceType(typeName, ResourceTypeCode.UserTypes);
var rsrcElem = new ResourceElement {
Name = Path.GetFileName(filename),
ResourceData = new BinaryResourceData(userType, serializedData),
};
return rsrcElem;
}
/// <summary>
/// Serializes the object
/// </summary>
/// <param name="obj">Data</param>
/// <returns></returns>
public static byte[] Serialize(object obj) {
//TODO: The asm names of the saved types are saved in the serialized data. If the current
// module is eg. a .NET 2.0 asm, you should replace the versions from 4.0.0.0 to 2.0.0.0.
var formatter = new BinaryFormatter();
var outStream = new MemoryStream();
formatter.Serialize(outStream, obj);
return outStream.ToArray();
}
/// <summary>
/// Deserializes the data
/// </summary>
/// <param name="data">Serialized data</param>
/// <param name="obj">Deserialized data</param>
/// <returns></returns>
public static string Deserialize(byte[] data, out object? obj) {
try {
obj = new BinaryFormatter().Deserialize(new MemoryStream(data));
return string.Empty;
}
catch (Exception ex) {
obj = null;
return string.Format(dnSpy_Contracts_DnSpy_Resources.CouldNotDeserializeData, ex.Message);
}
}
/// <summary>
/// Creates an object from a string
/// </summary>
/// <param name="targetType">Target type</param>
/// <param name="typeAsString">Data as a string</param>
/// <param name="obj">Updated with the deserialized data</param>
/// <returns></returns>
public static string CreateObjectFromString(Type targetType, string typeAsString, out object? obj) {
obj = null;
try {
var typeConverter = TypeDescriptor.GetConverter(targetType);
if (typeConverter.CanConvertFrom(null, typeof(string))) {
obj = typeConverter.ConvertFrom(null, CultureInfo.InvariantCulture, typeAsString);
return string.Empty;
}
}
catch (Exception ex) {
return string.Format(dnSpy_Contracts_DnSpy_Resources.CouldNotConvertFromString, ex.Message);
}
return string.Format(dnSpy_Contracts_DnSpy_Resources.NoTypeConverter, targetType);
}
/// <summary>
/// Converts data to a string
/// </summary>
/// <param name="obj">Data</param>
/// <returns></returns>
public static string? ConvertObjectToString(object obj) {
var objType = obj.GetType();
try {
var typeConverter = TypeDescriptor.GetConverter(objType);
if (typeConverter.CanConvertTo(null, typeof(string))) {
if (typeConverter.ConvertTo(null, CultureInfo.InvariantCulture, obj, typeof(string)) is string s)
return s;
}
}
catch {
}
return obj.ToString();
}
}
}
| {
"pile_set_name": "Github"
} |
#pragma once
#include <Register/Utility.hpp>
namespace Kvasir {
//Multipurpose Clock Generator module
namespace McgC1{ ///<MCG Control 1 Register
using Addr = Register::Address<0x40064000,0xffffff00,0x00000000,unsigned char>;
///Internal Reference Stop Enable
enum class IrefstenVal {
v0=0x00000000, ///<Internal reference clock is disabled in Stop mode.
v1=0x00000001, ///<Internal reference clock is enabled in Stop mode if IRCLKEN is set or if MCG is in FEI, FBI, or BLPI modes before entering Stop mode.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,IrefstenVal> irefsten{};
namespace IrefstenValC{
constexpr Register::FieldValue<decltype(irefsten)::Type,IrefstenVal::v0> v0{};
constexpr Register::FieldValue<decltype(irefsten)::Type,IrefstenVal::v1> v1{};
}
///Internal Reference Clock Enable
enum class IrclkenVal {
v0=0x00000000, ///<MCGIRCLK inactive.
v1=0x00000001, ///<MCGIRCLK active.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,IrclkenVal> irclken{};
namespace IrclkenValC{
constexpr Register::FieldValue<decltype(irclken)::Type,IrclkenVal::v0> v0{};
constexpr Register::FieldValue<decltype(irclken)::Type,IrclkenVal::v1> v1{};
}
///Internal Reference Select
enum class IrefsVal {
v0=0x00000000, ///<External reference clock is selected.
v1=0x00000001, ///<The slow internal reference clock is selected.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,IrefsVal> irefs{};
namespace IrefsValC{
constexpr Register::FieldValue<decltype(irefs)::Type,IrefsVal::v0> v0{};
constexpr Register::FieldValue<decltype(irefs)::Type,IrefsVal::v1> v1{};
}
///FLL External Reference Divider
enum class FrdivVal {
v000=0x00000000, ///<If RANGE 0 = 0 or OSCSEL=1 , Divide Factor is 1; for all other RANGE 0 values, Divide Factor is 32.
v001=0x00000001, ///<If RANGE 0 = 0 or OSCSEL=1 , Divide Factor is 2; for all other RANGE 0 values, Divide Factor is 64.
v010=0x00000002, ///<If RANGE 0 = 0 or OSCSEL=1 , Divide Factor is 4; for all other RANGE 0 values, Divide Factor is 128.
v011=0x00000003, ///<If RANGE 0 = 0 or OSCSEL=1 , Divide Factor is 8; for all other RANGE 0 values, Divide Factor is 256.
v100=0x00000004, ///<If RANGE 0 = 0 or OSCSEL=1 , Divide Factor is 16; for all other RANGE 0 values, Divide Factor is 512.
v101=0x00000005, ///<If RANGE 0 = 0 or OSCSEL=1 , Divide Factor is 32; for all other RANGE 0 values, Divide Factor is 1024.
v110=0x00000006, ///<If RANGE 0 = 0 or OSCSEL=1 , Divide Factor is 64; for all other RANGE 0 values, Divide Factor is 1280 .
v111=0x00000007, ///<If RANGE 0 = 0 or OSCSEL=1 , Divide Factor is 128; for all other RANGE 0 values, Divide Factor is 1536 .
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,3),Register::ReadWriteAccess,FrdivVal> frdiv{};
namespace FrdivValC{
constexpr Register::FieldValue<decltype(frdiv)::Type,FrdivVal::v000> v000{};
constexpr Register::FieldValue<decltype(frdiv)::Type,FrdivVal::v001> v001{};
constexpr Register::FieldValue<decltype(frdiv)::Type,FrdivVal::v010> v010{};
constexpr Register::FieldValue<decltype(frdiv)::Type,FrdivVal::v011> v011{};
constexpr Register::FieldValue<decltype(frdiv)::Type,FrdivVal::v100> v100{};
constexpr Register::FieldValue<decltype(frdiv)::Type,FrdivVal::v101> v101{};
constexpr Register::FieldValue<decltype(frdiv)::Type,FrdivVal::v110> v110{};
constexpr Register::FieldValue<decltype(frdiv)::Type,FrdivVal::v111> v111{};
}
///Clock Source Select
enum class ClksVal {
v00=0x00000000, ///<Encoding 0 - Output of FLL or PLL is selected (depends on PLLS control bit).
v01=0x00000001, ///<Encoding 1 - Internal reference clock is selected.
v10=0x00000002, ///<Encoding 2 - External reference clock is selected.
v11=0x00000003, ///<Encoding 3 - Reserved, defaults to 00.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,ClksVal> clks{};
namespace ClksValC{
constexpr Register::FieldValue<decltype(clks)::Type,ClksVal::v00> v00{};
constexpr Register::FieldValue<decltype(clks)::Type,ClksVal::v01> v01{};
constexpr Register::FieldValue<decltype(clks)::Type,ClksVal::v10> v10{};
constexpr Register::FieldValue<decltype(clks)::Type,ClksVal::v11> v11{};
}
}
namespace McgC2{ ///<MCG Control 2 Register
using Addr = Register::Address<0x40064001,0xffffff40,0x00000000,unsigned char>;
///Internal Reference Clock Select
enum class IrcsVal {
v0=0x00000000, ///<Slow internal reference clock selected.
v1=0x00000001, ///<Fast internal reference clock selected.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,IrcsVal> ircs{};
namespace IrcsValC{
constexpr Register::FieldValue<decltype(ircs)::Type,IrcsVal::v0> v0{};
constexpr Register::FieldValue<decltype(ircs)::Type,IrcsVal::v1> v1{};
}
///Low Power Select
enum class LpVal {
v0=0x00000000, ///<FLL (or PLL) is not disabled in bypass modes.
v1=0x00000001, ///<FLL (or PLL) is disabled in bypass modes (lower power)
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,LpVal> lp{};
namespace LpValC{
constexpr Register::FieldValue<decltype(lp)::Type,LpVal::v0> v0{};
constexpr Register::FieldValue<decltype(lp)::Type,LpVal::v1> v1{};
}
///External Reference Select
enum class Erefs0Val {
v0=0x00000000, ///<External reference clock requested.
v1=0x00000001, ///<Oscillator requested.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,Erefs0Val> erefs0{};
namespace Erefs0ValC{
constexpr Register::FieldValue<decltype(erefs0)::Type,Erefs0Val::v0> v0{};
constexpr Register::FieldValue<decltype(erefs0)::Type,Erefs0Val::v1> v1{};
}
///High Gain Oscillator Select
enum class Hgo0Val {
v0=0x00000000, ///<Configure crystal oscillator for low-power operation.
v1=0x00000001, ///<Configure crystal oscillator for high-gain operation.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,Hgo0Val> hgo0{};
namespace Hgo0ValC{
constexpr Register::FieldValue<decltype(hgo0)::Type,Hgo0Val::v0> v0{};
constexpr Register::FieldValue<decltype(hgo0)::Type,Hgo0Val::v1> v1{};
}
///Frequency Range Select
enum class Range0Val {
v00=0x00000000, ///<Encoding 0 - Low frequency range selected for the crystal oscillator .
v01=0x00000001, ///<Encoding 1 - High frequency range selected for the crystal oscillator .
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,Range0Val> range0{};
namespace Range0ValC{
constexpr Register::FieldValue<decltype(range0)::Type,Range0Val::v00> v00{};
constexpr Register::FieldValue<decltype(range0)::Type,Range0Val::v01> v01{};
}
///Loss of Clock Reset Enable
enum class Locre0Val {
v0=0x00000000, ///<Interrupt request is generated on a loss of OSC0 external reference clock.
v1=0x00000001, ///<Generate a reset request on a loss of OSC0 external reference clock
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,Locre0Val> locre0{};
namespace Locre0ValC{
constexpr Register::FieldValue<decltype(locre0)::Type,Locre0Val::v0> v0{};
constexpr Register::FieldValue<decltype(locre0)::Type,Locre0Val::v1> v1{};
}
}
namespace McgC3{ ///<MCG Control 3 Register
using Addr = Register::Address<0x40064002,0xffffff00,0x00000000,unsigned char>;
///Slow Internal Reference Clock Trim Setting
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> sctrim{};
}
namespace McgC4{ ///<MCG Control 4 Register
using Addr = Register::Address<0x40064003,0xffffff00,0x00000000,unsigned char>;
///Slow Internal Reference Clock Fine Trim
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> scftrim{};
///Fast Internal Reference Clock Trim Setting
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,1),Register::ReadWriteAccess,unsigned> fctrim{};
///DCO Range Select
enum class DrstdrsVal {
v00=0x00000000, ///<Encoding 0 - Low range (reset default).
v01=0x00000001, ///<Encoding 1 - Mid range.
v10=0x00000002, ///<Encoding 2 - Mid-high range.
v11=0x00000003, ///<Encoding 3 - High range.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,5),Register::ReadWriteAccess,DrstdrsVal> drstDrs{};
namespace DrstdrsValC{
constexpr Register::FieldValue<decltype(drstDrs)::Type,DrstdrsVal::v00> v00{};
constexpr Register::FieldValue<decltype(drstDrs)::Type,DrstdrsVal::v01> v01{};
constexpr Register::FieldValue<decltype(drstDrs)::Type,DrstdrsVal::v10> v10{};
constexpr Register::FieldValue<decltype(drstDrs)::Type,DrstdrsVal::v11> v11{};
}
///DCO Maximum Frequency with 32.768 kHz Reference
enum class Dmx32Val {
v0=0x00000000, ///<DCO has a default range of 25%.
v1=0x00000001, ///<DCO is fine-tuned for maximum frequency with 32.768 kHz reference.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,Dmx32Val> dmx32{};
namespace Dmx32ValC{
constexpr Register::FieldValue<decltype(dmx32)::Type,Dmx32Val::v0> v0{};
constexpr Register::FieldValue<decltype(dmx32)::Type,Dmx32Val::v1> v1{};
}
}
namespace McgC5{ ///<MCG Control 5 Register
using Addr = Register::Address<0x40064004,0xffffff80,0x00000000,unsigned char>;
///PLL External Reference Divider
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::ReadWriteAccess,unsigned> prdiv0{};
///PLL Stop Enable
enum class Pllsten0Val {
v0=0x00000000, ///<MCGPLLCLK is disabled in any of the Stop modes.
v1=0x00000001, ///<MCGPLLCLK is enabled if system is in Normal Stop mode.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,Pllsten0Val> pllsten0{};
namespace Pllsten0ValC{
constexpr Register::FieldValue<decltype(pllsten0)::Type,Pllsten0Val::v0> v0{};
constexpr Register::FieldValue<decltype(pllsten0)::Type,Pllsten0Val::v1> v1{};
}
///PLL Clock Enable
enum class Pllclken0Val {
v0=0x00000000, ///<MCGPLLCLK is inactive.
v1=0x00000001, ///<MCGPLLCLK is active.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,Pllclken0Val> pllclken0{};
namespace Pllclken0ValC{
constexpr Register::FieldValue<decltype(pllclken0)::Type,Pllclken0Val::v0> v0{};
constexpr Register::FieldValue<decltype(pllclken0)::Type,Pllclken0Val::v1> v1{};
}
}
namespace McgC6{ ///<MCG Control 6 Register
using Addr = Register::Address<0x40064005,0xffffff00,0x00000000,unsigned char>;
///VCO 0 Divider
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::ReadWriteAccess,unsigned> vdiv0{};
///Clock Monitor Enable
enum class Cme0Val {
v0=0x00000000, ///<External clock monitor is disabled for OSC0.
v1=0x00000001, ///<External clock monitor is enabled for OSC0.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,Cme0Val> cme0{};
namespace Cme0ValC{
constexpr Register::FieldValue<decltype(cme0)::Type,Cme0Val::v0> v0{};
constexpr Register::FieldValue<decltype(cme0)::Type,Cme0Val::v1> v1{};
}
///PLL Select
enum class PllsVal {
v0=0x00000000, ///<FLL is selected.
v1=0x00000001, ///<PLL is selected (PRDIV 0 need to be programmed to the correct divider to generate a PLL reference clock in the range of 2 - 4 MHz prior to setting the PLLS bit).
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,PllsVal> plls{};
namespace PllsValC{
constexpr Register::FieldValue<decltype(plls)::Type,PllsVal::v0> v0{};
constexpr Register::FieldValue<decltype(plls)::Type,PllsVal::v1> v1{};
}
///Loss of Lock Interrrupt Enable
enum class Lolie0Val {
v0=0x00000000, ///<No interrupt request is generated on loss of lock.
v1=0x00000001, ///<Generate an interrupt request on loss of lock.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,Lolie0Val> lolie0{};
namespace Lolie0ValC{
constexpr Register::FieldValue<decltype(lolie0)::Type,Lolie0Val::v0> v0{};
constexpr Register::FieldValue<decltype(lolie0)::Type,Lolie0Val::v1> v1{};
}
}
namespace McgS{ ///<MCG Status Register
using Addr = Register::Address<0x40064006,0xffffff00,0x00000000,unsigned char>;
///Internal Reference Clock Status
enum class IrcstVal {
v0=0x00000000, ///<Source of internal reference clock is the slow clock (32 kHz IRC).
v1=0x00000001, ///<Source of internal reference clock is the fast clock (2 MHz IRC).
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,IrcstVal> ircst{};
namespace IrcstValC{
constexpr Register::FieldValue<decltype(ircst)::Type,IrcstVal::v0> v0{};
constexpr Register::FieldValue<decltype(ircst)::Type,IrcstVal::v1> v1{};
}
///OSC Initialization
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> oscinit0{};
///Clock Mode Status
enum class ClkstVal {
v00=0x00000000, ///<Encoding 0 - Output of the FLL is selected (reset default).
v01=0x00000001, ///<Encoding 1 - Internal reference clock is selected.
v10=0x00000002, ///<Encoding 2 - External reference clock is selected.
v11=0x00000003, ///<Encoding 3 - Output of the PLL is selected.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,ClkstVal> clkst{};
namespace ClkstValC{
constexpr Register::FieldValue<decltype(clkst)::Type,ClkstVal::v00> v00{};
constexpr Register::FieldValue<decltype(clkst)::Type,ClkstVal::v01> v01{};
constexpr Register::FieldValue<decltype(clkst)::Type,ClkstVal::v10> v10{};
constexpr Register::FieldValue<decltype(clkst)::Type,ClkstVal::v11> v11{};
}
///Internal Reference Status
enum class IrefstVal {
v0=0x00000000, ///<Source of FLL reference clock is the external reference clock.
v1=0x00000001, ///<Source of FLL reference clock is the internal reference clock.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,IrefstVal> irefst{};
namespace IrefstValC{
constexpr Register::FieldValue<decltype(irefst)::Type,IrefstVal::v0> v0{};
constexpr Register::FieldValue<decltype(irefst)::Type,IrefstVal::v1> v1{};
}
///PLL Select Status
enum class PllstVal {
v0=0x00000000, ///<Source of PLLS clock is FLL clock.
v1=0x00000001, ///<Source of PLLS clock is PLL clock.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,PllstVal> pllst{};
namespace PllstValC{
constexpr Register::FieldValue<decltype(pllst)::Type,PllstVal::v0> v0{};
constexpr Register::FieldValue<decltype(pllst)::Type,PllstVal::v1> v1{};
}
///Lock Status
enum class Lock0Val {
v0=0x00000000, ///<PLL is currently unlocked.
v1=0x00000001, ///<PLL is currently locked.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,Lock0Val> lock0{};
namespace Lock0ValC{
constexpr Register::FieldValue<decltype(lock0)::Type,Lock0Val::v0> v0{};
constexpr Register::FieldValue<decltype(lock0)::Type,Lock0Val::v1> v1{};
}
///Loss of Lock Status
enum class Lols0Val {
v0=0x00000000, ///<PLL has not lost lock since LOLS 0 was last cleared.
v1=0x00000001, ///<PLL has lost lock since LOLS 0 was last cleared.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,Lols0Val> lols0{};
namespace Lols0ValC{
constexpr Register::FieldValue<decltype(lols0)::Type,Lols0Val::v0> v0{};
constexpr Register::FieldValue<decltype(lols0)::Type,Lols0Val::v1> v1{};
}
}
namespace McgSc{ ///<MCG Status and Control Register
using Addr = Register::Address<0x40064008,0xffffff00,0x00000000,unsigned char>;
///OSC0 Loss of Clock Status
enum class Locs0Val {
v0=0x00000000, ///<Loss of OSC0 has not occurred.
v1=0x00000001, ///<Loss of OSC0 has occurred.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,Locs0Val> locs0{};
namespace Locs0ValC{
constexpr Register::FieldValue<decltype(locs0)::Type,Locs0Val::v0> v0{};
constexpr Register::FieldValue<decltype(locs0)::Type,Locs0Val::v1> v1{};
}
///Fast Clock Internal Reference Divider
enum class FcrdivVal {
v000=0x00000000, ///<Divide Factor is 1
v001=0x00000001, ///<Divide Factor is 2.
v010=0x00000002, ///<Divide Factor is 4.
v011=0x00000003, ///<Divide Factor is 8.
v100=0x00000004, ///<Divide Factor is 16
v101=0x00000005, ///<Divide Factor is 32
v110=0x00000006, ///<Divide Factor is 64
v111=0x00000007, ///<Divide Factor is 128.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,1),Register::ReadWriteAccess,FcrdivVal> fcrdiv{};
namespace FcrdivValC{
constexpr Register::FieldValue<decltype(fcrdiv)::Type,FcrdivVal::v000> v000{};
constexpr Register::FieldValue<decltype(fcrdiv)::Type,FcrdivVal::v001> v001{};
constexpr Register::FieldValue<decltype(fcrdiv)::Type,FcrdivVal::v010> v010{};
constexpr Register::FieldValue<decltype(fcrdiv)::Type,FcrdivVal::v011> v011{};
constexpr Register::FieldValue<decltype(fcrdiv)::Type,FcrdivVal::v100> v100{};
constexpr Register::FieldValue<decltype(fcrdiv)::Type,FcrdivVal::v101> v101{};
constexpr Register::FieldValue<decltype(fcrdiv)::Type,FcrdivVal::v110> v110{};
constexpr Register::FieldValue<decltype(fcrdiv)::Type,FcrdivVal::v111> v111{};
}
///FLL Filter Preserve Enable
enum class FltprsrvVal {
v0=0x00000000, ///<FLL filter and FLL frequency will reset on changes to currect clock mode.
v1=0x00000001, ///<Fll filter and FLL frequency retain their previous values during new clock mode change.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,FltprsrvVal> fltprsrv{};
namespace FltprsrvValC{
constexpr Register::FieldValue<decltype(fltprsrv)::Type,FltprsrvVal::v0> v0{};
constexpr Register::FieldValue<decltype(fltprsrv)::Type,FltprsrvVal::v1> v1{};
}
///Automatic Trim machine Fail Flag
enum class AtmfVal {
v0=0x00000000, ///<Automatic Trim Machine completed normally.
v1=0x00000001, ///<Automatic Trim Machine failed.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,AtmfVal> atmf{};
namespace AtmfValC{
constexpr Register::FieldValue<decltype(atmf)::Type,AtmfVal::v0> v0{};
constexpr Register::FieldValue<decltype(atmf)::Type,AtmfVal::v1> v1{};
}
///Automatic Trim Machine Select
enum class AtmsVal {
v0=0x00000000, ///<32 kHz Internal Reference Clock selected.
v1=0x00000001, ///<4 MHz Internal Reference Clock selected.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,AtmsVal> atms{};
namespace AtmsValC{
constexpr Register::FieldValue<decltype(atms)::Type,AtmsVal::v0> v0{};
constexpr Register::FieldValue<decltype(atms)::Type,AtmsVal::v1> v1{};
}
///Automatic Trim Machine Enable
enum class AtmeVal {
v0=0x00000000, ///<Auto Trim Machine disabled.
v1=0x00000001, ///<Auto Trim Machine enabled.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,AtmeVal> atme{};
namespace AtmeValC{
constexpr Register::FieldValue<decltype(atme)::Type,AtmeVal::v0> v0{};
constexpr Register::FieldValue<decltype(atme)::Type,AtmeVal::v1> v1{};
}
}
namespace McgAtcvh{ ///<MCG Auto Trim Compare Value High Register
using Addr = Register::Address<0x4006400a,0xffffff00,0x00000000,unsigned char>;
///ATM Compare Value High
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> atcvh{};
}
namespace McgAtcvl{ ///<MCG Auto Trim Compare Value Low Register
using Addr = Register::Address<0x4006400b,0xffffff00,0x00000000,unsigned char>;
///ATM Compare Value Low
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> atcvl{};
}
namespace McgC7{ ///<MCG Control 7 Register
using Addr = Register::Address<0x4006400c,0xfffffffe,0x00000000,unsigned char>;
///MCG OSC Clock Select
enum class OscselVal {
v0=0x00000000, ///<Selects System Oscillator (OSCCLK).
v1=0x00000001, ///<Selects 32 kHz RTC Oscillator.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,OscselVal> oscsel{};
namespace OscselValC{
constexpr Register::FieldValue<decltype(oscsel)::Type,OscselVal::v0> v0{};
constexpr Register::FieldValue<decltype(oscsel)::Type,OscselVal::v1> v1{};
}
}
namespace McgC8{ ///<MCG Control 8 Register
using Addr = Register::Address<0x4006400d,0xffffff1e,0x00000000,unsigned char>;
///RTC Loss of Clock Status
enum class Locs1Val {
v0=0x00000000, ///<Loss of RTC has not occur.
v1=0x00000001, ///<Loss of RTC has occur
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,Locs1Val> locs1{};
namespace Locs1ValC{
constexpr Register::FieldValue<decltype(locs1)::Type,Locs1Val::v0> v0{};
constexpr Register::FieldValue<decltype(locs1)::Type,Locs1Val::v1> v1{};
}
///Clock Monitor Enable1
enum class Cme1Val {
v0=0x00000000, ///<External clock monitor is disabled for RTC clock.
v1=0x00000001, ///<External clock monitor is enabled for RTC clock.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,Cme1Val> cme1{};
namespace Cme1ValC{
constexpr Register::FieldValue<decltype(cme1)::Type,Cme1Val::v0> v0{};
constexpr Register::FieldValue<decltype(cme1)::Type,Cme1Val::v1> v1{};
}
///no description available
enum class LolreVal {
v0=0x00000000, ///<Interrupt request is generated on a PLL loss of lock indication. The PLL loss of lock interrupt enable bit must also be set to generate the interrupt request.
v1=0x00000001, ///<Generate a reset request on a PLL loss of lock indication.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,LolreVal> lolre{};
namespace LolreValC{
constexpr Register::FieldValue<decltype(lolre)::Type,LolreVal::v0> v0{};
constexpr Register::FieldValue<decltype(lolre)::Type,LolreVal::v1> v1{};
}
///Loss of Clock Reset Enable
enum class Locre1Val {
v0=0x00000000, ///<Interrupt request is generated on a loss of RTC external reference clock.
v1=0x00000001, ///<Generate a reset request on a loss of RTC external reference clock
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,Locre1Val> locre1{};
namespace Locre1ValC{
constexpr Register::FieldValue<decltype(locre1)::Type,Locre1Val::v0> v0{};
constexpr Register::FieldValue<decltype(locre1)::Type,Locre1Val::v1> v1{};
}
}
}
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EasyImgur.StatisticsMetrics
{
abstract class StatisticsMetric
{
public object Value
{
get { return Gather(); }
}
// Should be implemented by deriving classes in order to obtain a value that
// is desired to be measured/gathered.
protected abstract object Gather();
}
}
| {
"pile_set_name": "Github"
} |
declare module "safe-buffer" {
export class Buffer {
length: number
write(string: string, offset?: number, length?: number, encoding?: string): number;
toString(encoding?: string, start?: number, end?: number): string;
toJSON(): { type: 'Buffer', data: any[] };
equals(otherBuffer: Buffer): boolean;
compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number;
copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
slice(start?: number, end?: number): Buffer;
writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
readIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
readIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
readUInt8(offset: number, noAssert?: boolean): number;
readUInt16LE(offset: number, noAssert?: boolean): number;
readUInt16BE(offset: number, noAssert?: boolean): number;
readUInt32LE(offset: number, noAssert?: boolean): number;
readUInt32BE(offset: number, noAssert?: boolean): number;
readInt8(offset: number, noAssert?: boolean): number;
readInt16LE(offset: number, noAssert?: boolean): number;
readInt16BE(offset: number, noAssert?: boolean): number;
readInt32LE(offset: number, noAssert?: boolean): number;
readInt32BE(offset: number, noAssert?: boolean): number;
readFloatLE(offset: number, noAssert?: boolean): number;
readFloatBE(offset: number, noAssert?: boolean): number;
readDoubleLE(offset: number, noAssert?: boolean): number;
readDoubleBE(offset: number, noAssert?: boolean): number;
swap16(): Buffer;
swap32(): Buffer;
swap64(): Buffer;
writeUInt8(value: number, offset: number, noAssert?: boolean): number;
writeUInt16LE(value: number, offset: number, noAssert?: boolean): number;
writeUInt16BE(value: number, offset: number, noAssert?: boolean): number;
writeUInt32LE(value: number, offset: number, noAssert?: boolean): number;
writeUInt32BE(value: number, offset: number, noAssert?: boolean): number;
writeInt8(value: number, offset: number, noAssert?: boolean): number;
writeInt16LE(value: number, offset: number, noAssert?: boolean): number;
writeInt16BE(value: number, offset: number, noAssert?: boolean): number;
writeInt32LE(value: number, offset: number, noAssert?: boolean): number;
writeInt32BE(value: number, offset: number, noAssert?: boolean): number;
writeFloatLE(value: number, offset: number, noAssert?: boolean): number;
writeFloatBE(value: number, offset: number, noAssert?: boolean): number;
writeDoubleLE(value: number, offset: number, noAssert?: boolean): number;
writeDoubleBE(value: number, offset: number, noAssert?: boolean): number;
fill(value: any, offset?: number, end?: number): this;
indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean;
/**
* Allocates a new buffer containing the given {str}.
*
* @param str String to store in buffer.
* @param encoding encoding to use, optional. Default is 'utf8'
*/
constructor (str: string, encoding?: string);
/**
* Allocates a new buffer of {size} octets.
*
* @param size count of octets to allocate.
*/
constructor (size: number);
/**
* Allocates a new buffer containing the given {array} of octets.
*
* @param array The octets to store.
*/
constructor (array: Uint8Array);
/**
* Produces a Buffer backed by the same allocated memory as
* the given {ArrayBuffer}.
*
*
* @param arrayBuffer The ArrayBuffer with which to share memory.
*/
constructor (arrayBuffer: ArrayBuffer);
/**
* Allocates a new buffer containing the given {array} of octets.
*
* @param array The octets to store.
*/
constructor (array: any[]);
/**
* Copies the passed {buffer} data onto a new {Buffer} instance.
*
* @param buffer The buffer to copy.
*/
constructor (buffer: Buffer);
prototype: Buffer;
/**
* Allocates a new Buffer using an {array} of octets.
*
* @param array
*/
static from(array: any[]): Buffer;
/**
* When passed a reference to the .buffer property of a TypedArray instance,
* the newly created Buffer will share the same allocated memory as the TypedArray.
* The optional {byteOffset} and {length} arguments specify a memory range
* within the {arrayBuffer} that will be shared by the Buffer.
*
* @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer()
* @param byteOffset
* @param length
*/
static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer;
/**
* Copies the passed {buffer} data onto a new Buffer instance.
*
* @param buffer
*/
static from(buffer: Buffer): Buffer;
/**
* Creates a new Buffer containing the given JavaScript string {str}.
* If provided, the {encoding} parameter identifies the character encoding.
* If not provided, {encoding} defaults to 'utf8'.
*
* @param str
*/
static from(str: string, encoding?: string): Buffer;
/**
* Returns true if {obj} is a Buffer
*
* @param obj object to test.
*/
static isBuffer(obj: any): obj is Buffer;
/**
* Returns true if {encoding} is a valid encoding argument.
* Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex'
*
* @param encoding string to test.
*/
static isEncoding(encoding: string): boolean;
/**
* Gives the actual byte length of a string. encoding defaults to 'utf8'.
* This is not the same as String.prototype.length since that returns the number of characters in a string.
*
* @param string string to test.
* @param encoding encoding used to evaluate (defaults to 'utf8')
*/
static byteLength(string: string, encoding?: string): number;
/**
* Returns a buffer which is the result of concatenating all the buffers in the list together.
*
* If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer.
* If the list has exactly one item, then the first item of the list is returned.
* If the list has more than one item, then a new Buffer is created.
*
* @param list An array of Buffer objects to concatenate
* @param totalLength Total length of the buffers when concatenated.
* If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly.
*/
static concat(list: Buffer[], totalLength?: number): Buffer;
/**
* The same as buf1.compare(buf2).
*/
static compare(buf1: Buffer, buf2: Buffer): number;
/**
* Allocates a new buffer of {size} octets.
*
* @param size count of octets to allocate.
* @param fill if specified, buffer will be initialized by calling buf.fill(fill).
* If parameter is omitted, buffer will be filled with zeros.
* @param encoding encoding used for call to buf.fill while initalizing
*/
static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer;
/**
* Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents
* of the newly created Buffer are unknown and may contain sensitive data.
*
* @param size count of octets to allocate
*/
static allocUnsafe(size: number): Buffer;
/**
* Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents
* of the newly created Buffer are unknown and may contain sensitive data.
*
* @param size count of octets to allocate
*/
static allocUnsafeSlow(size: number): Buffer;
}
} | {
"pile_set_name": "Github"
} |
//: ----------------------------------------------------------------------------
//: Copyright (C) 2017 Verizon. All Rights Reserved.
//: All Rights Reserved
//:
//: file: decoder.go
//: details: decodes IPFIX packets
//: author: Mehrdad Arshad Rad
//: date: 02/01/2017
//:
//: 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 ipfix
import (
"bytes"
"errors"
"fmt"
"io"
"net"
"github.com/VerizonDigital/vflow/reader"
)
// Decoder represents IPFIX payload and remote address
type Decoder struct {
raddr net.IP
reader *reader.Reader
}
// MessageHeader represents IPFIX message header
type MessageHeader struct {
Version uint16 // Version of IPFIX to which this Message conforms
Length uint16 // Total length of the IPFIX Message, measured in octets
ExportTime uint32 // Time at which the IPFIX Message Header leaves the Exporter
SequenceNo uint32 // Incremental sequence counter modulo 2^32
DomainID uint32 // A 32-bit id that is locally unique to the Exporting Process
}
// TemplateHeader represents template fields
type TemplateHeader struct {
TemplateID uint16
FieldCount uint16
ScopeFieldCount uint16
}
// TemplateRecord represents template records
type TemplateRecord struct {
TemplateID uint16
FieldCount uint16
FieldSpecifiers []TemplateFieldSpecifier
ScopeFieldCount uint16
ScopeFieldSpecifiers []TemplateFieldSpecifier
}
// TemplateFieldSpecifier represents field properties
type TemplateFieldSpecifier struct {
ElementID uint16
Length uint16
EnterpriseNo uint32
}
// Message represents IPFIX decoded data
type Message struct {
AgentID string
Header MessageHeader
DataSets [][]DecodedField
}
// DecodedField represents a decoded field
type DecodedField struct {
ID uint16
Value interface{}
EnterpriseNo uint32
}
// SetHeader represents set header fields
type SetHeader struct {
SetID uint16
Length uint16
}
type nonfatalError struct {
error
}
var rpcChan = make(chan RPCRequest, 1)
// NewDecoder constructs a decoder
func NewDecoder(raddr net.IP, b []byte) *Decoder {
return &Decoder{raddr, reader.NewReader(b)}
}
// Decode decodes the IPFIX raw data
func (d *Decoder) Decode(mem MemCache) (*Message, error) {
var msg = new(Message)
// IPFIX Message Header decoding
if err := msg.Header.unmarshal(d.reader); err != nil {
return nil, err
}
// IPFIX Message Header validation
if err := msg.Header.validate(); err != nil {
return nil, err
}
// Add source IP address as Agent ID
msg.AgentID = d.raddr.String()
// In case there are multiple non-fatal errors, collect them and report all of them.
// The rest of the received sets will still be interpreted, until a fatal error is encountered.
// A non-fatal error is for example an illegal data record or unknown template id.
var decodeErrors []error
for d.reader.Len() > 4 {
if err := d.decodeSet(mem, msg); err != nil {
switch err.(type) {
case nonfatalError:
decodeErrors = append(decodeErrors, err)
default:
return nil, err
}
}
}
return msg, combineErrors(decodeErrors...)
}
// RFC 7011 - part 3.B IPFIX Message Format
// +----------------------------------------------------+
// | Message Header |
// +----------------------------------------------------+
// | Set |
// +----------------------------------------------------+
// | Set |
// +----------------------------------------------------+
// ...
// +----------------------------------------------------+
// | Set |
// +----------------------------------------------------+
func (d *Decoder) decodeSet(mem MemCache, msg *Message) error {
startCount := d.reader.ReadCount()
setHeader := new(SetHeader)
if err := setHeader.unmarshal(d.reader); err != nil {
return err
}
if setHeader.Length < 4 {
return io.ErrUnexpectedEOF
}
var tr TemplateRecord
var err error
// This check is somewhat redundant with the switch-clause below, but the retrieve() operation should not be executed inside the loop.
if setHeader.SetID > 255 {
var ok bool
if tr, ok = mem.retrieve(setHeader.SetID, d.raddr); !ok {
select {
case rpcChan <- RPCRequest{
ID: setHeader.SetID,
IP: d.raddr,
}:
default:
}
err = nonfatalError{fmt.Errorf("%s unknown ipfix template id# %d",
d.raddr.String(),
setHeader.SetID,
)}
}
}
// the next set should be greater than 4 bytes otherwise that's padding
for err == nil && setHeader.Length > uint16(d.reader.ReadCount()-startCount) && d.reader.Len() > 4 && setHeader.Length-uint16(d.reader.ReadCount()-startCount) > 4 {
if setID := setHeader.SetID; setID == 2 || setID == 3 {
// Template record or template option record
// Check if only padding is left in this set. A template id of zero indicates padding bytes, which MUST be zero.
if templateID, err := d.reader.PeekUint16(); err == nil && templateID == 0 {
break
}
tr := TemplateRecord{}
if setID == 2 {
err = tr.unmarshal(d.reader)
} else {
err = tr.unmarshalOpts(d.reader)
}
if err == nil {
mem.insert(tr.TemplateID, d.raddr, tr)
}
} else if setID >= 4 && setID <= 255 {
// Reserved set, do not read any records
break
} else if setID == 0 {
// Invalid set
return fmt.Errorf("failed to decodeSet / invalid setID")
} else {
// Data set
var data []DecodedField
if data, err = d.decodeData(tr); err == nil {
msg.DataSets = append(msg.DataSets, data)
} else {
switch err.(type) {
case nonfatalError:
default:
return err
}
}
}
}
// Skip the rest of the set in order to properly continue with the next set
// This is necessary if the set is padded, has a reserved set ID, or a nonfatal error occurred
leftoverBytes := setHeader.Length - uint16(d.reader.ReadCount()-startCount)
if leftoverBytes > 0 {
if _, skipErr := d.reader.Read(int(leftoverBytes)); skipErr != nil {
err = skipErr
}
}
return err
}
// RFC 7011 - part 3.1. Message Header Format
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Version Number | Length |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Export Time |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Sequence Number |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Observation Domain ID |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
func (h *MessageHeader) unmarshal(r *reader.Reader) error {
var err error
if h.Version, err = r.Uint16(); err != nil {
return err
}
if h.Length, err = r.Uint16(); err != nil {
return err
}
if h.ExportTime, err = r.Uint32(); err != nil {
return err
}
if h.SequenceNo, err = r.Uint32(); err != nil {
return err
}
if h.DomainID, err = r.Uint32(); err != nil {
return err
}
return nil
}
func (h *MessageHeader) validate() error {
if h.Version != 0x000a {
return fmt.Errorf("invalid ipfix version (%d)", h.Version)
}
// TODO: needs more validation
return nil
}
// RFC 7011 - part 3.3.2 Set Header Format
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Set ID | Length |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
func (h *SetHeader) unmarshal(r *reader.Reader) error {
var err error
if h.SetID, err = r.Uint16(); err != nil {
return err
}
if h.Length, err = r.Uint16(); err != nil {
return err
}
return nil
}
// RFC 7011
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Set ID = (2 or 3) | Length |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Template ID | Field Count |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
func (t *TemplateHeader) unmarshal(r *reader.Reader) error {
var err error
if t.TemplateID, err = r.Uint16(); err != nil {
return err
}
if t.FieldCount, err = r.Uint16(); err != nil {
return err
}
return nil
}
// RFC 7011 3.4.2.2. Options Template Record Format
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Set ID = 3 | Length |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Template ID | Field Count = N + M |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Scope Field Count = N |0| Scope 1 Infor. Element id. |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
func (t *TemplateHeader) unmarshalOpts(r *reader.Reader) error {
var err error
if t.TemplateID, err = r.Uint16(); err != nil {
return err
}
if t.FieldCount, err = r.Uint16(); err != nil {
return err
}
if t.ScopeFieldCount, err = r.Uint16(); err != nil {
return err
}
return nil
}
// RFC 7011
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |E| Information Element ident. | Field Length |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Enterprise Number |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
func (f *TemplateFieldSpecifier) unmarshal(r *reader.Reader) error {
var err error
if f.ElementID, err = r.Uint16(); err != nil {
return err
}
if f.Length, err = r.Uint16(); err != nil {
return err
}
if f.ElementID > 0x8000 {
f.ElementID = f.ElementID & 0x7fff
if f.EnterpriseNo, err = r.Uint32(); err != nil {
return err
}
} else {
f.EnterpriseNo = 0
}
return nil
}
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Set ID = 2 | Length |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Template ID = 256 | Field Count = N |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |1| Information Element id. 1.1 | Field Length 1.1 |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Enterprise Number 1.1 |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |0| Information Element id. 1.2 | Field Length 1.2 |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | ... | ... |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
func (tr *TemplateRecord) unmarshal(r *reader.Reader) error {
var (
th = TemplateHeader{}
tf = TemplateFieldSpecifier{}
)
if err := th.unmarshal(r); err != nil {
return err
}
tr.TemplateID = th.TemplateID
tr.FieldCount = th.FieldCount
for i := th.FieldCount; i > 0; i-- {
if err := tf.unmarshal(r); err != nil {
return err
}
tr.FieldSpecifiers = append(tr.FieldSpecifiers, tf)
}
return nil
}
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Set ID = 3 | Length |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Template ID = X | Field Count = N + M |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Scope Field Count = N |0| Scope 1 Infor. Element id. |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Scope 1 Field Length |0| Scope 2 Infor. Element id. |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Scope 2 Field Length | ... |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | ... |1| Scope N Infor. Element id. |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Scope N Field Length | Scope N Enterprise Number ...
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// ... Scope N Enterprise Number |1| Option 1 Infor. Element id. |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Option 1 Field Length | Option 1 Enterprise Number ...
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// ... Option 1 Enterprise Number | ... |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | ... |0| Option M Infor. Element id. |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Option M Field Length | Padding (optional) |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
func (tr *TemplateRecord) unmarshalOpts(r *reader.Reader) error {
var (
th = TemplateHeader{}
tf = TemplateFieldSpecifier{}
)
if err := th.unmarshalOpts(r); err != nil {
return err
}
tr.TemplateID = th.TemplateID
tr.FieldCount = th.FieldCount
tr.ScopeFieldCount = th.ScopeFieldCount
for i := th.ScopeFieldCount; i > 0; i-- {
if err := tf.unmarshal(r); err != nil {
return err
}
tr.ScopeFieldSpecifiers = append(tr.FieldSpecifiers, tf)
}
for i := th.FieldCount - th.ScopeFieldCount; i > 0; i-- {
if err := tf.unmarshal(r); err != nil {
return err
}
tr.FieldSpecifiers = append(tr.FieldSpecifiers, tf)
}
return nil
}
func (d *Decoder) getDataLength(fieldSpecifierLen uint16, t FieldType) (uint16, error) {
var (
err error
readLength uint16
)
r := d.reader
if (t == String || t == OctetArray) && (fieldSpecifierLen == 65535) {
var len8 uint8
if len8, err = r.Uint8(); err != nil {
return 0, err
} else if len8 == 255 {
if readLength, err = r.Uint16(); err != nil {
return 0, err
}
} else {
readLength = uint16(len8)
}
} else {
readLength = fieldSpecifierLen
}
return readLength, nil
}
func (d *Decoder) decodeData(tr TemplateRecord) ([]DecodedField, error) {
var (
fields []DecodedField
err error
b []byte
readLength uint16
)
r := d.reader
for i := 0; i < len(tr.ScopeFieldSpecifiers); i++ {
m, ok := InfoModel[ElementKey{
tr.ScopeFieldSpecifiers[i].EnterpriseNo,
tr.ScopeFieldSpecifiers[i].ElementID,
}]
if !ok {
return nil, nonfatalError{fmt.Errorf("IPFIX element key (%d) not exist (scope)",
tr.ScopeFieldSpecifiers[i].ElementID)}
}
if readLength, err = d.getDataLength(tr.ScopeFieldSpecifiers[i].Length, m.Type); err != nil {
return nil, err
}
if b, err = r.Read(int(readLength)); err != nil {
return nil, err
}
fields = append(fields, DecodedField{
ID: m.FieldID,
Value: Interpret(&b, m.Type),
EnterpriseNo: tr.ScopeFieldSpecifiers[i].EnterpriseNo,
})
}
for i := 0; i < len(tr.FieldSpecifiers); i++ {
m, ok := InfoModel[ElementKey{
tr.FieldSpecifiers[i].EnterpriseNo,
tr.FieldSpecifiers[i].ElementID,
}]
if !ok {
return nil, nonfatalError{fmt.Errorf("IPFIX element key (%d) not exist",
tr.FieldSpecifiers[i].ElementID)}
}
if readLength, err = d.getDataLength(tr.FieldSpecifiers[i].Length, m.Type); err != nil {
return nil, err
}
if b, err = r.Read(int(readLength)); err != nil {
return nil, err
}
fields = append(fields, DecodedField{
ID: m.FieldID,
Value: Interpret(&b, m.Type),
})
}
if len(fields) == 0 {
return nil, fmt.Errorf("failed to decodeData")
}
return fields, nil
}
func combineErrors(errorSlice ...error) (err error) {
switch len(errorSlice) {
case 0:
case 1:
err = errorSlice[0]
default:
var errMsg bytes.Buffer
errMsg.WriteString("Multiple errors:")
for _, subError := range errorSlice {
errMsg.WriteString("\n- " + subError.Error())
}
err = errors.New(errMsg.String())
}
return
}
| {
"pile_set_name": "Github"
} |
{
"ver": "1.0.5",
"uuid": "92090668-218b-4659-80c9-0118a1d872d5",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
} | {
"pile_set_name": "Github"
} |
import * as Nexus from '@nexus/schema'
import { CustomInputArg } from './builder'
import { DmmfDocument, DmmfTypes } from './dmmf'
import { scalarsNameValues } from './graphql'
import { dmmfFieldToNexusFieldConfig, Index } from './utils'
import { GraphQLScalarType } from 'graphql'
export class Publisher {
typesPublished: Index<boolean> = {}
constructor(
public dmmf: DmmfDocument,
public nexusBuilder: Nexus.PluginBuilderLens,
public scalars: Record<string, GraphQLScalarType>
) {}
inputType(
customArg: CustomInputArg
):
| string
| Nexus.core.NexusInputObjectTypeDef<string>
| Nexus.core.NexusEnumTypeDef<string>
| Nexus.core.NexusScalarTypeDef<string>
| Nexus.core.NexusArgDef<any>
| GraphQLScalarType {
const typeName = customArg.type.name
// If type is already published, just reference it
if (this.isPublished(typeName)) {
return Nexus.arg(
dmmfFieldToNexusFieldConfig({
...customArg.arg.inputType,
type: customArg.type.name,
})
)
}
if (customArg.arg.inputType.kind === 'scalar') {
return this.publishScalar(customArg.type.name)
}
if (customArg.arg.inputType.kind === 'enum') {
return this.publishEnum(customArg.type.name)
}
const inputType = customArg.type as DmmfTypes.InputType
return this.publishInputObjectType(inputType)
}
// Return type of 'any' to prevent a type mismatch with `type` property of nexus
public outputType(outputTypeName: string, field: DmmfTypes.SchemaField): any {
/**
* Rules:
* - If outputTypeName is already published
* - Or if outputTypeName matches a prisma model name
* - Then simply reference the type. Types that matches a prisma model name should be published manually by users.
*/
if (this.isPublished(outputTypeName) || this.dmmf.hasModel(outputTypeName)) {
return outputTypeName
}
// If output object type, just reference the type
if (field.outputType.kind === 'object') {
return this.publishObject(outputTypeName)
}
if (this.dmmf.hasEnumType(outputTypeName)) {
return this.publishEnum(outputTypeName)
}
if (field.outputType.kind === 'scalar') {
return this.publishScalar(outputTypeName)
}
return outputTypeName
}
protected publishObject(name: string) {
const dmmfObject = this.dmmf.getOutputType(name)
this.markTypeAsPublished(name)
return Nexus.objectType({
name,
definition: (t) => {
for (const field of dmmfObject.fields) {
t.field(field.name, dmmfFieldToNexusFieldConfig(field.outputType))
}
},
})
}
protected publishScalar(typeName: string) {
if (scalarsNameValues.includes(typeName as any)) {
return typeName
}
this.markTypeAsPublished(typeName)
if (this.scalars[typeName]) {
return this.scalars[typeName]
}
return Nexus.scalarType({
name: typeName,
serialize(value) {
return value
},
})
}
protected publishEnum(typeName: string) {
const dmmfEnum = this.dmmf.getEnumType(typeName)
this.markTypeAsPublished(typeName)
return Nexus.enumType({
name: typeName,
members: dmmfEnum.values,
})
}
publishInputObjectType(inputType: DmmfTypes.InputType) {
this.markTypeAsPublished(inputType.name)
return Nexus.inputObjectType({
name: inputType.name,
definition: (t) => {
inputType.fields
.map((field) => {
// TODO: Do not filter JsonFilter once Prisma implements them
// https://github.com/prisma/prisma/issues/2563
if (['JsonFilter', 'NullableJsonFilter'].includes(field.inputType.type)) {
return null
}
return {
...field,
inputType: {
...field.inputType,
type: this.isPublished(field.inputType.type)
? // Simply reference the field input type if it's already been visited, otherwise create it
field.inputType.type
: this.inputType({
arg: field,
type: this.getTypeFromArg(field),
}),
},
}
})
.forEach((field) => {
if (field) {
t.field(field.name, dmmfFieldToNexusFieldConfig(field.inputType))
}
})
},
})
}
protected getTypeFromArg(arg: DmmfTypes.SchemaArg): CustomInputArg['type'] {
const kindToType = {
scalar: (typeName: string) => ({
name: typeName,
}),
enum: (typeName: string) => this.dmmf.getEnumType(typeName),
object: (typeName: string) => this.dmmf.getInputType(typeName),
}
return kindToType[arg.inputType.kind](arg.inputType.type)
}
isPublished(typeName: string) {
// If the user's app has published a type of the same name treat it as an
// override to us auto publishing.
return this.nexusBuilder.hasType(typeName) || this.typesPublished[typeName]
}
markTypeAsPublished(typeName: string) {
this.typesPublished[typeName] = true
}
}
| {
"pile_set_name": "Github"
} |
using GB28181.WinTool.Codec;
using StreamingKit;
using System;
using System.IO;
namespace GB28181.WinTool.Mixer.Audio
{
internal class AacDec : DecoderLine
{
private bool _inited = false;
private byte[] buffer;
FFImp _aac;
// FaadImp _aac;
public override void Dec(byte[] src)
{
this.Init(src);
if (_aac != null)
{
buffer = DecMultiAAC(src);
if (buffer == null)
return;
if (buffer.Length == 0)
Console.WriteLine(Buffer.Length + DateTime.Now.ToString());
if (this.buffer.Length != 0)
{
this.QueueBuffer.Enqueue(buffer);
}
}
}
private byte[] DecMultiAAC(byte[] buffer)
{
AAC_ADTS[] aacs = null;
try
{
aacs = AAC_ADTS.GetMultiAAC(buffer);
}
catch(Exception ex)
{
Console.WriteLine(ex);
aacs = null;
}
if (aacs != null)
{
if (aacs.Length == 1)
{
return DecAAC(buffer);
}
else
{
return DecMultiAAC(aacs);
}
}
else
{
return null;
}
}
private byte[] DecMultiAAC(AAC_ADTS[] aacs)
{
var ms = new MemoryStream();
foreach (var item in aacs)
{
if (item != null)
{
var bytes = DecAAC(item.FrameData);
ms.Write(bytes, 0, bytes.Length);
}
}
return ms.ToArray();
}
private byte[] DecAAC(byte[] buffer)
{
byte[] @out = new byte[0];
// return _aac.Decode(buffer);
int len = _aac.AudioDec(buffer, ref @out);
if (len > 0)
{
if (len != @out.Length)
Array.Resize<byte>(ref @out, len);
return @out;
}
else
{
return new byte[0];
}
}
private void Init(byte[] buffer)
{
if (!_inited)
{
AAC_ADTS[] adtss = AAC_ADTS.GetMultiAAC(buffer);
if (adtss != null)
{
int channels = adtss[0].MPEG_4_Channel_Configuration;
int frequency = adtss[0].Frequency;
//_aac = new FaadImp();
_aac = new FFImp(AVCodecCfg.CreateAudio(channels, frequency, (int)AVCode.CODEC_ID_AAC), true,false);
_inited = true;
}
}
}
public override void Close()
{
if (_aac != null)
{
// _aac.Dispose();
_aac.Release();
}
}
}
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en" data-auth="false" data-template="false">
<head>
<meta charset="utf-8" />
<title translate="yes">登出</title>
<meta http-equiv="refresh" content="1;url=/account/signout-complete">
<link href="/public/pure-min.css" rel="stylesheet">
<link href="/public/content.css" rel="stylesheet">
<link href="/public/content-additional.css" rel="stylesheet">
<base target="_top" href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p class="entry-form" translate="yes">请等待注销完成。</p>
</body>
</html>
| {
"pile_set_name": "Github"
} |
import random
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers \
import Dense, Embedding, LSTM, GRU, TimeDistributed
from tensorflow.keras.preprocessing.sequence import pad_sequences
from utils.datasets.small_parallel_enja import load_small_parallel_enja
from utils.preprocessing.sequence import sort
class EncoderDecoder(Model):
def __init__(self,
input_dim,
hidden_dim,
output_dim,
bos_value=1,
max_len=20):
super().__init__()
self.encoder = Encoder(input_dim, hidden_dim)
self.decoder = Decoder(hidden_dim, output_dim)
self._BOS = bos_value
self._max_len = max_len
self.output_dim = output_dim
def call(self, source, target=None, use_teacher_forcing=False):
batch_size = source.shape[0]
if target is not None:
len_target_sequences = target.shape[1]
else:
len_target_sequences = self._max_len
_, states = self.encoder(source)
# output, _ = self.decoder(target, states)
# return output
y = tf.ones((batch_size, 1), dtype=tf.int32) * self._BOS
output = tf.zeros((batch_size, 1, self.output_dim), dtype=tf.float32)
for t in range(len_target_sequences):
out, states = self.decoder(y, states)
output = tf.concat([output, out[:, :1]], axis=1)
if use_teacher_forcing and target is not None:
y = target[:, t][:, tf.newaxis]
else:
y = tf.argmax(out, axis=-1, output_type=tf.int32)
return output[:, 1:]
class Encoder(Model):
def __init__(self,
input_dim,
hidden_dim):
super().__init__()
self.embedding = Embedding(input_dim, hidden_dim, mask_zero=True)
self.lstm = LSTM(hidden_dim, return_state=True)
def call(self, x):
x = self.embedding(x)
y, state_h, state_c = self.lstm(x)
return y, (state_h, state_c)
class Decoder(Model):
def __init__(self,
hidden_dim,
output_dim):
super().__init__()
self.embedding = Embedding(output_dim, hidden_dim, mask_zero=True)
self.lstm = LSTM(hidden_dim, return_state=True, return_sequences=True)
#
# We don't need TimeDistributed here
# because we apply the data at each timestep.
#
# self.out = TimeDistributed(Dense(output_dim, activation='softmax'))
self.out = Dense(output_dim, activation='softmax')
def call(self, x, states):
x = self.embedding(x)
x, state_h, state_c = self.lstm(x, states)
y = self.out(x)
return y, (state_h, state_c)
if __name__ == '__main__':
np.random.seed(1234)
tf.random.set_seed(1234)
@tf.function
def compute_loss(label, pred):
return criterion(label, pred)
# @tf.function
def train_step(x, t, depth_t,
teacher_forcing_rate=0.5,
pad_value=0):
use_teacher_forcing = (random.random() < teacher_forcing_rate)
with tf.GradientTape() as tape:
preds = model(x, t, use_teacher_forcing=use_teacher_forcing)
label = tf.one_hot(t, depth=depth_t, dtype=tf.float32)
mask_t = tf.cast(tf.not_equal(t, pad_value), tf.float32)
label = label * mask_t[:, :, tf.newaxis]
loss = compute_loss(label, preds)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
train_loss(loss)
return preds
@tf.function
def valid_step(x, t, depth_t, pad_value=0):
preds = model(x, t, use_teacher_forcing=False)
label = tf.one_hot(t, depth=depth_t, dtype=tf.float32)
mask_t = tf.cast(tf.not_equal(t, pad_value), tf.float32)
label = label * mask_t[:, :, tf.newaxis]
loss = compute_loss(label, preds)
valid_loss(loss)
return preds
@tf.function
def test_step(x):
preds = model(x)
return preds
def ids_to_sentence(ids, i2w):
return [i2w[id] for id in ids]
'''
Load data
'''
(x_train, y_train), \
(x_test, y_test), \
(num_x, num_y), \
(w2i_x, w2i_y), (i2w_x, i2w_y) = \
load_small_parallel_enja(to_ja=True, add_bos=False)
N = len(x_train)
train_size = int(N * 0.8)
valid_size = N - train_size
(x_train, y_train), (x_valid, y_valid) = \
(x_train[:train_size], y_train[:train_size]), \
(x_train[train_size:], y_train[train_size:])
x_train, y_train = sort(x_train, y_train)
x_valid, y_valid = sort(x_valid, y_valid)
x_test, y_test = sort(x_test, y_test)
train_size = 40000
valid_size = 200
test_size = 10
x_train, y_train = x_train[:train_size], y_train[:train_size]
x_valid, y_valid = x_valid[:valid_size], y_valid[:valid_size]
x_test, y_test = x_test[:test_size], y_test[:test_size]
'''
Build model
'''
input_dim = num_x
hidden_dim = 128
output_dim = num_y
model = EncoderDecoder(input_dim, hidden_dim, output_dim)
criterion = tf.losses.CategoricalCrossentropy()
optimizer = tf.keras.optimizers.Adam()
'''
Train model
'''
epochs = 20
batch_size = 100
n_batches = len(x_train) // batch_size
train_loss = tf.keras.metrics.Mean()
valid_loss = tf.keras.metrics.Mean()
for epoch in range(epochs):
print('-' * 20)
print('Epoch: {}'.format(epoch+1))
for batch in range(n_batches):
start = batch * batch_size
end = start + batch_size
_x_train = pad_sequences(x_train[start:end], padding='post')
_y_train = pad_sequences(y_train[start:end], padding='post')
train_step(_x_train, _y_train, num_y)
_x_valid = pad_sequences(x_valid, padding='post')
_y_valid = pad_sequences(y_valid, padding='post')
valid_step(_x_valid, _y_valid, num_y)
print('Valid loss: {:.3}'.format(valid_loss.result()))
for i, source in enumerate(x_test):
out = test_step(np.array(source)[np.newaxis, :])[0]
out = tf.argmax(out, axis=-1).numpy()
out = ' '.join(ids_to_sentence(out, i2w_y))
source = ' '.join(ids_to_sentence(source, i2w_x))
target = ' '.join(ids_to_sentence(y_test[i], i2w_y))
print('>', source)
print('=', target)
print('<', out)
print()
| {
"pile_set_name": "Github"
} |
/*
_______________________________________________________________________________
_______________________________________________________________________________
Title: Mount
Mount any path as a drive with subst.exe
_______________________________________________________________________________
_______________________________________________________________________________
License:
(C) Copyright 2006, 2007, 2009, 2010 Tuncay
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
(see lgplv3.png)
See the file COPYING.txt and COPYING.LESSER.txt for license and copying conditions.
About: Introduction
Any parameter enclosed between '[' and ']' are optional.
Mount([SourcePath], [Mountpoint], [Options])
Returns on success mounted drive with ending backslash and on failure
a string without content.
If Mountpoint is not given, then it looks for first free drive otherwise
existing SourcePath will be mounted to given Mountpoint. If SourcePath
is not given, it defaults to WorkingDir.
The SourcePath can contain wildcards ("*" and "?") and the relative
directory dots ("." for current dir and ".." for one up dir).
Any existing Mountpoint will be updated (first umount the old one, and
then remounting the new one).
Currently there is only one option used to unmount the drive.
Mount_UnMount([Mountpoint], [Options])
Like Mount(), but without the need of SourcePath. Also the unmount
option is here given over to Mount() always.
Mount_GetMount([Path])
If the specified Path is a drive, the full real path is returned. If
the Path is not given, first virtual drive will be get.
Mount_GetMountPathes([Variable])
It gets all virtual drives and paths. The Variable will hold a list in
following format: Drive . ">" . Path . "`n"
The return contains the number of all virtual drives.
Links:
* Discussion: [http://www.autohotkey.com/forum/viewtopic.php?t=46226]
* License: [http://www.gnu.org/licenses/lgpl-3.0.html]
Date:
2010-03-05
Revision:
1.0
Developers:
* Tuncay, (Author)
License:
GNU Lesser General Public License 3.0 or higher [http://www.gnu.org/licenses/lgpl-3.0.html]
Category:
FileSystem
Type:
Library
About: Examples
Example 1
> Mount()
-> F:
Calling Mount() without any parameter mounts current WorkingDir to first
found free drive letter and returns it.
Example 2
> FileSelectFolder, SourcePath, ::{20d04fe0-3aea-1069-a2d8-08002b30309d}, 3, Select folder to mount
> Mount(SourcePath, "x")
-> X:
Here SourcePath will be mounted to drive letter X, if it`s free. If the
drive letter is not free and if its a virtual drive letter, then the drive
(here "X:") will be unmounted and SourcePath will be mounted as the new one.
Example 3
> Mount_UnMount()
-> X:
Calling Mount_UnMount() without any parameter unmounts the first founded virtual
drive, mapped with Mount(). It returns the founded drive path (here "X:\").
Example 4
> MsgBox % Mount_GetMount()
-> X:
Calling Mount_GetMount() without any parameter gets the drive letter of first
virtual drive letter (without backslash). But this slow.
Example 5
> MsgBox % Mount_GetMount("x")
-> D:\files\subdirectory
Calling Mount_GetMount() with drive letter returns the real full path of mapped
virtual drive (without backslash). But if the given drive letter does not
exist or isn`t a mounted drive, then a void string is returned.
Example 6
> Mount_GetMountPathes()
-> 2
Calling Mount_GetMountPathes() will get number of mounted pathes and a string with
all founded virtual drives.
-> E:>C:/Windows
-> F:>D:/Emulators/zsnes
*/
/*
Public Function Mount
Mounts with subst.exe any path to a Windows drive.
2007 by Tuncay
*/
Mount(SourcePath = "", Mountpoint = "", Options = "")
{
GoSub, SetOptions@Mount
GoSub, SetMountPath@Mount
If NOT Option?UnMount AND FileExist(Mount_GetMount(MountPath))
{
Option?UnMount := True
Option?Update := True
}
If Option?UnMount
Command = subst %MountPath% /d
Else
{
If (SourcePath = "")
SourcePath = %A_WorkingDir%
Else
{
Loop, %SourcePath%, 2
{
SourcePath = %A_LoopFileLongPath%
Break
}
}
Command = subst %MountPath% "%SourcePath%"
}
If (NOT Option?UnMount AND NOT FileExist(MountPath . "\") AND FileExist(SourcePath))
OR (Option?UnMount AND FileExist(MountPath))
{
RunWait, "%comspec%" /c %Command%,, Hide UseErrorLevel
If ErrorLevel = ERROR
{
MountPath =
; Failed to launch subst.exe
ErrorLevel = 2
}
Else
ErrorLevel = 0
}
Else
{
MountPath =
ErrorLevel = 1
}
If Option?Update
MountPath := Mount(SourcePath, Mountpoint)
Return MountPath
SetMountPath@Mount:
If (Mountpoint = "") ; Search drive.
{
DriveGet, ActualDrives, List
If NOT Option?UnMount ; Get first free drive.
{
FreeDriveLetters = CDEFGHIJKLMNOPQRSTUVWXYZ
Loop, Parse, ActualDrives
StringReplace, FreeDriveLetters,FreeDriveLetters,%A_LoopField%
Loop, Parse, FreeDriveLetters
{
MountPath = %A_LoopField%:
Break
}
}
Else If Option?UnMount ; Get first subst.exe mounted drive.
MountPath := Mount_GetMount()
}
Else If Mountpoint Is Alpha ; Add double colon on drive letter.
MountPath = %Mountpoint%:
Else ; Drive will be extracted from any path.
SplitPath, MountPath,,,,, Mountpoint
Return
SetOptions@Mount:
; Default settings
Option?UnMount := False
If NOT (Options = "")
{
CurrentStringCaseSense := A_StringCaseSense
StringCaseSense, On
If Options Contains --
{
StringReplace, Options, Options,--unmount,-u
}
StringReplace, Options, Options,/,-, All
; Overwriting default settings.
OptionsFoundList := "" ; For performance, not to loop if already founded
; and avoid dublicates.
Loop, Parse, Options,-,%A_SPACE%
{
If A_LoopField In ,%A_SPACE%
Continue
; Inner Loop for enabling the short style for grouping of options.
Loop, Parse, A_LoopField
{
If InStr(OptionsFoundList, A_LoopField, True)
Continue
; Option?UnMount
; 0=creates a virtual drive from given path (default)
; 1=deletes the given virtual drive mounted by subst.exe
If InStr(A_LoopField, "u", True)
{
Option?UnMount := True
OptionsFoundList .= A_LoopField
Continue
}
}
}
StringCaseSense, %CurrentStringCaseSense%
}
Return
}
/*
Public Function UnMount
UnMounts a virtual drive mapped with subst.exe.
2006 by Tuncay
*/
Mount_UnMount(Mountpoint = "", Options = "")
{
Return Mount("", Mountpoint, "-u " . Options)
}
/*
Public Function GetMountPathes
Get a list of all virtual drives and real paths of them. Returns number of paths.
Format: Drive . ">" . Path . "`n"
2007 by Tuncay
*/
Mount_GetMountPathes(ByRef pPathes)
{
Drive0 = 0
pPathes =
TempFile = %A_Temp%\{D74BA6E8-2728-4FC6-8185-623EA7DAD412}_%A_Now%.~tmp
Command = subst >"%TempFile%"
RunWait, "%comspec%" /c %Command%,, Hide UseErrorLevel
If ErrorLevel = ERROR
ErrorLevel := 2 ; Failed to launch subst.exe
Else
{
ErrorLevel = 0
; Process all drive letters.
Loop, Read, %TempFile%
{
StringMid, Drive, A_LoopReadLine, 1, 2
StringMid, Path, A_LoopReadLine, 9
Drive0++
pPathes .= Drive . ">" . Path . "`n"
}
}
FileDelete, %TempFile%
Return Drive0
}
/*
Public Function GetMount
Converts virtual path mapped with subst.exe to real physical full path.
2007 by Tuncay
*/
Mount_GetMount(pPath = "")
{
If pPath
pPath := SubStr(pPath, 1, 1) . ":"
Else
SplitPath, pPath,,,,, pPath
TempFile = %A_Temp%\{D74BA6E8-2728-4FC6-8185-623EA7DAD412}_%A_Now%.~tmp
Command = subst >"%TempFile%"
RunWait, "%comspec%" /c %Command%,, Hide UseErrorLevel
If ErrorLevel = ERROR
ErrorLevel := 2 ; Failed to launch subst.exe
Else
{
ErrorLevel = 0
If pPath
{
Loop, Read, %TempFile%
{
StringMid, MountDrive, A_LoopReadLine, 1, 2
If (pPath = MountDrive)
{
StringMid, MountPath, A_LoopReadLine, 9
Break
}
}
}
Else
{
; Get first virtual drive.
Loop, Read, %TempFile%
{
DriveGet, ActualDrives, List
MountDrive := SubStr(A_LoopReadLine, 1, 1)
If InStr(ActualDrives, MountDrive)
{
MountPath = %MountDrive%:
Break
}
Else
Continue
}
}
}
FileDelete, %TempFile%
Return MountPath
}
| {
"pile_set_name": "Github"
} |
<html>
<head>
<title>045.php</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
function navigate(e) {
var keynum = (window.event) // IE
? e.keyCode
: e.which;
if (keynum == 8) {
window.location = "044" + ".html";
return false;
}
if (keynum == 13 || keynum == 32) {
window.location = "046" + ".html";
return false;
}
if (keynum == 73 || keynum == 105) {
window.location = "index.html";
return false;
}
return true;
}
</script>
</head>
<body onkeypress="return navigate(event)">
<pre> SplObjectStorage #3
<?php
$obj1 = new StdClass;
$obj1->name = 'Thrall';
$obj2 = new StdClass;
$obj2->name = 'Sylvanas';
$obj3 = new StdClass;
$obj3->name = 'Cairne';
$obj4 = new StdClass;
$obj4->name = 'Voljin';
$sos = new SplObjectStorage();
$sos->attach($obj1, 'Orc');
$sos->attach($obj2, 'Undead');
$sos->attach($obj3, 'Tauren');
$sos->attach($obj4, 'Troll');
foreach ($sos as $obj) {
echo $obj->name, " - ", $sos->getInfo(), "\n";
}
echo "--\n";
$sos->detach($obj3); // 케른 블러드후프 사망
foreach ($sos as $obj) {
if ($obj == $obj2) {
$sos->setInfo('Blood Elf'); // 실바나스는 블엘로
}
}
foreach ($sos as $obj) {
echo $obj->name, " - ", $sos->getInfo(), "\n";
}
?>
</pre>
</body>
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2015 Etnaviv Project
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __ETNAVIV_DRV_H__
#define __ETNAVIV_DRV_H__
#include <linux/kernel.h>
#include <linux/clk.h>
#include <linux/cpufreq.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/pm.h>
#include <linux/pm_runtime.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/iommu.h>
#include <linux/types.h>
#include <linux/sizes.h>
#include <drm/drmP.h>
#include <drm/drm_crtc_helper.h>
#include <drm/drm_fb_helper.h>
#include <drm/drm_gem.h>
#include <drm/etnaviv_drm.h>
struct etnaviv_cmdbuf;
struct etnaviv_gpu;
struct etnaviv_mmu;
struct etnaviv_gem_object;
struct etnaviv_gem_submit;
struct etnaviv_file_private {
/* currently we don't do anything useful with this.. but when
* per-context address spaces are supported we'd keep track of
* the context's page-tables here.
*/
int dummy;
};
struct etnaviv_drm_private {
int num_gpus;
struct etnaviv_gpu *gpu[ETNA_MAX_PIPES];
/* list of GEM objects: */
struct mutex gem_lock;
struct list_head gem_list;
struct workqueue_struct *wq;
};
static inline void etnaviv_queue_work(struct drm_device *dev,
struct work_struct *w)
{
struct etnaviv_drm_private *priv = dev->dev_private;
queue_work(priv->wq, w);
}
int etnaviv_ioctl_gem_submit(struct drm_device *dev, void *data,
struct drm_file *file);
int etnaviv_gem_mmap(struct file *filp, struct vm_area_struct *vma);
int etnaviv_gem_fault(struct vm_area_struct *vma, struct vm_fault *vmf);
int etnaviv_gem_mmap_offset(struct drm_gem_object *obj, u64 *offset);
struct sg_table *etnaviv_gem_prime_get_sg_table(struct drm_gem_object *obj);
void *etnaviv_gem_prime_vmap(struct drm_gem_object *obj);
void etnaviv_gem_prime_vunmap(struct drm_gem_object *obj, void *vaddr);
struct drm_gem_object *etnaviv_gem_prime_import_sg_table(struct drm_device *dev,
struct dma_buf_attachment *attach, struct sg_table *sg);
int etnaviv_gem_prime_pin(struct drm_gem_object *obj);
void etnaviv_gem_prime_unpin(struct drm_gem_object *obj);
void *etnaviv_gem_vmap(struct drm_gem_object *obj);
int etnaviv_gem_cpu_prep(struct drm_gem_object *obj, u32 op,
struct timespec *timeout);
int etnaviv_gem_cpu_fini(struct drm_gem_object *obj);
void etnaviv_gem_free_object(struct drm_gem_object *obj);
int etnaviv_gem_new_handle(struct drm_device *dev, struct drm_file *file,
u32 size, u32 flags, u32 *handle);
struct drm_gem_object *etnaviv_gem_new_locked(struct drm_device *dev,
u32 size, u32 flags);
struct drm_gem_object *etnaviv_gem_new(struct drm_device *dev,
u32 size, u32 flags);
int etnaviv_gem_new_userptr(struct drm_device *dev, struct drm_file *file,
uintptr_t ptr, u32 size, u32 flags, u32 *handle);
u16 etnaviv_buffer_init(struct etnaviv_gpu *gpu);
u16 etnaviv_buffer_config_mmuv2(struct etnaviv_gpu *gpu, u32 mtlb_addr, u32 safe_addr);
void etnaviv_buffer_end(struct etnaviv_gpu *gpu);
void etnaviv_buffer_queue(struct etnaviv_gpu *gpu, unsigned int event,
struct etnaviv_cmdbuf *cmdbuf);
void etnaviv_validate_init(void);
bool etnaviv_cmd_validate_one(struct etnaviv_gpu *gpu,
u32 *stream, unsigned int size,
struct drm_etnaviv_gem_submit_reloc *relocs, unsigned int reloc_size);
#ifdef CONFIG_DEBUG_FS
void etnaviv_gem_describe_objects(struct etnaviv_drm_private *priv,
struct seq_file *m);
#endif
void __iomem *etnaviv_ioremap(struct platform_device *pdev, const char *name,
const char *dbgname);
void etnaviv_writel(u32 data, void __iomem *addr);
u32 etnaviv_readl(const void __iomem *addr);
#define DBG(fmt, ...) DRM_DEBUG(fmt"\n", ##__VA_ARGS__)
#define VERB(fmt, ...) if (0) DRM_DEBUG(fmt"\n", ##__VA_ARGS__)
/*
* Return the storage size of a structure with a variable length array.
* The array is nelem elements of elem_size, where the base structure
* is defined by base. If the size overflows size_t, return zero.
*/
static inline size_t size_vstruct(size_t nelem, size_t elem_size, size_t base)
{
if (elem_size && nelem > (SIZE_MAX - base) / elem_size)
return 0;
return base + nelem * elem_size;
}
/* returns true if fence a comes after fence b */
static inline bool fence_after(u32 a, u32 b)
{
return (s32)(a - b) > 0;
}
static inline bool fence_after_eq(u32 a, u32 b)
{
return (s32)(a - b) >= 0;
}
static inline unsigned long etnaviv_timeout_to_jiffies(
const struct timespec *timeout)
{
unsigned long timeout_jiffies = timespec_to_jiffies(timeout);
unsigned long start_jiffies = jiffies;
unsigned long remaining_jiffies;
if (time_after(start_jiffies, timeout_jiffies))
remaining_jiffies = 0;
else
remaining_jiffies = timeout_jiffies - start_jiffies;
return remaining_jiffies;
}
#endif /* __ETNAVIV_DRV_H__ */
| {
"pile_set_name": "Github"
} |
import FWCore.ParameterSet.Config as cms
process = cms.Process("TEST")
process.MessageLogger=cms.Service("MessageLogger",
destinations=cms.untracked.vstring("cout"),
cout=cms.untracked.PSet(
threshold=cms.untracked.string("INFO")
)
)
process.load("CondCore.DBCommon.CondDBCommon_cfi")
process.CondDBCommon.connect = cms.string('sqlite_file:testExample.db')
process.CondDBCommon.DBParameters.authenticationPath = cms.untracked.string('/afs/cern.ch/cms/DB/conddb')
process.source = cms.Source("EmptyIOVSource",
timetype = cms.string('runnumber'),
firstValue = cms.uint64(1),
lastValue = cms.uint64(1),
interval = cms.uint64(1)
)
process.es_ascii = cms.ESSource("HcalTextCalibrations",
input = cms.VPSet(cms.PSet(
object = cms.string('LongRecoParams'),
file = cms.FileInPath('CondTools/Hcal/test/testdata/LongRecoParams2011-run153943.txt')
))
)
process.PoolDBOutputService = cms.Service("PoolDBOutputService",
process.CondDBCommon,
timetype = cms.untracked.string('runnumber'),
logconnect= cms.untracked.string('sqlite_file:log.db'),
toPut = cms.VPSet(cms.PSet(
record = cms.string('HcalLongRecoParamsRcd'),
tag = cms.string('hcal_longrecoparams_v1.00_test')
))
)
process.mytest = cms.EDAnalyzer("HcalLongRecoParamsPopConAnalyzer",
record = cms.string('HcalLongRecoParamsRcd'),
loggingOn= cms.untracked.bool(True),
SinceAppendMode=cms.bool(True),
Source=cms.PSet(
# firstSince=cms.untracked.double(300)
IOVRun=cms.untracked.uint32(1)
)
)
process.p = cms.Path(process.mytest)
| {
"pile_set_name": "Github"
} |
# Copyright 2019 Google LLC
#
# 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.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Content.V2.Model.OrderAddress do
@moduledoc """
## Attributes
* `country` (*type:* `String.t`, *default:* `nil`) - CLDR country code (e.g. "US").
* `fullAddress` (*type:* `list(String.t)`, *default:* `nil`) - Strings representing the lines of the printed label for mailing the order, for example:
John Smith
1600 Amphitheatre Parkway
Mountain View, CA, 94043
United States
* `isPostOfficeBox` (*type:* `boolean()`, *default:* `nil`) - Whether the address is a post office box.
* `locality` (*type:* `String.t`, *default:* `nil`) - City, town or commune. May also include dependent localities or sublocalities (e.g. neighborhoods or suburbs).
* `postalCode` (*type:* `String.t`, *default:* `nil`) - Postal Code or ZIP (e.g. "94043").
* `recipientName` (*type:* `String.t`, *default:* `nil`) - Name of the recipient.
* `region` (*type:* `String.t`, *default:* `nil`) - Top-level administrative subdivision of the country. For example, a state like California ("CA") or a province like Quebec ("QC").
* `streetAddress` (*type:* `list(String.t)`, *default:* `nil`) - Street-level part of the address.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:country => String.t(),
:fullAddress => list(String.t()),
:isPostOfficeBox => boolean(),
:locality => String.t(),
:postalCode => String.t(),
:recipientName => String.t(),
:region => String.t(),
:streetAddress => list(String.t())
}
field(:country)
field(:fullAddress, type: :list)
field(:isPostOfficeBox)
field(:locality)
field(:postalCode)
field(:recipientName)
field(:region)
field(:streetAddress, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.OrderAddress do
def decode(value, options) do
GoogleApi.Content.V2.Model.OrderAddress.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.OrderAddress do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v3/proto/enums/app_payment_model_type.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='google/ads/googleads_v3/proto/enums/app_payment_model_type.proto',
package='google.ads.googleads.v3.enums',
syntax='proto3',
serialized_options=_b('\n!com.google.ads.googleads.v3.enumsB\030AppPaymentModelTypeProtoP\001ZBgoogle.golang.org/genproto/googleapis/ads/googleads/v3/enums;enums\242\002\003GAA\252\002\035Google.Ads.GoogleAds.V3.Enums\312\002\035Google\\Ads\\GoogleAds\\V3\\Enums\352\002!Google::Ads::GoogleAds::V3::Enums'),
serialized_pb=_b('\n@google/ads/googleads_v3/proto/enums/app_payment_model_type.proto\x12\x1dgoogle.ads.googleads.v3.enums\x1a\x1cgoogle/api/annotations.proto\"X\n\x17\x41ppPaymentModelTypeEnum\"=\n\x13\x41ppPaymentModelType\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0b\n\x07UNKNOWN\x10\x01\x12\x08\n\x04PAID\x10\x1e\x42\xed\x01\n!com.google.ads.googleads.v3.enumsB\x18\x41ppPaymentModelTypeProtoP\x01ZBgoogle.golang.org/genproto/googleapis/ads/googleads/v3/enums;enums\xa2\x02\x03GAA\xaa\x02\x1dGoogle.Ads.GoogleAds.V3.Enums\xca\x02\x1dGoogle\\Ads\\GoogleAds\\V3\\Enums\xea\x02!Google::Ads::GoogleAds::V3::Enumsb\x06proto3')
,
dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,])
_APPPAYMENTMODELTYPEENUM_APPPAYMENTMODELTYPE = _descriptor.EnumDescriptor(
name='AppPaymentModelType',
full_name='google.ads.googleads.v3.enums.AppPaymentModelTypeEnum.AppPaymentModelType',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='UNSPECIFIED', index=0, number=0,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='UNKNOWN', index=1, number=1,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='PAID', index=2, number=30,
serialized_options=None,
type=None),
],
containing_type=None,
serialized_options=None,
serialized_start=156,
serialized_end=217,
)
_sym_db.RegisterEnumDescriptor(_APPPAYMENTMODELTYPEENUM_APPPAYMENTMODELTYPE)
_APPPAYMENTMODELTYPEENUM = _descriptor.Descriptor(
name='AppPaymentModelTypeEnum',
full_name='google.ads.googleads.v3.enums.AppPaymentModelTypeEnum',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
],
extensions=[
],
nested_types=[],
enum_types=[
_APPPAYMENTMODELTYPEENUM_APPPAYMENTMODELTYPE,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=129,
serialized_end=217,
)
_APPPAYMENTMODELTYPEENUM_APPPAYMENTMODELTYPE.containing_type = _APPPAYMENTMODELTYPEENUM
DESCRIPTOR.message_types_by_name['AppPaymentModelTypeEnum'] = _APPPAYMENTMODELTYPEENUM
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
AppPaymentModelTypeEnum = _reflection.GeneratedProtocolMessageType('AppPaymentModelTypeEnum', (_message.Message,), dict(
DESCRIPTOR = _APPPAYMENTMODELTYPEENUM,
__module__ = 'google.ads.googleads_v3.proto.enums.app_payment_model_type_pb2'
,
__doc__ = """Represents a criterion for targeting paid apps.
""",
# @@protoc_insertion_point(class_scope:google.ads.googleads.v3.enums.AppPaymentModelTypeEnum)
))
_sym_db.RegisterMessage(AppPaymentModelTypeEnum)
DESCRIPTOR._options = None
# @@protoc_insertion_point(module_scope)
| {
"pile_set_name": "Github"
} |
/*
** ClanLib SDK
** Copyright (c) 1997-2016 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
*/
#pragma once
// Keyboard & mouse platform independence support.
#if defined(WIN32)
#include <windows.h>
#elif defined(__APPLE__) || defined(__ANDROID__)
// No headers for Apple
#else
#include <X11/keysym.h>
#endif
namespace clan
{
/// \addtogroup clanDisplay_Input clanDisplay Input
/// \{
enum InputCode
{
mouse_left = 0,
mouse_right = 1,
mouse_middle = 2,
mouse_wheel_up = 3,
mouse_wheel_down = 4,
mouse_xbutton1 = 5,
mouse_xbutton2 = 6,
mouse_count = 7,
joystick_x = 0,
joystick_y,
joystick_z,
joystick_rx,
joystick_ry,
joystick_rz,
joystick_slider,
joystick_dial,
joystick_wheel,
joystick_vx,
joystick_vy,
joystick_vz,
joystick_vrx,
joystick_vry,
joystick_vrz,
joystick_vslider0,
joystick_vslider1,
joystick_ax,
joystick_ay,
joystick_az,
joystick_arx,
joystick_ary,
joystick_arz,
joystick_aslider0,
joystick_aslider1,
joystick_fx,
joystick_fy,
joystick_fz,
joystick_frx,
joystick_fry,
joystick_frz,
joystick_fslider0,
joystick_fslider1,
joystick_button = 0, // "id_offset" set
joystick_hat = 0, // "id_offset" set
#if defined(WIN32)
keycode_backspace = VK_BACK,
keycode_tab = VK_TAB,
keycode_clear = VK_CLEAR,
keycode_return = VK_RETURN,
keycode_shift = VK_SHIFT,
keycode_control = VK_CONTROL,
keycode_menu = VK_MENU,
keycode_pause = VK_PAUSE,
keycode_escape = VK_ESCAPE,
#if !defined(__CYGWIN__) && !defined(__MINGW32__)
keycode_kanji = VK_KANJI,
keycode_convert = VK_CONVERT,
keycode_nonconvert = VK_NONCONVERT,
#endif
keycode_space = VK_SPACE,
keycode_prior = VK_PRIOR,
keycode_next = VK_NEXT,
keycode_end = VK_END,
keycode_home = VK_HOME,
keycode_left = VK_LEFT,
keycode_up = VK_UP,
keycode_right = VK_RIGHT,
keycode_down = VK_DOWN,
keycode_select = VK_SELECT,
keycode_print = VK_PRINT,
keycode_execute = VK_EXECUTE,
keycode_insert = VK_INSERT,
keycode_delete = VK_DELETE,
keycode_help = VK_HELP,
keycode_0 = '0',
keycode_1 = '1',
keycode_2 = '2',
keycode_3 = '3',
keycode_4 = '4',
keycode_5 = '5',
keycode_6 = '6',
keycode_7 = '7',
keycode_8 = '8',
keycode_9 = '9',
keycode_a = 'A',
keycode_b = 'B',
keycode_c = 'C',
keycode_d = 'D',
keycode_e = 'E',
keycode_f = 'F',
keycode_g = 'G',
keycode_h = 'H',
keycode_i = 'I',
keycode_j = 'J',
keycode_k = 'K',
keycode_l = 'L',
keycode_m = 'M',
keycode_n = 'N',
keycode_o = 'O',
keycode_p = 'P',
keycode_q = 'Q',
keycode_r = 'R',
keycode_s = 'S',
keycode_t = 'T',
keycode_u = 'U',
keycode_v = 'V',
keycode_w = 'W',
keycode_x = 'X',
keycode_y = 'Y',
keycode_z = 'Z',
keycode_lwin = VK_LWIN,
keycode_rwin = VK_RWIN,
keycode_apps = VK_APPS,
keycode_numpad0 = VK_NUMPAD0,
keycode_numpad1 = VK_NUMPAD1,
keycode_numpad2 = VK_NUMPAD2,
keycode_numpad3 = VK_NUMPAD3,
keycode_numpad4 = VK_NUMPAD4,
keycode_numpad5 = VK_NUMPAD5,
keycode_numpad6 = VK_NUMPAD6,
keycode_numpad7 = VK_NUMPAD7,
keycode_numpad8 = VK_NUMPAD8,
keycode_numpad9 = VK_NUMPAD9,
keycode_numpad_enter = keycode_return,
keycode_multiply = VK_MULTIPLY,
keycode_add = VK_ADD,
keycode_separator = VK_SEPARATOR,
keycode_subtract = VK_SUBTRACT,
keycode_decimal = VK_DECIMAL,
keycode_divide = VK_DIVIDE,
keycode_f1 = VK_F1,
keycode_f2 = VK_F2,
keycode_f3 = VK_F3,
keycode_f4 = VK_F4,
keycode_f5 = VK_F5,
keycode_f6 = VK_F6,
keycode_f7 = VK_F7,
keycode_f8 = VK_F8,
keycode_f9 = VK_F9,
keycode_f10 = VK_F10,
keycode_f11 = VK_F11,
keycode_f12 = VK_F12,
keycode_f13 = VK_F13,
keycode_f14 = VK_F14,
keycode_f15 = VK_F15,
keycode_f16 = VK_F16,
keycode_f17 = VK_F17,
keycode_f18 = VK_F18,
keycode_f19 = VK_F19,
keycode_f20 = VK_F20,
keycode_f21 = VK_F21,
keycode_f22 = VK_F22,
keycode_f23 = VK_F23,
keycode_f24 = VK_F24,
keycode_numlock = VK_NUMLOCK,
keycode_scroll = VK_SCROLL,
keycode_lshift = VK_LSHIFT,
keycode_rshift = VK_RSHIFT,
keycode_lcontrol = VK_LCONTROL,
keycode_rcontrol = VK_RCONTROL,
keycode_lmenu = VK_LMENU,
keycode_rmenu = VK_RMENU,
#elif defined(__APPLE__) || defined(__ANDROID__)
// Seems like this platform dont have keysyms, or their docs suck so much I
// can't find it.
//
// To solve this matter I've made my own virtual key numbering. If a key
// pressed does not match any of these, then it will return the actual
// MacOSX keycode in the high order word (keycode + 0x10000000).
//
// Naturally this require that they dont use keycode values above 0xffff,
// but if they do complain to Apple for their crappy keyboard support.
// Already kinda annoyed that the keys for typing { and } are alt+shift+8 and
// alt+shift+9, plus that backslash is alt+shift+7. How hostile is that!?!?
// Oh well what can you expect from a company that write "Designed by Apple
// in California" with big letters when you open your box that the powerbook
// came in. Yes it shows thats its designed in California!!
//
// (No offence to California though. Been there once and loved the place.)
keycode_backspace=10,
keycode_tab=11,
keycode_clear=12,
keycode_return=13,
keycode_shift=14,
keycode_control=15,
keycode_menu=16,
keycode_pause=17,
keycode_kanji=18,
keycode_escape=19,
keycode_convert=20,
keycode_nonconvert=21,
keycode_space=22,
keycode_prior=23,
keycode_next=24,
keycode_end=25,
keycode_home=26,
keycode_left=27,
keycode_up=28,
keycode_right=29,
keycode_down=30,
keycode_select=31,
keycode_print=32,
keycode_execute=33,
keycode_insert=34,
keycode_delete=35,
keycode_help=36,
keycode_0=37,
keycode_1=38,
keycode_2=39,
keycode_3=40,
keycode_4=41,
keycode_5=42,
keycode_6=43,
keycode_7=44,
keycode_8=45,
keycode_9=46,
keycode_a=47,
keycode_b=48,
keycode_c=49,
keycode_d=50,
keycode_e=51,
keycode_f=52,
keycode_g=53,
keycode_h=54,
keycode_i=55,
keycode_j=56,
keycode_k=57,
keycode_l=58,
keycode_m=59,
keycode_n=60,
keycode_o=61,
keycode_p=62,
keycode_q=63,
keycode_r=64,
keycode_s=65,
keycode_t=66,
keycode_u=67,
keycode_v=68,
keycode_w=69,
keycode_x=70,
keycode_y=71,
keycode_z=72,
keycode_lwin=73,
keycode_rwin=74,
keycode_apps=75,
keycode_numpad0=76,
keycode_numpad1=77,
keycode_numpad2=78,
keycode_numpad3=79,
keycode_numpad4=80,
keycode_numpad5=81,
keycode_numpad6=82,
keycode_numpad7=83,
keycode_numpad8=84,
keycode_numpad9=85,
keycode_numpad_enter=keycode_return,
keycode_multiply=86,
keycode_add=87,
keycode_separator=88,
keycode_subtract=89,
keycode_decimal=90,
keycode_divide=91,
keycode_f1=92,
keycode_f2=93,
keycode_f3=94,
keycode_f4=95,
keycode_f5=96,
keycode_f6=97,
keycode_f7=98,
keycode_f8=99,
keycode_f9=100,
keycode_f10=101,
keycode_f11=102,
keycode_f12=103,
keycode_f13=104,
keycode_f14=105,
keycode_f15=106,
keycode_f16=107,
keycode_f17=108,
keycode_f18=109,
keycode_f19=110,
keycode_f20=111,
keycode_f21=112,
keycode_f22=113,
keycode_f23=114,
keycode_f24=115,
keycode_numlock=116,
keycode_scroll=117,
keycode_lshift=118,
keycode_rshift=119,
keycode_lcontrol=120,
keycode_rcontrol=121,
keycode_lmenu=122,
keycode_rmenu=123,
keycode_count=124,
#else
keycode_backspace=XK_BackSpace,
keycode_tab=XK_Tab,
keycode_clear=XK_Clear,
keycode_return=XK_Return,
keycode_shift=XK_Shift_L,
keycode_control=XK_Control_L,
keycode_menu=XK_Menu, // there is no XK_Alt, only XK_Alt_L and XK_Alt_R. Maybe remove this key? -- mbn 30 sep 2003
keycode_pause=XK_Pause,
keycode_kanji=XK_Kanji,
keycode_escape=XK_Escape,
keycode_convert=XK_Henkan_Mode,
keycode_nonconvert=XK_Muhenkan,
keycode_space=XK_space,
keycode_prior=XK_Prior,
keycode_next=XK_Next,
keycode_end=XK_End,
keycode_home=XK_Home,
keycode_left=XK_Left,
keycode_up=XK_Up,
keycode_right=XK_Right,
keycode_down=XK_Down,
keycode_select=XK_Select,
keycode_print=XK_Print,
keycode_execute=XK_Execute,
keycode_insert=XK_Insert,
keycode_delete=XK_Delete,
keycode_help=XK_Help,
keycode_0=XK_0,
keycode_1=XK_1,
keycode_2=XK_2,
keycode_3=XK_3,
keycode_4=XK_4,
keycode_5=XK_5,
keycode_6=XK_6,
keycode_7=XK_7,
keycode_8=XK_8,
keycode_9=XK_9,
keycode_a=XK_a,
keycode_b=XK_b,
keycode_c=XK_c,
keycode_d=XK_d,
keycode_e=XK_e,
keycode_f=XK_f,
keycode_g=XK_g,
keycode_h=XK_h,
keycode_i=XK_i,
keycode_j=XK_j,
keycode_k=XK_k,
keycode_l=XK_l,
keycode_m=XK_m,
keycode_n=XK_n,
keycode_o=XK_o,
keycode_p=XK_p,
keycode_q=XK_q,
keycode_r=XK_r,
keycode_s=XK_s,
keycode_t=XK_t,
keycode_u=XK_u,
keycode_v=XK_v,
keycode_w=XK_w,
keycode_x=XK_x,
keycode_y=XK_y,
keycode_z=XK_z,
keycode_lwin=XK_Super_L,
keycode_rwin=XK_Multi_key,
keycode_apps=XK_Menu,
keycode_numpad0=XK_KP_0,
keycode_numpad1=XK_KP_1,
keycode_numpad2=XK_KP_2,
keycode_numpad3=XK_KP_3,
keycode_numpad4=XK_KP_4,
keycode_numpad5=XK_KP_5,
keycode_numpad6=XK_KP_6,
keycode_numpad7=XK_KP_7,
keycode_numpad8=XK_KP_8,
keycode_numpad9=XK_KP_9,
keycode_numpad_enter=XK_KP_Enter,
keycode_multiply=XK_KP_Multiply,
keycode_add=XK_KP_Add,
keycode_separator=XK_KP_Separator,
keycode_subtract=XK_KP_Subtract,
keycode_decimal=XK_KP_Decimal,
keycode_divide=XK_KP_Divide,
keycode_f1=XK_F1,
keycode_f2=XK_F2,
keycode_f3=XK_F3,
keycode_f4=XK_F4,
keycode_f5=XK_F5,
keycode_f6=XK_F6,
keycode_f7=XK_F7,
keycode_f8=XK_F8,
keycode_f9=XK_F9,
keycode_f10=XK_F10,
keycode_f11=XK_F11,
keycode_f12=XK_F12,
keycode_f13=XK_F13,
keycode_f14=XK_F14,
keycode_f15=XK_F15,
keycode_f16=XK_F16,
keycode_f17=XK_F17,
keycode_f18=XK_F18,
keycode_f19=XK_F19,
keycode_f20=XK_F20,
keycode_f21=XK_F21,
keycode_f22=XK_F22,
keycode_f23=XK_F23,
keycode_f24=XK_F24,
keycode_numlock=XK_Num_Lock,
keycode_scroll=XK_Scroll_Lock,
keycode_lshift=XK_Shift_L,
keycode_rshift=XK_Shift_R,
keycode_lcontrol=XK_Control_L,
keycode_rcontrol=XK_Control_R,
keycode_lmenu=XK_Meta_L,
keycode_rmenu=XK_Meta_R,
#endif
keycode_enter = keycode_return,
keycode_lapple = keycode_lwin,
keycode_rapple = keycode_rwin,
keycode_unknown = -1
};
/// \}
}
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <MetricKitServices/MXService.h>
@class MXSourceXPCPayload, NSMutableArray, NSObject;
@protocol OS_dispatch_queue, OS_os_log;
@interface MXPowerlogService : MXService
{
NSMutableArray *_powerlogDataPaths;
MXSourceXPCPayload *_unarchivedPowerlogData;
NSObject<OS_os_log> *_MXPowerLogServiceLogHandle;
NSObject<OS_dispatch_queue> *_requestQueue;
}
+ (id)sharedPowerlogService;
- (void).cxx_destruct;
@property(retain, nonatomic) NSObject<OS_dispatch_queue> *requestQueue; // @synthesize requestQueue=_requestQueue;
@property(retain) NSObject<OS_os_log> *MXPowerLogServiceLogHandle; // @synthesize MXPowerLogServiceLogHandle=_MXPowerLogServiceLogHandle;
@property(retain) MXSourceXPCPayload *unarchivedPowerlogData; // @synthesize unarchivedPowerlogData=_unarchivedPowerlogData;
@property(retain) NSMutableArray *powerlogDataPaths; // @synthesize powerlogDataPaths=_powerlogDataPaths;
- (BOOL)metricsAvailableForDate:(id)arg1;
- (id)getMetricsForClient:(id)arg1 dateString:(id)arg2;
- (BOOL)_updateMetrics;
- (BOOL)stopService;
- (BOOL)startService;
- (id)init;
@end
| {
"pile_set_name": "Github"
} |
# Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
#pylint: disable=no-init,invalid-name,too-many-instance-attributes
from mantid.api import *
from mantid.kernel import *
from distutils.version import LooseVersion
import numpy as np
import os
class ExportSampleLogsToCSVFile(PythonAlgorithm):
""" Python algorithm to export sample logs to spread sheet file
for VULCAN
"""
_wksp = None
_outputfilename = None
_sampleloglist = None
_headerconten = None
_writeheader = None
_headercontent = None
_timezone = None
_timeTolerance = None
_maxtimestamp = None
_maxtime = None
_starttime = None
_localtimediff = None
_writeHeaderToSeparateFile = True
_append = False
def __init__(self):
""" Initialization
@return:
"""
PythonAlgorithm.__init__(self)
return
def category(self):
""" Category
"""
return "DataHandling\\Logs"
def seeAlso(self):
return [ "ExportExperimentLog" ]
def name(self):
""" Algorithm name
"""
return "ExportSampleLogsToCSVFile"
def summary(self):
return "Exports sample logs to spreadsheet file."
def PyInit(self):
""" Declare properties
"""
# Input workspace
self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input),
"Name of data workspace containing sample logs to be exported. ")
# Output file name
self.declareProperty(FileProperty("OutputFilename", "", FileAction.Save, [".txt"]),
"Name of the output sample environment log file name.")
# Sample log names
self.declareProperty(StringArrayProperty("SampleLogNames", values=[], direction=Direction.Input),
"Names of sample logs to be exported in a same file.")
# Header
self.declareProperty("WriteHeaderFile", False, "Flag to generate a sample log header file.")
self.declareProperty("Header", "", "String in the header file.")
self.declareProperty('DateTitleInHeader', True,
'If true, then the first 2 lines of header will be experiment date and title.'
'Otherwise, there will be only 1 line in header.')
self.declareProperty('SeparateHeaderFile', True,
'If true, then the header is written to another file.'
'Otherwise, header will be in the same output file.')
# Time zone
timezones = ["UTC", "America/New_York", "Asia/Shanghai", "Australia/Sydney", "Europe/London",
"GMT+0", "Europe/Paris", "Europe/Copenhagen"]
description = "Sample logs recorded in NeXus files (in SNS) are in UTC time. " \
"TimeZone can allow the algorithm to output the log with local time."
self.declareProperty("TimeZone", "America/New_York", StringListValidator(timezones), description)
# Log time tolerance
self.declareProperty("TimeTolerance", 0.01,
"If any 2 log entries with log times within the time tolerance, "
+ "they will be recorded in one line. Unit is second. ")
return
def PyExec(self):
""" Main executor
"""
# Read inputs
self._getProperties()
# Write header file as an option
if self._writeheader is True:
# check
assert self._wksp is not None
# get date and description to write
if self.getProperty('DateTitleInHeader').value:
testdatetime = self._wksp.getRun().getProperty("run_start").value
description = self._wksp.getTitle()
else:
testdatetime = None
description = None
self._writeHeaderFile(testdatetime, description)
# Read in logs
logtimesdict, logvaluedict, loglength = self._readSampleLogs()
# Local time difference
localtimediff = self._calTimeOffset(logtimesdict, loglength)
# Write log file
logtimeslist = []
logvaluelist = []
for logname in self._sampleloglist:
logtimeslist.append(logtimesdict[logname])
logvaluelist.append(logvaluedict[logname])
self._writeAscynLogFile(logtimeslist, logvaluelist, localtimediff, self._timeTolerance)
return
def _getProperties(self):
""" Get and process properties
"""
self._wksp = self.getProperty("InputWorkspace").value
self._outputfilename = self.getProperty("OutputFilename").value
filedir = os.path.split(self._outputfilename)[0]
if os.path.exists(filedir) is False:
raise NotImplementedError("Directory %s does not exist. File cannot be written." % (filedir))
self._sampleloglist = self.getProperty("SampleLogNames").value
if len(self._sampleloglist) == 0:
raise NotImplementedError("Sample logs names cannot be empty.")
self._writeheader = self.getProperty("WriteHeaderFile").value
self._headercontent = self.getProperty("Header").value
if self._writeheader is True and len(self._headercontent.strip()) == 0:
self.log().warning("Header is empty. Thus WriteHeaderFile is forced to be False.")
self._writeheader = False
self._timezone = self.getProperty("TimeZone").value
self._timeTolerance = self.getProperty("TimeTolerance").value
if (self._timeTolerance) <= 0.:
raise NotImplementedError("TimeTolerance must be larger than zero.")
self._timeTolerance = np.timedelta64(int(self._timeTolerance*1e9), 'ns')
# Set the flag to write header to separate file
if self._writeheader is True:
self._writeHeaderToSeparateFile = self.getProperty('SeparateHeaderFile').value
else:
self._writeHeaderToSeparateFile = False
return
def _calTimeOffset(self, logtimesdict, loglength):
""" Calcualte the time epoch in local time
"""
# Find out local time
if loglength > 0:
# Locate time0
for key in logtimesdict.keys():
times = logtimesdict[key]
if times is not None:
time0 = logtimesdict[key][0]
break
# Local time difference
localtimediff = getLocalTimeShiftInSecond(time0, self._timezone, self.log())
else:
localtimediff = np.timedelta64(0, 's')
epoch = '1990-01-01T00:00'
# older numpy assumes local timezone
if LooseVersion(np.__version__) < LooseVersion('1.9'):
epoch = epoch+'Z'
return np.datetime64(epoch) + localtimediff
def _getLogsInfo(self, logtimeslist):
""" Get maximum number of lines, staring time and ending time in the output log file
"""
maxnumlines = 0
first = True
for logtimes in logtimeslist:
# skip NONE
if logtimes is None:
continue
# count on lines
tmplines = len(logtimes)
maxnumlines += tmplines
# start and max time
tmpstarttime = logtimes[0]
tmpmaxtime = logtimes[-1]
if first is True:
starttime = tmpstarttime
maxtime = tmpmaxtime
first = False
else:
if tmpmaxtime > maxtime:
maxtime = tmpmaxtime
if tmpstarttime < starttime:
starttime = tmpstarttime
# ENDIFELSE
return maxnumlines, starttime, maxtime
def _writeAscynLogFile(self, logtimeslist, logvaluelist, localtimediff, timetol):
"""
Logs are recorded upon the change of the data
time tolerance : two log entries within time tolerance will be recorded as one
@param logtimeslist:
@param logvaluelist:
@param localtimediff:
@param timetol: tolerance of time (in second)
@return:
"""
# Check input
if logtimeslist.__class__.__name__ != "list":
raise NotImplementedError("Input log times is not list")
if logvaluelist.__class__.__name__ != "list":
raise NotImplementedError("Input log value is not list")
wbuf = ""
currtimeindexes = []
for dummy_i in range(len(logtimeslist)):
currtimeindexes.append(0)
nextlogindexes = []
continuewrite = True
linecount = 0
maxcount, mintime, maxtime = self._getLogsInfo(logtimeslist)
self._maxtimestamp = maxcount
self._maxtime = maxtime
self._starttime = mintime
self._localtimediff = localtimediff
while continuewrite:
self._findNextTimeStamps(logtimeslist, currtimeindexes, timetol, nextlogindexes)
self.log().debug("Next time stamp log indexes: %s" % (str(nextlogindexes)))
if len(nextlogindexes) == 0:
# No new indexes that can be found
continuewrite = False
else:
#
templine = self._writeNewLine(logtimeslist, logvaluelist, currtimeindexes, nextlogindexes)
self.log().debug("Write new line %d: %s" % (linecount, templine))
self._progressTimeIndexes(currtimeindexes, nextlogindexes)
wbuf += templine + "\n"
linecount += 1
# ENDIF
if linecount > maxcount:
raise NotImplementedError("Logic error.")
# ENDWHILE
# Remove last "\n"
if wbuf[-1] == "\n":
wbuf = wbuf[:-1]
try:
if self._append is True:
log_file = open(self._outputfilename, 'a')
else:
log_file = open(self._outputfilename, "w")
log_file.write(wbuf)
log_file.close()
except IOError:
raise NotImplementedError("Unable to write file %s. Check permission." % (self._outputfilename))
return
def _findNextTimeStamps(self, logtimeslist, currtimeindexes, timetol, nexttimelogindexes):
"""
Find next time stamp among all logs
@param logtimeslist:
@param currtimeindexes:
@param timetol:
@param nexttimelogindexes: (output) indexes of logs for next time stamp
@return:
"""
# clear output
nexttimelogindexes[:] = []
# Initialize
nexttime = self._maxtime
for i in range(0, len(logtimeslist)):
# skip the None log
if logtimeslist[i] is None:
continue
timeindex = currtimeindexes[i]
if timeindex >= len(logtimeslist[i]):
# skip as out of boundary of log
continue
tmptime = logtimeslist[i][timeindex]
self.log().debug("tmptime type = %s " % ( type(tmptime)))
# difftime = calTimeDiff(tmptime, nexttime)
difftime = (tmptime - nexttime)
if abs(difftime) < timetol:
# same ...
nexttimelogindexes.append(i)
elif difftime/np.timedelta64(1, 's') < 0:
# new smaller time
nexttime = tmptime
nexttimelogindexes[:] = []
nexttimelogindexes.append(i)
# ENDIF
# ENDIF
return
def _writeNewLine(self, logtimeslist, logvaluelist, currtimeindexes, nexttimelogindexes):
""" Write a new line
"""
# Check
if len(nexttimelogindexes) == 0:
raise NotImplementedError("Logic error")
# Log time
# self.log().information("logtimelist of type %s." % (type(logtimeslist)))
#logtime = logtimeslist[currtimeindexes[nexttimelogindexes[0]]]
logindex = nexttimelogindexes[0]
logtimes = logtimeslist[logindex]
thislogtime = logtimes[currtimeindexes[logindex]]
abstime = (thislogtime - self._localtimediff) / np.timedelta64(1, 's') # time from epoch in seconds
reltime = (thislogtime - self._starttime) / np.timedelta64(1, 's') # time from start of run in seconds
wbuf = "%.6f\t%.6f\t" % (abstime, reltime)
# Log valuess
for i in range(len(logvaluelist)):
timeindex = currtimeindexes[i]
if i not in nexttimelogindexes:
timeindex -= 1
if timeindex < 0:
timeindex = 0
if logvaluelist[i] is None:
logvalue = 0.
else:
logvalue = logvaluelist[i][timeindex]
# FIXME - This case is not considered yet
# if logvaluedict[samplelog] is not None:
# logvalue = logvaluedict[samplelog][i]
# else:
# logvalue = 0.
wbuf += "%.6f\t" % (logvalue)
# ENDFOR
return wbuf
def _progressTimeIndexes(self, currtimeindexes, nexttimelogindexes):
""" Progress index
"""
for i in range(len(currtimeindexes)):
if i in nexttimelogindexes:
currtimeindexes[i] += 1
return
def _readSampleLogs(self):
""" Read sample logs
"""
import sys
# Get all properties' times and value and check whether all the logs are in workspaces
samplerun = self._wksp.getRun()
logtimesdict = {}
logvaluedict = {}
for samplename in self._sampleloglist:
# Check existence
logexist = samplerun.hasProperty(samplename)
if logexist is True:
# Get hold of sample values
p = samplerun.getProperty(samplename)
logtimesdict[samplename] = p.times
logvaluedict[samplename] = p.value
else:
# Add None
self.log().warning("Sample log %s does not exist. " % (samplename))
logtimesdict[samplename] = None
logvaluedict[samplename] = None
# ENDIF
# ENDFOR
# Check properties' size
loglength = sys.maxsize
for i in range(len(self._sampleloglist)):
if logtimesdict[self._sampleloglist[i]] is not None:
tmplength = len(logtimesdict[self._sampleloglist[i]])
if loglength != tmplength:
if loglength != sys.maxsize:
self.log().warning("Log %s has different length from previous ones. " % (self._sampleloglist[i]))
loglength = min(loglength, tmplength)
# ENDIF
# ENDIF
# ENDFOR
if loglength == sys.maxsize:
self.log().warning("None of given log names is found in workspace. ")
loglength = 0
else:
self.log().information("Final Log length = %d" % (loglength))
return logtimesdict, logvaluedict, loglength
def _writeHeaderFile(self, test_datetime, description):
"""
Write the header file for a LoadFrame
Requirements: test_datetime and description are either None or string
@param test_datetime:
@param description:
@return:
"""
if test_datetime is None or description is None:
line0 = ''
line1 = ''
else:
# Construct 3 lines of the header file
testdatetime_mk = DateAndTime(test_datetime)
line0 = 'Test date: %s (%.6f) Time Zone: %s\n' % (str(test_datetime),
float(testdatetime_mk.totalNanoseconds()) / 1.0E9,
self._timezone)
line1 = 'Test description: %s\n' % description
# END-IF-ELSE
line2 = self._headercontent
# Write file
wbuf = line0 + line1 + line2 + '\n'
filepath = os.path.dirname(self._outputfilename)
basename = os.path.basename(self._outputfilename)
if self._writeHeaderToSeparateFile is True:
baseheadername = basename.split(".txt")[0] + "_header.txt"
headerfilename = os.path.join(filepath, baseheadername)
else:
headerfilename = self._outputfilename
self._append = True
self.log().information("Writing header file %s ... " % (headerfilename))
try:
ofile = open(headerfilename, "w")
ofile.write(wbuf)
ofile.close()
except OSError as err:
self.log().error(str(err))
return
def getLocalTimeShiftInSecond(utctime, localtimezone, currentlogger = None):
""" Calculate the difference between UTC time and local time of given
DataAndTime
"""
from datetime import datetime
from dateutil import tz
if currentlogger:
currentlogger.information("Input UTC time = %s" % (str(utctime)))
# Return early if local time zone is UTC
if localtimezone == "UTC":
return 0
# Find out difference in time zone
from_zone = tz.gettz('UTC')
to_zone = tz.gettz(localtimezone)
t1str = (str(utctime)).split('.')[0].strip()
if currentlogger:
currentlogger.information("About to convert time string: %s" % t1str)
try:
if t1str.count("T") == 1:
utc = datetime.strptime(t1str, '%Y-%m-%dT%H:%M:%S')
else:
utc = datetime.strptime(t1str, '%Y-%m-%d %H:%M:%S')
except ValueError as err:
raise err
utc = utc.replace(tzinfo=from_zone)
sns = utc.astimezone(to_zone)
newsns = sns.replace(tzinfo=None)
newutc = utc.replace(tzinfo=None)
shift = newutc-newsns
return np.timedelta64(shift.seconds, 's')
# Register algorithm with Mantid
AlgorithmFactory.subscribe(ExportSampleLogsToCSVFile)
| {
"pile_set_name": "Github"
} |
function validateBillingInfo() {
console.log("Validating billing info...");
}
export function processPayment(){
console.log("processing payment...");
} | {
"pile_set_name": "Github"
} |
{
"created_at": "2015-02-27T22:28:30.212529",
"description": "Go library to collect and emit metric and logging data from CF components.",
"fork": false,
"full_name": "cloudfoundry/dropsonde",
"language": "Go",
"updated_at": "2015-02-28T08:41:15.635911"
} | {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/>
* Copyright (C) 2009-2011 MaNGOSZero <https://github.com/mangos/zero>
* Copyright (C) 2011-2016 Nostalrius <https://nostalrius.org>
* Copyright (C) 2016-2017 Elysium Project <https://github.com/elysium-project>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef MANGOSSERVER_QUEST_H
#define MANGOSSERVER_QUEST_H
#include "Platform/Define.h"
#include "Database/DatabaseEnv.h"
#include <string>
#include <vector>
class Player;
class ObjectMgr;
#define MAX_QUEST_LOG_SIZE 20
#define QUEST_OBJECTIVES_COUNT 4
#define QUEST_ITEM_OBJECTIVES_COUNT QUEST_OBJECTIVES_COUNT
#define QUEST_SOURCE_ITEM_IDS_COUNT 4
#define QUEST_REWARD_CHOICES_COUNT 6
#define QUEST_REWARDS_COUNT 4
#define QUEST_DEPLINK_COUNT 10
#define QUEST_REPUTATIONS_COUNT 5
#define QUEST_EMOTE_COUNT 4
enum QuestFailedReasons
{
INVALIDREASON_DONT_HAVE_REQ = 0, // this is default case
INVALIDREASON_QUEST_FAILED_LOW_LEVEL = 1, // You are not high enough level for that quest.
INVALIDREASON_QUEST_FAILED_REQS = 2, // You don't meet the requirements for that quest.
INVALIDREASON_QUEST_FAILED_INVENTORY_FULL = 4, // Inventory is full. (Also 50. From SMSG_QUESTGIVER_QUEST_FAILED)
INVALIDREASON_QUEST_FAILED_WRONG_RACE = 6, // That quest is not available to your race.
INVALIDREASON_QUEST_ONLY_ONE_TIMED = 12, // You can only be on one timed quest at a time.
INVALIDREASON_QUEST_ALREADY_ON = 13, // You are already on that quest
INVALIDREASON_QUEST_FAILED_DUPLICATE_ITEM = 17, // Duplicate item found. (From SMSG_QUESTGIVER_QUEST_FAILED)
INVALIDREASON_QUEST_FAILED_MISSING_ITEMS = 20, // You don't have the required items with you. Check storage.
INVALIDREASON_QUEST_FAILED_NOT_ENOUGH_MONEY = 22 // You don't have enough money for that quest.
// INVALIDREASON_QUEST_FAILED_REQS = 3,4,5,7-11,14-19,21
};
enum QuestShareMessages
{
QUEST_PARTY_MSG_SHARING_QUEST = 0, // ERR_QUEST_PUSH_SUCCESS_S
QUEST_PARTY_MSG_CANT_TAKE_QUEST = 1, // ERR_QUEST_PUSH_INVALID_S
QUEST_PARTY_MSG_ACCEPT_QUEST = 2, // ERR_QUEST_PUSH_ACCEPTED_S
QUEST_PARTY_MSG_DECLINE_QUEST = 3, // ERR_QUEST_PUSH_DECLINED_S
QUEST_PARTY_MSG_TOO_FAR = 4, // removed in 3.x
QUEST_PARTY_MSG_BUSY = 5, // ERR_QUEST_PUSH_BUSY_S
QUEST_PARTY_MSG_LOG_FULL = 6, // ERR_QUEST_PUSH_LOG_FULL_S
QUEST_PARTY_MSG_HAVE_QUEST = 7, // ERR_QUEST_PUSH_ONQUEST_S
QUEST_PARTY_MSG_FINISH_QUEST = 8, // ERR_QUEST_PUSH_ALREADY_DONE_S
};
enum __QuestTradeSkill
{
QUEST_TRSKILL_NONE = 0,
QUEST_TRSKILL_ALCHEMY = 1,
QUEST_TRSKILL_BLACKSMITHING = 2,
QUEST_TRSKILL_COOKING = 3,
QUEST_TRSKILL_ENCHANTING = 4,
QUEST_TRSKILL_ENGINEERING = 5,
QUEST_TRSKILL_FIRSTAID = 6,
QUEST_TRSKILL_HERBALISM = 7,
QUEST_TRSKILL_LEATHERWORKING = 8,
QUEST_TRSKILL_POISONS = 9,
QUEST_TRSKILL_TAILORING = 10,
QUEST_TRSKILL_MINING = 11,
QUEST_TRSKILL_FISHING = 12,
QUEST_TRSKILL_SKINNING = 13,
};
enum QuestStatus
{
QUEST_STATUS_NONE = 0,
QUEST_STATUS_COMPLETE = 1,
QUEST_STATUS_UNAVAILABLE = 2,
QUEST_STATUS_INCOMPLETE = 3,
QUEST_STATUS_AVAILABLE = 4, // unused in fact
QUEST_STATUS_FAILED = 5,
MAX_QUEST_STATUS
};
inline char const* QuestStatusToString(QuestStatus status)
{
switch (status)
{
case QUEST_STATUS_NONE: return "NONE";
case QUEST_STATUS_COMPLETE: return "COMPLETE";
case QUEST_STATUS_UNAVAILABLE: return "UNAVAILABLE";
case QUEST_STATUS_INCOMPLETE: return "INCOMPLETE";
case QUEST_STATUS_AVAILABLE: return "AVAILABLE";
case QUEST_STATUS_FAILED: return "FAILED";
default: break;
}
return "UNKNOWN";
}
enum __QuestGiverStatus
{
DIALOG_STATUS_NONE = 0,
DIALOG_STATUS_UNAVAILABLE = 1,
DIALOG_STATUS_CHAT = 2,
DIALOG_STATUS_INCOMPLETE = 3,
DIALOG_STATUS_REWARD_REP = 4,
DIALOG_STATUS_AVAILABLE = 5,
DIALOG_STATUS_REWARD_OLD = 6, // red dot on minimap
DIALOG_STATUS_REWARD2 = 7, // yellow dot on minimap
// [-ZERO] tbc? DIALOG_STATUS_REWARD = 8 // yellow dot on minimap
DIALOG_STATUS_UNDEFINED = 100 // Used as result for unassigned ScriptCall
};
// values based at QuestInfo.dbc
enum QuestTypes
{
QUEST_TYPE_ELITE = 1,
QUEST_TYPE_LIFE = 21,
QUEST_TYPE_PVP = 41,
QUEST_TYPE_RAID = 62,
QUEST_TYPE_DUNGEON = 81,
//tbc?
QUEST_TYPE_WORLD_EVENT = 82,
QUEST_TYPE_LEGENDARY = 83,
QUEST_TYPE_ESCORT = 84,
};
enum QuestFlags
{
// Flags used at server and sent to client
QUEST_FLAGS_NONE = 0x00000000,
QUEST_FLAGS_STAY_ALIVE = 0x00000001, // Not used currently
QUEST_FLAGS_PARTY_ACCEPT = 0x00000002, // If player in party, all players that can accept this quest will receive confirmation box to accept quest CMSG_QUEST_CONFIRM_ACCEPT/SMSG_QUEST_CONFIRM_ACCEPT
QUEST_FLAGS_EXPLORATION = 0x00000004, // Not used currently
QUEST_FLAGS_SHARABLE = 0x00000008, // Can be shared: Player::CanShareQuest()
//QUEST_FLAGS_NONE2 = 0x00000010, // Not used currently
QUEST_FLAGS_EPIC = 0x00000020, // Not used currently: Unsure of content
QUEST_FLAGS_RAID = 0x00000040, // Not used currently
QUEST_FLAGS_UNK2 = 0x00000100, // Not used currently: _DELIVER_MORE Quest needs more than normal _q-item_ drops from mobs
QUEST_FLAGS_HIDDEN_REWARDS = 0x00000200, // Items and money rewarded only sent in SMSG_QUESTGIVER_OFFER_REWARD (not in SMSG_QUESTGIVER_QUEST_DETAILS or in client quest log(SMSG_QUEST_QUERY_RESPONSE))
QUEST_FLAGS_AUTO_REWARDED = 0x00000400, // These quests are automatically rewarded on quest complete and they will never appear in quest log client side.
};
enum QuestSpecialFlags
{
// Mangos flags for set SpecialFlags in DB if required but used only at server
QUEST_SPECIAL_FLAG_REPEATABLE = 0x001, // |1 in SpecialFlags from DB
QUEST_SPECIAL_FLAG_EXPLORATION_OR_EVENT = 0x002, // |2 in SpecialFlags from DB (if required area explore, spell SPELL_EFFECT_QUEST_COMPLETE casting, table `*_script` command SCRIPT_COMMAND_QUEST_EXPLORED use, set from script DLL)
// reserved for future versions 0x004, // |4 in SpecialFlags.
// Mangos flags for internal use only
QUEST_SPECIAL_FLAG_DELIVER = 0x008, // Internal flag computed only
QUEST_SPECIAL_FLAG_SPEAKTO = 0x010, // Internal flag computed only
QUEST_SPECIAL_FLAG_KILL_OR_CAST = 0x020, // Internal flag computed only
QUEST_SPECIAL_FLAG_TIMED = 0x040, // Internal flag computed only
};
enum QuestMethod
{
QUEST_METHOD_AUTOCOMPLETE = 0x0,
QUEST_METHOD_DISABLED = 0x1,
QUEST_METHOD_DELIVER = 0x2,
QUEST_METHOD_LIMIT = 0x3, // Highest Method entry DB should have
};
#define QUEST_SPECIAL_FLAG_DB_ALLOWED (QUEST_SPECIAL_FLAG_REPEATABLE | QUEST_SPECIAL_FLAG_EXPLORATION_OR_EVENT)
struct QuestLocale
{
QuestLocale() { ObjectiveText.resize(QUEST_OBJECTIVES_COUNT); }
std::vector<std::string> Title;
std::vector<std::string> Details;
std::vector<std::string> Objectives;
std::vector<std::string> OfferRewardText;
std::vector<std::string> RequestItemsText;
std::vector<std::string> EndText;
std::vector< std::vector<std::string> > ObjectiveText;
};
// This Quest class provides a convenient way to access a few pretotaled (cached) quest details,
// all base quest information, and any utility functions such as generating the amount of
// xp to give
class Quest
{
friend class ObjectMgr;
public:
Quest(Field* questRecord);
uint32 XPValue(Player* pPlayer) const;
uint32 GetQuestFlags() const { return m_QuestFlags; }
bool HasQuestFlag(QuestFlags flag) const { return (m_QuestFlags & flag) != 0; }
bool HasSpecialFlag(QuestSpecialFlags flag) const { return (m_SpecialFlags & flag) != 0; }
void SetSpecialFlag(QuestSpecialFlags flag) { m_SpecialFlags |= flag; }
// table data accessors:
uint32 GetQuestId() const { return QuestId; }
uint32 GetQuestMethod() const { return QuestMethod; }
int32 GetZoneOrSort() const { return ZoneOrSort; }
uint32 GetMinLevel() const { return MinLevel; }
uint32 GetMaxLevel() const { return MaxLevel; }
uint32 GetQuestLevel() const { return QuestLevel; }
uint32 GetType() const { return Type; }
uint32 GetRequiredClasses() const { return RequiredClasses; }
uint32 GetRequiredRaces() const { return RequiredRaces; }
uint32 GetRequiredSkill() const { return RequiredSkill; }
uint32 GetRequiredSkillValue() const { return RequiredSkillValue; }
uint32 GetRequiredCondition() const { return RequiredCondition; }
uint32 GetRepObjectiveFaction() const { return RepObjectiveFaction; }
int32 GetRepObjectiveValue() const { return RepObjectiveValue; }
uint32 GetRequiredMinRepFaction() const { return RequiredMinRepFaction; }
int32 GetRequiredMinRepValue() const { return RequiredMinRepValue; }
uint32 GetRequiredMaxRepFaction() const { return RequiredMaxRepFaction; }
int32 GetRequiredMaxRepValue() const { return RequiredMaxRepValue; }
uint32 GetSuggestedPlayers() const { return SuggestedPlayers; }
uint32 GetLimitTime() const { return LimitTime; }
int32 GetPrevQuestId() const { return PrevQuestId; }
int32 GetNextQuestId() const { return NextQuestId; }
int32 GetExclusiveGroup() const { return ExclusiveGroup; }
uint32 GetNextQuestInChain() const { return NextQuestInChain; }
// [-ZERO] not exist
uint32 GetSrcItemId() const { return SrcItemId; }
uint32 GetSrcItemCount() const { return SrcItemCount; }
uint32 GetSrcSpell() const { return SrcSpell; }
std::string GetTitle() const { return Title; }
std::string GetDetails() const { return Details; }
std::string GetObjectives() const { return Objectives; }
std::string GetOfferRewardText() const { return OfferRewardText; }
std::string GetRequestItemsText() const { return RequestItemsText; }
std::string GetEndText() const { return EndText; }
int32 GetRewOrReqMoney() const;
uint32 GetRewMoneyMaxLevel() const { return RewMoneyMaxLevel; }
int32 GetRewMoneyMaxLevelAtComplete() const;
uint32 GetRewXP() const { return RewXP; }
// use in XP calculation at client
uint32 GetRewSpell() const { return RewSpell; }
uint32 GetRewSpellCast() const { return RewSpellCast; }
int32 GetRewMailTemplateId() const { return RewMailTemplateId; }
uint32 GetRewMailDelaySecs() const { return RewMailDelaySecs; }
uint32 GetRewMailMoney() const { return RewMailMoney; }
uint32 GetPointMapId() const { return PointMapId; }
float GetPointX() const { return PointX; }
float GetPointY() const { return PointY; }
uint32 GetPointOpt() const { return PointOpt; }
uint32 GetIncompleteEmote() const { return IncompleteEmote; }
uint32 GetCompleteEmote() const { return CompleteEmote; }
uint32 GetQuestStartScript() const { return QuestStartScript; }
uint32 GetQuestCompleteScript() const { return QuestCompleteScript; }
bool IsRepeatable() const { return m_SpecialFlags & QUEST_SPECIAL_FLAG_REPEATABLE; }
bool IsAutoComplete() const { return QuestMethod ? false : true; }
bool IsAllowedInRaid() const;
// quest can be fully deactivated and will not be available for any player
void SetQuestActiveState(bool state) { m_isActive = state; }
bool IsActive() const { return m_isActive; }
// multiple values
std::string ObjectiveText[QUEST_OBJECTIVES_COUNT];
uint32 ReqItemId[QUEST_ITEM_OBJECTIVES_COUNT];
uint32 ReqItemCount[QUEST_ITEM_OBJECTIVES_COUNT];
uint32 ReqSourceId[QUEST_SOURCE_ITEM_IDS_COUNT];
uint32 ReqSourceCount[QUEST_SOURCE_ITEM_IDS_COUNT];
int32 ReqCreatureOrGOId[QUEST_OBJECTIVES_COUNT]; // >0 Creature <0 Gameobject
uint32 ReqCreatureOrGOCount[QUEST_OBJECTIVES_COUNT];
uint32 ReqSpell[QUEST_OBJECTIVES_COUNT];
uint32 RewChoiceItemId[QUEST_REWARD_CHOICES_COUNT];
uint32 RewChoiceItemCount[QUEST_REWARD_CHOICES_COUNT];
uint32 RewItemId[QUEST_REWARDS_COUNT];
uint32 RewItemCount[QUEST_REWARDS_COUNT];
uint32 RewRepFaction[QUEST_REPUTATIONS_COUNT];
int32 RewRepValue[QUEST_REPUTATIONS_COUNT];
uint32 DetailsEmote[QUEST_EMOTE_COUNT];
uint32 DetailsEmoteDelay[QUEST_EMOTE_COUNT];
uint32 OfferRewardEmote[QUEST_EMOTE_COUNT];
uint32 OfferRewardEmoteDelay[QUEST_EMOTE_COUNT];
uint32 GetReqItemsCount() const { return m_reqitemscount; }
uint32 GetReqCreatureOrGOcount() const { return m_reqCreatureOrGOcount; }
uint32 GetRewChoiceItemsCount() const { return m_rewchoiceitemscount; }
uint32 GetRewItemsCount() const { return m_rewitemscount; }
typedef std::vector<int32> PrevQuests;
PrevQuests prevQuests;
typedef std::vector<uint32> PrevChainQuests;
PrevChainQuests prevChainQuests;
// cached data
private:
uint32 m_reqitemscount;
uint32 m_reqCreatureOrGOcount;
uint32 m_rewchoiceitemscount;
uint32 m_rewitemscount;
bool m_isActive;
// table data
protected:
uint32 QuestId;
uint32 QuestMethod;
int32 ZoneOrSort;
uint32 MinLevel;
uint32 MaxLevel;
uint32 QuestLevel;
uint32 Type;
uint32 RequiredClasses;
uint32 RequiredRaces;
uint32 RequiredSkill;
uint32 RequiredSkillValue;
uint32 RequiredCondition;
uint32 RepObjectiveFaction;
int32 RepObjectiveValue;
uint32 RequiredMinRepFaction;
int32 RequiredMinRepValue;
uint32 RequiredMaxRepFaction;
int32 RequiredMaxRepValue;
uint32 SuggestedPlayers;
uint32 LimitTime;
uint32 m_QuestFlags;
uint32 m_SpecialFlags;
int32 PrevQuestId;
int32 NextQuestId;
int32 ExclusiveGroup;
uint32 NextQuestInChain;
uint32 SrcItemId;
uint32 SrcItemCount;
uint32 SrcSpell;
std::string Title;
std::string Details;
std::string Objectives;
std::string OfferRewardText;
std::string RequestItemsText;
std::string EndText;
uint32 RewXP;
int32 RewOrReqMoney;
uint32 RewMoneyMaxLevel;
uint32 RewSpell;
uint32 RewSpellCast;
int32 RewMailTemplateId;
uint32 RewMailDelaySecs;
uint32 RewMailMoney;
uint32 PointMapId;
float PointX;
float PointY;
uint32 PointOpt;
uint32 IncompleteEmote;
uint32 CompleteEmote;
uint32 QuestStartScript;
uint32 QuestCompleteScript;
};
enum QuestUpdateState
{
QUEST_UNCHANGED = 0,
QUEST_CHANGED = 1,
QUEST_NEW = 2,
QUEST_DELETED = 3,
};
struct QuestStatusData
{
QuestStatusData()
: m_status(QUEST_STATUS_NONE),m_rewarded(false),
m_explored(false), m_timer(0), uState(QUEST_NEW), m_reward_choice(0)
{
memset(m_itemcount, 0, QUEST_OBJECTIVES_COUNT * sizeof(uint32));
memset(m_creatureOrGOcount, 0, QUEST_OBJECTIVES_COUNT * sizeof(uint32));
}
QuestStatus m_status;
bool m_rewarded;
bool m_explored;
uint32 m_timer;
QuestUpdateState uState;
uint32 m_reward_choice;
uint32 m_itemcount[ QUEST_OBJECTIVES_COUNT ];
uint32 m_creatureOrGOcount[ QUEST_OBJECTIVES_COUNT ];
};
#endif
| {
"pile_set_name": "Github"
} |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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/. */
/* Template-based metaprogramming and type-testing facilities. */
#ifndef mozilla_TypeTraits_h
#define mozilla_TypeTraits_h
/*
* These traits are approximate copies of the traits and semantics from C++11's
* <type_traits> header. Don't add traits not in that header! When all
* platforms provide that header, we can convert all users and remove this one.
*/
#include <wchar.h>
namespace mozilla {
/* Forward declarations. */
template<typename> struct RemoveCV;
/* 20.9.3 Helper classes [meta.help] */
/**
* Helper class used as a base for various type traits, exposed publicly
* because <type_traits> exposes it as well.
*/
template<typename T, T Value>
struct IntegralConstant
{
static const T value = Value;
typedef T ValueType;
typedef IntegralConstant<T, Value> Type;
};
/** Convenient aliases. */
typedef IntegralConstant<bool, true> TrueType;
typedef IntegralConstant<bool, false> FalseType;
/* 20.9.4 Unary type traits [meta.unary] */
/* 20.9.4.1 Primary type categories [meta.unary.cat] */
namespace detail {
template <typename T>
struct IsIntegralHelper : FalseType {};
template<> struct IsIntegralHelper<char> : TrueType {};
template<> struct IsIntegralHelper<signed char> : TrueType {};
template<> struct IsIntegralHelper<unsigned char> : TrueType {};
template<> struct IsIntegralHelper<short> : TrueType {};
template<> struct IsIntegralHelper<unsigned short> : TrueType {};
template<> struct IsIntegralHelper<int> : TrueType {};
template<> struct IsIntegralHelper<unsigned int> : TrueType {};
template<> struct IsIntegralHelper<long> : TrueType {};
template<> struct IsIntegralHelper<unsigned long> : TrueType {};
template<> struct IsIntegralHelper<long long> : TrueType {};
template<> struct IsIntegralHelper<unsigned long long> : TrueType {};
template<> struct IsIntegralHelper<bool> : TrueType {};
template<> struct IsIntegralHelper<wchar_t> : TrueType {};
} /* namespace detail */
/**
* IsIntegral determines whether a type is an integral type.
*
* mozilla::IsIntegral<int>::value is true;
* mozilla::IsIntegral<unsigned short>::value is true;
* mozilla::IsIntegral<const long>::value is true;
* mozilla::IsIntegral<int*>::value is false;
* mozilla::IsIntegral<double>::value is false;
*
* Note that the behavior of IsIntegral on char16_t and char32_t is
* unspecified.
*/
template<typename T>
struct IsIntegral : detail::IsIntegralHelper<typename RemoveCV<T>::Type>
{};
template<typename T, typename U>
struct IsSame;
namespace detail {
template<typename T>
struct IsFloatingPointHelper
: IntegralConstant<bool,
IsSame<T, float>::value ||
IsSame<T, double>::value ||
IsSame<T, long double>::value>
{};
} // namespace detail
/**
* IsFloatingPoint determines whether a type is a floating point type (float,
* double, long double).
*
* mozilla::IsFloatingPoint<int>::value is false;
* mozilla::IsFloatingPoint<const float>::value is true;
* mozilla::IsFloatingPoint<long double>::value is true;
* mozilla::IsFloatingPoint<double*>::value is false.
*/
template<typename T>
struct IsFloatingPoint
: detail::IsFloatingPointHelper<typename RemoveCV<T>::Type>
{};
/**
* IsPointer determines whether a type is a pointer type (but not a pointer-to-
* member type).
*
* mozilla::IsPointer<struct S*>::value is true;
* mozilla::IsPointer<int**>::value is true;
* mozilla::IsPointer<void (*)(void)>::value is true;
* mozilla::IsPointer<int>::value is false;
* mozilla::IsPointer<struct S>::value is false.
*/
template<typename T>
struct IsPointer : FalseType {};
template<typename T>
struct IsPointer<T*> : TrueType {};
namespace detail {
// __is_enum is a supported extension across all of our supported compilers.
template<typename T>
struct IsEnumHelper
: IntegralConstant<bool, __is_enum(T)>
{};
} // namespace detail
/**
* IsEnum determines whether a type is an enum type.
*
* mozilla::IsEnum<enum S>::value is true;
* mozilla::IsEnum<enum S*>::value is false;
* mozilla::IsEnum<int>::value is false;
*/
template<typename T>
struct IsEnum
: detail::IsEnumHelper<typename RemoveCV<T>::Type>
{};
/* 20.9.4.2 Composite type traits [meta.unary.comp] */
/**
* IsArithmetic determines whether a type is arithmetic. A type is arithmetic
* iff it is an integral type or a floating point type.
*
* mozilla::IsArithmetic<int>::value is true;
* mozilla::IsArithmetic<double>::value is true;
* mozilla::IsArithmetic<long double*>::value is false.
*/
template<typename T>
struct IsArithmetic
: IntegralConstant<bool, IsIntegral<T>::value || IsFloatingPoint<T>::value>
{};
/* 20.9.4.3 Type properties [meta.unary.prop] */
/**
* IsConst determines whether a type is const or not.
*
* mozilla::IsConst<int>::value is false;
* mozilla::IsConst<void* const>::value is true;
* mozilla::IsConst<const char*>::value is false.
*/
template<typename T>
struct IsConst : FalseType {};
template<typename T>
struct IsConst<const T> : TrueType {};
/**
* IsVolatile determines whether a type is volatile or not.
*
* mozilla::IsVolatile<int>::value is false;
* mozilla::IsVolatile<void* volatile>::value is true;
* mozilla::IsVolatile<volatile char*>::value is false.
*/
template<typename T>
struct IsVolatile : FalseType {};
template<typename T>
struct IsVolatile<volatile T> : TrueType {};
/**
* Traits class for identifying POD types. Until C++11 there's no automatic
* way to detect PODs, so for the moment this is done manually. Users may
* define specializations of this class that inherit from mozilla::TrueType and
* mozilla::FalseType (or equivalently mozilla::IntegralConstant<bool, true or
* false>, or conveniently from mozilla::IsPod for composite types) as needed to
* ensure correct IsPod behavior.
*/
template<typename T>
struct IsPod : public FalseType {};
template<> struct IsPod<char> : TrueType {};
template<> struct IsPod<signed char> : TrueType {};
template<> struct IsPod<unsigned char> : TrueType {};
template<> struct IsPod<short> : TrueType {};
template<> struct IsPod<unsigned short> : TrueType {};
template<> struct IsPod<int> : TrueType {};
template<> struct IsPod<unsigned int> : TrueType {};
template<> struct IsPod<long> : TrueType {};
template<> struct IsPod<unsigned long> : TrueType {};
template<> struct IsPod<long long> : TrueType {};
template<> struct IsPod<unsigned long long> : TrueType {};
template<> struct IsPod<bool> : TrueType {};
template<> struct IsPod<float> : TrueType {};
template<> struct IsPod<double> : TrueType {};
template<> struct IsPod<wchar_t> : TrueType {};
template<typename T> struct IsPod<T*> : TrueType {};
namespace detail {
template<typename T, bool = IsFloatingPoint<T>::value>
struct IsSignedHelper;
template<typename T>
struct IsSignedHelper<T, true> : TrueType {};
template<typename T>
struct IsSignedHelper<T, false>
: IntegralConstant<bool, IsArithmetic<T>::value && T(-1) < T(1)>
{};
} // namespace detail
/**
* IsSigned determines whether a type is a signed arithmetic type. |char| is
* considered a signed type if it has the same representation as |signed char|.
*
* Don't use this if the type might be user-defined! You might or might not get
* a compile error, depending.
*
* mozilla::IsSigned<int>::value is true;
* mozilla::IsSigned<const unsigned int>::value is false;
* mozilla::IsSigned<unsigned char>::value is false;
* mozilla::IsSigned<float>::value is true.
*/
template<typename T>
struct IsSigned : detail::IsSignedHelper<T> {};
namespace detail {
template<typename T, bool = IsFloatingPoint<T>::value>
struct IsUnsignedHelper;
template<typename T>
struct IsUnsignedHelper<T, true> : FalseType {};
template<typename T>
struct IsUnsignedHelper<T, false>
: IntegralConstant<bool,
IsArithmetic<T>::value &&
(IsSame<typename RemoveCV<T>::Type, bool>::value ||
T(1) < T(-1))>
{};
} // namespace detail
/**
* IsUnsigned determines whether a type is an unsigned arithmetic type.
*
* Don't use this if the type might be user-defined! You might or might not get
* a compile error, depending.
*
* mozilla::IsUnsigned<int>::value is false;
* mozilla::IsUnsigned<const unsigned int>::value is true;
* mozilla::IsUnsigned<unsigned char>::value is true;
* mozilla::IsUnsigned<float>::value is false.
*/
template<typename T>
struct IsUnsigned : detail::IsUnsignedHelper<T> {};
/* 20.9.5 Type property queries [meta.unary.prop.query] */
/* 20.9.6 Relationships between types [meta.rel] */
/**
* IsSame tests whether two types are the same type.
*
* mozilla::IsSame<int, int>::value is true;
* mozilla::IsSame<int*, int*>::value is true;
* mozilla::IsSame<int, unsigned int>::value is false;
* mozilla::IsSame<void, void>::value is true;
* mozilla::IsSame<const int, int>::value is false;
* mozilla::IsSame<struct S, struct S>::value is true.
*/
template<typename T, typename U>
struct IsSame : FalseType {};
template<typename T>
struct IsSame<T, T> : TrueType {};
namespace detail {
// The trickery used to implement IsBaseOf here makes it possible to use it for
// the cases of private and multiple inheritance. This code was inspired by the
// sample code here:
//
// http://stackoverflow.com/questions/2910979/how-is-base-of-works
template<class Base, class Derived>
struct BaseOfHelper
{
public:
operator Base*() const;
operator Derived*();
};
template<class Base, class Derived>
struct BaseOfTester
{
private:
template<class T>
static char test(Derived*, T);
static int test(Base*, int);
public:
static const bool value =
sizeof(test(BaseOfHelper<Base, Derived>(), int())) == sizeof(char);
};
template<class Base, class Derived>
struct BaseOfTester<Base, const Derived>
{
private:
template<class T>
static char test(Derived*, T);
static int test(Base*, int);
public:
static const bool value =
sizeof(test(BaseOfHelper<Base, Derived>(), int())) == sizeof(char);
};
template<class Base, class Derived>
struct BaseOfTester<Base&, Derived&> : FalseType {};
template<class Type>
struct BaseOfTester<Type, Type> : TrueType {};
template<class Type>
struct BaseOfTester<Type, const Type> : TrueType {};
} /* namespace detail */
/*
* IsBaseOf allows to know whether a given class is derived from another.
*
* Consider the following class definitions:
*
* class A {};
* class B : public A {};
* class C {};
*
* mozilla::IsBaseOf<A, B>::value is true;
* mozilla::IsBaseOf<A, C>::value is false;
*/
template<class Base, class Derived>
struct IsBaseOf
: IntegralConstant<bool, detail::BaseOfTester<Base, Derived>::value>
{};
namespace detail {
template<typename From, typename To>
struct ConvertibleTester
{
private:
static From create();
template<typename From1, typename To1>
static char test(To to);
template<typename From1, typename To1>
static int test(...);
public:
static const bool value =
sizeof(test<From, To>(create())) == sizeof(char);
};
} // namespace detail
/**
* IsConvertible determines whether a value of type From will implicitly convert
* to a value of type To. For example:
*
* struct A {};
* struct B : public A {};
* struct C {};
*
* mozilla::IsConvertible<A, A>::value is true;
* mozilla::IsConvertible<A*, A*>::value is true;
* mozilla::IsConvertible<B, A>::value is true;
* mozilla::IsConvertible<B*, A*>::value is true;
* mozilla::IsConvertible<C, A>::value is false;
* mozilla::IsConvertible<A, C>::value is false;
* mozilla::IsConvertible<A*, C*>::value is false;
* mozilla::IsConvertible<C*, A*>::value is false.
*
* For obscure reasons, you can't use IsConvertible when the types being tested
* are related through private inheritance, and you'll get a compile error if
* you try. Just don't do it!
*/
template<typename From, typename To>
struct IsConvertible
: IntegralConstant<bool, detail::ConvertibleTester<From, To>::value>
{};
/* 20.9.7 Transformations between types [meta.trans] */
/* 20.9.7.1 Const-volatile modifications [meta.trans.cv] */
/**
* RemoveConst removes top-level const qualifications on a type.
*
* mozilla::RemoveConst<int>::Type is int;
* mozilla::RemoveConst<const int>::Type is int;
* mozilla::RemoveConst<const int*>::Type is const int*;
* mozilla::RemoveConst<int* const>::Type is int*.
*/
template<typename T>
struct RemoveConst
{
typedef T Type;
};
template<typename T>
struct RemoveConst<const T>
{
typedef T Type;
};
/**
* RemoveVolatile removes top-level volatile qualifications on a type.
*
* mozilla::RemoveVolatile<int>::Type is int;
* mozilla::RemoveVolatile<volatile int>::Type is int;
* mozilla::RemoveVolatile<volatile int*>::Type is volatile int*;
* mozilla::RemoveVolatile<int* volatile>::Type is int*.
*/
template<typename T>
struct RemoveVolatile
{
typedef T Type;
};
template<typename T>
struct RemoveVolatile<volatile T>
{
typedef T Type;
};
/**
* RemoveCV removes top-level const and volatile qualifications on a type.
*
* mozilla::RemoveCV<int>::Type is int;
* mozilla::RemoveCV<const int>::Type is int;
* mozilla::RemoveCV<volatile int>::Type is int;
* mozilla::RemoveCV<int* const volatile>::Type is int*.
*/
template<typename T>
struct RemoveCV
{
typedef typename RemoveConst<typename RemoveVolatile<T>::Type>::Type Type;
};
/* 20.9.7.2 Reference modifications [meta.trans.ref] */
/* 20.9.7.3 Sign modifications [meta.trans.sign] */
template<bool B, typename T = void>
struct EnableIf;
template<bool Condition, typename A, typename B>
struct Conditional;
namespace detail {
template<bool MakeConst, typename T>
struct WithC : Conditional<MakeConst, const T, T>
{};
template<bool MakeVolatile, typename T>
struct WithV : Conditional<MakeVolatile, volatile T, T>
{};
template<bool MakeConst, bool MakeVolatile, typename T>
struct WithCV : WithC<MakeConst, typename WithV<MakeVolatile, T>::Type>
{};
template<typename T>
struct CorrespondingSigned;
template<>
struct CorrespondingSigned<char> { typedef signed char Type; };
template<>
struct CorrespondingSigned<unsigned char> { typedef signed char Type; };
template<>
struct CorrespondingSigned<unsigned short> { typedef short Type; };
template<>
struct CorrespondingSigned<unsigned int> { typedef int Type; };
template<>
struct CorrespondingSigned<unsigned long> { typedef long Type; };
template<>
struct CorrespondingSigned<unsigned long long> { typedef long long Type; };
template<typename T,
typename CVRemoved = typename RemoveCV<T>::Type,
bool IsSignedIntegerType = IsSigned<CVRemoved>::value &&
!IsSame<char, CVRemoved>::value>
struct MakeSigned;
template<typename T, typename CVRemoved>
struct MakeSigned<T, CVRemoved, true>
{
typedef T Type;
};
template<typename T, typename CVRemoved>
struct MakeSigned<T, CVRemoved, false>
: WithCV<IsConst<T>::value, IsVolatile<T>::value,
typename CorrespondingSigned<CVRemoved>::Type>
{};
} // namespace detail
/**
* MakeSigned produces the corresponding signed integer type for a given
* integral type T, with the const/volatile qualifiers of T. T must be a
* possibly-const/volatile-qualified integral type that isn't bool.
*
* If T is already a signed integer type (not including char!), then T is
* produced.
*
* Otherwise, if T is an unsigned integer type, the signed variety of T, with
* T's const/volatile qualifiers, is produced.
*
* Otherwise, the integral type of the same size as T, with the lowest rank,
* with T's const/volatile qualifiers, is produced. (This basically only acts
* to produce signed char when T = char.)
*
* mozilla::MakeSigned<unsigned long>::Type is signed long;
* mozilla::MakeSigned<volatile int>::Type is volatile int;
* mozilla::MakeSigned<const unsigned short>::Type is const signed short;
* mozilla::MakeSigned<const char>::Type is const signed char;
* mozilla::MakeSigned<bool> is an error;
* mozilla::MakeSigned<void*> is an error.
*/
template<typename T>
struct MakeSigned
: EnableIf<IsIntegral<T>::value && !IsSame<bool, typename RemoveCV<T>::Type>::value,
typename detail::MakeSigned<T>
>::Type
{};
namespace detail {
template<typename T>
struct CorrespondingUnsigned;
template<>
struct CorrespondingUnsigned<char> { typedef unsigned char Type; };
template<>
struct CorrespondingUnsigned<signed char> { typedef unsigned char Type; };
template<>
struct CorrespondingUnsigned<short> { typedef unsigned short Type; };
template<>
struct CorrespondingUnsigned<int> { typedef unsigned int Type; };
template<>
struct CorrespondingUnsigned<long> { typedef unsigned long Type; };
template<>
struct CorrespondingUnsigned<long long> { typedef unsigned long long Type; };
template<typename T,
typename CVRemoved = typename RemoveCV<T>::Type,
bool IsUnsignedIntegerType = IsUnsigned<CVRemoved>::value &&
!IsSame<char, CVRemoved>::value>
struct MakeUnsigned;
template<typename T, typename CVRemoved>
struct MakeUnsigned<T, CVRemoved, true>
{
typedef T Type;
};
template<typename T, typename CVRemoved>
struct MakeUnsigned<T, CVRemoved, false>
: WithCV<IsConst<T>::value, IsVolatile<T>::value,
typename CorrespondingUnsigned<CVRemoved>::Type>
{};
} // namespace detail
/**
* MakeUnsigned produces the corresponding unsigned integer type for a given
* integral type T, with the const/volatile qualifiers of T. T must be a
* possibly-const/volatile-qualified integral type that isn't bool.
*
* If T is already an unsigned integer type (not including char!), then T is
* produced.
*
* Otherwise, if T is an signed integer type, the unsigned variety of T, with
* T's const/volatile qualifiers, is produced.
*
* Otherwise, the unsigned integral type of the same size as T, with the lowest
* rank, with T's const/volatile qualifiers, is produced. (This basically only
* acts to produce unsigned char when T = char.)
*
* mozilla::MakeUnsigned<signed long>::Type is unsigned long;
* mozilla::MakeUnsigned<volatile unsigned int>::Type is volatile unsigned int;
* mozilla::MakeUnsigned<const signed short>::Type is const unsigned short;
* mozilla::MakeUnsigned<const char>::Type is const unsigned char;
* mozilla::MakeUnsigned<bool> is an error;
* mozilla::MakeUnsigned<void*> is an error.
*/
template<typename T>
struct MakeUnsigned
: EnableIf<IsIntegral<T>::value && !IsSame<bool, typename RemoveCV<T>::Type>::value,
typename detail::MakeUnsigned<T>
>::Type
{};
/* 20.9.7.4 Array modifications [meta.trans.arr] */
/* 20.9.7.5 Pointer modifications [meta.trans.ptr] */
/* 20.9.7.6 Other transformations [meta.trans.other] */
/**
* EnableIf is a struct containing a typedef of T if and only if B is true.
*
* mozilla::EnableIf<true, int>::Type is int;
* mozilla::EnableIf<false, int>::Type is a compile-time error.
*
* Use this template to implement SFINAE-style (Substitution Failure Is not An
* Error) requirements. For example, you might use it to impose a restriction
* on a template parameter:
*
* template<typename T>
* class PodVector // vector optimized to store POD (memcpy-able) types
* {
* EnableIf<IsPod<T>::value, T>::Type* vector;
* size_t length;
* ...
* };
*/
template<bool B, typename T>
struct EnableIf
{};
template<typename T>
struct EnableIf<true, T>
{
typedef T Type;
};
/**
* Conditional selects a class between two, depending on a given boolean value.
*
* mozilla::Conditional<true, A, B>::Type is A;
* mozilla::Conditional<false, A, B>::Type is B;
*/
template<bool Condition, typename A, typename B>
struct Conditional
{
typedef A Type;
};
template<class A, class B>
struct Conditional<false, A, B>
{
typedef B Type;
};
} /* namespace mozilla */
#endif /* mozilla_TypeTraits_h */
| {
"pile_set_name": "Github"
} |
/* Prompts a person to go to the URL listed to enter the confirmation code that is presented to them above the given string. */
"DeviceLogin.LogInPrompt" = "%@ -এ যান এবং উপরে যে কোডটি দেখানো হয়েছে সেটি লিখুন।";
/* Prompts a person that the next thing they need to do to finish connecting their Smart TV and Facebook application is to navigate to their Facebook application on their mobile device and look through their notifications for a message about the connection being formed */
"DeviceLogin.SmartLogInPrompt" = "আপনার অ্যাকাউন্টে সংযোগ করতে, আপনার মোবাইল ডিভাইসে Facebook অ্যাপটি খুলুন এবং বিজ্ঞপ্তি চেক করুন।";
/* Displayed as a separator between two options. First option is on a line above this, and second option is below */
"DeviceLogin.SmartLogInOrLabel" = "- অথবা -";
/* The title of the label to dismiss the alert when presenting user facing error messages */
"ErrorRecovery.Alert.OK" = "ঠিক আছে";
/* The title of the label to decline attempting error recovery */
"ErrorRecovery.Cancel" = "বাতিল করুন";
/* The fallback message to display to recover invalidated tokens */
"ErrorRecovery.Login.Suggestion" = "আপনার Facebook অ্যাকাউন্টটিতে পুনরায় সংযোগ করার জন্য অনুগ্রহ করে এই অ্যাপটিতে লগ ইন করুন৷";
/* The title of the label to start attempting error recovery */
"ErrorRecovery.OK" = "ঠিক আছে";
/* The fallback message to display to retry transient errors */
"ErrorRecovery.Transient.Suggestion" = "এই সার্ভারটি সাময়িকভাবে ব্যস্ত আছে, অনুগ্রহ করে পুনরায় চেষ্টা করুন৷";
/* The label for the FBSDKLikeButton when the object is not currently liked. */
"LikeButton.Like" = "পছন্দ করুন";
/* The label for the FBSDKLikeButton when the object is currently liked. */
"LikeButton.Liked" = "পছন্দ করা হয়েছে";
/* The label for the FBSDKLoginButton action sheet to cancel logging out */
"LoginButton.CancelLogout" = "বাতিল করুন";
/* The label for the FBSDKLoginButton action sheet to confirm logging out */
"LoginButton.ConfirmLogOut" = "লগ আউট করুন";
/* The fallback string for the FBSDKLoginButton label when the user name is not available yet */
"LoginButton.LoggedIn" = "Facebook ব্যবহার করে লগ ইন করা হয়েছে";
/* The format string for the FBSDKLoginButton label when the user is logged in */
"LoginButton.LoggedInAs" = "%@ হিসাবে লগ ইন করা হয়েছে";
/* The short label for the FBSDKLoginButton when the user is currently logged out */
"LoginButton.LogIn" = "লগ ইন করুন";
/* The long label for the FBSDKLoginButton when the user is currently logged out */
"LoginButton.LogInContinue" = "Facebook এর সাথে চালিয়ে যান";
/* The long label for the FBSDKLoginButton when the user is currently logged out */
"LoginButton.LogInLong" = "Facebook -এর সাথে লগ ইন করুন";
/* The label for the FBSDKLoginButton when the user is currently logged in */
"LoginButton.LogOut" = "লগ আউট করুন";
/* The user facing error message when the app slider has been disabled and login fails. */
"LoginError.SystemAccount.Disabled" = "Facebook অ্যাকাউন্টটিতে অ্যাক্সেস করার অনুমতি নেই৷ ডিভাইস সেটিংস যাচাই করুন৷";
/* The user facing error message when the Accounts framework encounters a network error. */
"LoginError.SystemAccount.Network" = "Facebook-এ সংযোগ করা যাচ্ছে না৷ আপনার নেটওয়ার্ক সংযোগটি পরীক্ষা করুন এবং পুনরায় চেষ্টা করুন৷";
/* The user facing error message when the device Facebook account password is incorrect and login fails. */
"LoginError.SystemAccount.PasswordChange" = "আপনার Facebook পাসওয়ার্ডটি পরিবর্তিত হয়েছে৷ আপনার পাসওয়ার্ডটি নিশ্চিত করতে, সেটিংস > Facebook খুলুন এবং আপনার নামটি ট্যাপ করুন৷";
/* The user facing error message when the device Facebook account is unavailable and login fails. */
"LoginError.SystemAccount.Unavailable" = "Facebook অ্যাকাউন্টটি এই ডিভাইসে কনফিগার করা যাযনি৷";
/* The user facing error message when the Facebook account signed in to the Accounts framework becomes unconfirmed. */
"LoginError.SystemAccount.UnconfirmedUser" = "আপনার অ্যাকাউন্টটি নিশ্চিত করা যায়নি৷ অনুগ্রহ করে www.facebook.com-এ লগ ইন করুন এবং উল্লিখিত নির্দেশাবলী অনুসরণ করুন৷";
/* The user facing error message when the Facebook account signed in to the Accounts framework has been checkpointed. */
"LoginError.SystemAccount.UserCheckpointed" = "এই সময়ে আপনি অ্যাপসে লগ ইন করতে পারবেন না৷ অনুগ্রহ করে www.facebook.com-এ লগ ইন করুন এবং উল্লিখিত নির্দেশাবলী অনুসরণ করুন৷";
/* The message of the FBSDKLoginTooltipView */
"LoginTooltip.Message" = "আপনি নিয়ন্ত্রণে আছেন - অ্যাপ্সের সাথে আপনি যে তথ্য শেয়ার করতে চান তা বাছুন৷";
/* Title of the web dialog that prompts the user to log in to Facebook. */
"LoginWeb.LogInTitle" = "লগ ইন করুন";
/* The label for FBSDKSendButton */
"SendButton.Send" = "পাঠান";
/* The label for FBSDKShareButton */
"ShareButton.Share" = "ভাগ করুন";
/* Prompts a person if this is their current account */
"SmartLogin.NotYou" = "আপনি নন?";
/* Text on a button that a person presses to confirm that they are finished with the login experience */
"SmartLogin.ConfirmationTitle" = "লগ ইন নিশ্চিত করুন";
/* Text on a button that lets a person continue with their name linked to a Facebook account (Name = %@) */
"SmartLogin.Continue" = "%@ হিসেবে চালিয়ে যান";
| {
"pile_set_name": "Github"
} |
// created by cgo -cdefs and then converted to Go
// cgo -cdefs defs_netbsd.go defs_netbsd_386.go
package runtime
const (
_EINTR = 0x4
_EFAULT = 0xe
_PROT_NONE = 0x0
_PROT_READ = 0x1
_PROT_WRITE = 0x2
_PROT_EXEC = 0x4
_MAP_ANON = 0x1000
_MAP_PRIVATE = 0x2
_MAP_FIXED = 0x10
_MADV_FREE = 0x6
_SA_SIGINFO = 0x40
_SA_RESTART = 0x2
_SA_ONSTACK = 0x1
_SIGHUP = 0x1
_SIGINT = 0x2
_SIGQUIT = 0x3
_SIGILL = 0x4
_SIGTRAP = 0x5
_SIGABRT = 0x6
_SIGEMT = 0x7
_SIGFPE = 0x8
_SIGKILL = 0x9
_SIGBUS = 0xa
_SIGSEGV = 0xb
_SIGSYS = 0xc
_SIGPIPE = 0xd
_SIGALRM = 0xe
_SIGTERM = 0xf
_SIGURG = 0x10
_SIGSTOP = 0x11
_SIGTSTP = 0x12
_SIGCONT = 0x13
_SIGCHLD = 0x14
_SIGTTIN = 0x15
_SIGTTOU = 0x16
_SIGIO = 0x17
_SIGXCPU = 0x18
_SIGXFSZ = 0x19
_SIGVTALRM = 0x1a
_SIGPROF = 0x1b
_SIGWINCH = 0x1c
_SIGINFO = 0x1d
_SIGUSR1 = 0x1e
_SIGUSR2 = 0x1f
_FPE_INTDIV = 0x1
_FPE_INTOVF = 0x2
_FPE_FLTDIV = 0x3
_FPE_FLTOVF = 0x4
_FPE_FLTUND = 0x5
_FPE_FLTRES = 0x6
_FPE_FLTINV = 0x7
_FPE_FLTSUB = 0x8
_BUS_ADRALN = 0x1
_BUS_ADRERR = 0x2
_BUS_OBJERR = 0x3
_SEGV_MAPERR = 0x1
_SEGV_ACCERR = 0x2
_ITIMER_REAL = 0x0
_ITIMER_VIRTUAL = 0x1
_ITIMER_PROF = 0x2
_EV_ADD = 0x1
_EV_DELETE = 0x2
_EV_CLEAR = 0x20
_EV_RECEIPT = 0
_EV_ERROR = 0x4000
_EVFILT_READ = 0x0
_EVFILT_WRITE = 0x1
)
type sigaltstackt struct {
ss_sp uintptr
ss_size uintptr
ss_flags int32
}
type sigset struct {
__bits [4]uint32
}
type siginfo struct {
_signo int32
_code int32
_errno int32
_reason [20]byte
}
type stackt struct {
ss_sp uintptr
ss_size uintptr
ss_flags int32
}
type timespec struct {
tv_sec int64
tv_nsec int32
}
type timeval struct {
tv_sec int64
tv_usec int32
}
type itimerval struct {
it_interval timeval
it_value timeval
}
type mcontextt struct {
__gregs [19]uint32
__fpregs [644]byte
_mc_tlsbase int32
}
type ucontextt struct {
uc_flags uint32
uc_link *ucontextt
uc_sigmask sigset
uc_stack stackt
uc_mcontext mcontextt
__uc_pad [4]int32
}
type keventt struct {
ident uint32
filter uint32
flags uint32
fflags uint32
data int64
udata *byte
}
const (
_REG_GS = 0x0
_REG_FS = 0x1
_REG_ES = 0x2
_REG_DS = 0x3
_REG_EDI = 0x4
_REG_ESI = 0x5
_REG_EBP = 0x6
_REG_ESP = 0x7
_REG_EBX = 0x8
_REG_EDX = 0x9
_REG_ECX = 0xa
_REG_EAX = 0xb
_REG_TRAPNO = 0xc
_REG_ERR = 0xd
_REG_EIP = 0xe
_REG_CS = 0xf
_REG_EFL = 0x10
_REG_UESP = 0x11
_REG_SS = 0x12
)
| {
"pile_set_name": "Github"
} |
// RUN: %clang_cc1 -fsyntax-only -verify %s
char *const_cast_test(const char *var)
{
return const_cast<char*>(var);
}
struct A {
virtual ~A() {}
};
struct B : public A {
};
struct B *dynamic_cast_test(struct A *a)
{
return dynamic_cast<struct B*>(a);
}
char *reinterpret_cast_test()
{
return reinterpret_cast<char*>(0xdeadbeef);
}
double static_cast_test(int i)
{
return static_cast<double>(i);
}
char postfix_expr_test()
{
return reinterpret_cast<char*>(0xdeadbeef)[0];
}
// This was being incorrectly tentatively parsed.
namespace test1 {
template <class T> class A {}; // expected-note 2{{here}}
void foo() { A<int>(*(A<int>*)0); }
}
typedef char* c;
typedef A* a;
void test2(char x, struct B * b) {
(void)const_cast<::c>(&x); // expected-error{{found '<::' after a const_cast which forms the digraph '<:' (aka '[') and a ':', did you mean '< ::'?}}
(void)dynamic_cast<::a>(b); // expected-error{{found '<::' after a dynamic_cast which forms the digraph '<:' (aka '[') and a ':', did you mean '< ::'?}}
(void)reinterpret_cast<::c>(x); // expected-error{{found '<::' after a reinterpret_cast which forms the digraph '<:' (aka '[') and a ':', did you mean '< ::'?}}
(void)static_cast<::c>(&x); // expected-error{{found '<::' after a static_cast which forms the digraph '<:' (aka '[') and a ':', did you mean '< ::'?}}
// Do not do digraph correction.
(void)static_cast<: :c>(&x); //\
expected-error {{expected '<' after 'static_cast'}} \
expected-error {{expected expression}}\
expected-error {{expected ']'}}\
expected-note {{to match this '['}}
(void)static_cast<: // expected-error {{expected '<' after 'static_cast'}} \
expected-note {{to match this '['}}
:c>(&x); // expected-error {{expected expression}} \
expected-error {{expected ']'}}
#define LC <:
#define C :
test1::A LC:B> c; // expected-error {{cannot refer to class template 'A' without a template argument list}} expected-error 2{{}} expected-note{{}}
(void)static_cast LC:c>(&x); // expected-error {{expected '<' after 'static_cast'}} expected-error 2{{}} expected-note{{}}
test1::A<:C B> d; // expected-error {{cannot refer to class template 'A' without a template argument list}} expected-error 2{{}} expected-note{{}}
(void)static_cast<:C c>(&x); // expected-error {{expected '<' after 'static_cast'}} expected-error 2{{}} expected-note{{}}
#define LCC <::
test1::A LCC B> e; // expected-error{{found '<::' after a template name which forms the digraph '<:' (aka '[') and a ':', did you mean '< ::'?}}
(void)static_cast LCC c>(&x); // expected-error{{found '<::' after a static_cast which forms the digraph '<:' (aka '[') and a ':', did you mean '< ::'?}}
}
// This note comes from "::D[:F> A5;"
template <class T> class D {}; // expected-note{{template is declared here}}
template <class T> void E() {};
class F {};
void test3() {
::D<::F> A1; // expected-error{{found '<::' after a template name which forms the digraph '<:' (aka '[') and a ':', did you mean '< ::'?}}
D<::F> A2; // expected-error{{found '<::' after a template name which forms the digraph '<:' (aka '[') and a ':', did you mean '< ::'?}}
::E<::F>(); // expected-error{{found '<::' after a template name which forms the digraph '<:' (aka '[') and a ':', did you mean '< ::'?}}
E<::F>(); // expected-error{{found '<::' after a template name which forms the digraph '<:' (aka '[') and a ':', did you mean '< ::'?}}
::D< ::F> A3;
D< ::F> A4;
::E< ::F>();
E< ::F>();
// Make sure that parser doesn't expand '[:' to '< ::'
::D[:F> A5; // expected-error {{cannot refer to class template 'D' without a template argument list}} \
// expected-error {{expected expression}} \
// expected-error {{expected ']'}} \
// expected-note {{to match this '['}}
}
| {
"pile_set_name": "Github"
} |
/*
* selectable unit tests
*/
(function($) {
//
// Selectable Test Helper Functions
//
var el;
var drag = function(dx, dy) {
var off = el.offset(), pos = { clientX: off.left, clientY: off.top };
el.simulate("mousedown", pos);
$(document).simulate("mousemove", pos);
pos.clientX += dx;
pos.clientY += dy;
$(document).simulate("mousemove", pos);
$(document).simulate("mouseup", pos);
}
var border = function(el, side) { return parseInt(el.css('border-' + side + '-width')); }
var margin = function(el, side) { return parseInt(el.css('margin-' + side)); }
// Selectable Tests
module("selectable");
test("init", function() {
expect(6);
$("#selectable1").selectable().remove();
ok(true, '.selectable() called on element');
$([]).selectable().remove();
ok(true, '.selectable() called on empty collection');
$("<div/>").selectable().remove();
ok(true, '.selectable() called on disconnected DOMElement');
$("<div/>").selectable().selectable("foo").remove();
ok(true, 'arbitrary method called after init');
el = $("<div/>").selectable()
var foo = el.data("foo.selectable");
el.remove();
ok(true, 'arbitrary option getter after init');
$("<div/>").selectable().data("foo.selectable", "bar").remove();
ok(true, 'arbitrary option setter after init');
});
test("destroy", function() {
expect(6);
$("#selectable1").selectable().selectable("destroy").remove();
ok(true, '.selectable("destroy") called on element');
$([]).selectable().selectable("destroy").remove();
ok(true, '.selectable("destroy") called on empty collection');
$("<div/>").selectable().selectable("destroy").remove();
ok(true, '.selectable("destroy") called on disconnected DOMElement');
$("<div/>").selectable().selectable("destroy").selectable("foo").remove();
ok(true, 'arbitrary method called after destroy');
el = $("<div/>").selectable();
var foo = el.selectable("destroy").data("foo.selectable");
el.remove();
ok(true, 'arbitrary option getter after destroy');
$("<div/>").selectable().selectable("destroy").data("foo.selectable", "bar").remove();
ok(true, 'arbitrary option setter after destroy');
});
test("defaults", function() {
el = $('#selectable1').selectable();
var defaults = {
autoRefresh: true,
filter: '*'
};
$.each(defaults, function(key, val) {
var actual = el.data(key + ".selectable"), expected = val,
method = (expected && expected.constructor == Object) ?
compare2 : equals;
method(actual, expected, key);
});
el.remove();
});
module("selectable: Options");
test("autoRefresh", function() {
expect(3);
el = $("#selectable1");
var actual, sel = $("*", el), selected = function() { actual += 1 };
actual = 0;
el = $("#selectable1").selectable({ autoRefresh: false, selected: selected });
sel.hide();
drag(1000, 1000);
equals(actual, sel.length);
el.selectable("destroy");
actual = 0;
sel.show();
el = $("#selectable1").selectable({ autoRefresh: true, selected: selected });
sel.hide();
drag(1000, 1000);
equals(actual, 0);
sel.show();
drag(1000, 1000);
equals(actual, sel.length);
el.selectable("destroy");
sel.show();
});
test("filter", function() {
expect(2);
el = $("#selectable1");
var actual, sel = $("*", el), selected = function() { actual += 1 };
actual = 0;
el = $("#selectable1").selectable({ filter: '.special', selected: selected });
drag(1000, 1000);
ok(sel.length != 1, "this test assumes more than 1 selectee");
equals(actual, 1);
el.selectable("destroy");
});
module("selectable: Methods");
test("disable", function() {
expect(2);
var fired = false;
el = $("#selectable1");
el.selectable({
disabled: false,
start: function() { fired = true; }
});
el.simulate("drag", 20, 20);
equals(fired, true, "start fired");
el.selectable("disable");
fired = false;
el.simulate("drag", 20, 20);
equals(fired, false, "start fired");
el.selectable("destroy");
});
test("enable", function() {
expect(2);
var fired = false;
el = $("#selectable1");
el.selectable({
disabled: true,
start: function() { fired = true; }
});
el.simulate("drag", 20, 20);
equals(fired, false, "start fired");
el.selectable("enable");
el.simulate("drag", 20, 20);
equals(fired, true, "start fired");
el.selectable("destroy");
});
test("toggle", function() {
expect(2);
el = $("#selectable1").selectable({ disabled: true }).selectable("toggle");
equals(el.data("disabled.selectable"), false, "disabled -> enabled");
el.selectable("destroy");
el = $("#selectable1").selectable({ disabled: false }).selectable("toggle");
equals(el.data("disabled.selectable"), true, "enabled -> disabled");
el.selectable("destroy");
});
module("selectable: Callbacks");
test("start", function() {
expect(2);
el = $("#selectable1");
el.selectable({
start: function(ev, ui) {
ok(true, "drag fired start callback");
equals(this, el[0], "context of callback");
}
});
el.simulate("drag", 20, 20);
});
test("stop", function() {
expect(2);
el = $("#selectable1");
el.selectable({
start: function(ev, ui) {
ok(true, "drag fired stop callback");
equals(this, el[0], "context of callback");
}
});
el.simulate("drag", 20, 20);
});
module("selectable: Tickets");
})(jQuery);
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) Roman Arutyunyan
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include "ngx_rtmp_bandwidth.h"
void
ngx_rtmp_update_bandwidth(ngx_rtmp_bandwidth_t *bw, uint32_t bytes)
{
if (ngx_cached_time->sec > bw->intl_end) {
bw->bandwidth = ngx_cached_time->sec >
bw->intl_end + NGX_RTMP_BANDWIDTH_INTERVAL
? 0
: bw->intl_bytes / NGX_RTMP_BANDWIDTH_INTERVAL;
bw->intl_bytes = 0;
bw->intl_end = ngx_cached_time->sec + NGX_RTMP_BANDWIDTH_INTERVAL;
}
bw->bytes += bytes;
bw->intl_bytes += bytes;
}
| {
"pile_set_name": "Github"
} |
// Generated from definition io.k8s.api.core.v1.PreferredSchedulingTerm
/// An empty preferred scheduling term matches all objects with implicit weight 0 (i.e. it's a no-op). A null preferred scheduling term matches no objects (i.e. is also a no-op).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PreferredSchedulingTerm {
/// A node selector term, associated with the corresponding weight.
pub preference: crate::api::core::v1::NodeSelectorTerm,
/// Weight associated with matching the corresponding nodeSelectorTerm, in the range 1-100.
pub weight: i32,
}
impl<'de> serde::Deserialize<'de> for PreferredSchedulingTerm {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
#[allow(non_camel_case_types)]
enum Field {
Key_preference,
Key_weight,
Other,
}
impl<'de> serde::Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = Field;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("field identifier")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error {
Ok(match v {
"preference" => Field::Key_preference,
"weight" => Field::Key_weight,
_ => Field::Other,
})
}
}
deserializer.deserialize_identifier(Visitor)
}
}
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = PreferredSchedulingTerm;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("PreferredSchedulingTerm")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de> {
let mut value_preference: Option<crate::api::core::v1::NodeSelectorTerm> = None;
let mut value_weight: Option<i32> = None;
while let Some(key) = serde::de::MapAccess::next_key::<Field>(&mut map)? {
match key {
Field::Key_preference => value_preference = Some(serde::de::MapAccess::next_value(&mut map)?),
Field::Key_weight => value_weight = Some(serde::de::MapAccess::next_value(&mut map)?),
Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess::next_value(&mut map)?; },
}
}
Ok(PreferredSchedulingTerm {
preference: value_preference.ok_or_else(|| serde::de::Error::missing_field("preference"))?,
weight: value_weight.ok_or_else(|| serde::de::Error::missing_field("weight"))?,
})
}
}
deserializer.deserialize_struct(
"PreferredSchedulingTerm",
&[
"preference",
"weight",
],
Visitor,
)
}
}
impl serde::Serialize for PreferredSchedulingTerm {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer {
let mut state = serializer.serialize_struct(
"PreferredSchedulingTerm",
2,
)?;
serde::ser::SerializeStruct::serialize_field(&mut state, "preference", &self.preference)?;
serde::ser::SerializeStruct::serialize_field(&mut state, "weight", &self.weight)?;
serde::ser::SerializeStruct::end(state)
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* DO NOT EDIT THIS FILE!
*
* This file was automatically generated from external sources.
*
* Any manual change here will be lost the next time the SDK
* is updated. You've been warned!
*/
namespace DTS\eBaySDK\ReturnManagement\Enums;
class ReturnStatusInputType
{
const C_CLOSED = 'CLOSED';
const C_ITEM_SHIPPED = 'ITEM_SHIPPED';
const C_MY_RESPONSE_DUE = 'MY_RESPONSE_DUE';
const C_OTHER_PARTY_RESPONSE_DUE = 'OTHER_PARTY_RESPONSE_DUE';
const C_RETURN_STARTED = 'RETURN_STARTED';
}
| {
"pile_set_name": "Github"
} |
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"newLine": "LF",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"forceConsistentCasingInFileNames": true,
"lib": [
"es2017",
"dom"
],
"moduleResolution": "node",
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"strict": true,
"typeRoots": [
"node_modules/@types"
],
"outDir": "dist",
"declaration": true,
"declarationDir": "./types",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true
},
"exclude": [
"node_modules",
"types",
"dist",
"src/customTypes",
"src/**/*.test.ts",
"src/testData/*.ts"
]
}
| {
"pile_set_name": "Github"
} |
#------------------------------------------------------------------------------#
# FFT
#------------------------------------------------------------------------------#
@article{ct1965,
title={An algorithm for the machine calculation of complex Fourier series},
author={Cooley, James W and Tukey, John W},
journal={Mathematics of computation},
volume={19},
number={90},
pages={297--301},
year={1965},
publisher={JSTOR}
}
#------------------------------------------------------------------------------#
# Convex Hull
#------------------------------------------------------------------------------#
@article{jm1973,
title={On the identification of the convex hull of a finite set of points in the plane},
author={Jarvis, Ray A},
journal={Information processing letters},
volume={2},
number={1},
pages={18--21},
year={1973},
publisher={Elsevier}
}
@article{gs1972,
title={An efficient algorithm for determining the convex hull of a finite planar set},
author={Graham, Ronald L},
journal={Information processing letters},
volume={1},
number={4},
pages={132--133},
year={1972},
publisher={Elsevier}
}
#------------------------------------------------------------------------------#
# Plotting
#------------------------------------------------------------------------------#
@misc{gnuplot,
title={Gnuplot 5.0: An Interactive Plotting Program, Official Gnuplot Documentation},
author={Williams, T and Kelley, C},
year={2015}
}
#------------------------------------------------------------------------------#
# Computus
#------------------------------------------------------------------------------#
@book{bede725,
title={Bede, the Reckoning of Time},
author={Venerabilis, Beda and others},
volume={29},
year={1999},
publisher={Liverpool University Press}
}
@misc{dictcomputus,
title={Dictionary.com definition of computus},
url={https://www.merriam-webster.com/dictionary/computus},
year={2020}
}
@article{computus1876,
title={To find Easter: a new York correspondent sends us the following},
author={unknown},
journal={Nature},
year={1876}
}
@article{bien2004,
title={Gauss and beyond: The making of Easter algorithms},
author={Bien, Reinhold},
journal={Archive for history of exact sciences},
volume={58},
number={5},
pages={439--452},
year={2004},
publisher={Springer}
}
@inproceedings{servois,
title={84 Calendrier},
author={Servois, M},
booktitle={Annales de Mathématiques pures et appliquées},
volume={4},
number={1813-1814},
pages={84--90}
}
@article{standish2004,
title={The astronomical unit now},
author={Standish, EM},
journal={Proceedings of the International Astronomical Union},
volume={2004},
number={IAUC196},
pages={163--179},
year={2004},
publisher={Cambridge University Press}
}
@misc{lunar_month_wiki,
title={Wikipedia: Lunar Month},
url={https://en.wikipedia.org/wiki/Lunar_month},
year={2020}
}
#------------------------------------------------------------------------------#
# IFS
#------------------------------------------------------------------------------#
@misc{self-similar,
title={Wikipedia: Self-similarity},
url={https://en.wikipedia.org/wiki/Self-similarity},
year={2019}
}
@misc{hausdorff,
title={Wikipedia: Hausdorff dimension},
url={https://en.wikipedia.org/wiki/Hausdorff_dimension},
year={2019}
}
@misc{3b1bfractal,
author={Sanderson, G},
title={3blue1brown: Fractals are typically not self-similar},
url={https://www.youtube.com/watch?v=gB9n2gHsHN4},
year={2017}
}
@book{mandelbrot1983fractal,
title={The fractal geometry of nature},
author={Mandelbrot, Benoit B},
volume={173},
year={1983},
publisher={WH freeman New York}
}
@article{mandelbrot1967long,
title={How long is the coast of Britain? Statistical self-similarity and fractional dimension},
author={Mandelbrot, Benoit},
journal={science},
volume={156},
number={3775},
pages={636--638},
year={1967},
publisher={American Association for the Advancement of Science}
}
@article{jampour2010new,
title={A new fast technique for fingerprint identification with fractal and chaos game theory},
author={Jampour, Mahdi and Yaghoobi, Mahdi and Ashourzadeh, Maryam and Soleimani, Adel},
journal={Fractals},
volume={18},
number={03},
pages={293--300},
year={2010},
publisher={World Scientific}
}
@misc{fractal-compression,
title={Wikipedia: Fractal Compression},
url={https://en.wikipedia.org/wiki/Fractal_compression},
year={2019}
}
@article{saupe1994review,
title={A review of the fractal image compression literature},
author={Saupe, Dietmar and Hamzaoui, Raouf},
journal={ACM SIGGRAPH Computer Graphics},
volume={28},
number={4},
pages={268--276},
year={1994},
publisher={ACM}
}
@article{gneiting2012estimators,
title={Estimators of fractal dimension: Assessing the roughness of time series and spatial data},
author={Gneiting, Tilmann and Ševčíková, Hana and Percival, Donald B},
journal={Statistical Science},
pages={247--277},
year={2012},
publisher={JSTOR}
}
@article{hutchinson1981fractals,
title={Fractals and self similarity},
author={Hutchinson, John E},
journal={Indiana University Mathematics Journal},
volume={30},
number={5},
pages={713--747},
year={1981},
publisher={JSTOR}
}
@misc{hutchinson-operator,
title={Wikipedia: Hutchinson Operator},
url={https://en.wikipedia.org/wiki/Hutchinson_operator},
year={2019}
}
@misc{chaos-game,
title={Wikipedia: Chaos Game},
url={https://en.wikipedia.org/wiki/Chaos_game},
year={2019}
}
@misc{chaos-game-wolf,
title={Wolfram: Chaos Game},
url={http://mathworld.wolfram.com/ChaosGame.html},
year={2019}
}
#------------------------------------------------------------------------------#
# Domain Coloring
#------------------------------------------------------------------------------#
@misc{hsv,
title={Wikipedia: HSL and HSV},
url={https://en.wikipedia.org/wiki/HSL_and_HSV},
year={2020}
}
@article{schloss2019,
title={Massively parallel split-step Fourier techniques for simulating quantum systems on graphics processing units},
author={Schloss, James},
year={2019}
}
@book{pethick2008,
title={Bose--Einstein condensation in dilute gases},
author={Pethick, Christopher J and Smith, Henrik},
year={2008},
publisher={Cambridge university press}
}
@book{wegert2012,
title={Visual complex functions: an introduction with phase portraits},
author={Wegert, Elias},
year={2012},
publisher={Springer Science \& Business Media}
}
@article{poelkedomain,
title={Domain Coloring of Complex Functions},
author={Poelke, Konstantin and Polthier, Konrad}
}
@article{lundmark2004,
title={Visualizing complex analytic functions using domain coloring},
author={Lundmark, Hans},
journal={Recuperado el},
volume={24},
year={2004}
}
#------------------------------------------------------------------------------#
# Flood Fill
#------------------------------------------------------------------------------#
@misc{gimp_bucket,
title={Bucket Fill in Gimp},
url={https://docs.gimp.org/2.10/en/gimp-tool-bucket-fill.html},
year={2020}
}
@book{torbert2016,
title={Applied computer science},
author={Torbert, Shane},
year={2016},
pages={158},
publisher={Springer}
}
| {
"pile_set_name": "Github"
} |
--- a/src/mach-ixp42x/slugos-nslu2-16mb-armeb_config
+++ b/src/mach-ixp42x/slugos-nslu2-16mb-armeb_config
@@ -19,7 +19,7 @@ CONFIG_EXPERIMENTAL=y
#
# General Setup
#
-CONFIG_TARGET_DESCRIPTION="SlugOS NSLU2/BE (16MiB Flash)"
+CONFIG_TARGET_DESCRIPTION="OpenWrt NSLU2 (16MiB Flash)"
CONFIG_CROSS_COMPILE=""
CONFIG_AEABI=y
# CONFIG_DRIVER_LONG_LONG_SIZE is not set
@@ -163,9 +163,9 @@ CONFIG_ENV_REGION_KERNEL_ALT="fis://kern
# Overrides
#
CONFIG_ENV_DEFAULT_CMDLINE_OVERRIDE=y
-CONFIG_ENV_DEFAULT_CMDLINE="root=/dev/mtdblock4 rootfstype=jffs2 console=ttyS0,115200 init=/linuxrc"
+CONFIG_ENV_DEFAULT_CMDLINE="root=/dev/mtdblock4 rootfstype=squashfs,jffs2 console=ttyS0,115200 init=/etc/preinit noinitrd"
CONFIG_ENV_DEFAULT_CMDLINE_ALT_P=y
-CONFIG_ENV_DEFAULT_CMDLINE_ALT="root=/dev/mtdblock4 rootfstype=jffs2 console=ttyS0,115200 init=/linuxrc"
+CONFIG_ENV_DEFAULT_CMDLINE_ALT="root=/dev/mtdblock4 rootfstype=squashfs,jffs2 console=ttyS0,115200 init=/etc/preinit noinitrd"
# CONFIG_ENV_DEFAULT_STARTUP_OVERRIDE is not set
# CONFIG_ENV_DEFAULT_STARTUP_ALT_P is not set
CONFIG_USES_NOR_BOOTFLASH=y
| {
"pile_set_name": "Github"
} |
// RUN: %clang_cc1 %s -verify -fsyntax-only
void good() {
int dont_initialize_me __attribute((uninitialized));
}
void bad() {
int im_bad __attribute((uninitialized("zero"))); // expected-error {{'uninitialized' attribute takes no arguments}}
static int im_baaad __attribute((uninitialized)); // expected-warning {{'uninitialized' attribute only applies to local variables}}
}
extern int come_on __attribute((uninitialized)); // expected-warning {{'uninitialized' attribute only applies to local variables}}
int you_know __attribute((uninitialized)); // expected-warning {{'uninitialized' attribute only applies to local variables}}
static int and_the_whole_world_has_to __attribute((uninitialized)); // expected-warning {{'uninitialized' attribute only applies to local variables}}
void answer_right_now() __attribute((uninitialized)) {} // expected-warning {{'uninitialized' attribute only applies to local variables}}
void just_to_tell_you_once_again(__attribute((uninitialized)) int whos_bad) {} // expected-warning {{'uninitialized' attribute only applies to local variables}}
struct TheWordIsOut {
__attribute((uninitialized)) int youre_doin_wrong; // expected-warning {{'uninitialized' attribute only applies to local variables}}
} __attribute((uninitialized)); // expected-warning {{'uninitialized' attribute only applies to local variables}}
| {
"pile_set_name": "Github"
} |
import { get } from '../moment/get-set';
import hasOwnProp from '../utils/has-own-prop';
import { addFormatToken } from '../format/format';
import { addUnitAlias } from './aliases';
import { addUnitPriority } from './priorities';
import { addRegexToken, match1to2, match2, matchWord, regexEscape } from '../parse/regex';
import { addParseToken } from '../parse/token';
import { hooks } from '../utils/hooks';
import { MONTH } from './constants';
import toInt from '../utils/to-int';
import isArray from '../utils/is-array';
import isNumber from '../utils/is-number';
import mod from '../utils/mod';
import indexOf from '../utils/index-of';
import { createUTC } from '../create/utc';
import getParsingFlags from '../create/parsing-flags';
import { isLeapYear } from '../units/year';
export function daysInMonth(year, month) {
if (isNaN(year) || isNaN(month)) {
return NaN;
}
var modMonth = mod(month, 12);
year += (month - modMonth) / 12;
return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2);
}
// FORMATTING
addFormatToken('M', ['MM', 2], 'Mo', function () {
return this.month() + 1;
});
addFormatToken('MMM', 0, 0, function (format) {
return this.localeData().monthsShort(this, format);
});
addFormatToken('MMMM', 0, 0, function (format) {
return this.localeData().months(this, format);
});
// ALIASES
addUnitAlias('month', 'M');
// PRIORITY
addUnitPriority('month', 8);
// PARSING
addRegexToken('M', match1to2);
addRegexToken('MM', match1to2, match2);
addRegexToken('MMM', function (isStrict, locale) {
return locale.monthsShortRegex(isStrict);
});
addRegexToken('MMMM', function (isStrict, locale) {
return locale.monthsRegex(isStrict);
});
addParseToken(['M', 'MM'], function (input, array) {
array[MONTH] = toInt(input) - 1;
});
addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
var month = config._locale.monthsParse(input, token, config._strict);
// if we didn't find a month name, mark the date as invalid.
if (month != null) {
array[MONTH] = month;
} else {
getParsingFlags(config).invalidMonth = input;
}
});
// LOCALES
var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
export var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
export function localeMonths (m, format) {
if (!m) {
return isArray(this._months) ? this._months :
this._months['standalone'];
}
return isArray(this._months) ? this._months[m.month()] :
this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
}
export var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
export function localeMonthsShort (m, format) {
if (!m) {
return isArray(this._monthsShort) ? this._monthsShort :
this._monthsShort['standalone'];
}
return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
}
function handleStrictParse(monthName, format, strict) {
var i, ii, mom, llc = monthName.toLocaleLowerCase();
if (!this._monthsParse) {
// this is not used
this._monthsParse = [];
this._longMonthsParse = [];
this._shortMonthsParse = [];
for (i = 0; i < 12; ++i) {
mom = createUTC([2000, i]);
this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
}
}
if (strict) {
if (format === 'MMM') {
ii = indexOf.call(this._shortMonthsParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._longMonthsParse, llc);
return ii !== -1 ? ii : null;
}
} else {
if (format === 'MMM') {
ii = indexOf.call(this._shortMonthsParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._longMonthsParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._longMonthsParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortMonthsParse, llc);
return ii !== -1 ? ii : null;
}
}
}
export function localeMonthsParse (monthName, format, strict) {
var i, mom, regex;
if (this._monthsParseExact) {
return handleStrictParse.call(this, monthName, format, strict);
}
if (!this._monthsParse) {
this._monthsParse = [];
this._longMonthsParse = [];
this._shortMonthsParse = [];
}
// TODO: add sorting
// Sorting makes sure if one month (or abbr) is a prefix of another
// see sorting in computeMonthsParse
for (i = 0; i < 12; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, i]);
if (strict && !this._longMonthsParse[i]) {
this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
}
if (!strict && !this._monthsParse[i]) {
regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
}
// test the regex
if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
return i;
} else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
return i;
} else if (!strict && this._monthsParse[i].test(monthName)) {
return i;
}
}
}
// MOMENTS
export function setMonth (mom, value) {
var dayOfMonth;
if (!mom.isValid()) {
// No op
return mom;
}
if (typeof value === 'string') {
if (/^\d+$/.test(value)) {
value = toInt(value);
} else {
value = mom.localeData().monthsParse(value);
// TODO: Another silent failure?
if (!isNumber(value)) {
return mom;
}
}
}
dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
return mom;
}
export function getSetMonth (value) {
if (value != null) {
setMonth(this, value);
hooks.updateOffset(this, true);
return this;
} else {
return get(this, 'Month');
}
}
export function getDaysInMonth () {
return daysInMonth(this.year(), this.month());
}
var defaultMonthsShortRegex = matchWord;
export function monthsShortRegex (isStrict) {
if (this._monthsParseExact) {
if (!hasOwnProp(this, '_monthsRegex')) {
computeMonthsParse.call(this);
}
if (isStrict) {
return this._monthsShortStrictRegex;
} else {
return this._monthsShortRegex;
}
} else {
if (!hasOwnProp(this, '_monthsShortRegex')) {
this._monthsShortRegex = defaultMonthsShortRegex;
}
return this._monthsShortStrictRegex && isStrict ?
this._monthsShortStrictRegex : this._monthsShortRegex;
}
}
var defaultMonthsRegex = matchWord;
export function monthsRegex (isStrict) {
if (this._monthsParseExact) {
if (!hasOwnProp(this, '_monthsRegex')) {
computeMonthsParse.call(this);
}
if (isStrict) {
return this._monthsStrictRegex;
} else {
return this._monthsRegex;
}
} else {
if (!hasOwnProp(this, '_monthsRegex')) {
this._monthsRegex = defaultMonthsRegex;
}
return this._monthsStrictRegex && isStrict ?
this._monthsStrictRegex : this._monthsRegex;
}
}
function computeMonthsParse () {
function cmpLenRev(a, b) {
return b.length - a.length;
}
var shortPieces = [], longPieces = [], mixedPieces = [],
i, mom;
for (i = 0; i < 12; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, i]);
shortPieces.push(this.monthsShort(mom, ''));
longPieces.push(this.months(mom, ''));
mixedPieces.push(this.months(mom, ''));
mixedPieces.push(this.monthsShort(mom, ''));
}
// Sorting makes sure if one month (or abbr) is a prefix of another it
// will match the longer piece.
shortPieces.sort(cmpLenRev);
longPieces.sort(cmpLenRev);
mixedPieces.sort(cmpLenRev);
for (i = 0; i < 12; i++) {
shortPieces[i] = regexEscape(shortPieces[i]);
longPieces[i] = regexEscape(longPieces[i]);
}
for (i = 0; i < 24; i++) {
mixedPieces[i] = regexEscape(mixedPieces[i]);
}
this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
this._monthsShortRegex = this._monthsRegex;
this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Elasticsearch.Net" version="5.4.0" targetFramework="net452" />
<package id="NATS.Client" version="0.8.0" targetFramework="net452" />
<package id="NEST" version="5.4.0" targetFramework="net452" />
<package id="Newtonsoft.Json" version="10.0.2" targetFramework="net452" />
<package id="prometheus-net" version="1.3.5" targetFramework="net452" />
<package id="protobuf-net" version="2.0.0.668" targetFramework="net452" />
<package id="System.Reactive" version="3.1.1" targetFramework="net452" />
<package id="System.Reactive.Core" version="3.1.1" targetFramework="net452" />
<package id="System.Reactive.Interfaces" version="3.1.1" targetFramework="net452" />
<package id="System.Reactive.Linq" version="3.1.1" targetFramework="net452" />
<package id="System.Reactive.PlatformServices" version="3.1.1" targetFramework="net452" />
<package id="System.Reactive.Windows.Threading" version="3.1.1" targetFramework="net452" />
</packages> | {
"pile_set_name": "Github"
} |
/*
* (C) Copyright 2014 Amaury Crickx
*
* 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.bitsinharmony.recognito.features;
/**
* Base class for windowed features extractor
* <p>
* Constructor computes default window size by calling {@link #getWindowSize(float)}. <br/>
* @see {@link #getWindowSize(float)}
* </p>
* @author Amaury Crickx
* @param <T> the kind of features to extract, specified by implementing classes
*/
public abstract class WindowedFeaturesExtractor<T>
implements FeaturesExtractor<T> {
private static final int DEFAULT_TARGET_WINDOW_LENGTH_IN_MILLIS = 24;
private static final float MIN_SAMPLE_RATE = 8000.0F;
protected final int windowSize;
protected final float sampleRate;
/**
* Base constructor required by this abstract class
* @param sampleRate the sample rate of the voice samples, minimum 8000.0
*/
public WindowedFeaturesExtractor(float sampleRate) {
if(sampleRate < MIN_SAMPLE_RATE) {
throw new IllegalArgumentException("Sample rate should be at least 8000 Hz");
}
this.sampleRate = sampleRate;
this.windowSize = getWindowSize(sampleRate);
}
/* (non-Javadoc)
* @see com.recognito.processing.features.FeaturesExtractor#extractFeatures(double[])
*/
public abstract T extractFeatures(double[] voiceSample);
/**
* Called by the constructor of this class.
* This implementation delegates to {@link #getClosestPowerOfTwoWindowSize(float, int)}
* with default targetSizeInMillis value
* <p>
* Implementing classes may wish to override this method by delegating with another target value in millis
* or implement another logic alltogether
* </p>
* @param sampleRate the sample rate in Hz (times per second), minimum 8000.0
* @return the window size
*/
protected int getWindowSize(float sampleRate) {
return getClosestPowerOfTwoWindowSize(sampleRate, DEFAULT_TARGET_WINDOW_LENGTH_IN_MILLIS);
}
/**
* Computes the window size that is both the closest to targetSizeInMillis and a power of 2
* <p>
* Note : window size using a power of 2 is required e.g. when using discrete FFT algorithm
* </p>
* @param sampleRate the sample rate in Hz (times per second), minimum 8000.0
* @param targetSizeInMillis the target size in millis
* @return the window size
*/
protected final int getClosestPowerOfTwoWindowSize(float sampleRate, int targetSizeInMillis) {
boolean done = false;
int pow = 8; // 8 bytes == 1ms at 8000 Hz
float previousMillis = 0.0f;
while(!done) {
float millis = 1000 / sampleRate * pow;
if(millis < targetSizeInMillis) {
previousMillis = millis;
pow *= 2;
} else {
// closest value to target wins
if(Math.abs(targetSizeInMillis - millis) > targetSizeInMillis - previousMillis) {
pow /= 2; // previousMillis was closer
}
done = true;
}
}
return pow;
}
}
| {
"pile_set_name": "Github"
} |
// Crc32.cs
//
// Copyright (c) 2006, 2007 Microsoft Corporation. All rights reserved.
//
//
// Implements the CRC algorithm, which is used in zip files. The zip format calls for
// the zipfile to contain a CRC for the unencrypted byte stream of each file.
//
// It is based on example source code published at
// http://www.vbaccelerator.com/home/net/code/libraries/CRC32/Crc32_zip_CRC32_CRC32_cs.asp
//
// This implementation adds a tweak of that code for use within zip creation. While
// computing the CRC we also compress the byte stream, in the same read loop. This
// avoids the need to read through the uncompressed stream twice - once to computer CRC
// and another time to compress.
//
//
// Thu, 30 Mar 2006 13:58
//
using System;
namespace newtelligence.DasBlog.Runtime.Zip
{
/// <summary>
/// Calculates a 32bit Cyclic Redundancy Checksum (CRC) using the
/// same polynomial used by Zip.
/// </summary>
public class CRC32
{
private UInt32[] crc32Table;
private const int BUFFER_SIZE = 8192;
private Int32 _TotalBytesRead= 0;
public Int32 TotalBytesRead {
get {
return _TotalBytesRead;
}
}
/// <summary>
/// Returns the CRC32 for the specified stream.
/// </summary>
/// <param name="input">The stream over which to calculate the CRC32</param>
/// <returns>the CRC32 calculation</returns>
public UInt32 GetCrc32(System.IO.Stream input)
{
return GetCrc32AndCopy(input, null) ;
}
/// <summary>
/// Returns the CRC32 for the specified stream, and writes the input into the output stream.
/// </summary>
/// <param name="input">The stream over which to calculate the CRC32</param>
/// <param name="output">The stream into which to deflate the input</param>
/// <returns>the CRC32 calculation</returns>
public UInt32 GetCrc32AndCopy(System.IO.Stream input, System.IO.Stream output)
{
unchecked
{
UInt32 crc32Result;
crc32Result = 0xFFFFFFFF;
byte[] buffer = new byte[BUFFER_SIZE];
int readSize = BUFFER_SIZE;
_TotalBytesRead= 0;
int count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer,0,count);
_TotalBytesRead += count;
while (count > 0)
{
for (int i = 0; i < count; i++)
{
crc32Result = ((crc32Result) >> 8) ^ crc32Table[(buffer[i]) ^ ((crc32Result) & 0x000000FF)];
}
count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer,0,count);
_TotalBytesRead += count;
}
return ~crc32Result;
}
}
/// <summary>
/// Construct an instance of the CRC32 class, pre-initialising the table
/// for speed of lookup.
/// </summary>
public CRC32()
{
unchecked
{
// This is the official polynomial used by CRC32 in PKZip.
// Often the polynomial is shown reversed as 0x04C11DB7.
UInt32 dwPolynomial = 0xEDB88320;
UInt32 i, j;
crc32Table = new UInt32[256];
UInt32 dwCrc;
for(i = 0; i < 256; i++)
{
dwCrc = i;
for(j = 8; j > 0; j--)
{
if ((dwCrc & 1)==1)
{
dwCrc = (dwCrc >> 1) ^ dwPolynomial;
}
else
{
dwCrc >>= 1;
}
}
crc32Table[i] = dwCrc;
}
}
}
}
}
| {
"pile_set_name": "Github"
} |
import struct TSCBasic.AbsolutePath
typealias TemporaryFileFunction = (AbsolutePath?, String, String, Bool, (AbsolutePath) throws -> Void) throws -> Void
| {
"pile_set_name": "Github"
} |
/*
* 2002-10-18 written by Jim Houston jim.houston@ccur.com
* Copyright (C) 2002 by Concurrent Computer Corporation
* Distributed under the GNU GPL license version 2.
*
* Modified by George Anzinger to reuse immediately and to use
* find bit instructions. Also removed _irq on spinlocks.
*
* Modified by Nadia Derbey to make it RCU safe.
*
* Small id to pointer translation service.
*
* It uses a radix tree like structure as a sparse array indexed
* by the id to obtain the pointer. The bitmap makes allocating
* a new id quick.
*
* You call it to allocate an id (an int) an associate with that id a
* pointer or what ever, we treat it as a (void *). You can pass this
* id to a user for him to pass back at a later time. You then pass
* that id to this code and it returns your pointer.
* You can release ids at any time. When all ids are released, most of
* the memory is returned (we keep IDR_FREE_MAX) in a local pool so we
* don't need to go to the memory "store" during an id allocate, just
* so you don't need to be too concerned about locking and conflicts
* with the slab allocator.
*/
#ifndef TEST // to test in user space...
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/module.h>
#endif
#include <linux/err.h>
#include <linux/string.h>
#include <linux/idr.h>
#include <linux/spinlock.h>
static struct kmem_cache *idr_layer_cache;
static DEFINE_SPINLOCK(simple_ida_lock);
static struct idr_layer *get_from_free_list(struct idr *idp)
{
struct idr_layer *p;
unsigned long flags;
spin_lock_irqsave(&idp->lock, flags);
if ((p = idp->id_free)) {
idp->id_free = p->ary[0];
idp->id_free_cnt--;
p->ary[0] = NULL;
}
spin_unlock_irqrestore(&idp->lock, flags);
return(p);
}
static void idr_layer_rcu_free(struct rcu_head *head)
{
struct idr_layer *layer;
layer = container_of(head, struct idr_layer, rcu_head);
kmem_cache_free(idr_layer_cache, layer);
}
static inline void free_layer(struct idr_layer *p)
{
call_rcu(&p->rcu_head, idr_layer_rcu_free);
}
/* only called when idp->lock is held */
static void __move_to_free_list(struct idr *idp, struct idr_layer *p)
{
p->ary[0] = idp->id_free;
idp->id_free = p;
idp->id_free_cnt++;
}
static void move_to_free_list(struct idr *idp, struct idr_layer *p)
{
unsigned long flags;
/*
* Depends on the return element being zeroed.
*/
spin_lock_irqsave(&idp->lock, flags);
__move_to_free_list(idp, p);
spin_unlock_irqrestore(&idp->lock, flags);
}
static void idr_mark_full(struct idr_layer **pa, int id)
{
struct idr_layer *p = pa[0];
int l = 0;
__set_bit(id & IDR_MASK, &p->bitmap);
/*
* If this layer is full mark the bit in the layer above to
* show that this part of the radix tree is full. This may
* complete the layer above and require walking up the radix
* tree.
*/
while (p->bitmap == IDR_FULL) {
if (!(p = pa[++l]))
break;
id = id >> IDR_BITS;
__set_bit((id & IDR_MASK), &p->bitmap);
}
}
/**
* idr_pre_get - reserve resources for idr allocation
* @idp: idr handle
* @gfp_mask: memory allocation flags
*
* This function should be called prior to calling the idr_get_new* functions.
* It preallocates enough memory to satisfy the worst possible allocation. The
* caller should pass in GFP_KERNEL if possible. This of course requires that
* no spinning locks be held.
*
* If the system is REALLY out of memory this function returns %0,
* otherwise %1.
*/
int idr_pre_get(struct idr *idp, gfp_t gfp_mask)
{
while (idp->id_free_cnt < IDR_FREE_MAX) {
struct idr_layer *new;
new = kmem_cache_zalloc(idr_layer_cache, gfp_mask);
if (new == NULL)
return (0);
move_to_free_list(idp, new);
}
return 1;
}
EXPORT_SYMBOL(idr_pre_get);
static int sub_alloc(struct idr *idp, int *starting_id, struct idr_layer **pa)
{
int n, m, sh;
struct idr_layer *p, *new;
int l, id, oid;
unsigned long bm;
id = *starting_id;
restart:
p = idp->top;
l = idp->layers;
pa[l--] = NULL;
while (1) {
/*
* We run around this while until we reach the leaf node...
*/
n = (id >> (IDR_BITS*l)) & IDR_MASK;
bm = ~p->bitmap;
m = find_next_bit(&bm, IDR_SIZE, n);
if (m == IDR_SIZE) {
/* no space available go back to previous layer. */
l++;
oid = id;
id = (id | ((1 << (IDR_BITS * l)) - 1)) + 1;
/* if already at the top layer, we need to grow */
if (id >= 1 << (idp->layers * IDR_BITS)) {
*starting_id = id;
return IDR_NEED_TO_GROW;
}
p = pa[l];
BUG_ON(!p);
/* If we need to go up one layer, continue the
* loop; otherwise, restart from the top.
*/
sh = IDR_BITS * (l + 1);
if (oid >> sh == id >> sh)
continue;
else
goto restart;
}
if (m != n) {
sh = IDR_BITS*l;
id = ((id >> sh) ^ n ^ m) << sh;
}
if ((id >= MAX_ID_BIT) || (id < 0))
return IDR_NOMORE_SPACE;
if (l == 0)
break;
/*
* Create the layer below if it is missing.
*/
if (!p->ary[m]) {
new = get_from_free_list(idp);
if (!new)
return -1;
new->layer = l-1;
rcu_assign_pointer(p->ary[m], new);
p->count++;
}
pa[l--] = p;
p = p->ary[m];
}
pa[l] = p;
return id;
}
static int idr_get_empty_slot(struct idr *idp, int starting_id,
struct idr_layer **pa)
{
struct idr_layer *p, *new;
int layers, v, id;
unsigned long flags;
id = starting_id;
build_up:
p = idp->top;
layers = idp->layers;
if (unlikely(!p)) {
if (!(p = get_from_free_list(idp)))
return -1;
p->layer = 0;
layers = 1;
}
/*
* Add a new layer to the top of the tree if the requested
* id is larger than the currently allocated space.
*/
while ((layers < (MAX_LEVEL - 1)) && (id >= (1 << (layers*IDR_BITS)))) {
layers++;
if (!p->count) {
/* special case: if the tree is currently empty,
* then we grow the tree by moving the top node
* upwards.
*/
p->layer++;
continue;
}
if (!(new = get_from_free_list(idp))) {
/*
* The allocation failed. If we built part of
* the structure tear it down.
*/
spin_lock_irqsave(&idp->lock, flags);
for (new = p; p && p != idp->top; new = p) {
p = p->ary[0];
new->ary[0] = NULL;
new->bitmap = new->count = 0;
__move_to_free_list(idp, new);
}
spin_unlock_irqrestore(&idp->lock, flags);
return -1;
}
new->ary[0] = p;
new->count = 1;
new->layer = layers-1;
if (p->bitmap == IDR_FULL)
__set_bit(0, &new->bitmap);
p = new;
}
rcu_assign_pointer(idp->top, p);
idp->layers = layers;
v = sub_alloc(idp, &id, pa);
if (v == IDR_NEED_TO_GROW)
goto build_up;
return(v);
}
static int idr_get_new_above_int(struct idr *idp, void *ptr, int starting_id)
{
struct idr_layer *pa[MAX_LEVEL];
int id;
id = idr_get_empty_slot(idp, starting_id, pa);
if (id >= 0) {
/*
* Successfully found an empty slot. Install the user
* pointer and mark the slot full.
*/
rcu_assign_pointer(pa[0]->ary[id & IDR_MASK],
(struct idr_layer *)ptr);
pa[0]->count++;
idr_mark_full(pa, id);
}
return id;
}
/**
* idr_get_new_above - allocate new idr entry above or equal to a start id
* @idp: idr handle
* @ptr: pointer you want associated with the id
* @starting_id: id to start search at
* @id: pointer to the allocated handle
*
* This is the allocate id function. It should be called with any
* required locks.
*
* If allocation from IDR's private freelist fails, idr_get_new_above() will
* return %-EAGAIN. The caller should retry the idr_pre_get() call to refill
* IDR's preallocation and then retry the idr_get_new_above() call.
*
* If the idr is full idr_get_new_above() will return %-ENOSPC.
*
* @id returns a value in the range @starting_id ... %0x7fffffff
*/
int idr_get_new_above(struct idr *idp, void *ptr, int starting_id, int *id)
{
int rv;
rv = idr_get_new_above_int(idp, ptr, starting_id);
/*
* This is a cheap hack until the IDR code can be fixed to
* return proper error values.
*/
if (rv < 0)
return _idr_rc_to_errno(rv);
*id = rv;
return 0;
}
EXPORT_SYMBOL(idr_get_new_above);
/**
* idr_get_new - allocate new idr entry
* @idp: idr handle
* @ptr: pointer you want associated with the id
* @id: pointer to the allocated handle
*
* If allocation from IDR's private freelist fails, idr_get_new_above() will
* return %-EAGAIN. The caller should retry the idr_pre_get() call to refill
* IDR's preallocation and then retry the idr_get_new_above() call.
*
* If the idr is full idr_get_new_above() will return %-ENOSPC.
*
* @id returns a value in the range %0 ... %0x7fffffff
*/
int idr_get_new(struct idr *idp, void *ptr, int *id)
{
int rv;
rv = idr_get_new_above_int(idp, ptr, 0);
/*
* This is a cheap hack until the IDR code can be fixed to
* return proper error values.
*/
if (rv < 0)
return _idr_rc_to_errno(rv);
*id = rv;
return 0;
}
EXPORT_SYMBOL(idr_get_new);
static void idr_remove_warning(int id)
{
printk(KERN_WARNING
"idr_remove called for id=%d which is not allocated.\n", id);
dump_stack();
}
static void sub_remove(struct idr *idp, int shift, int id)
{
struct idr_layer *p = idp->top;
struct idr_layer **pa[MAX_LEVEL];
struct idr_layer ***paa = &pa[0];
struct idr_layer *to_free;
int n;
*paa = NULL;
*++paa = &idp->top;
while ((shift > 0) && p) {
n = (id >> shift) & IDR_MASK;
__clear_bit(n, &p->bitmap);
*++paa = &p->ary[n];
p = p->ary[n];
shift -= IDR_BITS;
}
n = id & IDR_MASK;
if (likely(p != NULL && test_bit(n, &p->bitmap))){
__clear_bit(n, &p->bitmap);
rcu_assign_pointer(p->ary[n], NULL);
to_free = NULL;
while(*paa && ! --((**paa)->count)){
if (to_free)
free_layer(to_free);
to_free = **paa;
**paa-- = NULL;
}
if (!*paa)
idp->layers = 0;
if (to_free)
free_layer(to_free);
} else
idr_remove_warning(id);
}
/**
* idr_remove - remove the given id and free its slot
* @idp: idr handle
* @id: unique key
*/
void idr_remove(struct idr *idp, int id)
{
struct idr_layer *p;
struct idr_layer *to_free;
/* Mask off upper bits we don't use for the search. */
id &= MAX_ID_MASK;
sub_remove(idp, (idp->layers - 1) * IDR_BITS, id);
if (idp->top && idp->top->count == 1 && (idp->layers > 1) &&
idp->top->ary[0]) {
/*
* Single child at leftmost slot: we can shrink the tree.
* This level is not needed anymore since when layers are
* inserted, they are inserted at the top of the existing
* tree.
*/
to_free = idp->top;
p = idp->top->ary[0];
rcu_assign_pointer(idp->top, p);
--idp->layers;
to_free->bitmap = to_free->count = 0;
free_layer(to_free);
}
while (idp->id_free_cnt >= IDR_FREE_MAX) {
p = get_from_free_list(idp);
/*
* Note: we don't call the rcu callback here, since the only
* layers that fall into the freelist are those that have been
* preallocated.
*/
kmem_cache_free(idr_layer_cache, p);
}
return;
}
EXPORT_SYMBOL(idr_remove);
/**
* idr_remove_all - remove all ids from the given idr tree
* @idp: idr handle
*
* idr_destroy() only frees up unused, cached idp_layers, but this
* function will remove all id mappings and leave all idp_layers
* unused.
*
* A typical clean-up sequence for objects stored in an idr tree will
* use idr_for_each() to free all objects, if necessay, then
* idr_remove_all() to remove all ids, and idr_destroy() to free
* up the cached idr_layers.
*/
void idr_remove_all(struct idr *idp)
{
int n, id, max;
int bt_mask;
struct idr_layer *p;
struct idr_layer *pa[MAX_LEVEL];
struct idr_layer **paa = &pa[0];
n = idp->layers * IDR_BITS;
p = idp->top;
rcu_assign_pointer(idp->top, NULL);
max = 1 << n;
id = 0;
while (id < max) {
while (n > IDR_BITS && p) {
n -= IDR_BITS;
*paa++ = p;
p = p->ary[(id >> n) & IDR_MASK];
}
bt_mask = id;
id += 1 << n;
/* Get the highest bit that the above add changed from 0->1. */
while (n < fls(id ^ bt_mask)) {
if (p)
free_layer(p);
n += IDR_BITS;
p = *--paa;
}
}
idp->layers = 0;
}
EXPORT_SYMBOL(idr_remove_all);
/**
* idr_destroy - release all cached layers within an idr tree
* @idp: idr handle
*/
void idr_destroy(struct idr *idp)
{
while (idp->id_free_cnt) {
struct idr_layer *p = get_from_free_list(idp);
kmem_cache_free(idr_layer_cache, p);
}
}
EXPORT_SYMBOL(idr_destroy);
/**
* idr_find - return pointer for given id
* @idp: idr handle
* @id: lookup key
*
* Return the pointer given the id it has been registered with. A %NULL
* return indicates that @id is not valid or you passed %NULL in
* idr_get_new().
*
* This function can be called under rcu_read_lock(), given that the leaf
* pointers lifetimes are correctly managed.
*/
void *idr_find(struct idr *idp, int id)
{
int n;
struct idr_layer *p;
p = rcu_dereference_raw(idp->top);
if (!p)
return NULL;
n = (p->layer+1) * IDR_BITS;
/* Mask off upper bits we don't use for the search. */
id &= MAX_ID_MASK;
if (id >= (1 << n))
return NULL;
BUG_ON(n == 0);
while (n > 0 && p) {
n -= IDR_BITS;
BUG_ON(n != p->layer*IDR_BITS);
p = rcu_dereference_raw(p->ary[(id >> n) & IDR_MASK]);
}
return((void *)p);
}
EXPORT_SYMBOL(idr_find);
/**
* idr_for_each - iterate through all stored pointers
* @idp: idr handle
* @fn: function to be called for each pointer
* @data: data passed back to callback function
*
* Iterate over the pointers registered with the given idr. The
* callback function will be called for each pointer currently
* registered, passing the id, the pointer and the data pointer passed
* to this function. It is not safe to modify the idr tree while in
* the callback, so functions such as idr_get_new and idr_remove are
* not allowed.
*
* We check the return of @fn each time. If it returns anything other
* than %0, we break out and return that value.
*
* The caller must serialize idr_for_each() vs idr_get_new() and idr_remove().
*/
int idr_for_each(struct idr *idp,
int (*fn)(int id, void *p, void *data), void *data)
{
int n, id, max, error = 0;
struct idr_layer *p;
struct idr_layer *pa[MAX_LEVEL];
struct idr_layer **paa = &pa[0];
n = idp->layers * IDR_BITS;
p = rcu_dereference_raw(idp->top);
max = 1 << n;
id = 0;
while (id < max) {
while (n > 0 && p) {
n -= IDR_BITS;
*paa++ = p;
p = rcu_dereference_raw(p->ary[(id >> n) & IDR_MASK]);
}
if (p) {
error = fn(id, (void *)p, data);
if (error)
break;
}
id += 1 << n;
while (n < fls(id)) {
n += IDR_BITS;
p = *--paa;
}
}
return error;
}
EXPORT_SYMBOL(idr_for_each);
/**
* idr_get_next - lookup next object of id to given id.
* @idp: idr handle
* @nextidp: pointer to lookup key
*
* Returns pointer to registered object with id, which is next number to
* given id. After being looked up, *@nextidp will be updated for the next
* iteration.
*/
void *idr_get_next(struct idr *idp, int *nextidp)
{
struct idr_layer *p, *pa[MAX_LEVEL];
struct idr_layer **paa = &pa[0];
int id = *nextidp;
int n, max;
/* find first ent */
n = idp->layers * IDR_BITS;
max = 1 << n;
p = rcu_dereference_raw(idp->top);
if (!p)
return NULL;
while (id < max) {
while (n > 0 && p) {
n -= IDR_BITS;
*paa++ = p;
p = rcu_dereference_raw(p->ary[(id >> n) & IDR_MASK]);
}
if (p) {
*nextidp = id;
return p;
}
id += 1 << n;
while (n < fls(id)) {
n += IDR_BITS;
p = *--paa;
}
}
return NULL;
}
EXPORT_SYMBOL(idr_get_next);
/**
* idr_replace - replace pointer for given id
* @idp: idr handle
* @ptr: pointer you want associated with the id
* @id: lookup key
*
* Replace the pointer registered with an id and return the old value.
* A %-ENOENT return indicates that @id was not found.
* A %-EINVAL return indicates that @id was not within valid constraints.
*
* The caller must serialize with writers.
*/
void *idr_replace(struct idr *idp, void *ptr, int id)
{
int n;
struct idr_layer *p, *old_p;
p = idp->top;
if (!p)
return ERR_PTR(-EINVAL);
n = (p->layer+1) * IDR_BITS;
id &= MAX_ID_MASK;
if (id >= (1 << n))
return ERR_PTR(-EINVAL);
n -= IDR_BITS;
while ((n > 0) && p) {
p = p->ary[(id >> n) & IDR_MASK];
n -= IDR_BITS;
}
n = id & IDR_MASK;
if (unlikely(p == NULL || !test_bit(n, &p->bitmap)))
return ERR_PTR(-ENOENT);
old_p = p->ary[n];
rcu_assign_pointer(p->ary[n], ptr);
return old_p;
}
EXPORT_SYMBOL(idr_replace);
void __init idr_init_cache(void)
{
idr_layer_cache = kmem_cache_create("idr_layer_cache",
sizeof(struct idr_layer), 0, SLAB_PANIC, NULL);
}
/**
* idr_init - initialize idr handle
* @idp: idr handle
*
* This function is use to set up the handle (@idp) that you will pass
* to the rest of the functions.
*/
void idr_init(struct idr *idp)
{
memset(idp, 0, sizeof(struct idr));
spin_lock_init(&idp->lock);
}
EXPORT_SYMBOL(idr_init);
/**
* DOC: IDA description
* IDA - IDR based ID allocator
*
* This is id allocator without id -> pointer translation. Memory
* usage is much lower than full blown idr because each id only
* occupies a bit. ida uses a custom leaf node which contains
* IDA_BITMAP_BITS slots.
*
* 2007-04-25 written by Tejun Heo <htejun@gmail.com>
*/
static void free_bitmap(struct ida *ida, struct ida_bitmap *bitmap)
{
unsigned long flags;
if (!ida->free_bitmap) {
spin_lock_irqsave(&ida->idr.lock, flags);
if (!ida->free_bitmap) {
ida->free_bitmap = bitmap;
bitmap = NULL;
}
spin_unlock_irqrestore(&ida->idr.lock, flags);
}
kfree(bitmap);
}
/**
* ida_pre_get - reserve resources for ida allocation
* @ida: ida handle
* @gfp_mask: memory allocation flag
*
* This function should be called prior to locking and calling the
* following function. It preallocates enough memory to satisfy the
* worst possible allocation.
*
* If the system is REALLY out of memory this function returns %0,
* otherwise %1.
*/
int ida_pre_get(struct ida *ida, gfp_t gfp_mask)
{
/* allocate idr_layers */
if (!idr_pre_get(&ida->idr, gfp_mask))
return 0;
/* allocate free_bitmap */
if (!ida->free_bitmap) {
struct ida_bitmap *bitmap;
bitmap = kmalloc(sizeof(struct ida_bitmap), gfp_mask);
if (!bitmap)
return 0;
free_bitmap(ida, bitmap);
}
return 1;
}
EXPORT_SYMBOL(ida_pre_get);
/**
* ida_get_new_above - allocate new ID above or equal to a start id
* @ida: ida handle
* @starting_id: id to start search at
* @p_id: pointer to the allocated handle
*
* Allocate new ID above or equal to @ida. It should be called with
* any required locks.
*
* If memory is required, it will return %-EAGAIN, you should unlock
* and go back to the ida_pre_get() call. If the ida is full, it will
* return %-ENOSPC.
*
* @p_id returns a value in the range @starting_id ... %0x7fffffff.
*/
int ida_get_new_above(struct ida *ida, int starting_id, int *p_id)
{
struct idr_layer *pa[MAX_LEVEL];
struct ida_bitmap *bitmap;
unsigned long flags;
int idr_id = starting_id / IDA_BITMAP_BITS;
int offset = starting_id % IDA_BITMAP_BITS;
int t, id;
restart:
/* get vacant slot */
t = idr_get_empty_slot(&ida->idr, idr_id, pa);
if (t < 0)
return _idr_rc_to_errno(t);
if (t * IDA_BITMAP_BITS >= MAX_ID_BIT)
return -ENOSPC;
if (t != idr_id)
offset = 0;
idr_id = t;
/* if bitmap isn't there, create a new one */
bitmap = (void *)pa[0]->ary[idr_id & IDR_MASK];
if (!bitmap) {
spin_lock_irqsave(&ida->idr.lock, flags);
bitmap = ida->free_bitmap;
ida->free_bitmap = NULL;
spin_unlock_irqrestore(&ida->idr.lock, flags);
if (!bitmap)
return -EAGAIN;
memset(bitmap, 0, sizeof(struct ida_bitmap));
rcu_assign_pointer(pa[0]->ary[idr_id & IDR_MASK],
(void *)bitmap);
pa[0]->count++;
}
/* lookup for empty slot */
t = find_next_zero_bit(bitmap->bitmap, IDA_BITMAP_BITS, offset);
if (t == IDA_BITMAP_BITS) {
/* no empty slot after offset, continue to the next chunk */
idr_id++;
offset = 0;
goto restart;
}
id = idr_id * IDA_BITMAP_BITS + t;
if (id >= MAX_ID_BIT)
return -ENOSPC;
__set_bit(t, bitmap->bitmap);
if (++bitmap->nr_busy == IDA_BITMAP_BITS)
idr_mark_full(pa, idr_id);
*p_id = id;
/* Each leaf node can handle nearly a thousand slots and the
* whole idea of ida is to have small memory foot print.
* Throw away extra resources one by one after each successful
* allocation.
*/
if (ida->idr.id_free_cnt || ida->free_bitmap) {
struct idr_layer *p = get_from_free_list(&ida->idr);
if (p)
kmem_cache_free(idr_layer_cache, p);
}
return 0;
}
EXPORT_SYMBOL(ida_get_new_above);
/**
* ida_get_new - allocate new ID
* @ida: idr handle
* @p_id: pointer to the allocated handle
*
* Allocate new ID. It should be called with any required locks.
*
* If memory is required, it will return %-EAGAIN, you should unlock
* and go back to the idr_pre_get() call. If the idr is full, it will
* return %-ENOSPC.
*
* @id returns a value in the range %0 ... %0x7fffffff.
*/
int ida_get_new(struct ida *ida, int *p_id)
{
return ida_get_new_above(ida, 0, p_id);
}
EXPORT_SYMBOL(ida_get_new);
/**
* ida_remove - remove the given ID
* @ida: ida handle
* @id: ID to free
*/
void ida_remove(struct ida *ida, int id)
{
struct idr_layer *p = ida->idr.top;
int shift = (ida->idr.layers - 1) * IDR_BITS;
int idr_id = id / IDA_BITMAP_BITS;
int offset = id % IDA_BITMAP_BITS;
int n;
struct ida_bitmap *bitmap;
/* clear full bits while looking up the leaf idr_layer */
while ((shift > 0) && p) {
n = (idr_id >> shift) & IDR_MASK;
__clear_bit(n, &p->bitmap);
p = p->ary[n];
shift -= IDR_BITS;
}
if (p == NULL)
goto err;
n = idr_id & IDR_MASK;
__clear_bit(n, &p->bitmap);
bitmap = (void *)p->ary[n];
if (!test_bit(offset, bitmap->bitmap))
goto err;
/* update bitmap and remove it if empty */
__clear_bit(offset, bitmap->bitmap);
if (--bitmap->nr_busy == 0) {
__set_bit(n, &p->bitmap); /* to please idr_remove() */
idr_remove(&ida->idr, idr_id);
free_bitmap(ida, bitmap);
}
return;
err:
printk(KERN_WARNING
"ida_remove called for id=%d which is not allocated.\n", id);
}
EXPORT_SYMBOL(ida_remove);
/**
* ida_destroy - release all cached layers within an ida tree
* @ida: ida handle
*/
void ida_destroy(struct ida *ida)
{
idr_destroy(&ida->idr);
kfree(ida->free_bitmap);
}
EXPORT_SYMBOL(ida_destroy);
/**
* ida_simple_get - get a new id.
* @ida: the (initialized) ida.
* @start: the minimum id (inclusive, < 0x8000000)
* @end: the maximum id (exclusive, < 0x8000000 or 0)
* @gfp_mask: memory allocation flags
*
* Allocates an id in the range start <= id < end, or returns -ENOSPC.
* On memory allocation failure, returns -ENOMEM.
*
* Use ida_simple_remove() to get rid of an id.
*/
int ida_simple_get(struct ida *ida, unsigned int start, unsigned int end,
gfp_t gfp_mask)
{
int ret, id;
unsigned int max;
BUG_ON((int)start < 0);
BUG_ON((int)end < 0);
if (end == 0)
max = 0x80000000;
else {
BUG_ON(end < start);
max = end - 1;
}
again:
if (!ida_pre_get(ida, gfp_mask))
return -ENOMEM;
spin_lock(&simple_ida_lock);
ret = ida_get_new_above(ida, start, &id);
if (!ret) {
if (id > max) {
ida_remove(ida, id);
ret = -ENOSPC;
} else {
ret = id;
}
}
spin_unlock(&simple_ida_lock);
if (unlikely(ret == -EAGAIN))
goto again;
return ret;
}
EXPORT_SYMBOL(ida_simple_get);
/**
* ida_simple_remove - remove an allocated id.
* @ida: the (initialized) ida.
* @id: the id returned by ida_simple_get.
*/
void ida_simple_remove(struct ida *ida, unsigned int id)
{
BUG_ON((int)id < 0);
spin_lock(&simple_ida_lock);
ida_remove(ida, id);
spin_unlock(&simple_ida_lock);
}
EXPORT_SYMBOL(ida_simple_remove);
/**
* ida_init - initialize ida handle
* @ida: ida handle
*
* This function is use to set up the handle (@ida) that you will pass
* to the rest of the functions.
*/
void ida_init(struct ida *ida)
{
memset(ida, 0, sizeof(struct ida));
idr_init(&ida->idr);
}
EXPORT_SYMBOL(ida_init);
| {
"pile_set_name": "Github"
} |
#region License
/*
* Copyright (C) 1999-2020 John Källén.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#endregion
using NUnit.Framework;
using Reko.Arch.Sparc;
using Reko.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Reko.UnitTests.Arch.Sparc
{
[TestFixture]
public class Sparc64DisassemblerTests : DisassemblerTestBase<SparcInstruction>
{
private readonly SparcArchitecture64 arch;
private readonly Address addrLoad;
public Sparc64DisassemblerTests()
{
this.arch = new SparcArchitecture64(CreateServiceContainer(), "sparc64");
this.addrLoad = Address.Ptr64(0x10_0000_0000);
}
public override IProcessorArchitecture Architecture => arch;
public override Address LoadAddress => addrLoad;
private void AssertCode(string sExp, string hexBytes)
{
var instr = DisassembleHexBytes(hexBytes);
Assert.AreEqual(sExp, instr.ToString());
}
[Test]
public void Sparc64Dasm_be_pn()
{
AssertCode("be,pn\t0000001000000020", "02600008");
}
[Test]
public void Sparc64Dasm_ldx()
{
AssertCode("ldx\t[%l7+%g1],%g1", "C25DC001");
}
[Test]
public void Sparc64Dasm_fblg_a()
{
AssertCode("fblg,a,pn\t0000000FFFF00000", "25640000");
}
[Test]
public void Sparc64Dasm_fbu()
{
AssertCode("fbu,a,pt\t0000000FFFF1A588", "2F6C6962");
}
[Test]
public void Sparc64Dasm_return()
{
AssertCode("return\t%i7+00000008", "81CFE008");
}
[Test]
public void Sparc64Dasm_stx()
{
AssertCode("stx\t%i1,[%i6+2176]", "F277A880");
}
}
}
| {
"pile_set_name": "Github"
} |
--- uboot/board/ingenic/isvp_t20/board.c 2018-09-28 03:16:06.000000000 +0200
+++ uboot_/board/ingenic/isvp_t20/board.c 2019-04-10 18:58:32.944987100 +0200
@@ -33,7 +33,7 @@
extern int jz_net_initialize(bd_t *bis);
struct cgu_clk_src cgu_clk_src[] = {
- {VPU, MPLL},
+ {VPU, VPLL},
{MACPHY, MPLL},
{MSC, APLL},
{SSI, MPLL},
@@ -67,6 +67,35 @@
#endif
/* used for usb_dete */
/*gpio_set_pull_dir(GPIO_PB(22), 1);*/
+
+ //printf("Sets yellow LED off\n");
+ //run_command("gpio set 38",0);
+ //printf("Sets blue LED off\n");
+ //run_command("gpio set 39",0);
+
+ printf("Enables USB\n");
+ run_command("gpio set 47",0);
+
+ printf("Run SF Probe\n");
+ run_command("sf probe",0);
+
+ printf("Enables SDCARD\n");
+ if (strncmp(getenv("count"), "1", 1) == 0) {
+ printf("ping\n");
+ run_command("gpio set 43",0);
+ run_command("gpio clear 48",0);
+ run_command("sleep 3",0);
+ run_command("gpio clear 43",0);
+ } else {
+ printf("pong\n");
+ run_command("gpio set 43",0);
+ run_command("sleep 1",0);
+ run_command("gpio clear 48",0);
+ }
+
+ //printf("Checks Auto Update\n");
+ //run_command("sdupdate",0);
+
return 0;
}
@@ -101,7 +130,7 @@
/* U-Boot common routines */
int checkboard(void)
{
- puts("Board: ISVP (Ingenic XBurst T20 SoC)\n");
+ puts("Board: Openfang compatible board (Ingenic XBurst T20 SoC)\n");
return 0;
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>CMSIS DSP Software Library: arm_max_q7.c File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javaScript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body onload='searchBox.OnSelectItem(0);'>
<!-- Generated by Doxygen 1.7.2 -->
<script type="text/javascript"><!--
var searchBox = new SearchBox("searchBox", "search",false,'Search');
--></script>
<div class="navigation" id="top">
<div class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li id="searchli">
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>Globals</span></a></li>
</ul>
</div>
</div>
<div class="header">
<div class="summary">
<a href="#func-members">Functions</a> </div>
<div class="headertitle">
<h1>arm_max_q7.c File Reference</h1> </div>
</div>
<div class="contents">
<code>#include "<a class="el" href="arm__math_8h_source.html">arm_math.h</a>"</code><br/>
<p><a href="arm__max__q7_8c_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="func-members"></a>
Functions</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="group___max.html#ga6afd64d381b5c232de59163ebfe71e35">arm_max_q7</a> (<a class="el" href="arm__math_8h.html#ae541b6f232c305361e9b416fc9eed263">q7_t</a> *pSrc, uint32_t <a class="el" href="arm__variance__example__f32_8c.html#ab6558f40a619c2502fbc24c880fd4fb0">blockSize</a>, <a class="el" href="arm__math_8h.html#ae541b6f232c305361e9b416fc9eed263">q7_t</a> *pResult, uint32_t *pIndex)</td></tr>
</table>
</div>
<!--- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark"> </span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark"> </span>Defines</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<hr class="footer"/><address class="footer"><small>Generated on Fri Jul 15 2011 13:16:19 for CMSIS DSP Software Library by 
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.2 </small></address>
</body>
</html>
| {
"pile_set_name": "Github"
} |
---
title: .NET Framework 中辅助功能的新增功能
description: 请参阅从 .NET Framework 4.7.1 开始的 .NET 辅助功能的新增功能。 利用辅助功能,应用可以为辅助技术用户提供正确的体验。
ms.date: 04/18/2019
dev_langs:
- csharp
- vb
helpviewer_keywords:
- what's new [.NET Framework]
ms.openlocfilehash: d204bea7f5ec1ed0c25b7b2dedd04d61c7f3e93d
ms.sourcegitcommit: aa6d8a90a4f5d8fe0f6e967980b8c98433f05a44
ms.translationtype: HT
ms.contentlocale: zh-CN
ms.lasthandoff: 09/16/2020
ms.locfileid: "90679542"
---
# <a name="whats-new-in-accessibility-in-the-net-framework"></a>.NET Framework 中辅助功能的新增功能
.NET Framework 旨在让用户更轻松地使用应用程序。 辅助功能使应用程序能够为辅助技术用户提供最佳体验。 从 .NET Framework 4.7.1 开始,.NET Framework 包括大量辅助功能改进,使开发人员能够创建易于访问的应用程序。
## <a name="accessibility-switches"></a>辅助功能开关
如果应用面向 .NET Framework 4.7 或更低版本,但是在 .NET Framework 4.7.1 或更高版本上运行,可以将应用配置为选择使用辅助功能。 如果应用面向 .NET Framework 4.7.1 或更高版本,还可以将应用配置为使用旧版功能(且不使用辅助功能)。 包括辅助功能的每个 .NET Framework 版本都有一个特定于版本的辅助开关,请将它添加到应用程序配置文件 [`<runtime>`](../configure-apps/file-schema/runtime/index.md) 部分中的 [`<AppContextSwitchOverrides>`](../configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md) 元素。 以下是受支持的开关:
|Version|开关|
|---|---|
|.NET Framework 4.7.1|"Switch.UseLegacyAccessibilityFeatures"|
|.NET Framework 4.7.2|"Switch.UseLegacyAccessibilityFeatures.2"|
|.NET Framework 4.8|"Switch.UseLegacyAccessibilityFeatures.3"|
### <a name="taking-advantage-of-accessibility-enhancements"></a>利用辅助功能改进
对于面向 .NET Framework 4.7.1 或更高版本的应用程序,新的辅助功能默认情况下处于启用状态。 此外,对于面向 .NET Framework 早期版本,但在 .NET Framework 4.7.1 或更高版本上运行的应用程序,可通过将开关添加到应用程序配置文件 [`<runtime>`](../configure-apps/file-schema/runtime/index.md) 部分中的 [`<AppContextSwitchOverrides>`](../configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md) 元素并将其值设为 `false` 来选择弃用旧辅助功能行为(因而利用辅助功能改进)。 以下代码演示如何选择使用 .NET Framework 4.7.1 中引入的辅助功能改进:
```xml
<runtime>
<!-- AppContextSwitchOverrides value attribute is in the form of 'key1=true|false;key2=true|false -->
<AppContextSwitchOverrides value="Switch.UseLegacyAccessibilityFeatures=false" />
</runtime>
```
如果选择使用更高的 .NET Framework 版本中的辅助功能,还必须显式选择使用更低 .NET Framework 版本的功能。 通过配置应用以利用 .NET Framework 4.7.1 和 4.7.2 中的辅助功能改进需要以下 [`<AppContextSwitchOverrides>`](../configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md) 元素:
```xml
<runtime>
<!-- AppContextSwitchOverrides value attribute is in the form of 'key1=true|false;key2=true|false -->
<AppContextSwitchOverrides value="Switch.UseLegacyAccessibilityFeatures=false;Switch.UseLegacyAccessibilityFeatures.2=false" />
</runtime>
```
通过配置应用以利用 .NET Framework 4.7.1、4.7.2 和 4.8 中的辅助功能改进需要以下 [`<AppContextSwitchOverrides>`](../configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md) 元素:
```xml
<runtime>
<!-- AppContextSwitchOverrides value attribute is in the form of 'key1=true|false;key2=true|false -->
<AppContextSwitchOverrides value="Switch.UseLegacyAccessibilityFeatures=false;Switch.UseLegacyAccessibilityFeatures.2=false;Switch.UseLegacyAccessibilityFeatures.3=false" />
</runtime>
```
### <a name="restoring-legacy-behavior"></a>还原旧行为
对于面向 .NET Framework 4.7.1 或更高版本的应用程序,可通过将开关添加到应用程序配置文件 [`<runtime>`](../configure-apps/file-schema/runtime/index.md) 部分中的 [`<AppContextSwitchOverrides>`](../configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md) 元素并将其值设为 `true` 来禁用辅助功能。 例如,以下配置选择弃用 .NET Framework 4.7.2 中引入的辅助功能:
```xml
<runtime>
<!-- AppContextSwitchOverrides value attribute is in the form of 'key1=true|false;key2=true|false -->
<AppContextSwitchOverrides value="Switch.UseLegacyAccessibilityFeatures.2=true" />
</runtime>
```
## <a name="whats-new-in-accessibility-in-net-framework-48"></a>.NET Framework 4.8 中辅助功能的新增功能
.NET Framework 4.8 在以下几个领域包含新增辅助功能:
- [Windows 窗体](#winforms48)
- [Windows Presentation Foundation (WPF)](#wpf48)
- [Windows Workflow Foundation (WF) 工作流设计器](#wf48)
<a name="winforms48"></a>
### <a name="windows-forms"></a>Windows 窗体
在 .NET Framework 4.8 中,Windows 窗体将对 LiveRegions 和通知事件的支持添加到多个常用控件中。 它还会在用户使用键盘导航到控件时添加工具提示支持。
**标签和 StatusStrips 中的 UIA LiveRegions 支持**
UIA LiveRegions 允许应用程序开发人员将用户工作位置之外的某个控件中的文本更改通知给屏幕阅读器。 例如,对于显示连接状态的 <xref:System.Windows.Forms.StatusStrip> 控件,这很有用。 如果连接断开且状态发生更改,开发人员可能会希望将此情况通知给屏幕阅读器。
从 .NET Framework 4.8 开始,Windows 窗体同时为 <xref:System.Windows.Forms.Label> 和 <xref:System.Windows.Forms.StatusStrip> 控件实现 UIA LiveRegions。 例如,以下代码在名为 `label1` 的 <xref:System.Windows.Forms.Label> 控件中使用 LiveRegion:
```csharp
public Form1()
{
InitializeComponent();
label1.AutomationLiveSetting = AutomationLiveSetting.Polite;
}
…
Label1.Text = “Ready!”;
```
无论用户在何处与应用程序交互,讲述人都会宣布“准备就绪”。
还可以将 <xref:System.Windows.Forms.UserControl> 实现为 LiveRegion:
```csharp
using System;
using System.Windows.Forms;
using System.Windows.Forms.Automation;
namespace WindowsFormsApplication
{
public partial class UserControl1 : UserControl, IAutomationLiveRegion
{
public UserControl1()
{
InitializeComponent();
}
public AutomationLiveSetting AutomationLiveSetting { get; set; }
private AutomationLiveSetting IAutomationLiveRegion.GetLiveSetting()
{
return this.AutomationLiveSetting;
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
AutomationNotifications.UiaRaiseLiveRegionChangedEvent(this.AccessibilityObject);
}
}
}
```
**UIA 通知事件**
Windows 10 Fall Creators Update 中引入的 UIA 通知事件允许应用程序引发 UIA 事件,这使得讲述人仅根据你为事件提供的文本来进行宣读,而无需在 UI 中使用相应的控件。 在某些情况下,这是一种能够显着改善应用辅助功能的简单方法。 也可以用于通知可能需要很长时间的某些进程的进度。 有关 UIA 通知事件的详细信息,请参阅[桌面应用程序是否可以利用新的 UI 通知事件?](/archive/blogs/winuiautomation/can-your-desktop-app-leverage-the-new-uia-notification-event-in-order-to-have-narrator-say-exactly-what-your-customers-need)。
下面的示例会引发[通知事件](xref:System.Windows.Forms.AccessibleObject.RaiseAutomationNotification%2A):
```csharp
MethodInfo raiseMethod = typeof(AccessibleObject).GetMethod("RaiseAutomationNotification");
if (raiseMethod != null) {
raiseMethod.Invoke(progressBar1.AccessibilityObject, new object[3] {/*Other*/ 4, /*All*/ 2, "The progress is 50%." });
}
```
**键盘访问工具提示**
在面向 .NET Framework 4.7.2 及更早版本的应用程序中,只能通过将鼠标指针移到控件上,才能触发控件[工具提示](xref:System.Windows.Forms.ToolTip)。 从 .NET Framework 4.8 开始,键盘用户可以通过使用 Tab 键或箭头键(具有或不具有修饰键)来聚焦控件,从而触发控件的工具提示。 要实现这一特定的辅助功能优化效果,需要额外的 [AppContext 开关](../configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md):
```xml
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
</startup>
<runtime>
<!-- AppContextSwitchOverrides values are in the form of 'key1=true|false;key2=true|false -->
<!-- Please note that disabling Switch.UseLegacyAccessibilityFeatures, Switch.UseLegacyAccessibilityFeatures.2 and Switch.UseLegacyAccessibilityFeatures.3 is required to disable Switch.System.Windows.Forms.UseLegacyToolTipDisplay -->
<AppContextSwitchOverrides value="Switch.UseLegacyAccessibilityFeatures=false;Switch.UseLegacyAccessibilityFeatures.2=false;Switch.UseLegacyAccessibilityFeatures.3=false;Switch.System.Windows.Forms.UseLegacyToolTipDisplay=false"/>
</runtime>
</configuration>
```
下图显示用户使用键盘选中按钮时的工具提示。

<a name="wpf48"></a>
### <a name="windows-presentation-foundation-wpf"></a>Windows Presentation Foundation (WPF)
从 .NET Framework 4.8 开始,WPF 包括大量辅助功能改进。
**屏幕讲述人不再宣读可见性为“折叠”或“隐藏”的元素**
可见性为“折叠”或“隐藏”的元素不再被屏幕讲述人宣读。 如果向用户宣读包含可见性为 <xref:System.Windows.Visibility.Collapsed?displayProperty=nameWithType> 或 <xref:System.Windows.Visibility.Hidden?displayProperty=nameWithType> 的元素的用户界面,屏幕阅读器可能会错误呈现这些界面。 从 .NET Framework 4.8 开始,WPF 不再在 UIAutomation 树的控制视图中包含折叠或隐藏的元素,屏幕阅读器无法再宣读这些元素。
**与非基于修饰器的文本选择配合使用的 SelectionTextBrush 属性**
在 .NET Framework 4.7.2 中,WPF 添加了无需使用修饰器层即可绘制 <xref:System.Windows.Controls.TextBox> 和 <xref:System.Windows.Controls.PasswordBox> 文本选择的功能。 此方案中所选文本的前景色由 <xref:System.Windows.SystemColors.HighlightTextBrush?displayProperty=nameWithType> 决定。
.NET Framework 4.8 添加了一个新属性 `SelectionTextBrush`,允许开发人员在使用非基于修饰器的文本选择时为所选文本选择特定画笔。 此属性仅适用于 <xref:System.Windows.Controls.Primitives.TextBoxBase> 派生的控件和启用了非基于修饰器的文本选择功能的 WPF 应用程序中的 <xref:System.Windows.Controls.PasswordBox> 控件。 该属性不适用于 <xref:System.Windows.Controls.RichTextBox> 控件。 如果未启用非基于修饰器的文本选择功能,则忽略此属性。
要使用此属性,只需将其添加到 XAML 代码,并使用适当的画笔或绑定。 生成的文本选择如下所示:

可以结合使用 `SelectionBrush` 和 `SelectionTextBrush` 属性来生成你认为合适的任何背景色和前景色组合。
**对 UIAutomation ControllerFor 属性的支持**
UIAutomation 的 `ControllerFor` 属性返回一系列由支持该属性的自动化元素操纵的自动化元素。 此属性通常用于自动建议辅助功能。 应在自动化元素会影响应用程序 UI 或桌面的一个或多个段时使用 `ControllerFor`。 否则,很难将控制操作的影响与 UI 元素关联。 此功能增加了控件为 `ControllerFor` 属性提供值的功能。
.NET framework 4.8 添加了新的虚拟方法 <xref:System.Windows.Automation.Peers.AutomationPeer.GetControlledPeersCore?displayProperty=nameWithType?displayProperty=nameWithType>。 要为 `ControllerFor` 属性提供值,只需替代此方法并为此 <xref:System.Windows.Automation.Peers.AutomationPeer> 操作的控件返回 `List<AutomationPeer>`:
```csharp
public class AutoSuggestTextBox: TextBox
{
protected override AutomationPeer OnCreateAutomationPeer()
{
return new AutoSuggestTextBoxAutomationPeer(this);
}
public ListBox SuggestionListBox;
}
internal class AutoSuggestTextBoxAutomationPeer : TextBoxAutomationPeer
{
public AutoSuggestTextBoxAutomationPeer(AutoSuggestTextBox owner) : base(owner)
{
}
protected override List<AutomationPeer> GetControlledPeersCore()
{
List<AutomationPeer> controlledPeers = new List<AutomationPeer>();
AutoSuggestTextBox owner = Owner as AutoSuggestTextBox;
controlledPeers.Add(UIElementAutomationPeer.CreatePeerForElement(owner.SuggestionListBox));
return controlledPeers;
}
}
```
**键盘访问工具提示**
在 .NET Framework 4.7.2 和更早版本中,仅当用户将鼠标光标悬停在控件上时,系统才会显示工具提示。 在 .NET Framework 4.8 中,工具提示还会在键盘聚焦时显示,也可以通过键盘快捷方式显示。
要启用此功能,应用程序需要面向 .NET Framework 4.8,或使用 `Switch.UseLegacyAccessibilityFeatures.3` 和 `Switch.UseLegacyToolTipDisplay` [AppContext](../configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md) 开关来选择加入。 下面是一个示例应用程序配置文件:
```xml
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<runtime>
<AppContextSwitchOverrides value="Switch.UseLegacyAccessibilityFeatures=false;Switch.UseLegacyAccessibilityFeatures.2=false;Switch.UseLegacyAccessibilityFeatures.3=false;Switch.UseLegacyToolTipDisplay=false" />
</runtime>
</configuration>
```
启用后,一旦控件接收到键盘焦点,包含工具提示的所有控件都会显示工具提示。 随时间推移或当键盘焦点发生变化时,可关闭工具提示。 用户还可以通过使用新的键盘快捷键 Ctrl+Shift+F10 手动关闭工具提示。 关闭工具提示后,可以使用相同的键盘快捷键再次显示。
> [!NOTE]
> <xref:System.Windows.Controls.Ribbon.Ribbon> 控件上的[功能区工具提示](xref:System.Windows.Controls.Ribbon.RibbonToolTip)不在键盘聚焦时显示;它们仅通过键盘快捷键显示。
**添加了对 SizeOfSet 和 PositionInSet UIAutomation 属性的支持**
Windows 10 引入了两个新的 UIAutomation 属性(`SizeOfSet` 和 `PositionInSet`),应用程序用其描述集合中的项数。 然后,UIAutomation 客户端应用程序(如屏幕阅读器)可以向某个应用程序查询这些属性,并宣布应用程序 UI 的准确表示形式。
从 .NET Framework 4.8 开始,WPF 向 WPF 应用程序中的 UIAutomation 公开这两个属性。 这可以通过以下两种方式实现:
- 通过使用依赖项属性。
WPF 添加了两个新的依赖项属性:<xref:System.Windows.Automation.AutomationProperties.SizeOfSet?displayProperty=nameWithType> 和 <xref:System.Windows.Automation.AutomationProperties.PositionInSet?displayProperty=nameWithType>。 开发人员可以使用 XAML 来设置它们的值:
```xaml
<Button AutomationProperties.SizeOfSet="3"
AutomationProperties.PositionInSet="1">Button 1</Button>
<Button AutomationProperties.SizeOfSet="3"
AutomationProperties.PositionInSet="2">Button 2</Button>
<Button AutomationProperties.SizeOfSet="3"
AutomationProperties.PositionInSet="3">Button 3</Button>
```
- 通过替代 AutomationPeer 虚拟方法。
<xref:System.Windows.Automation.Peers.AutomationPeer.GetSizeOfSetCore> 和 <xref:System.Windows.Automation.Peers.AutomationPeer.GetPositionInSetCore> 虚拟方法已添加到 AutomationPeer 类中。 开发人员可以通过替代这些方法为 `SizeOfSet` 和 `PositionInSet` 提供值,如以下示例所示:
```csharp
public class MyButtonAutomationPeer : ButtonAutomationPeer
{
protected override int GetSizeOfSetCore()
{
// Call into your own logic to provide a value for SizeOfSet
return CalculateSizeOfSet();
}
protected override int GetPositionInSetCore()
{
// Call into your own logic to provide a value for PositionInSet
return CalculatePositionInSet();
}
}
```
此外,开发人员无需执行其他操作,<xref:System.Windows.Controls.ItemsControl> 实例中的项会自动为这些属性提供值。 如果将 <xref:System.Windows.Controls.ItemsControl> 归组,则组的集合表示为一个集,并且每个组计为一个单独的集,该组内的每个项提供其在该组内的位置以及该组的大小。 虚拟化不会影响自动值。 即使没有实现某个项,它仍然会计入集的总大小,并影响其在同级项集中的位置。
仅当应用程序面向 .NET Framework 4.8 时,才会提供自动值。 对于面向 .NET Framework 早期版本的应用程序,可以设置 `Switch.UseLegacyAccessibilityFeatures.3` [AppContext 开关](../configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md),如以下 App.config 文件中所示:
```xml
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<runtime>
<AppContextSwitchOverrides value="Switch.UseLegacyAccessibilityFeatures=false;Switch.UseLegacyAccessibilityFeatures.2=false;Switch.UseLegacyAccessibilityFeatures.3=false" />
</runtime>
</configuration>
```
<a name="wf48"></a>
### <a name="windows-workflow-foundation-wf-workflow-designer"></a>Windows Workflow Foundation (WF) 工作流设计器
.NET Framework 4.8 中的工作流设计器包含以下更改:
- 使用讲述人的用户将体验到 FlowSwitch 事例标签的改进。
- 使用讲述人的用户将体验到按钮描述的改进。
- 选择高对比度主题的用户将看到工作流设计器及其控件可见性方面的改进,例如元素间的对比度效果更好和用于焦点元素的更明显的选择框。
如果应用程序面向 .NET Framework 4.7.2 或更早版本,则可以通过在应用程序配置文件中将 `Switch.UseLegacyAccessibilityFeatures.3` [AppContext 开关](../configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md)设置为 `false` 来选择这些更改。 有关详细信息,请参阅本文中的[利用辅助功能改进](#taking-advantage-of-accessibility-enhancements)部分。
## <a name="whats-new-in-accessibility-in-net-framework-472"></a>.NET Framework 4.7.2 中辅助功能的新增功能
.NET Framework 4.7.2 在以下几个领域包含新增辅助功能:
- [Windows 窗体](#winforms472)
- [Windows Presentation Foundation (WPF)](#wpf472)
<a name="winforms472"></a>
### <a name="windows-forms"></a>Windows 窗体
**高对比度主题中的 OS 定义的颜色**
自 .NET Framework 4.7.2 起,Windows 窗体使用高对比度主题中的操作系统定义的颜色。 这会影响以下控件:
- <xref:System.Windows.Forms.ToolStripDropDownButton> 控件的下拉箭头。
- <xref:System.Windows.Forms.ButtonBase.FlatStyle> 设为 <xref:System.Windows.Forms.FlatStyle.Flat?displayProperty=nameWithType> 或 <xref:System.Windows.Forms.FlatStyle.Popup?displayProperty=nameWithType> 的 <xref:System.Windows.Forms.Button>、<xref:System.Windows.Forms.RadioButton> 和 <xref:System.Windows.Forms.CheckBox> 控件。 以前,所选文本和背景颜色对比度低,难以阅读。
- <xref:System.Windows.Forms.Control.Enabled> 属性设为 `false` 的 <xref:System.Windows.Forms.GroupBox> 中所包含的控件。
- 在高对比度模式下,<xref:System.Windows.Forms.ToolStripButton>、<xref:System.Windows.Forms.ToolStripComboBox> 和 <xref:System.Windows.Forms.ToolStripDropDownButton> 控件的亮度对比度提高。
- <xref:System.Windows.Forms.DataGridViewLinkCell> 的 <xref:System.Windows.Forms.DataGridViewLinkCell.LinkColor> 属性。
**讲述人改进**
自 .NET Framework 4.7.2 起,讲述人支持在以下几个方面改进:
- 它在公布 <xref:System.Windows.Forms.ToolStripMenuItem> 的文本时会公布 <xref:System.Windows.Forms.ToolStripMenuItem.ShortcutKeys?displayProperty=nameWithType> 属性的值。
- 当 <xref:System.Windows.Forms.ToolStripMenuItem> 的 <xref:System.Windows.Forms.Control.Enabled> 属性设置为 `false` 时,它会有所指示。
- 当 <xref:System.Windows.Forms.ListView.CheckBoxes?displayProperty=nameWithType> 属性设置为 `true` 时,它会针对复选框的状态给出反馈。
- 讲述人扫描模式焦点顺序与 ClickOnce 下载对话框窗口中控件的视觉顺序一致。
**DataGridView 改进**
自 .NET Framework 4.7.2 起,<xref:System.Windows.Forms.DataGridView> 控件引入了以下辅助功能改进:
- 可以使用键盘对行进行排序。 用户可使用 F3 按当前列排序。
- 若 <xref:System.Windows.Forms.DataGridView.SelectionMode?displayProperty=nameWithType> 设置为 <xref:System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect?displayProperty=nameWithType>,当用户按 Tab 键遍历当前行中的单元格时,列标题将更改颜色来指示当前列。
- <xref:System.Windows.Forms.DataGridViewLinkCell.DataGridViewLinkCellAccessibleObject?displayProperty=nameWithType> 的 <xref:System.Windows.Forms.AccessibleObject.Parent?displayProperty=nameWithType> 属性返回正确的父控件。
**改进了视觉提示**
- 具有空 <xref:System.Windows.Forms.ButtonBase.Text> 属性的 <xref:System.Windows.Forms.RadioButton> 和 <xref:System.Windows.Forms.CheckBox> 控件在接收到焦点时会显示焦点指示器。
**改进了属性网格支持**
- 现在,仅在 PropertyGrid 元素启用时,<xref:System.Windows.Forms.PropertyGrid> 控件子元素才会为 <xref:System.Windows.Automation.ValuePattern.IsReadOnlyProperty> 属性返回 `true`。
- 仅在用户可更改 PropertyGrid 元素时,<xref:System.Windows.Forms.PropertyGrid> 控件子元素才会为 <xref:System.Windows.Automation.AutomationElement.IsEnabledProperty> 属性返回 `false`。
**改进了的键盘导航**
- <xref:System.Windows.Forms.ToolStripButton> 控件允许在焦点包含在 <xref:System.Windows.Forms.ToolStripPanel>(其 <xref:System.Windows.Forms.ToolStripPanel.TabStop> 属性设置为 `true`)中时进行聚焦
<a name="wpf472"></a>
### <a name="windows-presentation-foundation-wpf"></a>Windows Presentation Foundation (WPF)
**对复选框和单选按钮控件的更改**
在 .NET Framework 4.7.1 和更低版本中,WPF <xref:System.Windows.Controls.CheckBox?displayProperty=nameWithType> 和 <xref:System.Windows.Controls.RadioButton?displayProperty=nameWithType> 控件不一致且在经典和高对比度主题中具有不正确的焦点视觉对象。 控件没有内容集时会出现这些问题。 这会使得主题间的转换变得混乱且难以看到焦点视觉对象。
现在,在 .NET Framework 4.7.2 中,主题间的这些视觉对象更加一致,并且在经典和高对比度主题中更轻松可见。
**在 WPF 应用程序中托管的 WinForms 控件**
对于 .NET Framework 4.7.1 和更低版本中的 WPF 应用程序托管的 WinForms 控件,如果该层中的第一个或最后一个控件是 WPF <xref:System.Windows.Forms.Integration.ElementHost> 控件,那么用户不能按 Tab 退出 WinForms 层。 现在,在 .NET Framework 4.7.2 中,用户能够按 Tab 退出 WinForms 层。
但是,依赖于永不转义 WinForms 层的焦点的自动化应用程序不再会按预期工作。
## <a name="whats-new-in-accessibility-in-net-framework-471"></a>.NET Framework 4.7.1 中辅助功能的新增功能
.NET Framework 4.7.1 在以下几个领域包含新增辅助功能:
- [Windows Presentation Foundation (WPF)](#wpf471)
- [Windows 窗体](#winforms471)
- [ASP.NET Web 控件](#aspnet471)
- [.NET SDK 工具](#tools471)
- [Windows Workflow Foundation (WF) 工作流设计器](#wf471)
<a name="wpf471"></a>
### <a name="windows-presentation-foundation-wpf"></a>Windows Presentation Foundation (WPF)
**屏幕阅读器改进**
如果启用了辅助功能改进,.NET Framework 4.7.1 包括以下可影响屏幕阅读器的增强功能:
- 在 .NET Framework 4.7 及更低版本中,<xref:System.Windows.Controls.Expander> 控件由屏幕阅读器宣称为按钮。 从 .NET Framework 4.7.1 开始,它们被正确地称为可展开/可折叠组。
- 在 .NET Framework 4.7 及更低版本中,<xref:System.Windows.Controls.DataGridCell> 控件由屏幕阅读器宣称为“自定义”。 从 .NET Framework 4.7.1 开始,它们被正确地称为数据网格单元格(已本地化)。
- 从 .NET Framework 4.7.1 开始,屏幕阅读器宣布可编辑 <xref:System.Windows.Controls.ComboBox> 的名称。
- 在 .NET Framework 4.7 及更低版本中,<xref:System.Windows.Controls.PasswordBox> 控件被宣称为“视图中没有任何项”或有其他错误行为。 此问题已在 .NET Framework 4.7.1 及更高版本中解决。
**UIAutomation LiveRegion 支持**
屏幕阅读器(如讲述人)可帮助用户阅读应用程序的 UI 内容,通常通过具有焦点的 UI 内容的文本到语音转换输出实现。 但是,如果 UI 元素更改,并且不具有焦点,则用户可能不会收到通知,并且可能会错过重要信息。 活动区域旨在解决此问题。 开发人员可使用它们来通知屏幕阅读器或任何其他 UIAutomation 客户端 UI 元素有重要更改。 然后,屏幕阅读器可确定向用户通知此更改的方式和时间。
为了支持活动区域,向 WPF 添加了以下 API:
- <xref:System.Windows.Automation.AutomationElementIdentifiers.LiveSettingProperty?displayProperty=nameWithType> 和 <xref:System.Windows.Automation.AutomationElementIdentifiers.LiveRegionChangedEvent?displayProperty=nameWithType> 字段,用于标识 LiveSetting 属性和 LiveRegionChanged 事件。 可通过使用 XAML 来进行设置。
- AutomationProperties.LiveSetting 附加属性,用于向屏幕阅读器通知 UI 更改对用户的重要性。
- <xref:System.Windows.Automation.AutomationProperties.LiveSettingProperty?displayProperty=nameWithType> 属性,用于标识 AutomationProperties.LiveSetting 附加属性。
- <xref:System.Windows.Automation.Peers.AutomationPeer.GetLiveSettingCore%2A?displayProperty=nameWithType> 方法,可替代该方法以提供 LiveSetting 值。
- <xref:System.Windows.Automation.AutomationProperties.GetLiveSetting%2A?displayProperty=nameWithType> 和 <xref:System.Windows.Automation.AutomationProperties.SetLiveSetting%2A?displayProperty=nameWithType> 方法,用于获取和设置 LiveSetting 值。
- <xref:System.Windows.Automation.AutomationLiveSetting?displayProperty=nameWithType> 枚举,用于定义以下可能的 LiveSetting 值:
- <xref:System.Windows.Automation.AutomationLiveSetting.Off?displayProperty=nameWithType>。 如果活动区域的内容已更改,则该元素不会发送通知。
- <xref:System.Windows.Automation.AutomationLiveSetting.Polite?displayProperty=nameWithType>。 如果活动区域的内容已更改,则该元素将发送非中断通知。
- <xref:System.Windows.Automation.AutomationLiveSetting.Assertive?displayProperty=nameWithType>. 如果活动区域的内容已更改,则该元素将发送中断通知。
可通过对相关元素设置 AutomationProperties.LiveSetting 属性来创建 LiveRegion,如以下示例所示:
```xaml
<TextBlock Name="myTextBlock" AutomationProperties.LiveSetting="Assertive">announcement</TextBlock>
```
活动区域中的数据发生更改,并且需要通知屏幕阅读器时,可显式引发事件,如以下示例所示。
```csharp
var peer = FrameworkElementAutomationPeer.FromElement(myTextBlock);
peer.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged);
```
```vb
Dim peer = FrameworkElementAutomationPeer.FromElement(myTextBlock)
peer.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged)
```
**高对比度**
从 .NET Framework 4.7.1 开始,对多种 WPF 控件进行了高对比度改进。 可在设置 <xref:System.Windows.SystemParameters.HighContrast%2A> 主题后看到这些改进。 这些方法包括:
- <xref:System.Windows.Controls.Expander> 控件
<xref:System.Windows.Controls.Expander> 控件的焦点视觉对象现在可见。 <xref:System.Windows.Controls.ComboBox>、<xref:System.Windows.Controls.ListBox> 和 <xref:System.Windows.Controls.RadioButton> 控件的键盘视觉对象也可见。 例如:
在此之前:

之后:

- <xref:System.Windows.Controls.CheckBox> 和 <xref:System.Windows.Controls.RadioButton> 控件
在高对比度主题下选中时,<xref:System.Windows.Controls.CheckBox> 和 <xref:System.Windows.Controls.RadioButton> 控件中的文本更易于查看。 例如:
在此之前:

之后:

- <xref:System.Windows.Controls.ComboBox> 控件
从 .NET Framework 4.7.1 开始,已禁用的 <xref:System.Windows.Controls.ComboBox> 控件的边框与禁用的文本颜色相同。 例如:
在此之前:

之后:

此外,已禁用的按钮和具有焦点的按钮使用正确的主题颜色。
在此之前:

之后:

最后,在 .NET Framework 4.7 及更低版本中,将 <xref:System.Windows.Controls.ComboBox> 控件的样式设置为 `Toolbar.ComboBoxStyleKey` 会导致下拉箭头不可见。 此问题已在 .NET Framework 4.7.1 及更高版本中解决。 例如:
在此之前:

之后:

- <xref:System.Windows.Controls.DataGrid> 控件
从 .NET Framework 4.7.1 开始,<xref:System.Windows.Controls.DataGrid> 控件中的排序指示符箭头现在使用正确的主题颜色。 例如:
在此之前:

之后:

此外,在 .NET Framework 4.7 及更低版本中,在高对比度模式下,默认链接样式在鼠标悬停在其上时更改为不正确的颜色。 此问题已在 .NET Framework 4.7.1 及更高版本中解决。 同样,从 .NET Framework 4.7.1 开始,<xref:System.Windows.Controls.DataGrid> 复选框列对键盘焦点反馈使用预期的颜色。
在此之前:

之后:

有关 .NET Framework 4.7.1 中 WPF 辅助功能改进的详细信息,请参阅 [WPF 辅助功能改进](../migration-guide/retargeting/4.7-4.7.1.md#accessibility-improvements-in-wpf)。
<a name="winforms471"></a>
### <a name="windows-forms-accessibility-improvements"></a>Windows 窗体辅助功能改进
在 .NET Framework 4.7.1 中,Windows 窗体 (WinForms) 包括以下几个方面的辅助功能改进。
**改进了高对比度模式下的显示**
从 .NET Framework 4.7.1 开始,多种 WinForms 控件改进了高对比度模式下在操作系统中的呈现方式。 Windows 10 更改了一些高对比度系统颜色的值,而 Windows 窗体基于 Windows 10 Win32 框架。 为获得最佳体验,请运行最新版本的 Windows,并通过在测试应用程序中添加 app.manifest 文件选择使用最新的 OS 更改,同时取消注释 Windows 10 支持的 OS 行,最终结果如下所示:
```xml
<!-- Windows 10 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
```
高对比度更改的一些示例包括:
- <xref:System.Windows.Forms.MenuStrip> 项中的复选标记更易于查看。
- 选中后,禁用的 <xref:System.Windows.Forms.MenuStrip> 项更易于查看。
- 所选 <xref:System.Windows.Forms.Button> 控件中的文本与选中颜色形成鲜明对比。
- 禁用的文本更易于阅读。 例如:
在此之前:

之后:

- “线程异常”对话框中的高对比度改进。
**改进了讲述人支持**
.NET Framework 4.7.1 中的 Windows 窗体对讲述人进行了以下辅助功改进:
- 讲述人以及其他 UI 自动化工具可访问 <xref:System.Windows.Forms.MonthCalendar> 控件。
- 当某个项的选中状态更改时,<xref:System.Windows.Forms.CheckedListBox> 控件会通知讲述人,因此用户可获知更改了列表项的值。
- <xref:System.Windows.Forms.DataGridViewCell> 控件向讲述人报告正确的只读状态。
- 讲述人现在可以阅读已禁用的 <xref:System.Windows.Forms.ToolStripMenuItem> 文本,而以前它会跳过禁用的菜单项。
**增强了对 UIAutomation 辅助功能模式的支持**
从 .NET Framework 4.7.1 开始,辅助功能技术工具的开发人员可以利用常见的 API 辅助功能模式和多个 WinForms 控件的属性。 这些辅助功能改进包括:
- <xref:System.Windows.Forms.ComboBox> 和 <xref:System.Windows.Forms.ToolStripSplitButton> 现在支持[展开/折叠模式](../ui-automation/implementing-the-ui-automation-expandcollapse-control-pattern.md)。
- <xref:System.Windows.Forms.DataGridViewCheckBoxCell> 现在支持[切换模式](../ui-automation/implementing-the-ui-automation-toggle-control-pattern.md)。
- <xref:System.Windows.Forms.ToolStripItem> 控件支持 <xref:System.Windows.Automation.AutomationElement.AutomationElementInformation.Name> 属性和[展开/折叠模式](../ui-automation/implementing-the-ui-automation-expandcollapse-control-pattern.md)。
- <xref:System.Windows.Forms.NumericUpDown> 和 <xref:System.Windows.Forms.DomainUpDown> 控件支持 <xref:System.Windows.Automation.AutomationElement.AutomationElementInformation.Name> 属性。
**改进了属性浏览器体验**
从 .NET Framework 4.7.1 开始,Windows 窗体包括以下改进:
- 更好地通过各种下拉选择窗口使用键盘导航。
- 减少不必要的制表位。
- 更好地报告控件类型。
- 改进了讲述人行为。
<a name="aspnet471"></a>
### <a name="aspnet-web-controls"></a>ASP.NET Web 控件
自 .NET Framework 4.7.1 和 Visual Studio 2017 版本 15.3 起,ASP.NET 改进了 ASP.NET Web 控件与 Visual Studio 中的辅助功能技术配合使用的方式。 包括以下更改:
- 在以下控件中实现缺失 UI 的辅助功能模式:例如“详细信息视图”向导中的“添加字段”对话框或“ListView”向导的“配置 ListView”对话框 。
- 改善在高对比度模式下(如“数据页导航字段编辑器”)的显示。
- 改善以下控件的键盘导航体验:例如 DataPager 控件的“编辑页导航字段”向导中的“字段”对话框、“配置 ObjectContext”对话框或“配置数据源”向导的“配置数据选择”对话框 。
<a name="tools471"></a>
### <a name="net-sdk-tools"></a>.NET SDK 工具
[配置编辑器工具 (SvcConfigEditor.exe)](../wcf/configuration-editor-tool-svcconfigeditor-exe.md) 和[服务跟踪查看器工具 (SvcTraceViewer.exe)](../wcf/service-trace-viewer-tool-svctraceviewer-exe.md) 通过修复各种辅助功能问题得到改进。 其中大多数都是一些小问题,如未定义名称或未正确实现某些 UI 自动化模式。 虽然许多用户不会意识到这些小问题的重要性,但使用屏幕阅读器等辅助技术的客户会发现这些 SDK 工具更易于访问。
这些改进更改了某些旧行为,例如键盘焦点顺序。
<a name="wf471"></a>
### <a name="windows-workflow-foundation-wf-workflow-designer"></a>Windows Workflow Foundation (WF) 工作流设计器
工作流设计器中的辅助功能更改包括:
- 某些控件中 Tab 键顺序更改为从左到右以及从上到下:
- 设置 <xref:System.ServiceModel.Activities.InitializeCorrelation> 活动相关数据的初始化相关窗口。
- <xref:System.ServiceModel.Activities.Receive>、<xref:System.ServiceModel.Activities.Send>、<xref:System.ServiceModel.Activities.SendReply> 和 <xref:System.ServiceModel.Activities.ReceiveReply> 活动的内容定义窗口。
- 通过键盘可以使用更多功能:
- 编辑活动的属性时,属性组在第一次聚焦时可以通过键盘折叠。
- 警告图标可以通过键盘访问。
- “属性”窗口的“更多属性”按钮可以通过键盘访问 。
- 键盘用户可以访问工作流设计器“参数”和“变量”窗格的标题项 。
- 提升了聚焦项的可见性,例如当:
- 将行添加到工作流设计器和活动设计器使用的数据网格。
- 在 <xref:System.ServiceModel.Activities.ReceiveReply> 和 <xref:System.ServiceModel.Activities.SendReply> 活动中按 Tab 键切换字段。
- 设置变量或自变量的默认值
- 屏幕读取器现在可以正确识别:
- 工作流设计器中设置的断点。
- <xref:System.Activities.Statements.FlowSwitch%601>、<xref:System.Activities.Statements.FlowDecision> 和 <xref:System.ServiceModel.Activities.CorrelationScope> 活动。
- <xref:System.ServiceModel.Activities.Receive> 活动的内容。
- <xref:System.Activities.Statements.InvokeMethod> 活动的目标类型。
- <xref:System.Activities.Statements.TryCatch> 活动中的“异常”组合框和“最终”部分。
- 消息传递活动(<xref:System.ServiceModel.Activities.Receive>、<xref:System.ServiceModel.Activities.Send>、<xref:System.ServiceModel.Activities.SendReply> 和 <xref:System.ServiceModel.Activities.ReceiveReply>)中的“消息类型”组合框、“添加相关初始化表达式”窗口中的拆分器、“内容定义”窗口和“CorrelatesOn 定义”窗口。
- 状态机转换和转换目标。
- <xref:System.Activities.Statements.FlowDecision> 活动上的注释和连接器。
- 活动的上下文(右键单击)菜单。
- 属性值编辑器、“清除搜索”按钮、“按类别”和“按字母顺序”排序按钮以及属性网格中的“表达式编辑器”对话框。
- 工作流设计器中的缩放百分比。
- <xref:System.Activities.Statements.Parallel> 和 <xref:System.Activities.Statements.Pick> 活动中的分隔符。
- <xref:System.Activities.Statements.InvokeDelegate> 活动。
- 字典活动(`Microsoft.Activities.AddToDictionary<TKey,TValue>`、`Microsoft.Activities.RemoveFromDictionary<TKey,TValue>` 等)的“选择类型”窗口。
- “浏览和选择 .NET 类型”窗口。
- 工作流设计器中的痕迹导航。
- 选择高对比度主题的用户将看到工作流设计器及其控件可见性的许多改进,例如元素间更好的对比度和焦点元素更明显的选择框。
## <a name="see-also"></a>请参阅
- [.NET Framework 的新增功能](index.md)
| {
"pile_set_name": "Github"
} |
// RUN: %check_clang_tidy -std=c++17-or-later %s misc-unused-using-decls %t -- -- -fno-delayed-template-parsing -isystem %S/Inputs/
namespace ns {
template <typename T> class Foo {
public:
Foo(T);
};
// Deduction guide (CTAD)
template <typename T> Foo(T t) -> Foo<T>;
template <typename T> class Bar {
public:
Bar(T);
};
template <typename T> class Unused {};
} // namespace ns
using ns::Bar;
using ns::Foo;
using ns::Unused; // Unused
// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: using decl 'Unused' is unused
// CHECK-FIXES: {{^}}// Unused
void f() {
Foo(123);
Bar(1);
}
| {
"pile_set_name": "Github"
} |
---
layout: base
title: 'Statistics of goeswith:alt in UD_Upper_Sorbian'
udver: '2'
---
## Treebank Statistics: UD_Upper_Sorbian: Relations: `goeswith:alt`
This relation is a language-specific subtype of <tt><a href="hsb-dep-goeswith.html">goeswith</a></tt>.
2 nodes (0%) are attached to their parents as `goeswith:alt`.
2 instances of `goeswith:alt` (100%) are left-to-right (parent precedes child).
Average distance between parent and child is 2.
The following 2 pairs of parts of speech are connected with `goeswith:alt`: <tt><a href="hsb-pos-ADJ.html">ADJ</a></tt>-<tt><a href="hsb-pos-CCONJ.html">CCONJ</a></tt> (1; 50% instances), <tt><a href="hsb-pos-VERB.html">VERB</a></tt>-<tt><a href="hsb-pos-X.html">X</a></tt> (1; 50% instances).
~~~ conllu
# visual-style 5 bgColor:blue
# visual-style 5 fgColor:white
# visual-style 3 bgColor:blue
# visual-style 3 fgColor:white
# visual-style 3 5 goeswith:alt color:blue
1 Sy być AUX _ Mood=Ind|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin 3 cop _ _
2 wutrobnje wutrobnje ADV _ Degree=Pos 3 advmod _ _
3 přeprošeny přeprošeny ADJ _ Case=Nom|Gender=Masc|Number=Sing|VerbForm=Part|Voice=Pass 0 root _ SpaceAfter=No
4 ( ( PUNCT _ _ 5 punct _ SpaceAfter=No
5 a a CCONJ _ _ 3 goeswith:alt _ SpaceAfter=No
6 ) ) PUNCT _ _ 5 punct _ SpaceAfter=No
7 , , PUNCT _ _ 11 punct _ _
8 prašenja prašenje NOUN _ Case=Acc|Gender=Neut|Number=Plur 11 obj _ _
9 w w ADP _ _ 10 case _ _
10 korčmje korčmja NOUN _ Case=Loc|Gender=Fem|Number=Sing 11 obl _ _
11 stajić stajić VERB _ VerbForm=Inf 3 advcl _ SpaceAfter=No
12 . . PUNCT _ _ 3 punct _ _
~~~
~~~ conllu
# visual-style 9 bgColor:blue
# visual-style 9 fgColor:white
# visual-style 7 bgColor:blue
# visual-style 7 fgColor:white
# visual-style 7 9 goeswith:alt color:blue
1 Jeli jeli SCONJ _ _ 7 mark _ _
2 sy być AUX _ Mood=Ind|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin 7 aux _ _
3 jedyn jedyn NUM _ Case=Acc|Gender=Masc|Number=Sing|NumType=Card 7 obj _ _
4 z z ADP _ _ 6 case _ _
5 mjenowanych mjenowany ADJ _ Case=Gen|Gender=Masc|Number=Plur|VerbForm=Part|Voice=Pass 6 amod _ _
6 njedostatkow njedostatk NOUN _ Animacy=Inan|Case=Gen|Gender=Masc|Number=Plur 3 nmod _ _
7 skorigował skorigować VERB _ Gender=Masc|Number=Sing|Tense=Past|VerbForm=Part|Voice=Act 12 advcl _ SpaceAfter=No
8 ( ( PUNCT _ _ 9 punct _ SpaceAfter=No
9 a a X _ _ 7 goeswith:alt _ SpaceAfter=No
10 ) ) PUNCT _ _ 9 punct _ SpaceAfter=No
11 , , PUNCT _ _ 12 punct _ _
12 wotstroń wotstronić VERB _ Mood=Imp|Number=Sing|Person=2|VerbForm=Fin 0 root _ _
13 prošu prosyć VERB _ Mood=Ind|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin 12 discourse _ _
14 potrjecheny potrjecheny ADJ _ Animacy=Inan|Case=Acc|Gender=Masc|Number=Sing|VerbForm=Part|Voice=Pass 15 amod _ _
15 parameter parameter NOUN _ Animacy=Inan|Case=Acc|Gender=Masc|Number=Sing 12 obj _ _
16 předłohi předłoha NOUN _ Case=Gen|Gender=Fem|Number=Sing 15 nmod _ _
17 . . PUNCT _ _ 12 punct _ _
~~~
| {
"pile_set_name": "Github"
} |
/*
Copyright (C) 2019 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file qle/termstructures/dynamiccpivolatilitystructure.hpp
\brief dynamic zero inflation volatility structure
\ingroup termstructures
*/
#pragma once
#include <boost/make_shared.hpp>
#include <ql/termstructures/volatility/inflation/cpivolatilitystructure.hpp>
#include <ql/termstructures/volatility/smilesection.hpp>
#include <qle/termstructures/dynamicstype.hpp>
#include <qle/termstructures/interpolatedcpivolatilitysurface.hpp>
namespace QuantExt {
using namespace QuantLib;
//! Converts a CPIVolatilityStructure with fixed reference date into a floating reference date term structure.
/*! Different ways of reacting to time decay can be specified.
\ingroup termstructures
*/
class DynamicCPIVolatilitySurface : public CPIVolatilitySurface {
public:
DynamicCPIVolatilitySurface(const boost::shared_ptr<CPIVolatilitySurface>& source,
ReactionToTimeDecay decayMode = ConstantVariance);
protected:
//! \name CPIVolatilitySurface interface
//@{
Volatility volatilityImpl(Time length, Rate strike) const;
//@}
//! \name VolatilityTermStructure interface
//@{
Rate minStrike() const;
Rate maxStrike() const;
//@}
//! \name VolatilityTermStructure interface
//@{
Date maxDate() const;
//@}
//! \name Observer interface
//@{
void update();
//@}
private:
const boost::shared_ptr<CPIVolatilitySurface> source_;
ReactionToTimeDecay decayMode_;
const Date originalReferenceDate_;
};
} // namespace QuantExt
| {
"pile_set_name": "Github"
} |
/**
* Copyright 2011-2019 Asakusa Framework Team.
*
* 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.asakusafw.utils.gradle;
import java.nio.file.Path;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
/**
* Configures environment variables.
* @since 0.9.2
*/
public class EnvironmentConfigurator implements Consumer<BaseProject<?>> {
private final Map<String, String> edit;
/**
* Creates a new instance.
* @param edit edit
*/
public EnvironmentConfigurator(Map<String, String> edit) {
this.edit = new LinkedHashMap<>(edit);
}
/**
* Returns a NO-OP configurator.
* @return the created configurator
*/
public static EnvironmentConfigurator nothing() {
return of(Collections.emptyMap());
}
/**
* Returns a system {@link EnvironmentConfigurator}.
* @return a system {@link EnvironmentConfigurator}
*/
public static EnvironmentConfigurator system() {
return of(System.getenv());
}
/**
* Returns a configurator which edits the given environment variable.
* @param name the variable name
* @param value the variable value
* @return the created configurator
*/
public static EnvironmentConfigurator of(String name, String value) {
return of(Collections.singletonMap(name, value));
}
/**
* Returns a configurator which edits the given environment variable.
* @param name the variable name
* @param path the target path (nullable)
* @return the configurator
*/
public static EnvironmentConfigurator of(String name, Path path) {
return of(name, Optional.ofNullable(path).map(Path::toAbsolutePath).map(Path::toString).orElse(null));
}
/**
* Returns a configurator which edits the given environment variables.
* @param variables the variables
* @return the created configurator
*/
public static EnvironmentConfigurator of(Map<String, String> variables) {
return new EnvironmentConfigurator(variables);
}
@Override
public void accept(BaseProject<?> project) {
project.withEnvironment(m -> m.putAll(edit));
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Feed\Writer\Renderer\Entry\Atom;
use DateTime;
use DOMDocument;
use DOMElement;
use Zend\Feed\Writer;
use Zend\Feed\Writer\Renderer;
class Deleted extends Renderer\AbstractRenderer implements Renderer\RendererInterface
{
/**
* Constructor
*
* @param Writer\Deleted $container
*/
public function __construct(Writer\Deleted $container)
{
parent::__construct($container);
}
/**
* Render atom entry
*
* @return Writer\Renderer\Entry\Atom
*/
public function render()
{
$this->dom = new DOMDocument('1.0', $this->container->getEncoding());
$this->dom->formatOutput = true;
$entry = $this->dom->createElement('at:deleted-entry');
$this->dom->appendChild($entry);
$entry->setAttribute('ref', $this->container->getReference());
$entry->setAttribute('when', $this->container->getWhen()->format(DateTime::ATOM));
$this->_setBy($this->dom, $entry);
$this->_setComment($this->dom, $entry);
return $this;
}
/**
* Set tombstone comment
*
* @param DOMDocument $dom
* @param DOMElement $root
* @return void
*/
protected function _setComment(DOMDocument $dom, DOMElement $root)
{
if (!$this->getDataContainer()->getComment()) {
return;
}
$c = $dom->createElement('at:comment');
$root->appendChild($c);
$c->setAttribute('type', 'html');
$cdata = $dom->createCDATASection($this->getDataContainer()->getComment());
$c->appendChild($cdata);
}
/**
* Set entry authors
*
* @param DOMDocument $dom
* @param DOMElement $root
* @return void
*/
protected function _setBy(DOMDocument $dom, DOMElement $root)
{
$data = $this->container->getBy();
if ((!$data || empty($data))) {
return;
}
$author = $this->dom->createElement('at:by');
$name = $this->dom->createElement('name');
$author->appendChild($name);
$root->appendChild($author);
$text = $dom->createTextNode($data['name']);
$name->appendChild($text);
if (array_key_exists('email', $data)) {
$email = $this->dom->createElement('email');
$author->appendChild($email);
$text = $dom->createTextNode($data['email']);
$email->appendChild($text);
}
if (array_key_exists('uri', $data)) {
$uri = $this->dom->createElement('uri');
$author->appendChild($uri);
$text = $dom->createTextNode($data['uri']);
$uri->appendChild($text);
}
}
}
| {
"pile_set_name": "Github"
} |
// license:BSD-3-Clause
// copyright-holders:AJR
/****************************************************************************
Skeleton driver for EFO "Z-Pinball" hardware.
****************************************************************************/
#include "emu.h"
#include "audio/efo_zsu.h"
#include "cpu/z80/z80.h"
#include "machine/nvram.h"
#include "machine/z80ctc.h"
#include "sound/saa1099.h"
#include "speaker.h"
class zpinball_state : public driver_device
{
public:
zpinball_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag)
, m_zpumpu(*this, "zpumpu")
, m_zpuctc(*this, "zpuctc")
, m_zsu(*this, "zsu")
, m_pal_input(0)
, m_hc165_data(0)
, m_shift_clock(false)
, m_shift_enabled(false)
{
}
void zpinball(machine_config &config);
protected:
virtual void machine_start() override;
virtual void machine_reset() override;
private:
u8 pal_r();
void pal_w(u8 data);
void shift_load_w(u8 data);
DECLARE_WRITE_LINE_MEMBER(shift_toggle_w);
DECLARE_WRITE_LINE_MEMBER(clock_off_w);
u8 in1_r();
u8 in2_r();
void out1_w(u8 data);
void out2_w(u8 data);
void out3_w(u8 data);
void strobes_w(u8 data);
void o0_w(u8 data);
void o1_w(u8 data);
void o2_w(u8 data);
void o3_w(u8 data);
void o4_w(u8 data);
void o5_w(u8 data);
void o6_w(u8 data);
void zpu_mem(address_map &map);
void zpu_io(address_map &map);
required_device<z80_device> m_zpumpu;
required_device<z80ctc_device> m_zpuctc;
required_device<efo_zsu_device> m_zsu;
u8 m_pal_input;
u8 m_hc165_data;
bool m_shift_clock;
bool m_shift_enabled;
};
void zpinball_state::machine_start()
{
save_item(NAME(m_pal_input));
save_item(NAME(m_hc165_data));
save_item(NAME(m_shift_clock));
save_item(NAME(m_shift_enabled));
}
void zpinball_state::machine_reset()
{
m_shift_clock = false;
m_shift_enabled = false;
m_zpuctc->subdevice("ch0")->set_unscaled_clock(0);
// Clear latches
out1_w(0);
out2_w(0);
out3_w(0);
strobes_w(0);
o0_w(0);
o1_w(0);
o2_w(0);
o3_w(0);
o4_w(0);
o5_w(0);
o6_w(0);
}
u8 zpinball_state::pal_r()
{
// TODO: at least simulate this
return m_pal_input;
}
void zpinball_state::pal_w(u8 data)
{
m_pal_input = data;
}
void zpinball_state::shift_load_w(u8 data)
{
m_hc165_data = data;
m_shift_enabled = true;
m_zpuctc->subdevice("ch0")->set_unscaled_clock(8_MHz_XTAL / 4);
}
WRITE_LINE_MEMBER(zpinball_state::shift_toggle_w)
{
if (state && m_shift_enabled)
{
m_shift_clock = !m_shift_clock;
if (m_shift_clock)
m_hc165_data <<= 1;
}
}
WRITE_LINE_MEMBER(zpinball_state::clock_off_w)
{
if (state)
{
m_shift_clock = false;
m_shift_enabled = false;
m_zpuctc->subdevice("ch0")->set_unscaled_clock(0);
}
}
u8 zpinball_state::in1_r()
{
// TODO
return 0;
}
u8 zpinball_state::in2_r()
{
// TODO
return 0;
}
void zpinball_state::out1_w(u8 data)
{
logerror("%s: out1_w(0x%02X)\n", machine().describe_context(), data);
}
void zpinball_state::out2_w(u8 data)
{
logerror("%s: out2_w(0x%02X)\n", machine().describe_context(), data);
}
void zpinball_state::out3_w(u8 data)
{
logerror("%s: out3_w(0x%02X)\n", machine().describe_context(), data);
}
void zpinball_state::strobes_w(u8 data)
{
logerror("%s: strobes_w(0x%02X)\n", machine().describe_context(), data);
}
void zpinball_state::o0_w(u8 data)
{
logerror("%s: o0_w(0x%02X)\n", machine().describe_context(), data);
}
void zpinball_state::o1_w(u8 data)
{
logerror("%s: o1_w(0x%02X)\n", machine().describe_context(), data);
}
void zpinball_state::o2_w(u8 data)
{
logerror("%s: o2_w(0x%02X)\n", machine().describe_context(), data);
}
void zpinball_state::o3_w(u8 data)
{
logerror("%s: o3_w(0x%02X)\n", machine().describe_context(), data);
}
void zpinball_state::o4_w(u8 data)
{
logerror("%s: o4_w(0x%02X)\n", machine().describe_context(), data);
}
void zpinball_state::o5_w(u8 data)
{
logerror("%s: o5_w(0x%02X)\n", machine().describe_context(), data);
}
void zpinball_state::o6_w(u8 data)
{
logerror("%s: o6_w(0x%02X)\n", machine().describe_context(), data);
}
void zpinball_state::zpu_mem(address_map &map)
{
map(0x0000, 0x7fff).rom().region("zpurom", 0);
map(0x8000, 0x87ff).mirror(0x1800).ram().share("nvram");
map(0xa000, 0xa000).mirror(0x1fff).rw(FUNC(zpinball_state::pal_r), FUNC(zpinball_state::pal_w));
map(0xc000, 0xc000).mirror(0x1ff8).w(FUNC(zpinball_state::o0_w));
map(0xc001, 0xc001).mirror(0x1ff8).w(FUNC(zpinball_state::o1_w));
map(0xc002, 0xc002).mirror(0x1ff8).w(FUNC(zpinball_state::o2_w));
map(0xc003, 0xc003).mirror(0x1ff8).w(FUNC(zpinball_state::o3_w));
map(0xc004, 0xc004).mirror(0x1ff8).w(FUNC(zpinball_state::o4_w));
map(0xc005, 0xc005).mirror(0x1ff8).w(FUNC(zpinball_state::o5_w));
map(0xc006, 0xc006).mirror(0x1ff8).w(FUNC(zpinball_state::o6_w));
map(0xe000, 0xe001).mirror(0x1ffe).w("saa", FUNC(saa1099_device::write));
}
void zpinball_state::zpu_io(address_map &map)
{
map.global_mask(0x1f);
map(0x00, 0x03).rw(m_zpuctc, FUNC(z80ctc_device::read), FUNC(z80ctc_device::write));
map(0x04, 0x04).mirror(3).r(FUNC(zpinball_state::in1_r));
map(0x08, 0x08).mirror(3).r(FUNC(zpinball_state::in2_r));
map(0x0c, 0x0c).mirror(3).w(FUNC(zpinball_state::out1_w));
map(0x10, 0x10).mirror(3).w(FUNC(zpinball_state::shift_load_w));
map(0x14, 0x14).mirror(3).w(FUNC(zpinball_state::out2_w));
map(0x18, 0x18).mirror(3).w(FUNC(zpinball_state::strobes_w));
map(0x1c, 0x1c).mirror(3).w(FUNC(zpinball_state::out3_w));
}
static INPUT_PORTS_START(zpinball)
INPUT_PORTS_END
static const z80_daisy_config daisy_chain[] =
{
{ "zpuctc" },
{ nullptr }
};
void zpinball_state::zpinball(machine_config &config)
{
Z80(config, m_zpumpu, 8_MHz_XTAL / 2); // Z80A
m_zpumpu->set_addrmap(AS_PROGRAM, &zpinball_state::zpu_mem);
m_zpumpu->set_addrmap(AS_IO, &zpinball_state::zpu_io);
m_zpumpu->set_daisy_config(daisy_chain);
NVRAM(config, "nvram", nvram_device::DEFAULT_ALL_0); // 6116 + battery
Z80CTC(config, m_zpuctc, 8_MHz_XTAL / 2);
m_zpuctc->set_clk<0>(8_MHz_XTAL / 4);
m_zpuctc->set_clk<2>(100); // rectified from power supply
m_zpuctc->set_clk<3>(100);
m_zpuctc->intr_callback().set_inputline(m_zpumpu, INPUT_LINE_IRQ0);
m_zpuctc->zc_callback<0>().set(FUNC(zpinball_state::shift_toggle_w));
m_zpuctc->zc_callback<0>().append(m_zpuctc, FUNC(z80ctc_device::trg1));
m_zpuctc->zc_callback<1>().set(FUNC(zpinball_state::clock_off_w));
SPEAKER(config, "mono").front_center();
SAA1099(config, "saa", 8_MHz_XTAL).add_route(ALL_OUTPUTS, "mono", 1.0);
EFO_ZSU1(config, m_zsu, 0);
}
// Eight Ball Champ (Maibesa) on EFO "Z-Pinball" hardware - very different from the Bally original
// actual year uncertain; schematic in manual says hardware was designed in 1986, so probably not 1985 as claimed
ROM_START(eballchps)
ROM_REGION(0x8000, "zpurom", 0)
ROM_LOAD("u18-jeb 5a0 - cpu.bin", 0x0000, 0x8000, CRC(87615a7d) SHA1(b27ca2d863040a2641f88f9bd3143467a83f181b))
ROM_REGION(0x28000, "zsu:soundcpu", 0)
ROM_LOAD("u3-ebe a02 - sonido.bin", 0x00000, 0x8000, CRC(34be32ee) SHA1(ce0271540164639f28d617753760ecc479b6b0d0))
ROM_LOAD("u4-ebe b01 - sonido.bin", 0x08000, 0x8000, CRC(d696c4e8) SHA1(501e18c258e6d42819d25d72e1907984a6cfeecb))
ROM_LOAD("u5-ebe c01 - sonido.bin", 0x10000, 0x8000, CRC(fe78d7ef) SHA1(ed91c51dd230854a007f88446011f786759687ca))
ROM_LOAD("u6-ebe d02 - sonido.bin", 0x18000, 0x8000, CRC(a507081b) SHA1(72d025852a12f455981c61a405f97eaaac9c6fac))
ROM_END
// Cobra (Playbar)
ROM_START(cobrapb)
ROM_REGION(0x8000, "zpurom", 0)
ROM_LOAD("u18 - jcb 4 a0 - cpu.bin", 0x0000, 0x8000, CRC(c663910e) SHA1(c38692343f114388259c4e7b7943e5be934189ca))
ROM_REGION(0x28000, "zsu:soundcpu", 0)
ROM_LOAD("u3 - scb 1 a0 - sonido.bin", 0x00000, 0x8000, CRC(d3675770) SHA1(882ce748308f2d78cccd28fc8cd64fe69bd223e3))
ROM_LOAD("u4 - scb 1 b0 - sonido.bin", 0x08000, 0x8000, CRC(e8e1bdbb) SHA1(215bdfab751cb0ea47aa529df0ac30976de4f772))
ROM_LOAD("u5 - scb 1 c0 - sonido.bin", 0x10000, 0x8000, CRC(c36340ab) SHA1(cd662457959de3a929ba02779e2046ed18b797e2))
ROM_END
// Come Back (Nondum)
ROM_START(comeback)
ROM_REGION(0x8000, "zpurom", 0)
ROM_LOAD("jeb_5a0.u18", 0x0000, 0x8000, CRC(87615a7d) SHA1(b27ca2d863040a2641f88f9bd3143467a83f181b))
ROM_REGION(0x28000, "zsu:soundcpu", 0)
ROM_LOAD("cbs_3a0.u3", 0x00000, 0x8000, CRC(d0f55dc9) SHA1(91186e2cbe248323380418911240a9a5887063fb))
ROM_LOAD("cbs_3b0.u4", 0x08000, 0x8000, CRC(1da16d36) SHA1(9f7a27ae23064c1183a346ff042e6cba148257c7))
ROM_LOAD("cbs_1c0.u5", 0x10000, 0x8000, CRC(794ae588) SHA1(adaa5e69232523369a6a2da865ac05102cc04ec8))
ROM_END
GAME(1986, eballchps, eballchp, zpinball, zpinball, zpinball_state, empty_init, ROT0, "Bally (Maibesa license)", "Eight Ball Champ (Spain, Z-Pinball hardware)", MACHINE_IS_SKELETON_MECHANICAL)
GAME(1987, cobrapb, 0, zpinball, zpinball, zpinball_state, empty_init, ROT0, "Playbar", "Cobra (Playbar)", MACHINE_IS_SKELETON_MECHANICAL)
GAME(198?, comeback, 0, zpinball, zpinball, zpinball_state, empty_init, ROT0, "Nondum / CIFA", "Come Back", MACHINE_IS_SKELETON_MECHANICAL)
| {
"pile_set_name": "Github"
} |
# postgresql/pypostgresql.py
# Copyright (C) 2005-2019 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
.. dialect:: postgresql+pypostgresql
:name: py-postgresql
:dbapi: pypostgresql
:connectstring: postgresql+pypostgresql://user:password@host:port/dbname[?key=value&key=value...]
:url: http://python.projects.pgfoundry.org/
""" # noqa
from .base import PGDialect
from .base import PGExecutionContext
from ... import processors
from ... import types as sqltypes
from ... import util
class PGNumeric(sqltypes.Numeric):
def bind_processor(self, dialect):
return processors.to_str
def result_processor(self, dialect, coltype):
if self.asdecimal:
return None
else:
return processors.to_float
class PGExecutionContext_pypostgresql(PGExecutionContext):
pass
class PGDialect_pypostgresql(PGDialect):
driver = "pypostgresql"
supports_unicode_statements = True
supports_unicode_binds = True
description_encoding = None
default_paramstyle = "pyformat"
# requires trunk version to support sane rowcounts
# TODO: use dbapi version information to set this flag appropriately
supports_sane_rowcount = True
supports_sane_multi_rowcount = False
execution_ctx_cls = PGExecutionContext_pypostgresql
colspecs = util.update_copy(
PGDialect.colspecs,
{
sqltypes.Numeric: PGNumeric,
# prevents PGNumeric from being used
sqltypes.Float: sqltypes.Float,
},
)
@classmethod
def dbapi(cls):
from postgresql.driver import dbapi20
return dbapi20
_DBAPI_ERROR_NAMES = [
"Error",
"InterfaceError",
"DatabaseError",
"DataError",
"OperationalError",
"IntegrityError",
"InternalError",
"ProgrammingError",
"NotSupportedError",
]
@util.memoized_property
def dbapi_exception_translation_map(self):
if self.dbapi is None:
return {}
return dict(
(getattr(self.dbapi, name).__name__, name)
for name in self._DBAPI_ERROR_NAMES
)
def create_connect_args(self, url):
opts = url.translate_connect_args(username="user")
if "port" in opts:
opts["port"] = int(opts["port"])
else:
opts["port"] = 5432
opts.update(url.query)
return ([], opts)
def is_disconnect(self, e, connection, cursor):
return "connection is closed" in str(e)
dialect = PGDialect_pypostgresql
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<object-views xmlns="http://axelor.com/xml/ns/object-views"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://axelor.com/xml/ns/object-views http://axelor.com/xml/ns/object-views/object-views_5.3.xsd">
<grid name="production-batch-grid" title="Production batches" model="com.axelor.apps.production.db.ProductionBatch">
<field name="actionSelect" />
<field name="code" x-bind="{{code|unaccent|uppercase}}" />
<field name="company" form-view="company-form" grid-view="company-grid" if="__config__.app.getApp('base').getEnableMultiCompany()"/>
<field name="workshopStockLocation" form-view="stock-location-form" grid-view="stock-location-grid" />
<field name="createdOn"/>
<field name="createdBy" form-view="user-form" grid-view="user-grid"/>
</grid>
<form name="production-batch-form" title="Production Batch" model="com.axelor.apps.production.db.ProductionBatch" onNew="action-production-batch-record-on-new" width="large">
<toolbar>
<button name="printBtn" title="Work in progress valuation" hideIf="!batchList" onClick="save,action-production-batch-method-show-valuation"/>
</toolbar>
<panel name="mainPanel" >
<field name="actionSelect"/>
<field name="code" x-bind="{{code|unaccent|uppercase}}" onChange="action-base-batch-condition-check-unique-code"/>
<field name="company" widget="SuggestBox" form-view="company-form" grid-view="company-grid" />
<field name="workshopStockLocation" onSelect="action-production-batch-attrs-domain-stock-location" onChange="action-production-batch-record-set-company"
form-view="stock-location-form" grid-view="stock-location-grid" if="__config__.app.getApp('production').getManageWorkshop()" />
</panel>
<panel name="creationDetailsPanel">
<field name="createdOn" title="Created on"/>
<field name="createdBy" title="Created by" form-view="user-form" grid-view="user-grid"/>
<field name="valuationDate"/>
<spacer name="valuationDateSpacer" colSpan="6"/>
<button name="computeValutionBatchBtn" title="Compute work in progress valuation" onClick="save,action-production-batch-method-compute-valuation"/>
</panel>
<panel-tabs>
<panel name="descriptionPanel" title="Description">
<field name="description" showTitle="false" colSpan="12"/>
</panel>
<panel-related name="batchListPanel" field="batchList" colSpan="12" form-view="batch-form" grid-view="batch-grid" readonly="true" />
</panel-tabs>
</form>
<action-record name="action-production-batch-record-on-new" model="com.axelor.apps.production.db.ProductionBatch">
<field name="actionSelect" expr="1"/>
<field name="company" expr="eval:__user__.activeCompany" if="__user__.activeCompany != null"/>
<field name="company" expr="eval:__repo__(Company).all().fetchOne()" if="__user__.activeCompany == null && __repo__(Company).all().fetch().size == 1"/>
</action-record>
<action-record name="action-production-batch-record-set-company" model="com.axelor.apps.production.db.ProductionBatch">
<field name="company" expr="eval: workshopStockLocation?.company" if="!company"/>
</action-record>
<action-method name="action-production-batch-method-compute-valuation">
<call class="com.axelor.apps.production.web.ProductionBatchController" method="computeValuation"/>
</action-method>
<action-method name="action-production-batch-method-show-valuation">
<call class="com.axelor.apps.production.web.ProductionBatchController" method="showValuation"/>
</action-method>
<action-attrs name="action-production-batch-attrs-domain-stock-location">
<attribute name="domain" for="workshopStockLocation" expr="eval: company != null ? " self.company = :company " : null"/>
</action-attrs>
<search-filters name="production-batch-filters" model="com.axelor.apps.production.db.ProductionBatch" title="Production batch filters">
<field name="company" hidden="true" if="!__config__.app.getApp('base').getEnableMultiCompany()"/>
<field name="workshopStockLocation" hidden="true" if="!__config__.app.getApp('production').getManageWorkshop()" />
</search-filters>
</object-views>
| {
"pile_set_name": "Github"
} |
#!/usr/bin/python3
import os
import sys
from hashlib import sha512
from optparse import OptionParser
sys.path.insert(0, os.path.normpath(os.path.join(os.path.realpath(__file__), "../../modules")))
from merge.db_core import *
parser = OptionParser()
parser.add_option("--catpkg", dest="catpkg", help="catpkg of ebuild")
parser.add_option("--src_uri", dest="src_uri", help="download URL")
parser.add_option("--kit", dest="kit", help="kit of ebuild")
parser.add_option("--branch", dest="branch", help="branch of kit")
parser.add_option("--replace", dest="replace", action="store_true", default=False, help="replace existing distfile in fastpull.")
options, args = parser.parse_args()
if len(args) != 1:
print("Please specify a single file to inject into queued distfiles.")
sys.exit(1)
def get_sha512(fn):
with open(fn, "rb") as data:
my_hash = sha512()
my_hash.update(data.read())
return my_hash.hexdigest()
db = FastPullDatabase()
fn = args[0]
if not os.path.exists(fn):
print("File %s does not exist. Can't inject." % fn)
sys.exit(1)
with db.get_session() as session:
existing = session.query(db.Distfile).filter(db.Distfile.filename == os.path.basename(fn)).first()
if existing:
if options.replace is True:
print("Removing distfile entry for existing file.")
session.delete(existing)
session.commit()
else:
print("File already exists in distfiles. Skipping.")
sys.exit(1)
qdsf = db.QueuedDistfile()
qdsf.filename = os.path.basename(fn)
qdsf.catpkg = options.catpkg
qdsf.kit = options.kit
qdsf.branch = options.branch
qdsf.src_uri = options.src_uri
qdsf.size = os.path.getsize(fn)
qdsf.digest_type = "sha512"
qdsf.digest = get_sha512(fn)
with db.get_session() as session:
# get_sha512() can take a long time; session can time out.
session.add(qdsf)
session.commit()
print("Injected file %s into queued distfiles." % fn)
| {
"pile_set_name": "Github"
} |
[Desktop Entry]
Encoding=UTF-8
Name=Internet
Icon=mini-Internet.xpm
Type=Directory
| {
"pile_set_name": "Github"
} |
/*
* 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.flink.runtime.testutils.recordutils;
import java.util.Arrays;
import org.apache.flink.api.common.typeutils.TypeComparatorFactory;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.IllegalConfigurationException;
import org.apache.flink.types.Record;
import org.apache.flink.types.Value;
/**
* A factory for a {@link org.apache.flink.api.common.typeutils.TypeComparator} for {@link Record}. The comparator uses a subset of
* the fields for the comparison. That subset of fields (positions and types) is read from the
* supplied configuration.
*/
public class RecordComparatorFactory implements TypeComparatorFactory<Record> {
private static final String NUM_KEYS = "numkeys";
private static final String KEY_POS_PREFIX = "keypos.";
private static final String KEY_CLASS_PREFIX = "keyclass.";
private static final String KEY_SORT_DIRECTION_PREFIX = "key-direction.";
// --------------------------------------------------------------------------------------------
private int[] positions;
private Class<? extends Value>[] types;
private boolean[] sortDirections;
// --------------------------------------------------------------------------------------------
public RecordComparatorFactory() {
// do nothing, allow to be configured via config
}
public RecordComparatorFactory(int[] positions, Class<? extends Value>[] types) {
this(positions, types, null);
}
public RecordComparatorFactory(int[] positions, Class<? extends Value>[] types, boolean[] sortDirections) {
if (positions == null || types == null) {
throw new NullPointerException();
}
if (positions.length != types.length) {
throw new IllegalArgumentException();
}
this.positions = positions;
this.types = types;
if (sortDirections == null) {
this.sortDirections = new boolean[positions.length];
Arrays.fill(this.sortDirections, true);
} else if (sortDirections.length != positions.length) {
throw new IllegalArgumentException();
} else {
this.sortDirections = sortDirections;
}
}
@Override
public void writeParametersToConfig(Configuration config) {
for (int i = 0; i < this.positions.length; i++) {
if (this.positions[i] < 0) {
throw new IllegalArgumentException("The key position " + i + " is invalid: " + this.positions[i]);
}
if (this.types[i] == null || !Value.class.isAssignableFrom(this.types[i])) {
throw new IllegalArgumentException("The key type " + i + " is null or not implenting the interface " +
Value.class.getName() + ".");
}
}
// write the config
config.setInteger(NUM_KEYS, this.positions.length);
for (int i = 0; i < this.positions.length; i++) {
config.setInteger(KEY_POS_PREFIX + i, this.positions[i]);
config.setString(KEY_CLASS_PREFIX + i, this.types[i].getName());
config.setBoolean(KEY_SORT_DIRECTION_PREFIX + i, this.sortDirections[i]);
}
}
@SuppressWarnings("unchecked")
@Override
public void readParametersFromConfig(Configuration config, ClassLoader cl) throws ClassNotFoundException {
// figure out how many key fields there are
final int numKeyFields = config.getInteger(NUM_KEYS, -1);
if (numKeyFields < 0) {
throw new IllegalConfigurationException("The number of keys for the comparator is invalid: " + numKeyFields);
}
final int[] positions = new int[numKeyFields];
final Class<? extends Value>[] types = new Class[numKeyFields];
final boolean[] direction = new boolean[numKeyFields];
// read the individual key positions and types
for (int i = 0; i < numKeyFields; i++) {
// next key position
final int p = config.getInteger(KEY_POS_PREFIX + i, -1);
if (p >= 0) {
positions[i] = p;
} else {
throw new IllegalConfigurationException("Contained invalid position for key no positions for keys.");
}
// next key type
final String name = config.getString(KEY_CLASS_PREFIX + i, null);
if (name != null) {
types[i] = (Class<? extends Value>) Class.forName(name, true, cl).asSubclass(Value.class);
} else {
throw new IllegalConfigurationException("The key type (" + i +
") for the comparator is null");
}
// next key sort direction
direction[i] = config.getBoolean(KEY_SORT_DIRECTION_PREFIX + i, true);
}
this.positions = positions;
this.types = types;
this.sortDirections = direction;
}
@Override
public RecordComparator createComparator() {
return new RecordComparator(this.positions, this.types, this.sortDirections);
}
}
| {
"pile_set_name": "Github"
} |
/*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../../SDL_internal.h"
#if SDL_VIDEO_DRIVER_UIKIT
#include "SDL.h"
#include "SDL_uikitvideo.h"
#include "SDL_uikitwindow.h"
/* Display a UIKit message box */
static SDL_bool s_showingMessageBox = SDL_FALSE;
SDL_bool
UIKit_ShowingMessageBox(void)
{
return s_showingMessageBox;
}
static void
UIKit_WaitUntilMessageBoxClosed(const SDL_MessageBoxData *messageboxdata, int *clickedindex)
{
*clickedindex = messageboxdata->numbuttons;
@autoreleasepool {
/* Run the main event loop until the alert has finished */
/* Note that this needs to be done on the main thread */
s_showingMessageBox = SDL_TRUE;
while ((*clickedindex) == messageboxdata->numbuttons) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
s_showingMessageBox = SDL_FALSE;
}
}
static BOOL
UIKit_ShowMessageBoxAlertController(const SDL_MessageBoxData *messageboxdata, int *buttonid)
{
#ifdef __IPHONE_8_0
int i;
int __block clickedindex = messageboxdata->numbuttons;
const SDL_MessageBoxButtonData *buttons = messageboxdata->buttons;
UIWindow *window = nil;
UIWindow *alertwindow = nil;
if (![UIAlertController class]) {
return NO;
}
UIAlertController *alert;
alert = [UIAlertController alertControllerWithTitle:@(messageboxdata->title)
message:@(messageboxdata->message)
preferredStyle:UIAlertControllerStyleAlert];
for (i = 0; i < messageboxdata->numbuttons; i++) {
UIAlertAction *action;
UIAlertActionStyle style = UIAlertActionStyleDefault;
if (buttons[i].flags & SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT) {
style = UIAlertActionStyleCancel;
}
action = [UIAlertAction actionWithTitle:@(buttons[i].text)
style:style
handler:^(UIAlertAction *action) {
clickedindex = i;
}];
[alert addAction:action];
}
if (messageboxdata->window) {
SDL_WindowData *data = (__bridge SDL_WindowData *) messageboxdata->window->driverdata;
window = data.uiwindow;
}
if (window == nil || window.rootViewController == nil) {
alertwindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
alertwindow.rootViewController = [UIViewController new];
alertwindow.windowLevel = UIWindowLevelAlert;
window = alertwindow;
[alertwindow makeKeyAndVisible];
}
[window.rootViewController presentViewController:alert animated:YES completion:nil];
UIKit_WaitUntilMessageBoxClosed(messageboxdata, &clickedindex);
if (alertwindow) {
alertwindow.hidden = YES;
}
#if !TARGET_OS_TV
/* Force the main SDL window to re-evaluate home indicator state */
SDL_Window *focus = SDL_GetFocusWindow();
if (focus) {
SDL_WindowData *data = (__bridge SDL_WindowData *) focus->driverdata;
if (data != nil) {
if (@available(iOS 11.0, *)) {
[data.viewcontroller performSelectorOnMainThread:@selector(setNeedsUpdateOfHomeIndicatorAutoHidden) withObject:nil waitUntilDone:NO];
[data.viewcontroller performSelectorOnMainThread:@selector(setNeedsUpdateOfScreenEdgesDeferringSystemGestures) withObject:nil waitUntilDone:NO];
}
}
}
#endif /* !TARGET_OS_TV */
*buttonid = messageboxdata->buttons[clickedindex].buttonid;
return YES;
#else
return NO;
#endif /* __IPHONE_8_0 */
}
/* UIAlertView is deprecated in iOS 8+ in favor of UIAlertController. */
#if __IPHONE_OS_VERSION_MIN_REQUIRED < 80000
@interface SDLAlertViewDelegate : NSObject <UIAlertViewDelegate>
@property (nonatomic, assign) int *clickedIndex;
@end
@implementation SDLAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (_clickedIndex != NULL) {
*_clickedIndex = (int) buttonIndex;
}
}
@end
#endif /* __IPHONE_OS_VERSION_MIN_REQUIRED < 80000 */
static BOOL
UIKit_ShowMessageBoxAlertView(const SDL_MessageBoxData *messageboxdata, int *buttonid)
{
/* UIAlertView is deprecated in iOS 8+ in favor of UIAlertController. */
#if __IPHONE_OS_VERSION_MIN_REQUIRED < 80000
int i;
int clickedindex = messageboxdata->numbuttons;
const SDL_MessageBoxButtonData *buttons = messageboxdata->buttons;
UIAlertView *alert = [[UIAlertView alloc] init];
SDLAlertViewDelegate *delegate = [[SDLAlertViewDelegate alloc] init];
alert.delegate = delegate;
alert.title = @(messageboxdata->title);
alert.message = @(messageboxdata->message);
for (i = 0; i < messageboxdata->numbuttons; i++) {
[alert addButtonWithTitle:@(buttons[i].text)];
}
delegate.clickedIndex = &clickedindex;
[alert show];
UIKit_WaitUntilMessageBoxClosed(messageboxdata, &clickedindex);
alert.delegate = nil;
*buttonid = messageboxdata->buttons[clickedindex].buttonid;
return YES;
#else
return NO;
#endif /* __IPHONE_OS_VERSION_MIN_REQUIRED < 80000 */
}
int
UIKit_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
{
BOOL success = NO;
@autoreleasepool {
success = UIKit_ShowMessageBoxAlertController(messageboxdata, buttonid);
if (!success) {
success = UIKit_ShowMessageBoxAlertView(messageboxdata, buttonid);
}
}
if (!success) {
return SDL_SetError("Could not show message box.");
}
return 0;
}
#endif /* SDL_VIDEO_DRIVER_UIKIT */
/* vi: set ts=4 sw=4 expandtab: */
| {
"pile_set_name": "Github"
} |
// See http://www.boost.org/libs/any for Documentation.
#ifndef BOOST_ANY_INCLUDED
#define BOOST_ANY_INCLUDED
// what: variant type boost::any
// who: contributed by Kevlin Henney,
// with features contributed and bugs found by
// Ed Brey, Mark Rodgers, Peter Dimov, and James Curran
// when: July 2001
// where: tested with BCC 5.5, MSVC 6.0, and g++ 2.95
#include <algorithm>
#include <typeinfo>
#include "boost/config.hpp"
#include <boost/type_traits/remove_reference.hpp>
#include <boost/type_traits/is_reference.hpp>
#include <boost/throw_exception.hpp>
#include <boost/static_assert.hpp>
// See boost/python/type_id.hpp
// TODO: add BOOST_TYPEID_COMPARE_BY_NAME to config.hpp
# if (defined(__GNUC__) && __GNUC__ >= 3) \
|| defined(_AIX) \
|| ( defined(__sgi) && defined(__host_mips)) \
|| (defined(__hpux) && defined(__HP_aCC)) \
|| (defined(linux) && defined(__INTEL_COMPILER) && defined(__ICC))
# define BOOST_AUX_ANY_TYPE_ID_NAME
#include <cstring>
# endif
namespace boost
{
class any
{
public: // structors
any()
: content(0)
{
}
template<typename ValueType>
any(const ValueType & value)
: content(new holder<ValueType>(value))
{
}
any(const any & other)
: content(other.content ? other.content->clone() : 0)
{
}
~any()
{
delete content;
}
public: // modifiers
any & swap(any & rhs)
{
std::swap(content, rhs.content);
return *this;
}
template<typename ValueType>
any & operator=(const ValueType & rhs)
{
any(rhs).swap(*this);
return *this;
}
any & operator=(any rhs)
{
rhs.swap(*this);
return *this;
}
public: // queries
bool empty() const
{
return !content;
}
const std::type_info & type() const
{
return content ? content->type() : typeid(void);
}
#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
private: // types
#else
public: // types (public so any_cast can be non-friend)
#endif
class placeholder
{
public: // structors
virtual ~placeholder()
{
}
public: // queries
virtual const std::type_info & type() const = 0;
virtual placeholder * clone() const = 0;
};
template<typename ValueType>
class holder : public placeholder
{
public: // structors
holder(const ValueType & value)
: held(value)
{
}
public: // queries
virtual const std::type_info & type() const
{
return typeid(ValueType);
}
virtual placeholder * clone() const
{
return new holder(held);
}
public: // representation
ValueType held;
private: // intentionally left unimplemented
holder & operator=(const holder &);
};
#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
private: // representation
template<typename ValueType>
friend ValueType * any_cast(any *);
template<typename ValueType>
friend ValueType * unsafe_any_cast(any *);
#else
public: // representation (public so any_cast can be non-friend)
#endif
placeholder * content;
};
class bad_any_cast : public std::bad_cast
{
public:
virtual const char * what() const throw()
{
return "boost::bad_any_cast: "
"failed conversion using boost::any_cast";
}
};
template<typename ValueType>
ValueType * any_cast(any * operand)
{
return operand &&
#ifdef BOOST_AUX_ANY_TYPE_ID_NAME
std::strcmp(operand->type().name(), typeid(ValueType).name()) == 0
#else
operand->type() == typeid(ValueType)
#endif
? &static_cast<any::holder<ValueType> *>(operand->content)->held
: 0;
}
template<typename ValueType>
inline const ValueType * any_cast(const any * operand)
{
return any_cast<ValueType>(const_cast<any *>(operand));
}
template<typename ValueType>
ValueType any_cast(any & operand)
{
typedef BOOST_DEDUCED_TYPENAME remove_reference<ValueType>::type nonref;
#ifdef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
// If 'nonref' is still reference type, it means the user has not
// specialized 'remove_reference'.
// Please use BOOST_BROKEN_COMPILER_TYPE_TRAITS_SPECIALIZATION macro
// to generate specialization of remove_reference for your class
// See type traits library documentation for details
BOOST_STATIC_ASSERT(!is_reference<nonref>::value);
#endif
nonref * result = any_cast<nonref>(&operand);
if(!result)
boost::throw_exception(bad_any_cast());
return *result;
}
template<typename ValueType>
inline ValueType any_cast(const any & operand)
{
typedef BOOST_DEDUCED_TYPENAME remove_reference<ValueType>::type nonref;
#ifdef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
// The comment in the above version of 'any_cast' explains when this
// assert is fired and what to do.
BOOST_STATIC_ASSERT(!is_reference<nonref>::value);
#endif
return any_cast<const nonref &>(const_cast<any &>(operand));
}
// Note: The "unsafe" versions of any_cast are not part of the
// public interface and may be removed at any time. They are
// required where we know what type is stored in the any and can't
// use typeid() comparison, e.g., when our types may travel across
// different shared libraries.
template<typename ValueType>
inline ValueType * unsafe_any_cast(any * operand)
{
return &static_cast<any::holder<ValueType> *>(operand->content)->held;
}
template<typename ValueType>
inline const ValueType * unsafe_any_cast(const any * operand)
{
return unsafe_any_cast<ValueType>(const_cast<any *>(operand));
}
}
// Copyright Kevlin Henney, 2000, 2001, 2002. All rights reserved.
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#endif
| {
"pile_set_name": "Github"
} |
Cross Site Scripting aka XSS
Hi,
I found a reflected XSS on `xxx.xxxxxxxxxxxx.xxx`.
## Description
The parameter `yyy` is missing sanitization in the following url:
`http://xxx.xxxxxxxxxxxx.xxx/............`
Payload:
`.......`
Which render the following code:
`......`
## PoC
{}
## Risk
- hostile code insertion
- session hijacking
- user browser corruption
## Remediation
- encode special characters like `'` `"` `<` `>`
## See also
https://www.owasp.org/index.php/Top_10_2013-A3-Cross-Site_Scripting_(XSS)
Best regards,
Gwen
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.md.demo.vo.CityVo">
<select id="listCities" resultType="com.md.demo.vo.CityVo">
select * from city
</select>
<select id="getCityById" resultType="com.md.demo.vo.CityVo">
select * from city where id = #{id}
</select>
</mapper> | {
"pile_set_name": "Github"
} |
--------------------------------
-- @module VBox
-- @extend Layout
--------------------------------
-- overload function: create(size_table)
--
-- overload function: create()
--
-- @function [parent=#VBox] create
-- @param self
-- @param #size_table size
-- @return VBox#VBox ret (retunr value: ccui.VBox)
--------------------------------
-- @function [parent=#VBox] VBox
-- @param self
return nil
| {
"pile_set_name": "Github"
} |
/* Parser to convert "C" assignments to lisp using Bison in C. */
/* Compile: bison -d -y reflexexample3.y */
%{
#include <stdio.h>
#include "lex.yy.h"
void yyerror(const char*);
%}
%union {
int num;
char *str;
}
%token <str> STRING
%token <num> NUMBER
%%
assignments : assignment
| assignment assignments
;
assignment : STRING '=' NUMBER ';' { printf("(setf %s %d)\n", $1, $3); }
;
%%
int main()
{
yyparse();
return 0;
}
void yyerror(const char *msg)
{
fprintf(stderr, "%s at line %zu\n", msg, YY_SCANNER.matcher().lineno()); /* reflex-generated global `YY_SCANNER` */
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.