text
stringlengths 2
99.9k
| meta
dict |
|---|---|
package com.kunfei.bookshelf.widget.modialog;
import android.annotation.SuppressLint;
import android.content.Context;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.kunfei.bookshelf.R;
import com.kunfei.bookshelf.bean.TxtChapterRuleBean;
import com.kunfei.bookshelf.widget.views.ATEEditText;
public class TxtChapterRuleDialog {
private ATEEditText tieRuleName;
private ATEEditText tieRuleRegex;
private TextView tvOk;
private BaseDialog dialog;
private TxtChapterRuleBean txtChapterRuleBean;
public static TxtChapterRuleDialog builder(Context context, TxtChapterRuleBean txtChapterRuleBean) {
return new TxtChapterRuleDialog(context, txtChapterRuleBean);
}
private TxtChapterRuleDialog(Context context, TxtChapterRuleBean txtChapterRuleBean) {
if (txtChapterRuleBean != null) {
this.txtChapterRuleBean = txtChapterRuleBean.copy();
}
dialog = new BaseDialog(context, R.style.alertDialogTheme);
@SuppressLint("InflateParams") View view = LayoutInflater.from(context).inflate(R.layout.dialog_txt_chpater_rule, null);
bindView(view);
dialog.setContentView(view);
}
private void bindView(View view) {
tieRuleName = view.findViewById(R.id.tie_rule_name);
tieRuleRegex = view.findViewById(R.id.tie_rule_regex);
tvOk = view.findViewById(R.id.tv_ok);
if (txtChapterRuleBean != null) {
tieRuleName.setText(txtChapterRuleBean.getName());
tieRuleRegex.setText(txtChapterRuleBean.getRule());
}
}
public TxtChapterRuleDialog setPositiveButton(Callback callback) {
tvOk.setOnClickListener(v -> {
if (txtChapterRuleBean == null) {
txtChapterRuleBean = new TxtChapterRuleBean();
}
txtChapterRuleBean.setName(getEditableText(tieRuleName.getText()));
txtChapterRuleBean.setRule(getEditableText(tieRuleRegex.getText()));
callback.onPositiveButton(txtChapterRuleBean);
dialog.dismiss();
});
return this;
}
private String getEditableText(Editable editable) {
if (editable == null) {
return "";
}
return editable.toString();
}
public TxtChapterRuleDialog show() {
dialog.show();
return this;
}
public interface Callback {
void onPositiveButton(TxtChapterRuleBean txtChapterRuleBean);
}
}
|
{
"pile_set_name": "Github"
}
|
import i18n from 'i18n-js';
import { connectStyle } from 'native-base';
import React, { forwardRef } from 'react';
import { Text } from 'react-native';
const ValidationMessage = ({ children, ...props }) =>
children ? <Text {...props}>{i18n.t(children)}</Text> : null;
const styles = {
fontSize: 12,
marginHorizontal: 10,
marginTop: -5,
color: '#ed2f2f',
};
const Forwarded = forwardRef((props, ref) => <ValidationMessage {...props} forwardedRef={ref} />);
export default connectStyle('ABP.ValidationMessage', styles)(Forwarded);
|
{
"pile_set_name": "Github"
}
|
import pMap from 'p-map';
import differenceInMinutes from 'date-fns/difference_in_minutes';
import _debug from 'debug';
import JavLib from './videoLib/JavLibrary';
import database from './database';
import {
YouAV,
MyAVSuper,
Avgle,
JavMost,
Avsee,
JavForMe,
Jav777,
} from './AV';
import updateInfos from './utils/updateInfos';
const debug = _debug('crawler');
async function getVideosInfos(videos) {
const jav = new JavLib();
const now = new Date();
const foundInfos = [];
const skipInfos = [];
await pMap(
videos,
async video => {
try {
const info = await jav.getCodeInfos(video.code);
foundInfos.push({ ...info, ...video, updated_at: now });
debug(`find url: ${video.url}, code: ${video.code}`);
} catch (err) {
if (err.errorType === undefined) {
// will get error if code not found
skipInfos.push({ ...video, updated_at: now });
}
debug(err);
}
},
{ concurrency: 20 }
);
return { foundInfos, skipInfos };
}
const main = async () => {
const start = new Date();
console.log(`crawler start at ${start}`);
const db = await database();
const existedVideos = await db
.collection('sources')
.find()
.toArray();
const existedVideosSet = new Set(existedVideos.map(video => video.url));
const newAVSources = [
new YouAV(),
new MyAVSuper(),
new Avgle(),
new JavMost(),
new Avsee(),
new JavForMe(),
new Jav777(),
];
await pMap(
newAVSources,
async av => {
let videos = await av.getVideos();
videos = videos.filter(video => !existedVideosSet.has(video.url));
debug(`source: ${av.source}, videos length: ${videos.length}`);
const { foundInfos, skipInfos } = await getVideosInfos(videos);
if (process.env.NODE_ENV === 'production') {
await updateInfos(db, foundInfos, skipInfos);
}
console.log('================================');
console.log(`from: ${av.source}`);
console.log(`total videos: ${videos.length}`);
console.log(`find video url count: ${foundInfos.length}`);
console.log(`skip video url count: ${skipInfos.length}`);
console.log('================================');
},
{ concurrency: 3 }
);
const done = new Date();
console.log(`crawler done at ${done}`);
console.log(`take ${differenceInMinutes(done, start)} mins`);
db.close();
};
module.exports = main;
|
{
"pile_set_name": "Github"
}
|
##############################################################################
# Build global options
# NOTE: Can be overridden externally.
#
# Compiler options here.
ifeq ($(USE_OPT),)
USE_OPT = -O2 -ggdb -fomit-frame-pointer -falign-functions=16
endif
# C specific options here (added to USE_OPT).
ifeq ($(USE_COPT),)
USE_COPT =
endif
# C++ specific options here (added to USE_OPT).
ifeq ($(USE_CPPOPT),)
USE_CPPOPT = -fno-rtti
endif
# Enable this if you want the linker to remove unused code and data.
ifeq ($(USE_LINK_GC),)
USE_LINK_GC = yes
endif
# Linker extra options here.
ifeq ($(USE_LDOPT),)
USE_LDOPT =
endif
# Enable this if you want link time optimizations (LTO).
ifeq ($(USE_LTO),)
USE_LTO = yes
endif
# Enable this if you want to see the full log while compiling.
ifeq ($(USE_VERBOSE_COMPILE),)
USE_VERBOSE_COMPILE = no
endif
# If enabled, this option makes the build process faster by not compiling
# modules not used in the current configuration.
ifeq ($(USE_SMART_BUILD),)
USE_SMART_BUILD = yes
endif
#
# Build global options
##############################################################################
##############################################################################
# Architecture or project specific options
#
# Stack size to be allocated to the Cortex-M process stack. This stack is
# the stack used by the main() thread.
ifeq ($(USE_PROCESS_STACKSIZE),)
USE_PROCESS_STACKSIZE = 0x400
endif
# Stack size to the allocated to the Cortex-M main/exceptions stack. This
# stack is used for processing interrupts and exceptions.
ifeq ($(USE_EXCEPTIONS_STACKSIZE),)
USE_EXCEPTIONS_STACKSIZE = 0x400
endif
# Enables the use of FPU (no, softfp, hard).
ifeq ($(USE_FPU),)
USE_FPU = hard
endif
# FPU-related options.
ifeq ($(USE_FPU_OPT),)
USE_FPU_OPT = -mfloat-abi=$(USE_FPU) -mfpu=fpv4-sp-d16
endif
#
# Architecture or project specific options
##############################################################################
##############################################################################
# Project, target, sources and paths
#
# Define project name here
PROJECT = ch
# Target settings.
MCU = cortex-m4
# Imported source files and paths.
CHIBIOS := ../../../..
CONFDIR := ./cfg
BUILDDIR := ./build
DEPDIR := ./.dep
# Licensing files.
include $(CHIBIOS)/os/license/license.mk
# Startup files.
include $(CHIBIOS)/os/common/startup/ARMCMx/compilers/GCC/mk/startup_stm32f4xx.mk
# HAL-OSAL files (optional).
include $(CHIBIOS)/os/hal/hal.mk
include $(CHIBIOS)/os/hal/ports/STM32/STM32F4xx/platform.mk
include $(CHIBIOS)/os/hal/boards/ST_NUCLEO64_F401RE/board.mk
include $(CHIBIOS)/os/hal/osal/rt-nil/osal.mk
# RTOS files (optional).
include $(CHIBIOS)/os/rt/rt.mk
include $(CHIBIOS)/os/common/ports/ARMv7-M/compilers/GCC/mk/port.mk
# EX files (optional).
include $(CHIBIOS)/os/ex/devices/ST/lsm6ds0.mk
# Auto-build files in ./source recursively.
include $(CHIBIOS)/tools/mk/autobuild.mk
# Other files (optional).
include $(CHIBIOS)/os/hal/lib/streams/streams.mk
# Define linker script file here.
LDSCRIPT= $(STARTUPLD)/STM32F401xE.ld
# C sources that can be compiled in ARM or THUMB mode depending on the global
# setting.
CSRC = $(ALLCSRC) \
$(TESTSRC) \
main.c
# C++ sources that can be compiled in ARM or THUMB mode depending on the global
# setting.
CPPSRC = $(ALLCPPSRC)
# List ASM source files here.
ASMSRC = $(ALLASMSRC)
# List ASM with preprocessor source files here.
ASMXSRC = $(ALLXASMSRC)
# Inclusion directories.
INCDIR = $(CONFDIR) $(ALLINC) $(TESTINC)
# Define C warning options here.
CWARN = -Wall -Wextra -Wundef -Wstrict-prototypes
# Define C++ warning options here.
CPPWARN = -Wall -Wextra -Wundef
#
# Project, target, sources and paths
##############################################################################
##############################################################################
# Start of user section
#
# List all user C define here, like -D_DEBUG=1
UDEFS = -DCHPRINTF_USE_FLOAT=1
# Define ASM defines here
UADEFS =
# List all user directories here
UINCDIR =
# List the user directory to look for the libraries here
ULIBDIR =
# List all user libraries here
ULIBS =
#
# End of user section
##############################################################################
##############################################################################
# Common rules
#
RULESPATH = $(CHIBIOS)/os/common/startup/ARMCMx/compilers/GCC/mk
include $(RULESPATH)/arm-none-eabi.mk
include $(RULESPATH)/rules.mk
#
# Common rules
##############################################################################
##############################################################################
# Custom rules
#
#
# Custom rules
##############################################################################
|
{
"pile_set_name": "Github"
}
|
package crazypants.enderio.machines.machine.niard;
import javax.annotation.Nonnull;
import crazypants.enderio.base.EnderIO;
import io.netty.buffer.ByteBuf;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
public class PacketSFXFluidFizzle implements IMessage {
private NBTTagCompound tag;
private @Nonnull BlockPos pos = BlockPos.ORIGIN;
public PacketSFXFluidFizzle() {
}
public PacketSFXFluidFizzle(@Nonnull FluidStack fluid, @Nonnull BlockPos pos) {
this.tag = fluid.writeToNBT(new NBTTagCompound());
this.pos = pos;
}
@Override
public void toBytes(ByteBuf buf) {
ByteBufUtils.writeTag(buf, tag);
buf.writeLong(pos.toLong());
}
@Override
public void fromBytes(ByteBuf buf) {
tag = ByteBufUtils.readTag(buf);
pos = BlockPos.fromLong(buf.readLong());
}
public static class Handler implements IMessageHandler<PacketSFXFluidFizzle, IMessage> {
@Override
public IMessage onMessage(PacketSFXFluidFizzle message, MessageContext ctx) {
World world = EnderIO.proxy.getClientWorld();
FluidStack fluidStack = FluidStack.loadFluidStackFromNBT(message.tag);
if (fluidStack != null && world != null && world.isBlockLoaded(message.pos)) {
fluidStack.getFluid().vaporize(EnderIO.proxy.getClientPlayer(), world, message.pos, fluidStack);
}
return null;
}
}
}
|
{
"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.beam.sdk.nexmark.queries;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import org.apache.beam.sdk.nexmark.NexmarkConfiguration;
import org.apache.beam.sdk.nexmark.model.AuctionBid;
import org.apache.beam.sdk.values.TimestampedValue;
/** A direct implementation of {@link Query9}. */
public class Query9Model extends NexmarkQueryModel<AuctionBid> implements Serializable {
public Query9Model(NexmarkConfiguration configuration) {
super(configuration);
}
@Override
public AbstractSimulator<?, AuctionBid> simulator() {
return new WinningBidsSimulator(configuration);
}
@Override
protected Collection<String> toCollection(Iterator<TimestampedValue<AuctionBid>> itr) {
return toValue(itr);
}
}
|
{
"pile_set_name": "Github"
}
|
by("Stef")
module modules.optional "1" {
}
|
{
"pile_set_name": "Github"
}
|
goog.provide('jsqrcode.AlignmentPattern');
jsqrcode.FinderPattern = function(posX, posY, estimatedModuleSize) {
this.x = posX;
this.y = posY;
this.count = 1;
this.estimatedModuleSize = estimatedModuleSize;
};
jsqrcode.FinderPattern.prototype.getEstimatedModuleSize = function () {
return this.estimatedModuleSize;
};
jsqrcode.FinderPattern.prototype.getCount = function () {
return this.count;
};
jsqrcode.FinderPattern.prototype.getX = function () {
return this.x;
};
jsqrcode.FinderPattern.prototype.getY = function () {
return this.y;
};
jsqrcode.FinderPattern.prototype.incrementCount = function () {
this.count++;
};
jsqrcode.FinderPattern.prototype.aboutEquals = function (moduleSize, i, j) {
if (Math.abs(i - this.y) <= moduleSize && Math.abs(j - this.x) <= moduleSize) {
var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize);
return moduleSizeDiff <= 1.0 || moduleSizeDiff / this.estimatedModuleSize <= 1.0;
}
return false;
};
|
{
"pile_set_name": "Github"
}
|
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// https://github.com/golang/protobuf
//
// 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 Google Inc. 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.
syntax = "proto2";
package imp;
import "imp2.proto";
import "imp3.proto";
message ImportedMessage {
required int64 field = 1;
// The forwarded getters for these fields are fiddly to get right.
optional ImportedMessage2 local_msg = 2;
optional ForeignImportedMessage foreign_msg = 3; // in imp3.proto
optional Owner enum_field = 4;
oneof union {
int32 state = 9;
}
repeated string name = 5;
repeated Owner boss = 6;
repeated ImportedMessage2 memo = 7;
map<string, ImportedMessage2> msg_map = 8;
enum Owner {
DAVE = 1;
MIKE = 2;
}
extensions 90 to 100;
}
message ImportedMessage2 {
}
message ImportedExtendable {
option message_set_wire_format = true;
extensions 100 to max;
}
|
{
"pile_set_name": "Github"
}
|
/cannot/
/function/ { f = $8 }
/file/ { f = $8 }
/lines/ {
k = match ($1, "%") ;
p = substr ($1, 1, k-1) ;
if ((p+0) != 100)
{
printf "%8s %s\n", p, f
}
}
|
{
"pile_set_name": "Github"
}
|
# @(#)Makefile 8.1 (Berkeley) 5/31/93
PROG= teachgammon
NOMAN= noman
CFLAGS+=-DTEACHGAMMON_TEXT -I${.CURDIR}/../common_source
SRCS= allow.c board.c check.c data.c fancy.c init.c odds.c one.c save.c \
subs.c table.c teach.c ttext1.c ttext2.c tutor.c
GAMESCURSES=
.PATH: ${.CURDIR}/../common_source
# XXX: mismatches between types for static init
init.o: init.c
${CC} ${CFLAGS:N-flto} -c -o ${.TARGET} ${.IMPSRC}
.include "../../Makefile.inc"
.include <bsd.prog.mk>
|
{
"pile_set_name": "Github"
}
|
#
# This makefile can be used to build a Win32 application under Cygwin
#
include ../../../Makefile.in.$(shell uname)
PROGNAME=conv_stroke
OUTNAME=$(PROGNAME)
PLATFORM=win32
CXXFLAGS= $(AGGCXXFLAGS) -I../../../include \
-I/usr/X11R6/include \
-L/usr/X11R6/lib \
-L../../../src \
$(PIXFMT)
LIBS = $(AGGLIBS) -lm -lgdi32
SRC=\
../../$(PROGNAME).cpp \
../../../src/platform/$(PLATFORM)/agg_platform_support.cpp \
../../../src/platform/$(PLATFORM)/agg_win32_bmp.cpp
OBJ= $(SRC:.cpp=.o)
$(OUTNAME): $(OBJ)
$(CXX) $(CXXFLAGS) $^ -o $(OUTNAME) $(LIBS)
clean:
rm -f $(OUTNAME)
rm -f ../../$(PROGNAME).o
rm -f ../../../src/platform/$(PLATFORM)/agg_platform_support.o
rm -f gamma.txt
rm -f gamma.bin
%.o: %.cpp
@echo \< $*.cpp \>
$(CXX) -c $(CXXFLAGS) $*.cpp -o $@
|
{
"pile_set_name": "Github"
}
|
<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:html='http://www.w3.org/1999/xhtml'
xmlns:doc="http://nwalsh.com/xsl/documentation/1.0"
exclude-result-prefixes="doc html"
version='1.0'>
<!-- ********************************************************************
$Id: website.xsl 6910 2007-06-28 23:23:30Z xmldoc $
********************************************************************
This file is part of the WebSite distribution.
See ../README or http://nwalsh.com/website/ for copyright
copyright and other information.
******************************************************************** -->
<!-- ==================================================================== -->
<xsl:include href="website-common.xsl"/>
<xsl:include href="toc.xsl"/>
<xsl:output method="html"
indent="no"/>
<xsl:param name="autolayout" select="document($autolayout-file,/*[1])"/>
<xsl:attribute-set name="body.attributes"/>
<xsl:template name="body.attributes">
<!-- Turn off the template from the stock DocBook XSL -->
</xsl:template>
<!-- ==================================================================== -->
<xsl:template match="webpage">
<xsl:variable name="id">
<xsl:call-template name="object.id"/>
</xsl:variable>
<xsl:variable name="tocentry" select="$autolayout/autolayout//*[$id=@id]"/>
<xsl:variable name="toc" select="$tocentry/ancestor-or-self::toc"/>
<html>
<xsl:apply-templates select="head" mode="head.mode"/>
<xsl:apply-templates select="config" mode="head.mode"/>
<body class="website">
<xsl:call-template name="body.attributes"/>
<div class="{name(.)}">
<a name="{$id}"/>
<xsl:if test="$banner.before.navigation != 0">
<xsl:call-template name="allpages.banner"/>
</xsl:if>
<xsl:if test="$toc">
<div class="navhead">
<xsl:apply-templates select="$toc">
<xsl:with-param name="pageid" select="@id"/>
</xsl:apply-templates>
<xsl:if test="$header.hr != 0"><hr/></xsl:if>
</div>
</xsl:if>
<xsl:if test="$banner.before.navigation = 0">
<xsl:call-template name="allpages.banner"/>
</xsl:if>
<xsl:apply-templates select="./head/title" mode="title.mode"/>
<xsl:apply-templates select="child::node()[not(self::webpage)]"/>
<xsl:call-template name="process.footnotes"/>
<xsl:call-template name="webpage.footer"/>
</div>
</body>
</html>
</xsl:template>
<!-- ==================================================================== -->
<xsl:template match="webtoc">
<xsl:variable name="webpage" select="ancestor::webpage"/>
<xsl:variable name="relpath">
<xsl:call-template name="root-rel-path">
<xsl:with-param name="webpage" select="$webpage"/>
</xsl:call-template>
</xsl:variable>
<xsl:variable name="pageid" select="$webpage/@id"/>
<xsl:variable name="pages"
select="$autolayout//*[$pageid=@id]/tocentry"/>
<xsl:if test="count($pages) > 0">
<ul class="toc">
<xsl:for-each select="$pages">
<li>
<a>
<xsl:attribute name="href">
<xsl:choose>
<xsl:when test="@href">
<xsl:value-of select="@href"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$relpath"/>
<xsl:value-of select="@dir"/>
<xsl:value-of select="$filename-prefix"/>
<xsl:value-of select="@filename"/>
</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
<xsl:apply-templates select="title"/>
</a>
<xsl:if test="summary">
<xsl:text>--</xsl:text>
<xsl:apply-templates select="summary"/>
</xsl:if>
</li>
</xsl:for-each>
</ul>
</xsl:if>
</xsl:template>
<xsl:template match="toc/summary|tocentry/summary|notoc/summary">
<xsl:apply-templates/>
</xsl:template>
<!-- ==================================================================== -->
</xsl:stylesheet>
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* @package Joomla.Site
* @subpackage com_contact
*
* @copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* Contact Component Route Helper
*
* @static
* @package Joomla.Site
* @subpackage com_contact
* @since 1.5
*/
abstract class ContactHelperRoute
{
protected static $lookup;
/**
* Get the URL route for a contact from a contact ID, contact category ID and language
*
* @param integer $id The id of the contact
* @param integer $catid The id of the contact's category
* @param mixed $language The id of the language being used.
*
* @return string The link to the contact
*
* @since 1.5
*/
public static function getContactRoute($id, $catid, $language = 0)
{
$needles = array(
'contact' => array((int) $id)
);
// Create the link
$link = 'index.php?option=com_contact&view=contact&id=' . $id;
if ($catid > 1)
{
$categories = JCategories::getInstance('Contact');
$category = $categories->get($catid);
if ($category)
{
$needles['category'] = array_reverse($category->getPath());
$needles['categories'] = $needles['category'];
$link .= '&catid=' . $catid;
}
}
if ($language && $language != "*" && JLanguageMultilang::isEnabled())
{
$link .= '&lang=' . $language;
$needles['language'] = $language;
}
if ($item = self::_findItem($needles))
{
$link .= '&Itemid=' . $item;
}
return $link;
}
/**
* Get the URL route for a contact category from a contact category ID and language
*
* @param mixed $catid The id of the contact's category either an integer id or a instance of JCategoryNode
* @param mixed $language The id of the language being used.
*
* @return string The link to the contact
*
* @since 1.5
*/
public static function getCategoryRoute($catid, $language = 0)
{
if ($catid instanceof JCategoryNode)
{
$id = $catid->id;
$category = $catid;
}
else
{
$id = (int) $catid;
$category = JCategories::getInstance('Contact')->get($id);
}
if ($id < 1 || !($category instanceof JCategoryNode))
{
$link = '';
}
else
{
$needles = array();
// Create the link
$link = 'index.php?option=com_contact&view=category&id=' . $id;
$catids = array_reverse($category->getPath());
$needles['category'] = $catids;
$needles['categories'] = $catids;
if ($language && $language != "*" && JLanguageMultilang::isEnabled())
{
$link .= '&lang=' . $language;
$needles['language'] = $language;
}
if ($item = self::_findItem($needles))
{
$link .= '&Itemid=' . $item;
}
}
return $link;
}
/**
* Find an item ID.
*
* @param array $needles An array of language codes.
*
* @return mixed The ID found or null otherwise.
*
* @since 1.6
*/
protected static function _findItem($needles = null)
{
$app = JFactory::getApplication();
$menus = $app->getMenu('site');
$language = isset($needles['language']) ? $needles['language'] : '*';
// Prepare the reverse lookup array.
if (!isset(self::$lookup[$language]))
{
self::$lookup[$language] = array();
$component = JComponentHelper::getComponent('com_contact');
$attributes = array('component_id');
$values = array($component->id);
if ($language != '*')
{
$attributes[] = 'language';
$values[] = array($needles['language'], '*');
}
$items = $menus->getItems($attributes, $values);
foreach ($items as $item)
{
if (isset($item->query) && isset($item->query['view']))
{
$view = $item->query['view'];
if (!isset(self::$lookup[$language][$view]))
{
self::$lookup[$language][$view] = array();
}
if (isset($item->query['id']))
{
/**
* Here it will become a bit tricky
* language != * can override existing entries
* language == * cannot override existing entries
*/
if (!isset(self::$lookup[$language][$view][$item->query['id']]) || $item->language != '*')
{
self::$lookup[$language][$view][$item->query['id']] = $item->id;
}
}
}
}
}
if ($needles)
{
foreach ($needles as $view => $ids)
{
if (isset(self::$lookup[$language][$view]))
{
foreach ($ids as $id)
{
if (isset(self::$lookup[$language][$view][(int) $id]))
{
return self::$lookup[$language][$view][(int) $id];
}
}
}
}
}
// Check if the active menuitem matches the requested language
$active = $menus->getActive();
if ($active && ($language == '*' || in_array($active->language, array('*', $language)) || !JLanguageMultilang::isEnabled()))
{
return $active->id;
}
// If not found, return language specific home link
$default = $menus->getDefault($language);
return !empty($default->id) ? $default->id : null;
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* /MathJax/fonts/HTML-CSS/TeX/png/Fraktur/Bold/Main.js
*
* Copyright (c) 2010-2013 The MathJax Consortium
*
* Part of the MathJax library.
* See http://www.mathjax.org for details.
*
* Licensed under the Apache License, Version 2.0;
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
MathJax.OutputJax["HTML-CSS"].defineImageData({"MathJax_Fraktur-bold":{}});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].imgDir+"/Fraktur/Bold"+MathJax.OutputJax["HTML-CSS"].imgPacked+"/Main.js");
|
{
"pile_set_name": "Github"
}
|
<?php declare(strict_types=1);
/**
* This file is part of the Yasumi package.
*
* Copyright (c) 2015 - 2020 AzuyaLabs
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Sacha Telgenhof <me@sachatelgenhof.com>
*/
namespace Yasumi\tests\Australia\Tasmania;
use DateTime;
use DateTimeZone;
use Exception;
use ReflectionException;
use Yasumi\Holiday;
use Yasumi\tests\YasumiTestCaseInterface;
/**
* Class for testing Eight Hour Day in Tasmania (Australia)..
*/
class EightHourDayTest extends TasmaniaBaseTestCase implements YasumiTestCaseInterface
{
/**
* The name of the holiday
*/
public const HOLIDAY = 'eightHourDay';
/**
* Tests Eight Hour Day
*
* @dataProvider HolidayDataProvider
*
* @param int $year the year for which the holiday defined in this test needs to be tested
* @param string $expected the expected date
*
* @throws ReflectionException
* @throws Exception
*/
public function testHoliday($year, $expected): void
{
$this->assertHoliday(
$this->region,
self::HOLIDAY,
$year,
new DateTime($expected, new DateTimeZone($this->timezone))
);
}
/**
* Returns a list of test dates
*
* @return array list of test dates for the holiday defined in this test
*/
public function HolidayDataProvider(): array
{
return [
[2010, '2010-03-08'],
[2011, '2011-03-14'],
[2012, '2012-03-12'],
[2013, '2013-03-11'],
[2014, '2014-03-10'],
[2015, '2015-03-09'],
[2016, '2016-03-14'],
[2017, '2017-03-13'],
[2018, '2018-03-12'],
[2019, '2019-03-11'],
[2020, '2020-03-09'],
];
}
/**
* Tests the translated name of the holiday defined in this test.
* @throws ReflectionException
*/
public function testTranslation(): void
{
$this->assertTranslatedHolidayName(
$this->region,
self::HOLIDAY,
$this->generateRandomYear(1990),
[self::LOCALE => 'Eight Hour Day']
);
}
/**
* Tests type of the holiday defined in this test.
* @throws ReflectionException
*/
public function testHolidayType(): void
{
$this->assertHolidayType($this->region, self::HOLIDAY, $this->generateRandomYear(1990), Holiday::TYPE_OFFICIAL);
}
}
|
{
"pile_set_name": "Github"
}
|
#!/bin/sh
# Pandora
printf "\033]4;0;#000000;1;#ff4242;2;#74af68;3;#ffad29;4;#338f86;5;#9414e6;6;#23d7d7;7;#e2e2e2;8;#3f5648;9;#ff3242;10;#74cd68;11;#ffb929;12;#23d7d7;13;#ff37ff;14;#00ede1;15;#ffffff\007"
printf "\033]10;#e1e1e1;#141e43;#43d58e\007"
printf "\033]17;#2d37ff\007"
printf "\033]19;#82e0ff\007"
printf "\033]5;0;#67a672\007"
|
{
"pile_set_name": "Github"
}
|
#include "SSACallingConvApplier.h"
#include "CallingConvention.h"
#include "Architecture.h"
#include <assert.h>
namespace holodec {
bool SSACallingConvApplier::doTransformation (Function* function) {
printf ("Apply Calling Convention in Function at Address 0x%" PRIx64 "\n", function->baseaddr);
/*
CallingConvention* cc = arch->getCallingConvention (function->callingconvention);
Stack* stack = cc->stack ? arch->getStack (cc->stack) : nullptr;
Register* stackreg = stack && stack->trackingReg ? arch->getRegister (stack->trackingReg) : nullptr;
for (SSAExpression& expr : function->ssaRep.expressions) {
if (!expr.id)
continue;
if (expr.type == SSAExprType::eOutput) {
//TODO get Call method and get the calling convention of the target
//currently HACK to use own calling convention
assert (expr.subExpressions[0].type == SSAArgType::eId);
SSAExpression* callExpr = function->ssaRep.expressions.get (expr.subExpressions[0].ssaId);
assert (callExpr && callExpr->type == SSAExprType::eCall);
//TODO get correct stackreg
Register* localStackReg = stackreg;
bool isParam = false;
switch (expr.location) {
case SSALocation::eReg: {
for (StringRef& regStr : cc->nonVolatileReg) {
Register* reg = arch->getRegister (regStr);
if (expr.ref.refId == reg->id) {
assert (expr.subExpressions[0].type == SSAArgType::eId);
expr.type = SSAExprType::eAssign;
for (SSAArgument& arg : callExpr->subExpressions) {
if (arg.ref.isLocation(SSALocation::eReg) && arg.ref == expr.ref) {
expr.subExpressions[0] = arg;
}
}
isParam = true;
break;
}
}
if (!isParam && localStackReg && expr.ref.refId == localStackReg->id && cc->callerstackadjust == CCStackAdjust::eCallee) {
expr.type = SSAExprType::eAssign;
for (SSAArgument& arg : callExpr->subExpressions) {
if (arg.ref.isLocation(SSALocation::eReg) && arg.ref == expr.ref) {
expr.subExpressions[0] = arg;
}
}
//leave the arg
isParam = true;
}
if (!isParam) {
for (CCParameter& para : cc->returns) {
Register* reg = arch->getRegister (para.regref);
if (expr.ref.refId == reg->id) {
expr.subExpressions.push_back (SSAArgument::createUVal ( (uint64_t) para.index, arch->bytebase * arch->bitbase));
isParam = true;
break;
}
}
}
}
break;
case SSALocation::eMem: {
for (Memory& mem : arch->memories) {
if (expr.ref.refId == mem.id) {
expr.subExpressions.push_back (SSAArgument::createUVal ( (uint64_t) 0, arch->bytebase * arch->bitbase));
isParam = true;
}
}
}
break;
default:
break;
}
if (!isParam) {
expr.type = SSAExprType::eUndef;
if (!expr.subExpressions.empty())
expr.subExpressions.clear();
}
}
if (expr.type == SSAExprType::eReturn) {
for (auto it = expr.subExpressions.begin(); it != expr.subExpressions.end();) {
SSAArgument& arg = *it;
bool isParam = false;
if (arg.ref.isLocation(SSALocation::eReg)) {
if (!isParam) {
for (CCParameter& para : cc->returns) {
Register* reg = arch->getRegister (para.regref);
if (arg.ref.refId == reg->id) {
//leave as arg
isParam = true;
break;
}
}
}
} else if (arg.ref.isLocation(SSALocation::eMem)) {
isParam = true;
}
if (!isParam) {
it = expr.subExpressions.erase (it);
continue;
}
it++;
}
}
if (expr.type == SSAExprType::eInput) {
bool isParam = false;
switch (expr.location) {
case SSALocation::eReg: {
for (CCParameter& para : cc->parameters) {
Register* reg = arch->getRegister (para.regref);
if (expr.ref.refId == reg->id) {
expr.subExpressions.push_back (SSAArgument::createUVal ( (uint64_t) para.index, arch->bytebase * arch->bitbase));
isParam = true;
break;
}
}
if (!isParam && expr.ref.refId == stackreg->id) {
expr.subExpressions.push_back (SSAArgument::createUVal ( (uint64_t) 0, arch->bytebase * arch->bitbase));
isParam = true;
}
}
break;
case SSALocation::eMem: {
for (Memory& mem : arch->memories) {
if (expr.ref.refId == mem.id) {
expr.subExpressions.push_back (SSAArgument::createUVal ( (uint64_t) 0, arch->bytebase * arch->bitbase));
isParam = true;
}
}
}
break;
default:
break;
}
if (!isParam) {
expr.type = SSAExprType::eUndef;
if (!expr.subExpressions.empty())
expr.subExpressions.clear();
}
}
}
for (SSAExpression& expr : function->ssaRep.expressions) {
if (!expr.id)
continue;
if (expr.type == SSAExprType::eCall) {
//TODO get the calling convention of the target
//currently HACK to use own calling convention
//skip first parameter
for (auto it = expr.subExpressions.begin() + 1; it != expr.subExpressions.end();) {
SSAArgument& arg = *it;
bool isParam = false;
if (arg.ref.isLocation(SSALocation::eMem))
isParam = true;
if (!isParam) {
for (CCParameter& para : cc->parameters) {
Register* reg = arch->getRegister (para.regref);
if (arg.ref.refId == reg->id) {
//leave the arg
isParam = true;
break;
}
}
}
if (!isParam && stackreg && arg.ref.refId == stackreg->id) {
//leave the arg
isParam = true;
}
if (!isParam) {
//remove from arg list
it = expr.subExpressions.erase (it);
continue;
}
it++;
}
}
}*/
function->ssaRep.compress();
return false;
}
}
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env python
# Copyright (c) 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
import base64
from datetime import datetime
from tests.unit import unittest
from tests.unit import AWSMockServiceTestCase
from boto.ec2.autoscale import AutoScaleConnection
from boto.ec2.autoscale.group import AutoScalingGroup
from boto.ec2.autoscale.policy import ScalingPolicy
from boto.ec2.autoscale.tag import Tag
from boto.ec2.blockdevicemapping import EBSBlockDeviceType, BlockDeviceMapping
from boto.ec2.autoscale import launchconfig, LaunchConfiguration
class TestAutoScaleGroup(AWSMockServiceTestCase):
connection_class = AutoScaleConnection
def setUp(self):
super(TestAutoScaleGroup, self).setUp()
def default_body(self):
return b"""
<CreateLaunchConfigurationResponse>
<ResponseMetadata>
<RequestId>requestid</RequestId>
</ResponseMetadata>
</CreateLaunchConfigurationResponse>
"""
def test_autoscaling_group_with_termination_policies(self):
self.set_http_response(status_code=200)
autoscale = AutoScalingGroup(
name='foo', launch_config='lauch_config',
min_size=1, max_size=2,
termination_policies=['OldestInstance', 'OldestLaunchConfiguration'],
instance_id='test-id')
self.service_connection.create_auto_scaling_group(autoscale)
self.assert_request_parameters({
'Action': 'CreateAutoScalingGroup',
'AutoScalingGroupName': 'foo',
'LaunchConfigurationName': 'lauch_config',
'MaxSize': 2,
'MinSize': 1,
'TerminationPolicies.member.1': 'OldestInstance',
'TerminationPolicies.member.2': 'OldestLaunchConfiguration',
'InstanceId': 'test-id',
}, ignore_params_values=['Version'])
def test_autoscaling_group_single_vpc_zone_identifier(self):
self.set_http_response(status_code=200)
autoscale = AutoScalingGroup(
name='foo',
vpc_zone_identifier='vpc_zone_1')
self.service_connection.create_auto_scaling_group(autoscale)
self.assert_request_parameters({
'Action': 'CreateAutoScalingGroup',
'AutoScalingGroupName': 'foo',
'VPCZoneIdentifier': 'vpc_zone_1',
}, ignore_params_values=['MaxSize', 'MinSize', 'LaunchConfigurationName', 'Version'])
def test_autoscaling_group_vpc_zone_identifier_list(self):
self.set_http_response(status_code=200)
autoscale = AutoScalingGroup(
name='foo',
vpc_zone_identifier=['vpc_zone_1', 'vpc_zone_2'])
self.service_connection.create_auto_scaling_group(autoscale)
self.assert_request_parameters({
'Action': 'CreateAutoScalingGroup',
'AutoScalingGroupName': 'foo',
'VPCZoneIdentifier': 'vpc_zone_1,vpc_zone_2',
}, ignore_params_values=['MaxSize', 'MinSize', 'LaunchConfigurationName', 'Version'])
def test_autoscaling_group_vpc_zone_identifier_multi(self):
self.set_http_response(status_code=200)
autoscale = AutoScalingGroup(
name='foo',
vpc_zone_identifier='vpc_zone_1,vpc_zone_2')
self.service_connection.create_auto_scaling_group(autoscale)
self.assert_request_parameters({
'Action': 'CreateAutoScalingGroup',
'AutoScalingGroupName': 'foo',
'VPCZoneIdentifier': 'vpc_zone_1,vpc_zone_2',
}, ignore_params_values=['MaxSize', 'MinSize', 'LaunchConfigurationName', 'Version'])
class TestAutoScaleGroupHonorCooldown(AWSMockServiceTestCase):
connection_class = AutoScaleConnection
def default_body(self):
return b"""
<SetDesiredCapacityResponse>
<ResponseMetadata>
<RequestId>9fb7e2db-6998-11e2-a985-57c82EXAMPLE</RequestId>
</ResponseMetadata>
</SetDesiredCapacityResponse>
"""
def test_honor_cooldown(self):
self.set_http_response(status_code=200)
self.service_connection.set_desired_capacity('foo', 10, True)
self.assert_request_parameters({
'Action': 'SetDesiredCapacity',
'AutoScalingGroupName': 'foo',
'DesiredCapacity': 10,
'HonorCooldown': 'true',
}, ignore_params_values=['Version'])
class TestScheduledGroup(AWSMockServiceTestCase):
connection_class = AutoScaleConnection
def setUp(self):
super(TestScheduledGroup, self).setUp()
def default_body(self):
return b"""
<PutScheduledUpdateGroupActionResponse>
<ResponseMetadata>
<RequestId>requestid</RequestId>
</ResponseMetadata>
</PutScheduledUpdateGroupActionResponse>
"""
def test_scheduled_group_creation(self):
self.set_http_response(status_code=200)
self.service_connection.create_scheduled_group_action('foo',
'scheduled-foo',
desired_capacity=1,
start_time=datetime(2013, 1, 1, 22, 55, 31),
end_time=datetime(2013, 2, 1, 22, 55, 31),
min_size=1,
max_size=2,
recurrence='0 10 * * *')
self.assert_request_parameters({
'Action': 'PutScheduledUpdateGroupAction',
'AutoScalingGroupName': 'foo',
'ScheduledActionName': 'scheduled-foo',
'MaxSize': 2,
'MinSize': 1,
'DesiredCapacity': 1,
'EndTime': '2013-02-01T22:55:31',
'StartTime': '2013-01-01T22:55:31',
'Recurrence': '0 10 * * *',
}, ignore_params_values=['Version'])
class TestParseAutoScaleGroupResponse(AWSMockServiceTestCase):
connection_class = AutoScaleConnection
def default_body(self):
return b"""
<DescribeAutoScalingGroupsResult>
<AutoScalingGroups>
<member>
<Tags/>
<SuspendedProcesses/>
<AutoScalingGroupName>test_group</AutoScalingGroupName>
<HealthCheckType>EC2</HealthCheckType>
<CreatedTime>2012-09-27T20:19:47.082Z</CreatedTime>
<EnabledMetrics/>
<LaunchConfigurationName>test_launchconfig</LaunchConfigurationName>
<Instances>
<member>
<HealthStatus>Healthy</HealthStatus>
<AvailabilityZone>us-east-1a</AvailabilityZone>
<InstanceId>i-z118d054</InstanceId>
<LaunchConfigurationName>test_launchconfig</LaunchConfigurationName>
<LifecycleState>InService</LifecycleState>
</member>
</Instances>
<DesiredCapacity>1</DesiredCapacity>
<AvailabilityZones>
<member>us-east-1c</member>
<member>us-east-1a</member>
</AvailabilityZones>
<LoadBalancerNames/>
<MinSize>1</MinSize>
<VPCZoneIdentifier/>
<HealthCheckGracePeriod>0</HealthCheckGracePeriod>
<DefaultCooldown>300</DefaultCooldown>
<AutoScalingGroupARN>myarn</AutoScalingGroupARN>
<TerminationPolicies>
<member>OldestInstance</member>
<member>OldestLaunchConfiguration</member>
</TerminationPolicies>
<MaxSize>2</MaxSize>
<InstanceId>Something</InstanceId>
</member>
</AutoScalingGroups>
</DescribeAutoScalingGroupsResult>
"""
def test_get_all_groups_is_parsed_correctly(self):
self.set_http_response(status_code=200)
response = self.service_connection.get_all_groups(names=['test_group'])
self.assertEqual(len(response), 1, response)
as_group = response[0]
self.assertEqual(as_group.availability_zones, ['us-east-1c', 'us-east-1a'])
self.assertEqual(as_group.default_cooldown, 300)
self.assertEqual(as_group.desired_capacity, 1)
self.assertEqual(as_group.enabled_metrics, [])
self.assertEqual(as_group.health_check_period, 0)
self.assertEqual(as_group.health_check_type, 'EC2')
self.assertEqual(as_group.launch_config_name, 'test_launchconfig')
self.assertEqual(as_group.load_balancers, [])
self.assertEqual(as_group.min_size, 1)
self.assertEqual(as_group.max_size, 2)
self.assertEqual(as_group.name, 'test_group')
self.assertEqual(as_group.suspended_processes, [])
self.assertEqual(as_group.tags, [])
self.assertEqual(as_group.termination_policies,
['OldestInstance', 'OldestLaunchConfiguration'])
self.assertEqual(as_group.instance_id, 'Something')
class TestDescribeTerminationPolicies(AWSMockServiceTestCase):
connection_class = AutoScaleConnection
def default_body(self):
return b"""
<DescribeTerminationPolicyTypesResponse>
<DescribeTerminationPolicyTypesResult>
<TerminationPolicyTypes>
<member>ClosestToNextInstanceHour</member>
<member>Default</member>
<member>NewestInstance</member>
<member>OldestInstance</member>
<member>OldestLaunchConfiguration</member>
</TerminationPolicyTypes>
</DescribeTerminationPolicyTypesResult>
<ResponseMetadata>
<RequestId>requestid</RequestId>
</ResponseMetadata>
</DescribeTerminationPolicyTypesResponse>
"""
def test_autoscaling_group_with_termination_policies(self):
self.set_http_response(status_code=200)
response = self.service_connection.get_termination_policies()
self.assertListEqual(
response,
['ClosestToNextInstanceHour', 'Default',
'NewestInstance', 'OldestInstance', 'OldestLaunchConfiguration'])
class TestLaunchConfigurationDescribe(AWSMockServiceTestCase):
connection_class = AutoScaleConnection
def default_body(self):
# This is a dummy response
return b"""
<DescribeLaunchConfigurationsResponse>
<DescribeLaunchConfigurationsResult>
<LaunchConfigurations>
<member>
<AssociatePublicIpAddress>true</AssociatePublicIpAddress>
<SecurityGroups/>
<CreatedTime>2013-01-21T23:04:42.200Z</CreatedTime>
<KernelId/>
<LaunchConfigurationName>my-test-lc</LaunchConfigurationName>
<UserData/>
<InstanceType>m1.small</InstanceType>
<LaunchConfigurationARN>arn:aws:autoscaling:us-east-1:803981987763:launchConfiguration:9dbbbf87-6141-428a-a409-0752edbe6cad:launchConfigurationName/my-test-lc</LaunchConfigurationARN>
<BlockDeviceMappings/>
<ImageId>ami-514ac838</ImageId>
<KeyName/>
<RamdiskId/>
<InstanceMonitoring>
<Enabled>true</Enabled>
</InstanceMonitoring>
<EbsOptimized>false</EbsOptimized>
<ClassicLinkVPCId>vpc-12345</ClassicLinkVPCId>
<ClassicLinkVPCSecurityGroups>
<member>sg-1234</member>
</ClassicLinkVPCSecurityGroups>
</member>
</LaunchConfigurations>
</DescribeLaunchConfigurationsResult>
<ResponseMetadata>
<RequestId>d05a22f8-b690-11e2-bf8e-2113fEXAMPLE</RequestId>
</ResponseMetadata>
</DescribeLaunchConfigurationsResponse>
"""
def test_get_all_launch_configurations(self):
self.set_http_response(status_code=200)
response = self.service_connection.get_all_launch_configurations()
self.assertTrue(isinstance(response, list))
self.assertEqual(len(response), 1)
self.assertTrue(isinstance(response[0], LaunchConfiguration))
self.assertEqual(response[0].associate_public_ip_address, True)
self.assertEqual(response[0].name, "my-test-lc")
self.assertEqual(response[0].instance_type, "m1.small")
self.assertEqual(response[0].launch_configuration_arn, "arn:aws:autoscaling:us-east-1:803981987763:launchConfiguration:9dbbbf87-6141-428a-a409-0752edbe6cad:launchConfigurationName/my-test-lc")
self.assertEqual(response[0].image_id, "ami-514ac838")
self.assertTrue(isinstance(response[0].instance_monitoring, launchconfig.InstanceMonitoring))
self.assertEqual(response[0].instance_monitoring.enabled, 'true')
self.assertEqual(response[0].ebs_optimized, False)
self.assertEqual(response[0].block_device_mappings, [])
self.assertEqual(response[0].classic_link_vpc_id, 'vpc-12345')
self.assertEqual(response[0].classic_link_vpc_security_groups,
['sg-1234'])
self.assert_request_parameters({
'Action': 'DescribeLaunchConfigurations',
}, ignore_params_values=['Version'])
def test_get_all_configuration_limited(self):
self.set_http_response(status_code=200)
response = self.service_connection.get_all_launch_configurations(max_records=10, names=["my-test1", "my-test2"])
self.assert_request_parameters({
'Action': 'DescribeLaunchConfigurations',
'MaxRecords': 10,
'LaunchConfigurationNames.member.1': 'my-test1',
'LaunchConfigurationNames.member.2': 'my-test2'
}, ignore_params_values=['Version'])
class TestLaunchConfiguration(AWSMockServiceTestCase):
connection_class = AutoScaleConnection
def default_body(self):
# This is a dummy response
return b"""
<DescribeLaunchConfigurationsResponse>
</DescribeLaunchConfigurationsResponse>
"""
def test_launch_config(self):
# This unit test is based on #753 and #1343
self.set_http_response(status_code=200)
dev_sdf = EBSBlockDeviceType(snapshot_id='snap-12345')
bdm = BlockDeviceMapping()
bdm['/dev/sdf'] = dev_sdf
lc = launchconfig.LaunchConfiguration(
connection=self.service_connection,
name='launch_config',
image_id='123456',
instance_type='m1.large',
user_data='#!/bin/bash',
security_groups=['group1'],
spot_price='price',
block_device_mappings=[bdm],
associate_public_ip_address=True,
volume_type='atype',
delete_on_termination=False,
iops=3000,
classic_link_vpc_id='vpc-1234',
classic_link_vpc_security_groups=['classic_link_group']
)
response = self.service_connection.create_launch_configuration(lc)
self.assert_request_parameters({
'Action': 'CreateLaunchConfiguration',
'BlockDeviceMappings.member.1.DeviceName': '/dev/sdf',
'BlockDeviceMappings.member.1.Ebs.DeleteOnTermination': 'false',
'BlockDeviceMappings.member.1.Ebs.SnapshotId': 'snap-12345',
'EbsOptimized': 'false',
'LaunchConfigurationName': 'launch_config',
'ImageId': '123456',
'UserData': base64.b64encode(b'#!/bin/bash').decode('utf-8'),
'InstanceMonitoring.Enabled': 'false',
'InstanceType': 'm1.large',
'SecurityGroups.member.1': 'group1',
'SpotPrice': 'price',
'AssociatePublicIpAddress': 'true',
'VolumeType': 'atype',
'DeleteOnTermination': 'false',
'Iops': 3000,
'ClassicLinkVPCId': 'vpc-1234',
'ClassicLinkVPCSecurityGroups.member.1': 'classic_link_group'
}, ignore_params_values=['Version'])
class TestCreateAutoScalePolicy(AWSMockServiceTestCase):
connection_class = AutoScaleConnection
def setUp(self):
super(TestCreateAutoScalePolicy, self).setUp()
def default_body(self):
return b"""
<PutScalingPolicyResponse xmlns="http://autoscaling.amazonaws.com\
/doc/2011-01-01/">
<PutScalingPolicyResult>
<PolicyARN>arn:aws:autoscaling:us-east-1:803981987763:scaling\
Policy:b0dcf5e8
-02e6-4e31-9719-0675d0dc31ae:autoScalingGroupName/my-test-asg:\
policyName/my-scal
eout-policy</PolicyARN>
</PutScalingPolicyResult>
<ResponseMetadata>
<RequestId>3cfc6fef-c08b-11e2-a697-2922EXAMPLE</RequestId>
</ResponseMetadata>
</PutScalingPolicyResponse>
"""
def test_scaling_policy_with_min_adjustment_step(self):
self.set_http_response(status_code=200)
policy = ScalingPolicy(
name='foo', as_name='bar',
adjustment_type='PercentChangeInCapacity', scaling_adjustment=50,
min_adjustment_step=30)
self.service_connection.create_scaling_policy(policy)
self.assert_request_parameters({
'Action': 'PutScalingPolicy',
'PolicyName': 'foo',
'AutoScalingGroupName': 'bar',
'AdjustmentType': 'PercentChangeInCapacity',
'ScalingAdjustment': 50,
'MinAdjustmentStep': 30
}, ignore_params_values=['Version'])
def test_scaling_policy_with_wrong_adjustment_type(self):
self.set_http_response(status_code=200)
policy = ScalingPolicy(
name='foo', as_name='bar',
adjustment_type='ChangeInCapacity', scaling_adjustment=50,
min_adjustment_step=30)
self.service_connection.create_scaling_policy(policy)
self.assert_request_parameters({
'Action': 'PutScalingPolicy',
'PolicyName': 'foo',
'AutoScalingGroupName': 'bar',
'AdjustmentType': 'ChangeInCapacity',
'ScalingAdjustment': 50
}, ignore_params_values=['Version'])
def test_scaling_policy_without_min_adjustment_step(self):
self.set_http_response(status_code=200)
policy = ScalingPolicy(
name='foo', as_name='bar',
adjustment_type='PercentChangeInCapacity', scaling_adjustment=50)
self.service_connection.create_scaling_policy(policy)
self.assert_request_parameters({
'Action': 'PutScalingPolicy',
'PolicyName': 'foo',
'AutoScalingGroupName': 'bar',
'AdjustmentType': 'PercentChangeInCapacity',
'ScalingAdjustment': 50
}, ignore_params_values=['Version'])
class TestPutNotificationConfiguration(AWSMockServiceTestCase):
connection_class = AutoScaleConnection
def setUp(self):
super(TestPutNotificationConfiguration, self).setUp()
def default_body(self):
return b"""
<PutNotificationConfigurationResponse>
<ResponseMetadata>
<RequestId>requestid</RequestId>
</ResponseMetadata>
</PutNotificationConfigurationResponse>
"""
def test_autoscaling_group_put_notification_configuration(self):
self.set_http_response(status_code=200)
autoscale = AutoScalingGroup(
name='ana', launch_config='lauch_config',
min_size=1, max_size=2,
termination_policies=['OldestInstance', 'OldestLaunchConfiguration'])
self.service_connection.put_notification_configuration(autoscale, 'arn:aws:sns:us-east-1:19890506:AutoScaling-Up', ['autoscaling:EC2_INSTANCE_LAUNCH'])
self.assert_request_parameters({
'Action': 'PutNotificationConfiguration',
'AutoScalingGroupName': 'ana',
'NotificationTypes.member.1': 'autoscaling:EC2_INSTANCE_LAUNCH',
'TopicARN': 'arn:aws:sns:us-east-1:19890506:AutoScaling-Up',
}, ignore_params_values=['Version'])
class TestDeleteNotificationConfiguration(AWSMockServiceTestCase):
connection_class = AutoScaleConnection
def setUp(self):
super(TestDeleteNotificationConfiguration, self).setUp()
def default_body(self):
return b"""
<DeleteNotificationConfigurationResponse>
<ResponseMetadata>
<RequestId>requestid</RequestId>
</ResponseMetadata>
</DeleteNotificationConfigurationResponse>
"""
def test_autoscaling_group_put_notification_configuration(self):
self.set_http_response(status_code=200)
autoscale = AutoScalingGroup(
name='ana', launch_config='lauch_config',
min_size=1, max_size=2,
termination_policies=['OldestInstance', 'OldestLaunchConfiguration'])
self.service_connection.delete_notification_configuration(autoscale, 'arn:aws:sns:us-east-1:19890506:AutoScaling-Up')
self.assert_request_parameters({
'Action': 'DeleteNotificationConfiguration',
'AutoScalingGroupName': 'ana',
'TopicARN': 'arn:aws:sns:us-east-1:19890506:AutoScaling-Up',
}, ignore_params_values=['Version'])
class TestAutoScalingTag(AWSMockServiceTestCase):
connection_class = AutoScaleConnection
def default_body(self):
return b"""
<CreateOrUpdateTagsResponse>
<ResponseMetadata>
<RequestId>requestId</RequestId>
</ResponseMetadata>
</CreateOrUpdateTagsResponse>
"""
def test_create_or_update_tags(self):
self.set_http_response(status_code=200)
tags = [
Tag(
connection=self.service_connection,
key='alpha',
value='tango',
resource_id='sg-00000000',
resource_type='auto-scaling-group',
propagate_at_launch=True
),
Tag(
connection=self.service_connection,
key='bravo',
value='sierra',
resource_id='sg-00000000',
resource_type='auto-scaling-group',
propagate_at_launch=False
)]
response = self.service_connection.create_or_update_tags(tags)
self.assert_request_parameters({
'Action': 'CreateOrUpdateTags',
'Tags.member.1.ResourceType': 'auto-scaling-group',
'Tags.member.1.ResourceId': 'sg-00000000',
'Tags.member.1.Key': 'alpha',
'Tags.member.1.Value': 'tango',
'Tags.member.1.PropagateAtLaunch': 'true',
'Tags.member.2.ResourceType': 'auto-scaling-group',
'Tags.member.2.ResourceId': 'sg-00000000',
'Tags.member.2.Key': 'bravo',
'Tags.member.2.Value': 'sierra',
'Tags.member.2.PropagateAtLaunch': 'false'
}, ignore_params_values=['Version'])
def test_endElement(self):
for i in [
('Key', 'mykey', 'key'),
('Value', 'myvalue', 'value'),
('ResourceType', 'auto-scaling-group', 'resource_type'),
('ResourceId', 'sg-01234567', 'resource_id'),
('PropagateAtLaunch', 'true', 'propagate_at_launch')]:
self.check_tag_attributes_set(i[0], i[1], i[2])
def check_tag_attributes_set(self, name, value, attr):
tag = Tag()
tag.endElement(name, value, None)
if value == 'true':
self.assertEqual(getattr(tag, attr), True)
else:
self.assertEqual(getattr(tag, attr), value)
class TestAttachInstances(AWSMockServiceTestCase):
connection_class = AutoScaleConnection
def setUp(self):
super(TestAttachInstances, self).setUp()
def default_body(self):
return b"""
<AttachInstancesResponse>
<ResponseMetadata>
<RequestId>requestid</RequestId>
</ResponseMetadata>
</AttachInstancesResponse>
"""
def test_attach_instances(self):
self.set_http_response(status_code=200)
self.service_connection.attach_instances(
'autoscale',
['inst2', 'inst1', 'inst4']
)
self.assert_request_parameters({
'Action': 'AttachInstances',
'AutoScalingGroupName': 'autoscale',
'InstanceIds.member.1': 'inst2',
'InstanceIds.member.2': 'inst1',
'InstanceIds.member.3': 'inst4',
}, ignore_params_values=['Version'])
class TestDetachInstances(AWSMockServiceTestCase):
connection_class = AutoScaleConnection
def setUp(self):
super(TestDetachInstances, self).setUp()
def default_body(self):
return b"""
<DetachInstancesResponse>
<ResponseMetadata>
<RequestId>requestid</RequestId>
</ResponseMetadata>
</DetachInstancesResponse>
"""
def test_detach_instances(self):
self.set_http_response(status_code=200)
self.service_connection.detach_instances(
'autoscale',
['inst2', 'inst1', 'inst4']
)
self.assert_request_parameters({
'Action': 'DetachInstances',
'AutoScalingGroupName': 'autoscale',
'InstanceIds.member.1': 'inst2',
'InstanceIds.member.2': 'inst1',
'InstanceIds.member.3': 'inst4',
'ShouldDecrementDesiredCapacity': 'true',
}, ignore_params_values=['Version'])
def test_detach_instances_with_decrement_desired_capacity(self):
self.set_http_response(status_code=200)
self.service_connection.detach_instances(
'autoscale',
['inst2', 'inst1', 'inst4'],
True
)
self.assert_request_parameters({
'Action': 'DetachInstances',
'AutoScalingGroupName': 'autoscale',
'InstanceIds.member.1': 'inst2',
'InstanceIds.member.2': 'inst1',
'InstanceIds.member.3': 'inst4',
'ShouldDecrementDesiredCapacity': 'true',
}, ignore_params_values=['Version'])
def test_detach_instances_without_decrement_desired_capacity(self):
self.set_http_response(status_code=200)
self.service_connection.detach_instances(
'autoscale',
['inst2', 'inst1', 'inst4'],
False
)
self.assert_request_parameters({
'Action': 'DetachInstances',
'AutoScalingGroupName': 'autoscale',
'InstanceIds.member.1': 'inst2',
'InstanceIds.member.2': 'inst1',
'InstanceIds.member.3': 'inst4',
'ShouldDecrementDesiredCapacity': 'false',
}, ignore_params_values=['Version'])
class TestGetAccountLimits(AWSMockServiceTestCase):
connection_class = AutoScaleConnection
def setUp(self):
super(TestGetAccountLimits, self).setUp()
def default_body(self):
return b"""
<DescribeAccountLimitsAnswer>
<MaxNumberOfAutoScalingGroups>6</MaxNumberOfAutoScalingGroups>
<MaxNumberOfLaunchConfigurations>3</MaxNumberOfLaunchConfigurations>
<ResponseMetadata>
<RequestId>requestid</RequestId>
</ResponseMetadata>
</DescribeAccountLimitsAnswer>
"""
def test_autoscaling_group_put_notification_configuration(self):
self.set_http_response(status_code=200)
limits = self.service_connection.get_account_limits()
self.assert_request_parameters({
'Action': 'DescribeAccountLimits',
}, ignore_params_values=['Version'])
self.assertEqual(limits.max_autoscaling_groups, 6)
self.assertEqual(limits.max_launch_configurations, 3)
class TestGetAdjustmentTypes(AWSMockServiceTestCase):
connection_class = AutoScaleConnection
def setUp(self):
super(TestGetAdjustmentTypes, self).setUp()
def default_body(self):
return b"""
<DescribeAdjustmentTypesResponse xmlns="http://autoscaling.amazonaws.com/doc/201-01-01/">
<DescribeAdjustmentTypesResult>
<AdjustmentTypes>
<member>
<AdjustmentType>ChangeInCapacity</AdjustmentType>
</member>
<member>
<AdjustmentType>ExactCapacity</AdjustmentType>
</member>
<member>
<AdjustmentType>PercentChangeInCapacity</AdjustmentType>
</member>
</AdjustmentTypes>
</DescribeAdjustmentTypesResult>
<ResponseMetadata>
<RequestId>requestId</RequestId>
</ResponseMetadata>
</DescribeAdjustmentTypesResponse>
"""
def test_autoscaling_adjustment_types(self):
self.set_http_response(status_code=200)
response = self.service_connection.get_all_adjustment_types()
self.assert_request_parameters({
'Action': 'DescribeAdjustmentTypes'
}, ignore_params_values=['Version'])
self.assertTrue(isinstance(response, list))
self.assertEqual(response[0].adjustment_type, "ChangeInCapacity")
self.assertEqual(response[1].adjustment_type, "ExactCapacity")
self.assertEqual(response[2].adjustment_type, "PercentChangeInCapacity")
class TestLaunchConfigurationDescribeWithBlockDeviceTypes(AWSMockServiceTestCase):
connection_class = AutoScaleConnection
def default_body(self):
# This is a dummy response
return b"""
<DescribeLaunchConfigurationsResponse>
<DescribeLaunchConfigurationsResult>
<LaunchConfigurations>
<member>
<AssociatePublicIpAddress>true</AssociatePublicIpAddress>
<SecurityGroups/>
<CreatedTime>2013-01-21T23:04:42.200Z</CreatedTime>
<KernelId/>
<LaunchConfigurationName>my-test-lc</LaunchConfigurationName>
<UserData/>
<InstanceType>m1.small</InstanceType>
<LaunchConfigurationARN>arn:aws:autoscaling:us-east-1:803981987763:launchConfiguration:9dbbbf87-6141-428a-a409-0752edbe6cad:launchConfigurationName/my-test-lc</LaunchConfigurationARN>
<BlockDeviceMappings>
<member>
<DeviceName>/dev/xvdp</DeviceName>
<Ebs>
<SnapshotId>snap-1234abcd</SnapshotId>
<Iops>1000</Iops>
<DeleteOnTermination>true</DeleteOnTermination>
<VolumeType>io1</VolumeType>
<VolumeSize>100</VolumeSize>
</Ebs>
</member>
<member>
<VirtualName>ephemeral1</VirtualName>
<DeviceName>/dev/xvdc</DeviceName>
</member>
<member>
<VirtualName>ephemeral0</VirtualName>
<DeviceName>/dev/xvdb</DeviceName>
</member>
<member>
<DeviceName>/dev/xvdh</DeviceName>
<Ebs>
<Iops>2000</Iops>
<DeleteOnTermination>false</DeleteOnTermination>
<VolumeType>io1</VolumeType>
<VolumeSize>200</VolumeSize>
</Ebs>
</member>
</BlockDeviceMappings>
<ImageId>ami-514ac838</ImageId>
<KeyName/>
<RamdiskId/>
<InstanceMonitoring>
<Enabled>true</Enabled>
</InstanceMonitoring>
<EbsOptimized>false</EbsOptimized>
</member>
</LaunchConfigurations>
</DescribeLaunchConfigurationsResult>
<ResponseMetadata>
<RequestId>d05a22f8-b690-11e2-bf8e-2113fEXAMPLE</RequestId>
</ResponseMetadata>
</DescribeLaunchConfigurationsResponse>
"""
def test_get_all_launch_configurations_with_block_device_types(self):
self.set_http_response(status_code=200)
self.service_connection.use_block_device_types = True
response = self.service_connection.get_all_launch_configurations()
self.assertTrue(isinstance(response, list))
self.assertEqual(len(response), 1)
self.assertTrue(isinstance(response[0], LaunchConfiguration))
self.assertEqual(response[0].associate_public_ip_address, True)
self.assertEqual(response[0].name, "my-test-lc")
self.assertEqual(response[0].instance_type, "m1.small")
self.assertEqual(response[0].launch_configuration_arn, "arn:aws:autoscaling:us-east-1:803981987763:launchConfiguration:9dbbbf87-6141-428a-a409-0752edbe6cad:launchConfigurationName/my-test-lc")
self.assertEqual(response[0].image_id, "ami-514ac838")
self.assertTrue(isinstance(response[0].instance_monitoring, launchconfig.InstanceMonitoring))
self.assertEqual(response[0].instance_monitoring.enabled, 'true')
self.assertEqual(response[0].ebs_optimized, False)
self.assertEqual(response[0].block_device_mappings['/dev/xvdb'].ephemeral_name, 'ephemeral0')
self.assertEqual(response[0].block_device_mappings['/dev/xvdc'].ephemeral_name, 'ephemeral1')
self.assertEqual(response[0].block_device_mappings['/dev/xvdp'].snapshot_id, 'snap-1234abcd')
self.assertEqual(response[0].block_device_mappings['/dev/xvdp'].delete_on_termination, True)
self.assertEqual(response[0].block_device_mappings['/dev/xvdp'].iops, 1000)
self.assertEqual(response[0].block_device_mappings['/dev/xvdp'].size, 100)
self.assertEqual(response[0].block_device_mappings['/dev/xvdp'].volume_type, 'io1')
self.assertEqual(response[0].block_device_mappings['/dev/xvdh'].delete_on_termination, False)
self.assertEqual(response[0].block_device_mappings['/dev/xvdh'].iops, 2000)
self.assertEqual(response[0].block_device_mappings['/dev/xvdh'].size, 200)
self.assertEqual(response[0].block_device_mappings['/dev/xvdh'].volume_type, 'io1')
self.assert_request_parameters({
'Action': 'DescribeLaunchConfigurations',
}, ignore_params_values=['Version'])
def test_get_all_configuration_limited(self):
self.set_http_response(status_code=200)
response = self.service_connection.get_all_launch_configurations(max_records=10, names=["my-test1", "my-test2"])
self.assert_request_parameters({
'Action': 'DescribeLaunchConfigurations',
'MaxRecords': 10,
'LaunchConfigurationNames.member.1': 'my-test1',
'LaunchConfigurationNames.member.2': 'my-test2'
}, ignore_params_values=['Version'])
if __name__ == '__main__':
unittest.main()
|
{
"pile_set_name": "Github"
}
|
#pragma once
#include "maths.h"
// fixed size grid with wrapping, supports point queries only
template <typename T, int NumBuckets>
class HashGrid
{
public:
HashGrid(float cellSize=1.0f) : m_cellSize(cellSize)
, m_rcpCellSize(1.0f / cellSize)
{
memset(m_data, 0, sizeof(m_data));
}
~HashGrid()
{
Clear();
}
void Insert(const Point3& pos, const T& val)
{
int idx = GetCell(pos);
Entry* p = new Entry;
p->pos = pos;
p->val = val;
p->next = m_data[idx];
m_data[idx] = p;
assert(GetValue(pos));
}
// will call the functor specified for every entry within the query bounds
template <typename Func>
void QuerySphere(const Point3& p, float r, Func& f)
{
// by requiring cell size to be greater than the largest query radius we only
// can limit our search to the closest 8 neighboring cells
assert(r < m_cellSize);
const int x = int(floorf(p.x * m_rcpCellSize));
const int y = int(floorf(p.y * m_rcpCellSize));
const int z = int(floorf(p.z * m_rcpCellSize));
const float radiusSq = r*r;
// search the current cell and all neighbors
for (int i=x-1; i <= x+1; ++i)
{
for (int j=y-1; j <= y+1; ++j)
{
for (int k=z-1; k <= z+1; ++k)
{
int idx = GetCell(i, j, k);
Entry* head = m_data[idx];
Entry** prev = &m_data[idx]; // will be updated in case an element is deleted
for (Entry* iter=head; iter;)
{
Entry* next = iter->next;
// finally, the sphere test
if (LengthSq(iter->pos-p) <= radiusSq)
{
// invoke the functor, return value allows erasing element
bool erase = f(iter->pos, iter->val);
if (erase)
{
// update previous nodes pointer
*prev = next;
delete iter;
}
else
{
prev = &iter->next;
}
}
else
{
prev = &iter->next;
}
iter = next;
}
}
}
}
}
// iterates over entries
void QueryAll(T& func)
{
for (int i=0; i < NumBuckets; ++i)
{
for (Entry* iter=m_data[i]; iter; iter=iter->next)
{
func(iter->pos, iter->val);
}
}
}
void Clear()
{
for (int i=0; i < NumBuckets; ++i)
{
for (Entry* iter=m_data[i]; iter;)
{
Entry* next = iter->next;
delete iter;
iter = next;
}
}
memset(m_data, 0, sizeof(m_data));
}
const T* GetValue(const Point3& p) const
{
const int idx = GetCell(p);
// iterator over entries looking for given position
for (Entry* iter=m_data[idx]; iter; iter=iter->next)
{
if (iter->pos == p)
{
return &iter->val;
}
}
return NULL;
}
int GetCell(const Point3& p) const
{
return GetCell((int)floorf(p.x*m_rcpCellSize), (int)floorf(p.y*m_rcpCellSize), (int)floorf(p.z*m_rcpCellSize));
}
int GetCell(int x, int y, int z) const
{
// from RTCD p288
const int32_t h1 = 0x8da6b343;
const int32_t h2 = 0xd8163841;
const int32_t h3 = 0xcb1ab31f;
int32_t n = h1 * x + h2 * y + h3 * z;
n %= NumBuckets;
if (n < 0)
n += NumBuckets;
return n;
}
int GetSize() const
{
int s=0;
for (int i=0; i < NumBuckets; ++i)
{
for (Entry* iter=m_data[i]; iter; iter=iter->next)
{
++s;
}
}
return s;
}
struct Entry
{
Point3 pos;
T val;
Entry* next;
};
float m_cellSize;
float m_rcpCellSize; // 1.0f / cellSize;
// array big enough for xdiv*ydiv*zdiv, each entry points to the head of each cell
Entry* m_data[NumBuckets];
};
/*
// fixed size grid with wrapping, supports point queries only
template <typename T, int NumBuckets>
class HashGrid2D
{
public:
HashGrid2D(float cellSize=1.0f) : m_cellSize(cellSize)
, m_rcpCellSize(1.0f / cellSize)
{
memset(m_data, 0, sizeof(m_data));
m_pool = malloc(sizeof(Entry)*MaxItems);
}
~HashGrid2D()
{
Clear();
free(m_pool);
}
void Insert(const Vec2& pos, const T& val)
{
int idx = GetCell(pos);
Entry* p = &m_pool[m_numItems++];
p->pos = pos;
p->val = val;
p->next = m_data[idx];
m_data[idx] = p;
assert(GetValue(pos));
}
// will call the functor specified for every entry within the query bounds
template <typename Func>
void QuerySphere(const Vec2& p, float r, Func& f)
{
// by requiring cell size to be greater than the largest query radius we only
// can limit our search to the closest 8 neighboring cells
assert(r < m_cellSize);
const int x = int(floorf(p.x * m_rcpCellSize));
const int y = int(floorf(p.y * m_rcpCellSize));
const float radiusSq = r*r;
// search the current cell and all neighbors
for (int i=x-1; i <= x+1; ++i)
{
for (int j=y-1; j <= y+1; ++j)
{
int idx = GetCell(i, j);
Entry* head = m_data[idx];
Entry** prev = &m_data[idx]; // will be updated in case an element is deleted
for (Entry* iter=head; iter;)
{
Entry* next = iter->next;
// finally, the sphere test
if (LengthSq(iter->pos-p) <= radiusSq)
{
// invoke the functor, return value allows erasing element
f(iter->pos, iter->val);
prev = &iter->next;
}
else
{
prev = &iter->next;
}
iter = next;
}
}
}
}
}
// iterates over entries
void QueryAll(T& func)
{
for (int i=0; i < NumBuckets; ++i)
{
for (Entry* iter=m_data[i]; iter; iter=iter->next)
{
func(iter->pos, iter->val);
}
}
}
void Clear()
{
m_numItems = 0;
memset(m_data, 0, sizeof(m_data));
}
const T* GetValue(const Vec2& p) const
{
const int idx = GetCell(p);
// iterator over entries looking for given position
for (Entry* iter=m_data[idx]; iter; iter=iter->next)
{
if (iter->pos == p)
{
return &iter->val;
}
}
return NULL;
}
int GetCell(const Vec2& p) const
{
return GetCell((int)floorf(p.x*m_rcpCellSize), (int)floorf(p.y*m_rcpCellSize));
}
int GetCell(int x, int y) const
{
// from RTCD p288
const int32_t h1 = 0x8da6b343;
const int32_t h2 = 0xd8163841;
int32_t n = h1 * x + h2 * y;
n %= NumBuckets;
if (n < 0)
n += NumBuckets;
return n;
}
int GetSize() const
{
return m_numItems;
}
struct Entry
{
Vec2 pos;
T val;
Entry* next;
};
float m_cellSize;
float m_rcpCellSize; // 1.0f / cellSize;
// array big enough for xdiv*ydiv*zdiv, each entry points to the head of each cell
Entry* m_data[NumBuckets];
Entry* m_pool[MaxItems];
uint32_t m_numItems;
};*/
|
{
"pile_set_name": "Github"
}
|
/* crypto/asn1/asn1_mac.h */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#ifndef HEADER_ASN1_MAC_H
#define HEADER_ASN1_MAC_H
#include <openssl/asn1.h>
#ifdef __cplusplus
extern "C" {
#endif
#ifndef ASN1_MAC_ERR_LIB
#define ASN1_MAC_ERR_LIB ERR_LIB_ASN1
#endif
#define ASN1_MAC_H_err(f,r,line) \
ERR_PUT_error(ASN1_MAC_ERR_LIB,(f),(r),__FILE__,(line))
#define M_ASN1_D2I_vars(a,type,func) \
ASN1_const_CTX c; \
type ret=NULL; \
\
c.pp=(const unsigned char **)pp; \
c.q= *(const unsigned char **)pp; \
c.error=ERR_R_NESTED_ASN1_ERROR; \
if ((a == NULL) || ((*a) == NULL)) \
{ if ((ret=(type)func()) == NULL) \
{ c.line=__LINE__; goto err; } } \
else ret=(*a);
#define M_ASN1_D2I_Init() \
c.p= *(const unsigned char **)pp; \
c.max=(length == 0)?0:(c.p+length);
#define M_ASN1_D2I_Finish_2(a) \
if (!asn1_const_Finish(&c)) \
{ c.line=__LINE__; goto err; } \
*(const unsigned char **)pp=c.p; \
if (a != NULL) (*a)=ret; \
return(ret);
#define M_ASN1_D2I_Finish(a,func,e) \
M_ASN1_D2I_Finish_2(a); \
err:\
ASN1_MAC_H_err((e),c.error,c.line); \
asn1_add_error(*(const unsigned char **)pp,(int)(c.q- *pp)); \
if ((ret != NULL) && ((a == NULL) || (*a != ret))) func(ret); \
return(NULL)
#define M_ASN1_D2I_start_sequence() \
if (!asn1_GetSequence(&c,&length)) \
{ c.line=__LINE__; goto err; }
/* Begin reading ASN1 without a surrounding sequence */
#define M_ASN1_D2I_begin() \
c.slen = length;
/* End reading ASN1 with no check on length */
#define M_ASN1_D2I_Finish_nolen(a, func, e) \
*pp=c.p; \
if (a != NULL) (*a)=ret; \
return(ret); \
err:\
ASN1_MAC_H_err((e),c.error,c.line); \
asn1_add_error(*pp,(int)(c.q- *pp)); \
if ((ret != NULL) && ((a == NULL) || (*a != ret))) func(ret); \
return(NULL)
#define M_ASN1_D2I_end_sequence() \
(((c.inf&1) == 0)?(c.slen <= 0): \
(c.eos=ASN1_const_check_infinite_end(&c.p,c.slen)))
/* Don't use this with d2i_ASN1_BOOLEAN() */
#define M_ASN1_D2I_get(b, func) \
c.q=c.p; \
if (func(&(b),&c.p,c.slen) == NULL) \
{c.line=__LINE__; goto err; } \
c.slen-=(c.p-c.q);
/* Don't use this with d2i_ASN1_BOOLEAN() */
#define M_ASN1_D2I_get_x(type,b,func) \
c.q=c.p; \
if (((D2I_OF(type))func)(&(b),&c.p,c.slen) == NULL) \
{c.line=__LINE__; goto err; } \
c.slen-=(c.p-c.q);
/* use this instead () */
#define M_ASN1_D2I_get_int(b,func) \
c.q=c.p; \
if (func(&(b),&c.p,c.slen) < 0) \
{c.line=__LINE__; goto err; } \
c.slen-=(c.p-c.q);
#define M_ASN1_D2I_get_opt(b,func,type) \
if ((c.slen != 0) && ((M_ASN1_next & (~V_ASN1_CONSTRUCTED)) \
== (V_ASN1_UNIVERSAL|(type)))) \
{ \
M_ASN1_D2I_get(b,func); \
}
#define M_ASN1_D2I_get_int_opt(b,func,type) \
if ((c.slen != 0) && ((M_ASN1_next & (~V_ASN1_CONSTRUCTED)) \
== (V_ASN1_UNIVERSAL|(type)))) \
{ \
M_ASN1_D2I_get_int(b,func); \
}
#define M_ASN1_D2I_get_imp(b,func, type) \
M_ASN1_next=(_tmp& V_ASN1_CONSTRUCTED)|type; \
c.q=c.p; \
if (func(&(b),&c.p,c.slen) == NULL) \
{c.line=__LINE__; M_ASN1_next_prev = _tmp; goto err; } \
c.slen-=(c.p-c.q);\
M_ASN1_next_prev=_tmp;
#define M_ASN1_D2I_get_IMP_opt(b,func,tag,type) \
if ((c.slen != 0) && ((M_ASN1_next & (~V_ASN1_CONSTRUCTED)) == \
(V_ASN1_CONTEXT_SPECIFIC|(tag)))) \
{ \
unsigned char _tmp = M_ASN1_next; \
M_ASN1_D2I_get_imp(b,func, type);\
}
#define M_ASN1_D2I_get_set(r,func,free_func) \
M_ASN1_D2I_get_imp_set(r,func,free_func, \
V_ASN1_SET,V_ASN1_UNIVERSAL);
#define M_ASN1_D2I_get_set_type(type,r,func,free_func) \
M_ASN1_D2I_get_imp_set_type(type,r,func,free_func, \
V_ASN1_SET,V_ASN1_UNIVERSAL);
#define M_ASN1_D2I_get_set_opt(r,func,free_func) \
if ((c.slen != 0) && (M_ASN1_next == (V_ASN1_UNIVERSAL| \
V_ASN1_CONSTRUCTED|V_ASN1_SET)))\
{ M_ASN1_D2I_get_set(r,func,free_func); }
#define M_ASN1_D2I_get_set_opt_type(type,r,func,free_func) \
if ((c.slen != 0) && (M_ASN1_next == (V_ASN1_UNIVERSAL| \
V_ASN1_CONSTRUCTED|V_ASN1_SET)))\
{ M_ASN1_D2I_get_set_type(type,r,func,free_func); }
#define M_ASN1_I2D_len_SET_opt(a,f) \
if ((a != NULL) && (sk_num(a) != 0)) \
M_ASN1_I2D_len_SET(a,f);
#define M_ASN1_I2D_put_SET_opt(a,f) \
if ((a != NULL) && (sk_num(a) != 0)) \
M_ASN1_I2D_put_SET(a,f);
#define M_ASN1_I2D_put_SEQUENCE_opt(a,f) \
if ((a != NULL) && (sk_num(a) != 0)) \
M_ASN1_I2D_put_SEQUENCE(a,f);
#define M_ASN1_I2D_put_SEQUENCE_opt_type(type,a,f) \
if ((a != NULL) && (sk_##type##_num(a) != 0)) \
M_ASN1_I2D_put_SEQUENCE_type(type,a,f);
#define M_ASN1_D2I_get_IMP_set_opt(b,func,free_func,tag) \
if ((c.slen != 0) && \
(M_ASN1_next == \
(V_ASN1_CONTEXT_SPECIFIC|V_ASN1_CONSTRUCTED|(tag))))\
{ \
M_ASN1_D2I_get_imp_set(b,func,free_func,\
tag,V_ASN1_CONTEXT_SPECIFIC); \
}
#define M_ASN1_D2I_get_IMP_set_opt_type(type,b,func,free_func,tag) \
if ((c.slen != 0) && \
(M_ASN1_next == \
(V_ASN1_CONTEXT_SPECIFIC|V_ASN1_CONSTRUCTED|(tag))))\
{ \
M_ASN1_D2I_get_imp_set_type(type,b,func,free_func,\
tag,V_ASN1_CONTEXT_SPECIFIC); \
}
#define M_ASN1_D2I_get_seq(r,func,free_func) \
M_ASN1_D2I_get_imp_set(r,func,free_func,\
V_ASN1_SEQUENCE,V_ASN1_UNIVERSAL);
#define M_ASN1_D2I_get_seq_type(type,r,func,free_func) \
M_ASN1_D2I_get_imp_set_type(type,r,func,free_func,\
V_ASN1_SEQUENCE,V_ASN1_UNIVERSAL)
#define M_ASN1_D2I_get_seq_opt(r,func,free_func) \
if ((c.slen != 0) && (M_ASN1_next == (V_ASN1_UNIVERSAL| \
V_ASN1_CONSTRUCTED|V_ASN1_SEQUENCE)))\
{ M_ASN1_D2I_get_seq(r,func,free_func); }
#define M_ASN1_D2I_get_seq_opt_type(type,r,func,free_func) \
if ((c.slen != 0) && (M_ASN1_next == (V_ASN1_UNIVERSAL| \
V_ASN1_CONSTRUCTED|V_ASN1_SEQUENCE)))\
{ M_ASN1_D2I_get_seq_type(type,r,func,free_func); }
#define M_ASN1_D2I_get_IMP_set(r,func,free_func,x) \
M_ASN1_D2I_get_imp_set(r,func,free_func,\
x,V_ASN1_CONTEXT_SPECIFIC);
#define M_ASN1_D2I_get_IMP_set_type(type,r,func,free_func,x) \
M_ASN1_D2I_get_imp_set_type(type,r,func,free_func,\
x,V_ASN1_CONTEXT_SPECIFIC);
#define M_ASN1_D2I_get_imp_set(r,func,free_func,a,b) \
c.q=c.p; \
if (d2i_ASN1_SET(&(r),&c.p,c.slen,(char *(*)())func,\
(void (*)())free_func,a,b) == NULL) \
{ c.line=__LINE__; goto err; } \
c.slen-=(c.p-c.q);
#define M_ASN1_D2I_get_imp_set_type(type,r,func,free_func,a,b) \
c.q=c.p; \
if (d2i_ASN1_SET_OF_##type(&(r),&c.p,c.slen,func,\
free_func,a,b) == NULL) \
{ c.line=__LINE__; goto err; } \
c.slen-=(c.p-c.q);
#define M_ASN1_D2I_get_set_strings(r,func,a,b) \
c.q=c.p; \
if (d2i_ASN1_STRING_SET(&(r),&c.p,c.slen,a,b) == NULL) \
{ c.line=__LINE__; goto err; } \
c.slen-=(c.p-c.q);
#define M_ASN1_D2I_get_EXP_opt(r,func,tag) \
if ((c.slen != 0L) && (M_ASN1_next == \
(V_ASN1_CONSTRUCTED|V_ASN1_CONTEXT_SPECIFIC|tag))) \
{ \
int Tinf,Ttag,Tclass; \
long Tlen; \
\
c.q=c.p; \
Tinf=ASN1_get_object(&c.p,&Tlen,&Ttag,&Tclass,c.slen); \
if (Tinf & 0x80) \
{ c.error=ERR_R_BAD_ASN1_OBJECT_HEADER; \
c.line=__LINE__; goto err; } \
if (Tinf == (V_ASN1_CONSTRUCTED+1)) \
Tlen = c.slen - (c.p - c.q) - 2; \
if (func(&(r),&c.p,Tlen) == NULL) \
{ c.line=__LINE__; goto err; } \
if (Tinf == (V_ASN1_CONSTRUCTED+1)) { \
Tlen = c.slen - (c.p - c.q); \
if(!ASN1_const_check_infinite_end(&c.p, Tlen)) \
{ c.error=ERR_R_MISSING_ASN1_EOS; \
c.line=__LINE__; goto err; } \
}\
c.slen-=(c.p-c.q); \
}
#define M_ASN1_D2I_get_EXP_set_opt(r,func,free_func,tag,b) \
if ((c.slen != 0) && (M_ASN1_next == \
(V_ASN1_CONSTRUCTED|V_ASN1_CONTEXT_SPECIFIC|tag))) \
{ \
int Tinf,Ttag,Tclass; \
long Tlen; \
\
c.q=c.p; \
Tinf=ASN1_get_object(&c.p,&Tlen,&Ttag,&Tclass,c.slen); \
if (Tinf & 0x80) \
{ c.error=ERR_R_BAD_ASN1_OBJECT_HEADER; \
c.line=__LINE__; goto err; } \
if (Tinf == (V_ASN1_CONSTRUCTED+1)) \
Tlen = c.slen - (c.p - c.q) - 2; \
if (d2i_ASN1_SET(&(r),&c.p,Tlen,(char *(*)())func, \
(void (*)())free_func, \
b,V_ASN1_UNIVERSAL) == NULL) \
{ c.line=__LINE__; goto err; } \
if (Tinf == (V_ASN1_CONSTRUCTED+1)) { \
Tlen = c.slen - (c.p - c.q); \
if(!ASN1_check_infinite_end(&c.p, Tlen)) \
{ c.error=ERR_R_MISSING_ASN1_EOS; \
c.line=__LINE__; goto err; } \
}\
c.slen-=(c.p-c.q); \
}
#define M_ASN1_D2I_get_EXP_set_opt_type(type,r,func,free_func,tag,b) \
if ((c.slen != 0) && (M_ASN1_next == \
(V_ASN1_CONSTRUCTED|V_ASN1_CONTEXT_SPECIFIC|tag))) \
{ \
int Tinf,Ttag,Tclass; \
long Tlen; \
\
c.q=c.p; \
Tinf=ASN1_get_object(&c.p,&Tlen,&Ttag,&Tclass,c.slen); \
if (Tinf & 0x80) \
{ c.error=ERR_R_BAD_ASN1_OBJECT_HEADER; \
c.line=__LINE__; goto err; } \
if (Tinf == (V_ASN1_CONSTRUCTED+1)) \
Tlen = c.slen - (c.p - c.q) - 2; \
if (d2i_ASN1_SET_OF_##type(&(r),&c.p,Tlen,func, \
free_func,b,V_ASN1_UNIVERSAL) == NULL) \
{ c.line=__LINE__; goto err; } \
if (Tinf == (V_ASN1_CONSTRUCTED+1)) { \
Tlen = c.slen - (c.p - c.q); \
if(!ASN1_check_infinite_end(&c.p, Tlen)) \
{ c.error=ERR_R_MISSING_ASN1_EOS; \
c.line=__LINE__; goto err; } \
}\
c.slen-=(c.p-c.q); \
}
/* New macros */
#define M_ASN1_New_Malloc(ret,type) \
if ((ret=(type *)OPENSSL_malloc(sizeof(type))) == NULL) \
{ c.line=__LINE__; goto err2; }
#define M_ASN1_New(arg,func) \
if (((arg)=func()) == NULL) return(NULL)
#define M_ASN1_New_Error(a) \
/* err: ASN1_MAC_H_err((a),ERR_R_NESTED_ASN1_ERROR,c.line); \
return(NULL);*/ \
err2: ASN1_MAC_H_err((a),ERR_R_MALLOC_FAILURE,c.line); \
return(NULL)
/* BIG UGLY WARNING! This is so damn ugly I wanna puke. Unfortunately,
some macros that use ASN1_const_CTX still insist on writing in the input
stream. ARGH! ARGH! ARGH! Let's get rid of this macro package.
Please? -- Richard Levitte */
#define M_ASN1_next (*((unsigned char *)(c.p)))
#define M_ASN1_next_prev (*((unsigned char *)(c.q)))
/*************************************************/
#define M_ASN1_I2D_vars(a) int r=0,ret=0; \
unsigned char *p; \
if (a == NULL) return(0)
/* Length Macros */
#define M_ASN1_I2D_len(a,f) ret+=f(a,NULL)
#define M_ASN1_I2D_len_IMP_opt(a,f) if (a != NULL) M_ASN1_I2D_len(a,f)
#define M_ASN1_I2D_len_SET(a,f) \
ret+=i2d_ASN1_SET(a,NULL,f,V_ASN1_SET,V_ASN1_UNIVERSAL,IS_SET);
#define M_ASN1_I2D_len_SET_type(type,a,f) \
ret+=i2d_ASN1_SET_OF_##type(a,NULL,f,V_ASN1_SET, \
V_ASN1_UNIVERSAL,IS_SET);
#define M_ASN1_I2D_len_SEQUENCE(a,f) \
ret+=i2d_ASN1_SET(a,NULL,f,V_ASN1_SEQUENCE,V_ASN1_UNIVERSAL, \
IS_SEQUENCE);
#define M_ASN1_I2D_len_SEQUENCE_type(type,a,f) \
ret+=i2d_ASN1_SET_OF_##type(a,NULL,f,V_ASN1_SEQUENCE, \
V_ASN1_UNIVERSAL,IS_SEQUENCE)
#define M_ASN1_I2D_len_SEQUENCE_opt(a,f) \
if ((a != NULL) && (sk_num(a) != 0)) \
M_ASN1_I2D_len_SEQUENCE(a,f);
#define M_ASN1_I2D_len_SEQUENCE_opt_type(type,a,f) \
if ((a != NULL) && (sk_##type##_num(a) != 0)) \
M_ASN1_I2D_len_SEQUENCE_type(type,a,f);
#define M_ASN1_I2D_len_IMP_SET(a,f,x) \
ret+=i2d_ASN1_SET(a,NULL,f,x,V_ASN1_CONTEXT_SPECIFIC,IS_SET);
#define M_ASN1_I2D_len_IMP_SET_type(type,a,f,x) \
ret+=i2d_ASN1_SET_OF_##type(a,NULL,f,x, \
V_ASN1_CONTEXT_SPECIFIC,IS_SET);
#define M_ASN1_I2D_len_IMP_SET_opt(a,f,x) \
if ((a != NULL) && (sk_num(a) != 0)) \
ret+=i2d_ASN1_SET(a,NULL,f,x,V_ASN1_CONTEXT_SPECIFIC, \
IS_SET);
#define M_ASN1_I2D_len_IMP_SET_opt_type(type,a,f,x) \
if ((a != NULL) && (sk_##type##_num(a) != 0)) \
ret+=i2d_ASN1_SET_OF_##type(a,NULL,f,x, \
V_ASN1_CONTEXT_SPECIFIC,IS_SET);
#define M_ASN1_I2D_len_IMP_SEQUENCE(a,f,x) \
ret+=i2d_ASN1_SET(a,NULL,f,x,V_ASN1_CONTEXT_SPECIFIC, \
IS_SEQUENCE);
#define M_ASN1_I2D_len_IMP_SEQUENCE_opt(a,f,x) \
if ((a != NULL) && (sk_num(a) != 0)) \
ret+=i2d_ASN1_SET(a,NULL,f,x,V_ASN1_CONTEXT_SPECIFIC, \
IS_SEQUENCE);
#define M_ASN1_I2D_len_IMP_SEQUENCE_opt_type(type,a,f,x) \
if ((a != NULL) && (sk_##type##_num(a) != 0)) \
ret+=i2d_ASN1_SET_OF_##type(a,NULL,f,x, \
V_ASN1_CONTEXT_SPECIFIC, \
IS_SEQUENCE);
#define M_ASN1_I2D_len_EXP_opt(a,f,mtag,v) \
if (a != NULL)\
{ \
v=f(a,NULL); \
ret+=ASN1_object_size(1,v,mtag); \
}
#define M_ASN1_I2D_len_EXP_SET_opt(a,f,mtag,tag,v) \
if ((a != NULL) && (sk_num(a) != 0))\
{ \
v=i2d_ASN1_SET(a,NULL,f,tag,V_ASN1_UNIVERSAL,IS_SET); \
ret+=ASN1_object_size(1,v,mtag); \
}
#define M_ASN1_I2D_len_EXP_SEQUENCE_opt(a,f,mtag,tag,v) \
if ((a != NULL) && (sk_num(a) != 0))\
{ \
v=i2d_ASN1_SET(a,NULL,f,tag,V_ASN1_UNIVERSAL, \
IS_SEQUENCE); \
ret+=ASN1_object_size(1,v,mtag); \
}
#define M_ASN1_I2D_len_EXP_SEQUENCE_opt_type(type,a,f,mtag,tag,v) \
if ((a != NULL) && (sk_##type##_num(a) != 0))\
{ \
v=i2d_ASN1_SET_OF_##type(a,NULL,f,tag, \
V_ASN1_UNIVERSAL, \
IS_SEQUENCE); \
ret+=ASN1_object_size(1,v,mtag); \
}
/* Put Macros */
#define M_ASN1_I2D_put(a,f) f(a,&p)
#define M_ASN1_I2D_put_IMP_opt(a,f,t) \
if (a != NULL) \
{ \
unsigned char *q=p; \
f(a,&p); \
*q=(V_ASN1_CONTEXT_SPECIFIC|t|(*q&V_ASN1_CONSTRUCTED));\
}
#define M_ASN1_I2D_put_SET(a,f) i2d_ASN1_SET(a,&p,f,V_ASN1_SET,\
V_ASN1_UNIVERSAL,IS_SET)
#define M_ASN1_I2D_put_SET_type(type,a,f) \
i2d_ASN1_SET_OF_##type(a,&p,f,V_ASN1_SET,V_ASN1_UNIVERSAL,IS_SET)
#define M_ASN1_I2D_put_IMP_SET(a,f,x) i2d_ASN1_SET(a,&p,f,x,\
V_ASN1_CONTEXT_SPECIFIC,IS_SET)
#define M_ASN1_I2D_put_IMP_SET_type(type,a,f,x) \
i2d_ASN1_SET_OF_##type(a,&p,f,x,V_ASN1_CONTEXT_SPECIFIC,IS_SET)
#define M_ASN1_I2D_put_IMP_SEQUENCE(a,f,x) i2d_ASN1_SET(a,&p,f,x,\
V_ASN1_CONTEXT_SPECIFIC,IS_SEQUENCE)
#define M_ASN1_I2D_put_SEQUENCE(a,f) i2d_ASN1_SET(a,&p,f,V_ASN1_SEQUENCE,\
V_ASN1_UNIVERSAL,IS_SEQUENCE)
#define M_ASN1_I2D_put_SEQUENCE_type(type,a,f) \
i2d_ASN1_SET_OF_##type(a,&p,f,V_ASN1_SEQUENCE,V_ASN1_UNIVERSAL, \
IS_SEQUENCE)
#define M_ASN1_I2D_put_SEQUENCE_opt(a,f) \
if ((a != NULL) && (sk_num(a) != 0)) \
M_ASN1_I2D_put_SEQUENCE(a,f);
#define M_ASN1_I2D_put_IMP_SET_opt(a,f,x) \
if ((a != NULL) && (sk_num(a) != 0)) \
{ i2d_ASN1_SET(a,&p,f,x,V_ASN1_CONTEXT_SPECIFIC, \
IS_SET); }
#define M_ASN1_I2D_put_IMP_SET_opt_type(type,a,f,x) \
if ((a != NULL) && (sk_##type##_num(a) != 0)) \
{ i2d_ASN1_SET_OF_##type(a,&p,f,x, \
V_ASN1_CONTEXT_SPECIFIC, \
IS_SET); }
#define M_ASN1_I2D_put_IMP_SEQUENCE_opt(a,f,x) \
if ((a != NULL) && (sk_num(a) != 0)) \
{ i2d_ASN1_SET(a,&p,f,x,V_ASN1_CONTEXT_SPECIFIC, \
IS_SEQUENCE); }
#define M_ASN1_I2D_put_IMP_SEQUENCE_opt_type(type,a,f,x) \
if ((a != NULL) && (sk_##type##_num(a) != 0)) \
{ i2d_ASN1_SET_OF_##type(a,&p,f,x, \
V_ASN1_CONTEXT_SPECIFIC, \
IS_SEQUENCE); }
#define M_ASN1_I2D_put_EXP_opt(a,f,tag,v) \
if (a != NULL) \
{ \
ASN1_put_object(&p,1,v,tag,V_ASN1_CONTEXT_SPECIFIC); \
f(a,&p); \
}
#define M_ASN1_I2D_put_EXP_SET_opt(a,f,mtag,tag,v) \
if ((a != NULL) && (sk_num(a) != 0)) \
{ \
ASN1_put_object(&p,1,v,mtag,V_ASN1_CONTEXT_SPECIFIC); \
i2d_ASN1_SET(a,&p,f,tag,V_ASN1_UNIVERSAL,IS_SET); \
}
#define M_ASN1_I2D_put_EXP_SEQUENCE_opt(a,f,mtag,tag,v) \
if ((a != NULL) && (sk_num(a) != 0)) \
{ \
ASN1_put_object(&p,1,v,mtag,V_ASN1_CONTEXT_SPECIFIC); \
i2d_ASN1_SET(a,&p,f,tag,V_ASN1_UNIVERSAL,IS_SEQUENCE); \
}
#define M_ASN1_I2D_put_EXP_SEQUENCE_opt_type(type,a,f,mtag,tag,v) \
if ((a != NULL) && (sk_##type##_num(a) != 0)) \
{ \
ASN1_put_object(&p,1,v,mtag,V_ASN1_CONTEXT_SPECIFIC); \
i2d_ASN1_SET_OF_##type(a,&p,f,tag,V_ASN1_UNIVERSAL, \
IS_SEQUENCE); \
}
#define M_ASN1_I2D_seq_total() \
r=ASN1_object_size(1,ret,V_ASN1_SEQUENCE); \
if (pp == NULL) return(r); \
p= *pp; \
ASN1_put_object(&p,1,ret,V_ASN1_SEQUENCE,V_ASN1_UNIVERSAL)
#define M_ASN1_I2D_INF_seq_start(tag,ctx) \
*(p++)=(V_ASN1_CONSTRUCTED|(tag)|(ctx)); \
*(p++)=0x80
#define M_ASN1_I2D_INF_seq_end() *(p++)=0x00; *(p++)=0x00
#define M_ASN1_I2D_finish() *pp=p; \
return(r);
int asn1_GetSequence(ASN1_const_CTX *c, long *length);
void asn1_add_error(const unsigned char *address,int offset);
#ifdef __cplusplus
}
#endif
#endif
|
{
"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.
from aliyunsdkcore.request import RpcRequest
from aliyunsdkvod.endpoint import endpoint_data
class GetUploadDetailsRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'vod', '2017-03-21', 'GetUploadDetails','vod')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regional"):
setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional())
def get_ResourceOwnerId(self):
return self.get_query_params().get('ResourceOwnerId')
def set_ResourceOwnerId(self,ResourceOwnerId):
self.add_query_param('ResourceOwnerId',ResourceOwnerId)
def get_ResourceRealOwnerId(self):
return self.get_query_params().get('ResourceRealOwnerId')
def set_ResourceRealOwnerId(self,ResourceRealOwnerId):
self.add_query_param('ResourceRealOwnerId',ResourceRealOwnerId)
def get_MediaIds(self):
return self.get_query_params().get('MediaIds')
def set_MediaIds(self,MediaIds):
self.add_query_param('MediaIds',MediaIds)
def get_ResourceOwnerAccount(self):
return self.get_query_params().get('ResourceOwnerAccount')
def set_ResourceOwnerAccount(self,ResourceOwnerAccount):
self.add_query_param('ResourceOwnerAccount',ResourceOwnerAccount)
def get_OwnerId(self):
return self.get_query_params().get('OwnerId')
def set_OwnerId(self,OwnerId):
self.add_query_param('OwnerId',OwnerId)
def get_MediaType(self):
return self.get_query_params().get('MediaType')
def set_MediaType(self,MediaType):
self.add_query_param('MediaType',MediaType)
|
{
"pile_set_name": "Github"
}
|
#
# USB peripheral controller drivers
#
obj-$(CONFIG_USB_GADGET) += udc-core.o
obj-$(CONFIG_USB_DUMMY_HCD) += dummy_hcd.o
obj-$(CONFIG_USB_NET2272) += net2272.o
obj-$(CONFIG_USB_NET2280) += net2280.o
obj-$(CONFIG_USB_AMD5536UDC) += amd5536udc.o
obj-$(CONFIG_USB_PXA25X) += pxa25x_udc.o
obj-$(CONFIG_USB_PXA27X) += pxa27x_udc.o
obj-$(CONFIG_USB_GOKU) += goku_udc.o
obj-$(CONFIG_USB_OMAP) += omap_udc.o
obj-$(CONFIG_USB_S3C2410) += s3c2410_udc.o
obj-$(CONFIG_USB_AT91) += at91_udc.o
obj-$(CONFIG_USB_ATMEL_USBA) += atmel_usba_udc.o
obj-$(CONFIG_USB_BCM63XX_UDC) += bcm63xx_udc.o
obj-$(CONFIG_USB_FSL_USB2) += fsl_usb2_udc.o
fsl_usb2_udc-y := fsl_udc_core.o
fsl_usb2_udc-$(CONFIG_ARCH_MXC) += fsl_mxc_udc.o
obj-$(CONFIG_USB_M66592) += m66592-udc.o
obj-$(CONFIG_USB_R8A66597) += r8a66597-udc.o
obj-$(CONFIG_USB_FSL_QE) += fsl_qe_udc.o
obj-$(CONFIG_USB_S3C_HSUDC) += s3c-hsudc.o
obj-$(CONFIG_USB_LPC32XX) += lpc32xx_udc.o
obj-$(CONFIG_USB_EG20T) += pch_udc.o
obj-$(CONFIG_USB_MV_UDC) += mv_udc.o
mv_udc-y := mv_udc_core.o
obj-$(CONFIG_USB_FUSB300) += fusb300_udc.o
obj-$(CONFIG_USB_FOTG210_UDC) += fotg210-udc.o
obj-$(CONFIG_USB_MV_U3D) += mv_u3d_core.o
obj-$(CONFIG_USB_GR_UDC) += gr_udc.o
obj-$(CONFIG_USB_GADGET_XILINX) += udc-xilinx.o
obj-$(CONFIG_USB_BDC_UDC) += bdc/
|
{
"pile_set_name": "Github"
}
|
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include "AddNote.hpp"
#include <Midi/MidiProcess.hpp>
#include <Process/TimeValueSerialization.hpp>
#include <score/model/path/PathSerialization.hpp>
#include <score/tools/IdentifierGeneration.hpp>
namespace Midi
{
AddNote::AddNote(const ProcessModel& model, const NoteData& n)
: m_model{model}, m_id{getStrongId(model.notes)}, m_note{n}
{
}
void AddNote::undo(const score::DocumentContext& ctx) const
{
m_model.find(ctx).notes.remove(m_id);
}
void AddNote::redo(const score::DocumentContext& ctx) const
{
auto& model = m_model.find(ctx);
model.notes.add(new Note{m_id, m_note, &model});
}
void AddNote::serializeImpl(DataStreamInput& s) const
{
s << m_model << m_id << m_note;
}
void AddNote::deserializeImpl(DataStreamOutput& s)
{
s >> m_model >> m_id >> m_note;
}
ReplaceNotes::ReplaceNotes(
const ProcessModel& model,
const std::vector<NoteData>& n,
int min,
int max,
TimeVal d)
: m_model{model}
, m_oldmin{model.range().first}
, m_oldmax{model.range().second}
, m_newmin{min}
, m_newmax{max}
, m_olddur{model.duration()}
, m_newdur{d}
{
for (Note& note : model.notes)
{
m_old.push_back({note.id(), note.noteData()});
}
int i = 0;
for (auto& note : n)
m_new.push_back({Id<Midi::Note>{i++}, note});
}
void ReplaceNotes::undo(const score::DocumentContext& ctx) const
{
auto& model = m_model.find(ctx);
model.notes.clear();
model.setDuration(m_olddur);
for (auto& note : m_old)
model.notes.add(new Note{note.first, note.second, &model});
model.setRange(m_oldmin, m_oldmax);
}
void ReplaceNotes::redo(const score::DocumentContext& ctx) const
{
auto& model = m_model.find(ctx);
model.notes.clear();
model.setDuration(m_newdur);
for (auto& note : m_new)
model.notes.add(new Note{note.first, note.second, &model});
model.setRange(m_newmin, m_newmax);
}
void ReplaceNotes::serializeImpl(DataStreamInput& s) const
{
s << m_model << m_old << m_new << m_oldmin << m_oldmax << m_newmin << m_newmax << m_olddur
<< m_newdur;
}
void ReplaceNotes::deserializeImpl(DataStreamOutput& s)
{
s >> m_model >> m_old >> m_new >> m_oldmin >> m_oldmax >> m_newmin >> m_newmax >> m_olddur
>> m_newdur;
}
}
|
{
"pile_set_name": "Github"
}
|
org.wildfly.extension.microprofile.jwt.smallrye.MicroProfileJWTExtension
|
{
"pile_set_name": "Github"
}
|
{
"AssemblyIdentity": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60",
"Types": [
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.AssemblyAttributeGenerator",
"Visibility": "Public",
"Kind": "Class",
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "assembly",
"Type": "System.Reflection.Assembly"
}
],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.ClassNameModel",
"Visibility": "Public",
"Kind": "Class",
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "get_ClassName",
"Parameters": [],
"ReturnType": "System.String",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_ClassName",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_NamespaceName",
"Parameters": [],
"ReturnType": "System.String",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_NamespaceName",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "fullTypeName",
"Type": "System.String"
}
],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.CodeModelMetadata",
"Visibility": "Public",
"Kind": "Class",
"ImplementedInterfaces": [
"Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IModelMetadata"
],
"Members": [
{
"Kind": "Method",
"Name": "get_ModelType",
"Parameters": [],
"ReturnType": "System.Type",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IModelMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_Navigations",
"Parameters": [],
"ReturnType": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata[]",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IModelMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_PrimaryKeys",
"Parameters": [],
"ReturnType": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata[]",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IModelMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_Properties",
"Parameters": [],
"ReturnType": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata[]",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IModelMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "model",
"Type": "System.Type"
}
],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.CodeModelService",
"Visibility": "Public",
"Kind": "Class",
"ImplementedInterfaces": [
"Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.ICodeModelService"
],
"Members": [
{
"Kind": "Method",
"Name": "GetModelMetadata",
"Parameters": [
{
"Name": "modelType",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.ModelType"
}
],
"ReturnType": "System.Threading.Tasks.Task<Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.ContextProcessingResult>",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.ICodeModelService",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "context",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.Contracts.ProjectModel.IProjectContext"
},
{
"Name": "workspace",
"Type": "Microsoft.CodeAnalysis.Workspace"
},
{
"Name": "logger",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.ILogger"
},
{
"Name": "loader",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.DotNet.ICodeGenAssemblyLoadContext"
}
],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.ConnectionStringsWriter",
"Visibility": "Public",
"Kind": "Class",
"ImplementedInterfaces": [
"Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IConnectionStringsWriter"
],
"Members": [
{
"Kind": "Method",
"Name": "AddConnectionString",
"Parameters": [
{
"Name": "connectionStringName",
"Type": "System.String"
},
{
"Name": "dataBaseName",
"Type": "System.String"
},
{
"Name": "useSQLite",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IConnectionStringsWriter",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "applicationInfo",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.DotNet.IApplicationInfo"
}
],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.ContextProcessingResult",
"Visibility": "Public",
"Kind": "Class",
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "get_ContextProcessingStatus",
"Parameters": [],
"ReturnType": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.ContextProcessingStatus",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_ContextProcessingStatus",
"Parameters": [
{
"Name": "value",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.ContextProcessingStatus"
}
],
"ReturnType": "System.Void",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_ModelMetadata",
"Parameters": [],
"ReturnType": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IModelMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_ModelMetadata",
"Parameters": [
{
"Name": "value",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IModelMetadata"
}
],
"ReturnType": "System.Void",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.ContextProcessingStatus",
"Visibility": "Public",
"Kind": "Enumeration",
"Sealed": true,
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Field",
"Name": "ContextAvailable",
"Parameters": [],
"GenericParameter": [],
"Literal": "1"
},
{
"Kind": "Field",
"Name": "ContextAdded",
"Parameters": [],
"GenericParameter": [],
"Literal": "2"
},
{
"Kind": "Field",
"Name": "ContextAddedButRequiresConfig",
"Parameters": [],
"GenericParameter": [],
"Literal": "3"
},
{
"Kind": "Field",
"Name": "ContextEdited",
"Parameters": [],
"GenericParameter": [],
"Literal": "4"
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.DbContextEditorServices",
"Visibility": "Public",
"Kind": "Class",
"ImplementedInterfaces": [
"Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IDbContextEditorServices"
],
"Members": [
{
"Kind": "Method",
"Name": "AddNewContext",
"Parameters": [
{
"Name": "dbContextTemplateModel",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.NewDbContextTemplateModel"
}
],
"ReturnType": "System.Threading.Tasks.Task<Microsoft.CodeAnalysis.SyntaxTree>",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IDbContextEditorServices",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "AddModelToContext",
"Parameters": [
{
"Name": "dbContext",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.ModelType"
},
{
"Name": "modelType",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.ModelType"
}
],
"ReturnType": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.EditSyntaxTreeResult",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IDbContextEditorServices",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "EditStartupForNewContext",
"Parameters": [
{
"Name": "startUp",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.ModelType"
},
{
"Name": "dbContextTypeName",
"Type": "System.String"
},
{
"Name": "dbContextNamespace",
"Type": "System.String"
},
{
"Name": "dataBaseName",
"Type": "System.String"
}
],
"ReturnType": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.EditSyntaxTreeResult",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IDbContextEditorServices",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "projectContext",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.Contracts.ProjectModel.IProjectContext"
},
{
"Name": "applicationInfo",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.DotNet.IApplicationInfo"
},
{
"Name": "filesLocator",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.IFilesLocator"
},
{
"Name": "templatingService",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.Templating.ITemplating"
},
{
"Name": "connectionStringsWriter",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IConnectionStringsWriter"
}
],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.EditSyntaxTreeResult",
"Visibility": "Public",
"Kind": "Class",
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "get_Edited",
"Parameters": [],
"ReturnType": "System.Boolean",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_Edited",
"Parameters": [
{
"Name": "value",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_OldTree",
"Parameters": [],
"ReturnType": "Microsoft.CodeAnalysis.SyntaxTree",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_OldTree",
"Parameters": [
{
"Name": "value",
"Type": "Microsoft.CodeAnalysis.SyntaxTree"
}
],
"ReturnType": "System.Void",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_NewTree",
"Parameters": [],
"ReturnType": "Microsoft.CodeAnalysis.SyntaxTree",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_NewTree",
"Parameters": [
{
"Name": "value",
"Type": "Microsoft.CodeAnalysis.SyntaxTree"
}
],
"ReturnType": "System.Void",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.EntityFrameworkServices",
"Visibility": "Public",
"Kind": "Class",
"ImplementedInterfaces": [
"Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IEntityFrameworkService"
],
"Members": [
{
"Kind": "Method",
"Name": "GetModelMetadata",
"Parameters": [
{
"Name": "dbContextFullTypeName",
"Type": "System.String"
},
{
"Name": "modelTypeSymbol",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.ModelType"
},
{
"Name": "areaName",
"Type": "System.String"
}
],
"ReturnType": "System.Threading.Tasks.Task<Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.ContextProcessingResult>",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IEntityFrameworkService",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "projectContext",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.Contracts.ProjectModel.IProjectContext"
},
{
"Name": "applicationInfo",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.DotNet.IApplicationInfo"
},
{
"Name": "loader",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.DotNet.ICodeGenAssemblyLoadContext"
},
{
"Name": "modelTypesLocator",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.IModelTypesLocator"
},
{
"Name": "dbContextEditorServices",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IDbContextEditorServices"
},
{
"Name": "packageInstaller",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.IPackageInstaller"
},
{
"Name": "serviceProvider",
"Type": "System.IServiceProvider"
},
{
"Name": "workspace",
"Type": "Microsoft.CodeAnalysis.Workspace"
},
{
"Name": "fileSystem",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.IFileSystem"
},
{
"Name": "logger",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.ILogger"
}
],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.ICodeModelService",
"Visibility": "Public",
"Kind": "Interface",
"Abstract": true,
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "GetModelMetadata",
"Parameters": [
{
"Name": "modelType",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.ModelType"
}
],
"ReturnType": "System.Threading.Tasks.Task<Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.ContextProcessingResult>",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IConnectionStringsWriter",
"Visibility": "Public",
"Kind": "Interface",
"Abstract": true,
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "AddConnectionString",
"Parameters": [
{
"Name": "connectionStringName",
"Type": "System.String"
},
{
"Name": "dataBaseName",
"Type": "System.String"
},
{
"Name": "useSQLite",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IDbContextEditorServices",
"Visibility": "Public",
"Kind": "Interface",
"Abstract": true,
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "AddNewContext",
"Parameters": [
{
"Name": "dbContextTemplateModel",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.NewDbContextTemplateModel"
}
],
"ReturnType": "System.Threading.Tasks.Task<Microsoft.CodeAnalysis.SyntaxTree>",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "AddModelToContext",
"Parameters": [
{
"Name": "dbContext",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.ModelType"
},
{
"Name": "modelType",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.ModelType"
}
],
"ReturnType": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.EditSyntaxTreeResult",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "EditStartupForNewContext",
"Parameters": [
{
"Name": "startup",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.ModelType"
},
{
"Name": "dbContextTypeName",
"Type": "System.String"
},
{
"Name": "dbContextNamespace",
"Type": "System.String"
},
{
"Name": "dataBaseName",
"Type": "System.String"
}
],
"ReturnType": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.EditSyntaxTreeResult",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IEntityFrameworkService",
"Visibility": "Public",
"Kind": "Interface",
"Abstract": true,
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "GetModelMetadata",
"Parameters": [
{
"Name": "dbContextFullTypeName",
"Type": "System.String"
},
{
"Name": "modelTypeName",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.ModelType"
},
{
"Name": "areaName",
"Type": "System.String"
}
],
"ReturnType": "System.Threading.Tasks.Task<Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.ContextProcessingResult>",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IModelMetadata",
"Visibility": "Public",
"Kind": "Interface",
"Abstract": true,
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "get_Properties",
"Parameters": [],
"ReturnType": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata[]",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_PrimaryKeys",
"Parameters": [],
"ReturnType": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata[]",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_Navigations",
"Parameters": [],
"ReturnType": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata[]",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_ModelType",
"Parameters": [],
"ReturnType": "System.Type",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata",
"Visibility": "Public",
"Kind": "Interface",
"Abstract": true,
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "get_AssociationPropertyName",
"Parameters": [],
"ReturnType": "System.String",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_AssociationPropertyName",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_DisplayPropertyName",
"Parameters": [],
"ReturnType": "System.String",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_DisplayPropertyName",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_EntitySetName",
"Parameters": [],
"ReturnType": "System.String",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_EntitySetName",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_ForeignKeyPropertyNames",
"Parameters": [],
"ReturnType": "System.String[]",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_ForeignKeyPropertyNames",
"Parameters": [
{
"Name": "value",
"Type": "System.String[]"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_PrimaryKeyNames",
"Parameters": [],
"ReturnType": "System.String[]",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_PrimaryKeyNames",
"Parameters": [
{
"Name": "value",
"Type": "System.String[]"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_ShortTypeName",
"Parameters": [],
"ReturnType": "System.String",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_ShortTypeName",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_TypeName",
"Parameters": [],
"ReturnType": "System.String",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_TypeName",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"Kind": "Interface",
"Abstract": true,
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "get_IsAutoGenerated",
"Parameters": [],
"ReturnType": "System.Boolean",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_IsAutoGenerated",
"Parameters": [
{
"Name": "value",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_IsEnum",
"Parameters": [],
"ReturnType": "System.Boolean",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_IsEnum",
"Parameters": [
{
"Name": "value",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_IsEnumFlags",
"Parameters": [],
"ReturnType": "System.Boolean",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_IsEnumFlags",
"Parameters": [
{
"Name": "value",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_IsForeignKey",
"Parameters": [],
"ReturnType": "System.Boolean",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_IsForeignKey",
"Parameters": [
{
"Name": "value",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_IsPrimaryKey",
"Parameters": [],
"ReturnType": "System.Boolean",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_IsPrimaryKey",
"Parameters": [
{
"Name": "value",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_IsReadOnly",
"Parameters": [],
"ReturnType": "System.Boolean",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_IsReadOnly",
"Parameters": [
{
"Name": "value",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_PropertyName",
"Parameters": [],
"ReturnType": "System.String",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_PropertyName",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_Scaffold",
"Parameters": [],
"ReturnType": "System.Boolean",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_Scaffold",
"Parameters": [
{
"Name": "value",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_ShortTypeName",
"Parameters": [],
"ReturnType": "System.String",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_ShortTypeName",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_TypeName",
"Parameters": [],
"ReturnType": "System.String",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_TypeName",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_IsMultilineText",
"Parameters": [],
"ReturnType": "System.Boolean",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_IsMultilineText",
"Parameters": [
{
"Name": "value",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_PropertyInfo",
"Parameters": [],
"ReturnType": "System.Reflection.PropertyInfo",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_PropertyInfo",
"Parameters": [
{
"Name": "value",
"Type": "System.Reflection.PropertyInfo"
}
],
"ReturnType": "System.Void",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.ModelMetadata",
"Visibility": "Public",
"Kind": "Class",
"ImplementedInterfaces": [
"Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IModelMetadata"
],
"Members": [
{
"Kind": "Method",
"Name": "get_ModelType",
"Parameters": [],
"ReturnType": "System.Type",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IModelMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_EntityType",
"Parameters": [],
"ReturnType": "Microsoft.EntityFrameworkCore.Metadata.IEntityType",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_DbContexType",
"Parameters": [],
"ReturnType": "System.Type",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_EntitySetName",
"Parameters": [],
"ReturnType": "System.String",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_Properties",
"Parameters": [],
"ReturnType": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata[]",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IModelMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_PrimaryKeys",
"Parameters": [],
"ReturnType": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata[]",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IModelMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_Navigations",
"Parameters": [],
"ReturnType": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata[]",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IModelMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "entityType",
"Type": "Microsoft.EntityFrameworkCore.Metadata.IEntityType"
},
{
"Name": "dbContextType",
"Type": "System.Type"
}
],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.NavigationMetadata",
"Visibility": "Public",
"Kind": "Class",
"ImplementedInterfaces": [
"Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata"
],
"Members": [
{
"Kind": "Method",
"Name": "get_AssociationPropertyName",
"Parameters": [],
"ReturnType": "System.String",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_AssociationPropertyName",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_DisplayPropertyName",
"Parameters": [],
"ReturnType": "System.String",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_DisplayPropertyName",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_EntitySetName",
"Parameters": [],
"ReturnType": "System.String",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_EntitySetName",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_ForeignKeyPropertyNames",
"Parameters": [],
"ReturnType": "System.String[]",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_ForeignKeyPropertyNames",
"Parameters": [
{
"Name": "value",
"Type": "System.String[]"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_PrimaryKeyNames",
"Parameters": [],
"ReturnType": "System.String[]",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_PrimaryKeyNames",
"Parameters": [
{
"Name": "value",
"Type": "System.String[]"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_ShortTypeName",
"Parameters": [],
"ReturnType": "System.String",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_ShortTypeName",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_TypeName",
"Parameters": [],
"ReturnType": "System.String",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_TypeName",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.INavigationMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "navigation",
"Type": "Microsoft.EntityFrameworkCore.Metadata.INavigation"
},
{
"Name": "dbContextType",
"Type": "System.Type"
}
],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.NewDbContextTemplateModel",
"Visibility": "Public",
"Kind": "Class",
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "get_DbContextTypeName",
"Parameters": [],
"ReturnType": "System.String",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_DbContextNamespace",
"Parameters": [],
"ReturnType": "System.String",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_ModelTypeName",
"Parameters": [],
"ReturnType": "System.String",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_ModelTypeFullName",
"Parameters": [],
"ReturnType": "System.String",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_ProgramTypeName",
"Parameters": [],
"ReturnType": "System.String",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_ProgramNamespace",
"Parameters": [],
"ReturnType": "System.String",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_RequiredNamespaces",
"Parameters": [],
"ReturnType": "System.Collections.Generic.HashSet<System.String>",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "dbContextName",
"Type": "System.String"
},
{
"Name": "modelType",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.ModelType"
},
{
"Name": "programType",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.ModelType"
}
],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.PropertyMetadata",
"Visibility": "Public",
"Kind": "Class",
"ImplementedInterfaces": [
"Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata"
],
"Members": [
{
"Kind": "Method",
"Name": "get_IsAutoGenerated",
"Parameters": [],
"ReturnType": "System.Boolean",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_IsAutoGenerated",
"Parameters": [
{
"Name": "value",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_IsEnum",
"Parameters": [],
"ReturnType": "System.Boolean",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_IsEnum",
"Parameters": [
{
"Name": "value",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_IsEnumFlags",
"Parameters": [],
"ReturnType": "System.Boolean",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_IsEnumFlags",
"Parameters": [
{
"Name": "value",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_IsForeignKey",
"Parameters": [],
"ReturnType": "System.Boolean",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_IsForeignKey",
"Parameters": [
{
"Name": "value",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_IsPrimaryKey",
"Parameters": [],
"ReturnType": "System.Boolean",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_IsPrimaryKey",
"Parameters": [
{
"Name": "value",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_IsReadOnly",
"Parameters": [],
"ReturnType": "System.Boolean",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_IsReadOnly",
"Parameters": [
{
"Name": "value",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_PropertyName",
"Parameters": [],
"ReturnType": "System.String",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_PropertyName",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_Scaffold",
"Parameters": [],
"ReturnType": "System.Boolean",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_Scaffold",
"Parameters": [
{
"Name": "value",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_ShortTypeName",
"Parameters": [],
"ReturnType": "System.String",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_ShortTypeName",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_TypeName",
"Parameters": [],
"ReturnType": "System.String",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_TypeName",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_IsMultilineText",
"Parameters": [],
"ReturnType": "System.Boolean",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_IsMultilineText",
"Parameters": [
{
"Name": "value",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_PropertyInfo",
"Parameters": [],
"ReturnType": "System.Reflection.PropertyInfo",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_PropertyInfo",
"Parameters": [
{
"Name": "value",
"Type": "System.Reflection.PropertyInfo"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.IPropertyMetadata",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "property",
"Type": "System.Reflection.PropertyInfo"
}
],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.ReflectedTypesProvider",
"Visibility": "Public",
"Kind": "Class",
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "GetAllTypesInProject",
"Parameters": [
{
"Name": "throwOnError",
"Type": "System.Boolean",
"DefaultValue": "False"
}
],
"ReturnType": "System.Type[]",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "GetReflectedType",
"Parameters": [
{
"Name": "modelType",
"Type": "System.String"
}
],
"ReturnType": "System.Type",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "GetReflectedType",
"Parameters": [
{
"Name": "modelType",
"Type": "System.String"
},
{
"Name": "lookInDependencies",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Type",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "GetCompilationErrors",
"Parameters": [],
"ReturnType": "System.Collections.Generic.IEnumerable<System.String>",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "compilation",
"Type": "Microsoft.CodeAnalysis.Compilation"
},
{
"Name": "compilationModificationFunc",
"Type": "System.Func<Microsoft.CodeAnalysis.Compilation, Microsoft.CodeAnalysis.Compilation>"
},
{
"Name": "projectContext",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.Contracts.ProjectModel.IProjectContext"
},
{
"Name": "loader",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.DotNet.ICodeGenAssemblyLoadContext"
},
{
"Name": "logger",
"Type": "Microsoft.VisualStudio.Web.CodeGeneration.ILogger"
}
],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
}
]
}
|
{
"pile_set_name": "Github"
}
|
<!ENTITY windowtitle "Downloads toevoegen">
<!ENTITY adddescription.value "Voer de download-URL en (optioneel) de verwijzende pagina in.">
<!ENTITY createbatchdescriptor.label "Batchdefinitie maken">
<!ENTITY createbatchdescriptor.tooltip "Een batchdefinitie maken van de huidige tekstselectie">
<!ENTITY desc.batches.value "U kunt ook batchdefinities gebruiken om meerdere bestanden tegelijk te downloaden.">
<!ENTITY examples.value "Voorbeelden:">
|
{
"pile_set_name": "Github"
}
|
using System.Windows;
using System.Windows.Controls;
using Telerik.Windows.Controls.Map;
namespace ProvidersBingMapProvider
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
string bingMapsKey = this.BingMapsKey.Text;
BingRestMapProvider bingMap = new BingRestMapProvider(MapMode.Aerial, true, bingMapsKey);
this.radMap.Provider = bingMap;
}
}
}
|
{
"pile_set_name": "Github"
}
|
#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Kooboo.CMS.Sites.Providers.AzureTable")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f17188b0-75dc-44a0-9de2-92869702e7f7")]
|
{
"pile_set_name": "Github"
}
|
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@include file="/context/mytags.jsp"%>
<!DOCTYPE html>
<html>
<head>
<title>自定义布局模板</title>
<t:base type="jquery,easyui,tools"></t:base>
<SCRIPT type="text/javascript">
function test(data) {
$.messager.alert('提示信息', data.msg);
}
</SCRIPT>
</head>
<body>
<t:formvalid formid="formobj" beforeSubmit="setFtlContent()" dialog="true" usePlugin="password" layout="table" action="cgformFtlController.do?saveEditor" >
<input id="id" name="id" type="hidden" value="${cgformFtlPage.id}">
<input id="cgformId" name="cgformId" type="hidden" value="${cgformFtlPage.cgformId}">
<input id="ftlVersion" name="ftlVersion" type="hidden" value="${cgformFtlPage.ftlVersion}">
<input id="ftlWordUrl" name="ftlWordUrl" type="hidden" value="${cgformFtlPage.ftlWordUrl}">
<input id="createBy" name="createBy" type="hidden" value="${cgformFtlPage.createBy}">
<input id="createName" name="createName" type="hidden" value="${cgformFtlPage.createName}">
<input id="createDate" name="createDate" type="hidden" value="${cgformFtlPage.createDate}">
<input id="editorType" name="editorType" type="hidden" value="02">
<table cellpadding="0" cellspacing="1" class="formtable">
<tr>
<td align="right"><label class="Validform_label">模板名称:</label></td>
<td class="value"><input class="inputxt" id="cgformName" name="cgformName" value="${cgformFtlPage.cgformName}" datatype="*"> <span class="Validform_checktip"></span></td>
</tr>
<tr>
<td class="value" colspan=2>
<input type="hidden" id="ftl" name="ftlContent" >
<script id="ftlContent" type="text/plain" style="width:100%;">${cgformFtlPage.ftlContent == NULL || cgformFtlPage.ftlContent == '' ? '' : cgformFtlPage.ftlContent}</script>
</td>
</tr>
</table>
</t:formvalid>
<script>UEDITOR_HOME_URL='<%=path%>/plug-in/Formdesign/js/ueditor/';</script>
<script type="text/javascript" charset="utf-8" src="plug-in/Formdesign/js/ueditor/ueditor.config.js?2023"></script>
<script type="text/javascript" charset="utf-8" src="plug-in/Formdesign/js/ueditor/ueditor.all.js?2023"> </script>
<script type="text/javascript" charset="utf-8" src="plug-in/Formdesign/js/ueditor/lang/zh-cn/zh-cn.js?2023"></script>
<script type="text/javascript" charset="utf-8" src="plug-in/Formdesign/js/ueditor/formdesign/leipi.formdesign.v4.js?2023"></script>
<script type="text/javascript" charset="utf-8" src="plug-in/Formdesign/js/ueditor/formdesign/weixinplugs.js"></script>
<script type="text/javascript">
var leipiEditor = UE.getEditor('ftlContent',{
//allowDivTransToP: false,//阻止转换div 为p
toolleipi:true,//是否显示,设计器的 toolbars
textarea: 'design_content',
//这里可以选择自己需要的工具按钮名称,此处仅选择如下五个 /*
toolbars: [[
'fullscreen', 'source', '|', 'undo', 'redo', '|',
'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
'directionalityltr', 'directionalityrtl', 'indent', '|',
'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
'simpleupload', 'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|',
'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
'print', 'preview', 'searchreplace', 'help', 'drafts'
]],/*
toolbars:[[
'fullscreen', 'source', '|', 'undo', 'redo', '|','bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'removeformat',
'|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist','|', 'fontfamily', 'fontsize',
'|', 'indent', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
'link', 'unlink', '|', 'horizontal', 'spechars', 'wordimage', '|', 'inserttable',
'deletetable', 'mergecells', 'splittocells']],
//focus时自动清空初始化时的内容 */
//autoClearinitialContent:true,
//关闭字数统计
wordCount:false,
//关闭elementPath
elementPathEnabled:false,
//默认的编辑区域高度
initialFrameHeight:400
///,iframeCssUrl:"css/bootstrap/css/bootstrap.css" //引入自身 css使编辑器兼容你网站css
//更多其他参数,请参考ueditor.config.js中的配置项
});
var leipiFormDesign = {
/*执行控件*/
exec : function (method) {
leipiEditor.execCommand(method);
},
/*
Javascript 解析表单
template 表单设计器里的Html内容
fields 字段总数
*/
parse_form:function(template,fields)
{
//正则 radios|checkboxs|select 匹配的边界 |--| 因为当使用 {} 时js报错
var preg = /(\|-<span(((?!<span).)*leipiplugins=\"(radios|checkboxs|select|popup)\".*?)>(.*?)<\/span>-\||<(img|input|textarea|select).*?(<\/select>|<\/textarea>|\/>))/gi,
preg_attr =/(\w+)=\"(.?|.+?)\"/gi,
preg_group =/<input.*?\/>/gi;
if(!fields) fields = 0;
var template_parse = template,template_data = new Array(),add_fields=new Object(),checkboxs=0;
var pno = 0;
template.replace(preg, function(plugin,p1,p2,p3,p4,p5,p6){
var parse_attr = new Array(),attr_arr_all = new Object(),name = '', select_dot = '' , is_new=false;
var p0 = plugin;
var tag = p6 ? p6 : p4;
//alert(tag + " \n- t1 - "+p1 +" \n-2- " +p2+" \n-3- " +p3+" \n-4- " +p4+" \n-5- " +p5+" \n-6- " +p6);
if(tag == 'radios' || tag == 'checkboxs')
{
plugin = p2;
}else if(tag == 'select')
{
plugin = plugin.replace('|-','');
plugin = plugin.replace('-|','');
}
plugin.replace(preg_attr, function(str0,attr,val) {
if(attr=='name')
{
if(val=='leipiNewField')
{
is_new=true;
fields++;
val = 'data_'+fields;
}
name = val;
}
if(tag=='select' && attr=='value')
{
if(!attr_arr_all[attr]) attr_arr_all[attr] = '';
attr_arr_all[attr] += select_dot + val;
select_dot = ',';
}else
{
attr_arr_all[attr] = val;
}
var oField = new Object();
oField[attr] = val;
parse_attr.push(oField);
})
/*alert(JSON.stringify(parse_attr));return;*/
if(tag =='checkboxs') /*复选组 多个字段 */
{
plugin = p0;
plugin = plugin.replace('|-','');
plugin = plugin.replace('-|','');
var name = 'checkboxs_'+checkboxs;
attr_arr_all['parse_name'] = name;
attr_arr_all['name'] = '';
attr_arr_all['value'] = '';
attr_arr_all['content'] = '<span leipiplugins="checkboxs" title="'+attr_arr_all['title']+'">';
var dot_name ='', dot_value = '';
p5.replace(preg_group, function(parse_group) {
var is_new=false,option = new Object();
parse_group.replace(preg_attr, function(str0,k,val) {
if(k=='name')
{
if(val=='leipiNewField')
{
is_new=true;
fields++;
val = 'data_'+fields;
}
attr_arr_all['name'] += dot_name + val;
dot_name = ',';
}
else if(k=='value')
{
attr_arr_all['value'] += dot_value + val;
dot_value = ',';
}
option[k] = val;
});
if(!attr_arr_all['options']) attr_arr_all['options'] = new Array();
attr_arr_all['options'].push(option);
//if(!option['checked']) option['checked'] = '';
var checked = option['checked'] !=undefined ? 'checked="checked"' : '';
attr_arr_all['content'] +='<input type="checkbox" name="'+option['name']+'" value="'+option['value']+'" '+checked+'/>'+option['value']+' ';
if(is_new)
{
var arr = new Object();
arr['name'] = option['name'];
arr['leipiplugins'] = attr_arr_all['leipiplugins'];
add_fields[option['name']] = arr;
}
});
attr_arr_all['content'] += '</span>';
//parse
template = template.replace(plugin,attr_arr_all['content']);
template_parse = template_parse.replace(plugin,'{'+name+'}');
template_parse = template_parse.replace('{|-','');
template_parse = template_parse.replace('-|}','');
template_data[pno] = attr_arr_all;
checkboxs++;
}else if(name)
{
if(tag =='radios') /*单选组 一个字段*/
{
plugin = p0;
plugin = plugin.replace('|-','');
plugin = plugin.replace('-|','');
attr_arr_all['value'] = '';
attr_arr_all['content'] = '<span leipiplugins="radios" name="'+attr_arr_all['name']+'" title="'+attr_arr_all['title']+'">';
var dot='';
p5.replace(preg_group, function(parse_group) {
var option = new Object();
parse_group.replace(preg_attr, function(str0,k,val) {
if(k=='value')
{
attr_arr_all['value'] += dot + val;
dot = ',';
}
option[k] = val;
});
option['name'] = attr_arr_all['name'];
if(!attr_arr_all['options']) attr_arr_all['options'] = new Array();
attr_arr_all['options'].push(option);
//if(!option['checked']) option['checked'] = '';
var checked = option['checked'] !=undefined ? 'checked="checked"' : '';
attr_arr_all['content'] +='<input type="radio" name="'+attr_arr_all['name']+'" value="'+option['value']+'" '+checked+'/>'+option['value']+' ';
});
attr_arr_all['content'] += '</span>';
}else
{
attr_arr_all['content'] = is_new ? plugin.replace(/leipiNewField/,name) : plugin;
}
//attr_arr_all['itemid'] = fields;
//attr_arr_all['tag'] = tag;
template = template.replace(plugin,attr_arr_all['content']);
template_parse = template_parse.replace(plugin,'{'+name+'}');
template_parse = template_parse.replace('{|-','');
template_parse = template_parse.replace('-|}','');
if(is_new)
{
var arr = new Object();
arr['name'] = name;
arr['leipiplugins'] = attr_arr_all['leipiplugins'];
add_fields[arr['name']] = arr;
}
template_data[pno] = attr_arr_all;
}
pno++;
})
var parse_form = new Object({
'fields':fields,//总字段数
'template':template,//完整html
'parse':template_parse,//控件替换为{data_1}的html
'data':template_data,//控件属性
'add_fields':add_fields//新增控件
});
return JSON.stringify(parse_form);
},
/*type = save 保存设计 versions 保存版本 close关闭 */
fnCheckForm : function ( type ) {
if(leipiEditor.queryCommandState( 'source' ))
leipiEditor.execCommand('source');//切换到编辑模式才提交,否则有bug
if(leipiEditor.hasContents()){
leipiEditor.sync();/*同步内容*/
alert("你点击了保存,这里可以异步提交,请自行处理....");
$("#ftl").val(leipiEditor.getContent());
return false;
//--------------以下仅参考-----------------------------------------------------------------------------------------------------
var type_value='',formid=0,fields=$("#fields").val(),formeditor='';
if( typeof type!=='undefined' ){
type_value = type;
}
//获取表单设计器里的内容
formeditor=leipiEditor.getContent();
//解析表单设计器控件
var parse_form = this.parse_form(formeditor,fields);
//alert(parse_form);
//异步提交数据
$.ajax({
type: 'POST',
url : 'cgformFtlController.do?saveEditor',
//dataType : 'json',
data : {'type' : type_value,'formid':formid,'parse_form':parse_form},
success : function(data){
if(confirm('查看js解析后,提交到服务器的数据,请临时允许弹窗'))
{
win_parse=window.open('','','width=800,height=600');
//这里临时查看,所以替换一下,实际情况下不需要替换
data = data.replace(/<\/+textarea/,'<textarea');
win_parse.document.write('<textarea style="width:100%;height:100%">'+data+'</textarea>');
win_parse.focus();
}
/*
if(data.success==1){
alert('保存成功');
$('#submitbtn').button('reset');
}else{
alert('保存失败!');
}*/
}
});
} else {
alert('表单内容不能为空!')
$('#submitbtn').button('reset');
return false;
}
} ,
// 预览表单
fnReview : function (){
if(leipiEditor.queryCommandState( 'source' ))
leipiEditor.execCommand('source');
if(leipiEditor.hasContents()){
leipiEditor.sync();
var type_value='',formid=0,fields=$("#fields").val(),formeditor='';
formeditor=leipiEditor.getContent();
//解析表单设计器控件
var parse_form = this.parse_form(formeditor,fields);
var style= '<link rel="stylesheet" href="plug-in/Formdesign/js/ueditor/formdesign/bootstrap/css/bootstrap.css">'+
' <link rel="stylesheet" href="plug-in/Formdesign/js/ueditor/formdesign/leipi.style.css">';
$.ajax({
type: 'POST',
url : 'cgformFtlController.do?parseUeditorOld',
dataType : 'json',
data : {'action' :'edit','parseForm':parse_form},
success : function(msg){
//alert(msg);
W.$.dialog({
content:style+msg.msg,// "url:cgformFtlController.do?formEkeditor&editorType=preview&id=${cgformFtlPage.id}",
lock : true,
title:"模板预览 [${cgformFtlPage.cgformName}]",
opacity : 0.5,
width:500,
height:400,
cache:false,
modal:false,
ok: function(){
iframe = this.iframe.contentWindow;
iframe.goForm();
return false;
},
cancelVal: '关闭',
cancel: true
});
}
});
} else {
alert('表单内容不能为空!');
return false;
}
}
};
function setFtlContent(){
if(leipiEditor.queryCommandState( 'source' ))
leipiEditor.execCommand('source');//切换到编辑模式才提交,否则有bug
if(leipiEditor.hasContents()){
leipiEditor.sync();
$("#ftl").val(leipiEditor.getContent());
}
}
</script>
</body>
|
{
"pile_set_name": "Github"
}
|
// ****************************************************************
// Copyright 2009, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
namespace NUnit.Framework.Constraints
{
[TestFixture]
public class ComparerTests
{
private Tolerance tolerance;
[SetUp]
public void Setup()
{
tolerance = Tolerance.Empty;
}
[TestCase(4, 4)]
[TestCase(4.0d, 4.0d)]
[TestCase(4.0f, 4.0f)]
[TestCase(4, 4.0d)]
[TestCase(4, 4.0f)]
[TestCase(4.0d, 4)]
[TestCase(4.0d, 4.0f)]
[TestCase(4.0f, 4)]
[TestCase(4.0f, 4.0d)]
[TestCase(SpecialValue.Null, SpecialValue.Null)]
#if CLR_2_0 || CLR_4_0
[TestCase(null, null)]
#endif
public void EqualItems(object x, object y)
{
Assert.That(NUnitComparer.Default.Compare(x, y) == 0);
Assert.That(NUnitEqualityComparer.Default.AreEqual(x, y, ref tolerance));
}
[TestCase(4, 2)]
[TestCase(4.0d, 2.0d)]
[TestCase(4.0f, 2.0f)]
[TestCase(4, 2.0d)]
[TestCase(4, 2.0f)]
[TestCase(4.0d, 2)]
[TestCase(4.0d, 2.0f)]
[TestCase(4.0f, 2)]
[TestCase(4.0f, 2.0d)]
[TestCase(4, SpecialValue.Null)]
#if CLR_2_0 || CLR_4_0
[TestCase(4, null)]
#endif
public void UnequalItems(object greater, object lesser)
{
Assert.That(NUnitComparer.Default.Compare(greater, lesser) > 0);
Assert.That(NUnitComparer.Default.Compare(lesser, greater) < 0);
Assert.False(NUnitEqualityComparer.Default.AreEqual(greater, lesser, ref tolerance));
Assert.False(NUnitEqualityComparer.Default.AreEqual(lesser, greater, ref tolerance));
}
[TestCase(double.PositiveInfinity)]
[TestCase(double.NegativeInfinity)]
[TestCase(double.NaN)]
[TestCase(float.PositiveInfinity)]
[TestCase(float.NegativeInfinity)]
[TestCase(float.NaN)]
public void SpecialFloatingPointValues(object x)
{
Assert.That(NUnitEqualityComparer.Default.AreEqual(x, x, ref tolerance));
}
}
}
|
{
"pile_set_name": "Github"
}
|
{
"Names": {
"Africa\/Abidjan": "heure moyenne de Greenwich (Abidjan)",
"Africa\/Accra": "heure moyenne de Greenwich (Accra)",
"Africa\/Addis_Ababa": "heure normale d’Afrique de l’Est (Addis-Abeba)",
"Africa\/Algiers": "heure d’Europe centrale (Alger)",
"Africa\/Asmera": "heure normale d’Afrique de l’Est (Asmara)",
"Africa\/Bamako": "heure moyenne de Greenwich (Bamako)",
"Africa\/Bangui": "heure d’Afrique de l’Ouest (Bangui)",
"Africa\/Banjul": "heure moyenne de Greenwich (Banjul)",
"Africa\/Bissau": "heure moyenne de Greenwich (Bissau)",
"Africa\/Blantyre": "heure normale d’Afrique centrale (Blantyre)",
"Africa\/Brazzaville": "heure d’Afrique de l’Ouest (Brazzaville)",
"Africa\/Bujumbura": "heure normale d’Afrique centrale (Bujumbura)",
"Africa\/Cairo": "heure d’Europe de l’Est (Le Caire)",
"Africa\/Casablanca": "heure d’Europe de l’Ouest (Casablanca)",
"Africa\/Ceuta": "heure d’Europe centrale (Ceuta)",
"Africa\/Conakry": "heure moyenne de Greenwich (Conakry)",
"Africa\/Dakar": "heure moyenne de Greenwich (Dakar)",
"Africa\/Dar_es_Salaam": "heure normale d’Afrique de l’Est (Dar es Salaam)",
"Africa\/Djibouti": "heure normale d’Afrique de l’Est (Djibouti)",
"Africa\/Douala": "heure d’Afrique de l’Ouest (Douala)",
"Africa\/El_Aaiun": "heure d’Europe de l’Ouest (Laâyoune)",
"Africa\/Freetown": "heure moyenne de Greenwich (Freetown)",
"Africa\/Gaborone": "heure normale d’Afrique centrale (Gaborone)",
"Africa\/Harare": "heure normale d’Afrique centrale (Harare)",
"Africa\/Johannesburg": "heure normale d’Afrique méridionale (Johannesburg)",
"Africa\/Juba": "heure normale d’Afrique de l’Est (Juba)",
"Africa\/Kampala": "heure normale d’Afrique de l’Est (Kampala)",
"Africa\/Khartoum": "heure normale d’Afrique centrale (Khartoum)",
"Africa\/Kigali": "heure normale d’Afrique centrale (Kigali)",
"Africa\/Kinshasa": "heure d’Afrique de l’Ouest (Kinshasa)",
"Africa\/Lagos": "heure d’Afrique de l’Ouest (Lagos)",
"Africa\/Libreville": "heure d’Afrique de l’Ouest (Libreville)",
"Africa\/Lome": "heure moyenne de Greenwich (Lomé)",
"Africa\/Luanda": "heure d’Afrique de l’Ouest (Luanda)",
"Africa\/Lubumbashi": "heure normale d’Afrique centrale (Lubumbashi)",
"Africa\/Lusaka": "heure normale d’Afrique centrale (Lusaka)",
"Africa\/Malabo": "heure d’Afrique de l’Ouest (Malabo)",
"Africa\/Maputo": "heure normale d’Afrique centrale (Maputo)",
"Africa\/Maseru": "heure normale d’Afrique méridionale (Maseru)",
"Africa\/Mbabane": "heure normale d’Afrique méridionale (Mbabane)",
"Africa\/Mogadishu": "heure normale d’Afrique de l’Est (Mogadiscio)",
"Africa\/Monrovia": "heure moyenne de Greenwich (Monrovia)",
"Africa\/Nairobi": "heure normale d’Afrique de l’Est (Nairobi)",
"Africa\/Ndjamena": "heure d’Afrique de l’Ouest (N’Djamena)",
"Africa\/Niamey": "heure d’Afrique de l’Ouest (Niamey)",
"Africa\/Nouakchott": "heure moyenne de Greenwich (Nouakchott)",
"Africa\/Ouagadougou": "heure moyenne de Greenwich (Ouagadougou)",
"Africa\/Porto-Novo": "heure d’Afrique de l’Ouest (Porto-Novo)",
"Africa\/Sao_Tome": "heure moyenne de Greenwich (São Tomé)",
"Africa\/Tripoli": "heure d’Europe de l’Est (Tripoli (Libye))",
"Africa\/Tunis": "heure d’Europe centrale (Tunis)",
"Africa\/Windhoek": "heure normale d’Afrique centrale (Windhoek)",
"America\/Adak": "heure d’Hawaii - Aléoutiennes (Adak)",
"America\/Anchorage": "heure de l’Alaska (Anchorage)",
"America\/Anguilla": "heure de l’Atlantique (Anguilla)",
"America\/Antigua": "heure de l’Atlantique (Antigua)",
"America\/Araguaina": "heure de Brasilia (Araguaína)",
"America\/Argentina\/La_Rioja": "heure de l’Argentine (La Rioja)",
"America\/Argentina\/Rio_Gallegos": "heure de l’Argentine (Río Gallegos)",
"America\/Argentina\/Salta": "heure de l’Argentine (Salta)",
"America\/Argentina\/San_Juan": "heure de l’Argentine (San Juan)",
"America\/Argentina\/San_Luis": "heure de l’Argentine (San Luis)",
"America\/Argentina\/Tucuman": "heure de l’Argentine (Tucumán)",
"America\/Argentina\/Ushuaia": "heure de l’Argentine (Ushuaïa)",
"America\/Aruba": "heure de l’Atlantique (Aruba)",
"America\/Asuncion": "heure du Paraguay (Asunción)",
"America\/Bahia": "heure de Brasilia (Bahia)",
"America\/Bahia_Banderas": "heure du centre nord-américain (Bahia de Banderas)",
"America\/Barbados": "heure de l’Atlantique (La Barbade)",
"America\/Belem": "heure de Brasilia (Belém)",
"America\/Belize": "heure du centre nord-américain (Belize)",
"America\/Blanc-Sablon": "heure de l’Atlantique (Blanc-Sablon)",
"America\/Boa_Vista": "heure de l’Amazonie (Boa Vista)",
"America\/Bogota": "heure de Colombie (Bogota)",
"America\/Boise": "heure des Rocheuses (Boise)",
"America\/Buenos_Aires": "heure de l’Argentine (Buenos Aires)",
"America\/Cambridge_Bay": "heure des Rocheuses (Cambridge Bay)",
"America\/Campo_Grande": "heure de l’Amazonie (Campo Grande)",
"America\/Cancun": "heure de l’Est nord-américain (Cancún)",
"America\/Caracas": "heure du Venezuela (Caracas)",
"America\/Catamarca": "heure de l’Argentine (Catamarca)",
"America\/Cayenne": "heure de la Guyane française (Cayenne)",
"America\/Cayman": "heure de l’Est nord-américain (Caïmans)",
"America\/Chicago": "heure du centre nord-américain (Chicago)",
"America\/Chihuahua": "heure du Pacifique mexicain (Chihuahua)",
"America\/Coral_Harbour": "heure de l’Est nord-américain (Atikokan)",
"America\/Cordoba": "heure de l’Argentine (Córdoba)",
"America\/Costa_Rica": "heure du centre nord-américain (Costa Rica)",
"America\/Creston": "heure des Rocheuses (Creston)",
"America\/Cuiaba": "heure de l’Amazonie (Cuiabá)",
"America\/Curacao": "heure de l’Atlantique (Curaçao)",
"America\/Danmarkshavn": "heure moyenne de Greenwich (Danmarkshavn)",
"America\/Dawson": "heure du Pacifique nord-américain (Dawson)",
"America\/Dawson_Creek": "heure des Rocheuses (Dawson Creek)",
"America\/Denver": "heure des Rocheuses (Denver)",
"America\/Detroit": "heure de l’Est nord-américain (Détroit)",
"America\/Dominica": "heure de l’Atlantique (Dominique)",
"America\/Edmonton": "heure des Rocheuses (Edmonton)",
"America\/Eirunepe": "heure de l’Acre (Eirunepé)",
"America\/El_Salvador": "heure du centre nord-américain (El Salvador)",
"America\/Fort_Nelson": "heure des Rocheuses (Fort Nelson)",
"America\/Fortaleza": "heure de Brasilia (Fortaleza)",
"America\/Glace_Bay": "heure de l’Atlantique (Glace Bay)",
"America\/Godthab": "heure de l’Ouest du Groenland (Nuuk)",
"America\/Goose_Bay": "heure de l’Atlantique (Goose Bay)",
"America\/Grand_Turk": "heure de l’Est nord-américain (Grand Turk)",
"America\/Grenada": "heure de l’Atlantique (Grenade)",
"America\/Guadeloupe": "heure de l’Atlantique (Guadeloupe)",
"America\/Guatemala": "heure du centre nord-américain (Guatemala)",
"America\/Guayaquil": "heure de l’Équateur (Guayaquil)",
"America\/Guyana": "heure du Guyana",
"America\/Halifax": "heure de l’Atlantique (Halifax)",
"America\/Havana": "heure de Cuba (La Havane)",
"America\/Hermosillo": "heure du Pacifique mexicain (Hermosillo)",
"America\/Indiana\/Knox": "heure du centre nord-américain (Knox [Indiana])",
"America\/Indiana\/Marengo": "heure de l’Est nord-américain (Marengo [Indiana])",
"America\/Indiana\/Petersburg": "heure de l’Est nord-américain (Petersburg [Indiana])",
"America\/Indiana\/Tell_City": "heure du centre nord-américain (Tell City [Indiana])",
"America\/Indiana\/Vevay": "heure de l’Est nord-américain (Vevay [Indiana])",
"America\/Indiana\/Vincennes": "heure de l’Est nord-américain (Vincennes [Indiana])",
"America\/Indiana\/Winamac": "heure de l’Est nord-américain (Winamac [Indiana])",
"America\/Indianapolis": "heure de l’Est nord-américain (Indianapolis)",
"America\/Inuvik": "heure des Rocheuses (Inuvik)",
"America\/Iqaluit": "heure de l’Est nord-américain (Iqaluit)",
"America\/Jamaica": "heure de l’Est nord-américain (Jamaïque)",
"America\/Jujuy": "heure de l’Argentine (Jujuy)",
"America\/Juneau": "heure de l’Alaska (Juneau)",
"America\/Kentucky\/Monticello": "heure de l’Est nord-américain (Monticello [Kentucky])",
"America\/Kralendijk": "heure de l’Atlantique (Kralendijk)",
"America\/La_Paz": "heure de Bolivie (La Paz)",
"America\/Lima": "heure du Pérou (Lima)",
"America\/Los_Angeles": "heure du Pacifique nord-américain (Los Angeles)",
"America\/Louisville": "heure de l’Est nord-américain (Louisville)",
"America\/Lower_Princes": "heure de l’Atlantique (Lower Prince’s Quarter)",
"America\/Maceio": "heure de Brasilia (Maceió)",
"America\/Managua": "heure du centre nord-américain (Managua)",
"America\/Manaus": "heure de l’Amazonie (Manaos)",
"America\/Marigot": "heure de l’Atlantique (Marigot)",
"America\/Martinique": "heure de l’Atlantique (Martinique)",
"America\/Matamoros": "heure du centre nord-américain (Matamoros)",
"America\/Mazatlan": "heure du Pacifique mexicain (Mazatlán)",
"America\/Mendoza": "heure de l’Argentine (Mendoza)",
"America\/Menominee": "heure du centre nord-américain (Menominee)",
"America\/Merida": "heure du centre nord-américain (Mérida)",
"America\/Metlakatla": "heure de l’Alaska (Metlakatla)",
"America\/Mexico_City": "heure du centre nord-américain (Mexico)",
"America\/Miquelon": "heure de Saint-Pierre-et-Miquelon",
"America\/Moncton": "heure de l’Atlantique (Moncton)",
"America\/Monterrey": "heure du centre nord-américain (Monterrey)",
"America\/Montevideo": "heure de l’Uruguay (Montevideo)",
"America\/Montreal": "heure : Canada (Montreal)",
"America\/Montserrat": "heure de l’Atlantique (Montserrat)",
"America\/Nassau": "heure de l’Est nord-américain (Nassau)",
"America\/New_York": "heure de l’Est nord-américain (New York)",
"America\/Nipigon": "heure de l’Est nord-américain (Nipigon)",
"America\/Nome": "heure de l’Alaska (Nome)",
"America\/Noronha": "heure de Fernando de Noronha",
"America\/North_Dakota\/Beulah": "heure du centre nord-américain (Beulah (Dakota du Nord))",
"America\/North_Dakota\/Center": "heure du centre nord-américain (Center (Dakota du Nord))",
"America\/North_Dakota\/New_Salem": "heure du centre nord-américain (New Salem (Dakota du Nord))",
"America\/Ojinaga": "heure des Rocheuses (Ojinaga)",
"America\/Panama": "heure de l’Est nord-américain (Panama)",
"America\/Pangnirtung": "heure de l’Est nord-américain (Pangnirtung)",
"America\/Paramaribo": "heure du Suriname (Paramaribo)",
"America\/Phoenix": "heure des Rocheuses (Phoenix)",
"America\/Port-au-Prince": "heure de l’Est nord-américain (Port-au-Prince)",
"America\/Port_of_Spain": "heure de l’Atlantique (Port-d’Espagne)",
"America\/Porto_Velho": "heure de l’Amazonie (Porto Velho)",
"America\/Puerto_Rico": "heure de l’Atlantique (Porto Rico)",
"America\/Punta_Arenas": "heure du Chili (Punta Arenas)",
"America\/Rainy_River": "heure du centre nord-américain (Rainy River)",
"America\/Rankin_Inlet": "heure du centre nord-américain (Rankin Inlet)",
"America\/Recife": "heure de Brasilia (Recife)",
"America\/Regina": "heure du centre nord-américain (Regina)",
"America\/Resolute": "heure du centre nord-américain (Resolute)",
"America\/Rio_Branco": "heure de l’Acre (Rio Branco)",
"America\/Santa_Isabel": "heure du Nord-Ouest du Mexique (Santa Isabel)",
"America\/Santarem": "heure de Brasilia (Santarém)",
"America\/Santiago": "heure du Chili (Santiago)",
"America\/Santo_Domingo": "heure de l’Atlantique (Saint-Domingue)",
"America\/Sao_Paulo": "heure de Brasilia (São Paulo)",
"America\/Scoresbysund": "heure de l’Est du Groenland (Ittoqqortoormiit)",
"America\/Sitka": "heure de l’Alaska (Sitka)",
"America\/St_Barthelemy": "heure de l’Atlantique (Saint-Barthélemy)",
"America\/St_Johns": "heure de Terre-Neuve (Saint-Jean de Terre-Neuve)",
"America\/St_Kitts": "heure de l’Atlantique (Saint-Christophe)",
"America\/St_Lucia": "heure de l’Atlantique (Sainte-Lucie)",
"America\/St_Thomas": "heure de l’Atlantique (Saint-Thomas)",
"America\/St_Vincent": "heure de l’Atlantique (Saint-Vincent)",
"America\/Swift_Current": "heure du centre nord-américain (Swift Current)",
"America\/Tegucigalpa": "heure du centre nord-américain (Tégucigalpa)",
"America\/Thule": "heure de l’Atlantique (Thulé)",
"America\/Thunder_Bay": "heure de l’Est nord-américain (Thunder Bay)",
"America\/Tijuana": "heure du Pacifique nord-américain (Tijuana)",
"America\/Toronto": "heure de l’Est nord-américain (Toronto)",
"America\/Tortola": "heure de l’Atlantique (Tortola)",
"America\/Vancouver": "heure du Pacifique nord-américain (Vancouver)",
"America\/Whitehorse": "heure du Pacifique nord-américain (Whitehorse)",
"America\/Winnipeg": "heure du centre nord-américain (Winnipeg)",
"America\/Yakutat": "heure de l’Alaska (Yakutat)",
"America\/Yellowknife": "heure des Rocheuses (Yellowknife)",
"Antarctica\/Casey": "heure de l’Ouest de l’Australie (Casey)",
"Antarctica\/Davis": "heure de Davis",
"Antarctica\/DumontDUrville": "heure de Dumont-d’Urville",
"Antarctica\/Macquarie": "heure de l’île Macquarie",
"Antarctica\/Mawson": "heure de Mawson",
"Antarctica\/McMurdo": "heure de la Nouvelle-Zélande (McMurdo)",
"Antarctica\/Palmer": "heure du Chili (Palmer)",
"Antarctica\/Rothera": "heure de Rothera",
"Antarctica\/Syowa": "heure de Syowa (Showa)",
"Antarctica\/Troll": "heure moyenne de Greenwich (Troll)",
"Antarctica\/Vostok": "heure de Vostok",
"Arctic\/Longyearbyen": "heure d’Europe centrale (Longyearbyen)",
"Asia\/Aden": "heure de l’Arabie (Aden)",
"Asia\/Almaty": "heure de l’Est du Kazakhstan (Alma Ata)",
"Asia\/Amman": "heure d’Europe de l’Est (Amman)",
"Asia\/Anadyr": "heure d’Anadyr",
"Asia\/Aqtau": "heure de l’Ouest du Kazakhstan (Aktaou)",
"Asia\/Aqtobe": "heure de l’Ouest du Kazakhstan (Aktioubinsk)",
"Asia\/Ashgabat": "heure du Turkménistan (Achgabat)",
"Asia\/Atyrau": "heure de l’Ouest du Kazakhstan (Atyraou)",
"Asia\/Baghdad": "heure de l’Arabie (Bagdad)",
"Asia\/Bahrain": "heure de l’Arabie (Bahreïn)",
"Asia\/Baku": "heure de l’Azerbaïdjan (Bakou)",
"Asia\/Bangkok": "heure d’Indochine (Bangkok)",
"Asia\/Barnaul": "heure : Russie (Barnaul)",
"Asia\/Beirut": "heure d’Europe de l’Est (Beyrouth)",
"Asia\/Bishkek": "heure du Kirghizistan (Bichkek)",
"Asia\/Brunei": "heure du Brunéi (Brunei)",
"Asia\/Calcutta": "heure de l’Inde (Calcutta)",
"Asia\/Chita": "heure de Iakoutsk (Tchita)",
"Asia\/Choibalsan": "heure d’Oulan-Bator (Tchoïbalsan)",
"Asia\/Colombo": "heure de l’Inde (Colombo)",
"Asia\/Damascus": "heure d’Europe de l’Est (Damas)",
"Asia\/Dhaka": "heure du Bangladesh (Dhaka)",
"Asia\/Dili": "heure du Timor oriental (Dili)",
"Asia\/Dubai": "heure du Golfe (Dubaï)",
"Asia\/Dushanbe": "heure du Tadjikistan (Douchanbé)",
"Asia\/Famagusta": "heure d’Europe de l’Est (Famagouste)",
"Asia\/Gaza": "heure d’Europe de l’Est (Gaza)",
"Asia\/Hebron": "heure d’Europe de l’Est (Hébron)",
"Asia\/Hong_Kong": "heure de Hong Kong",
"Asia\/Hovd": "heure de Hovd",
"Asia\/Irkutsk": "heure d’Irkoutsk",
"Asia\/Jakarta": "heure de l’Ouest indonésien (Jakarta)",
"Asia\/Jayapura": "heure de l’Est indonésien (Jayapura)",
"Asia\/Jerusalem": "heure d’Israël (Jérusalem)",
"Asia\/Kabul": "heure de l’Afghanistan (Kaboul)",
"Asia\/Kamchatka": "heure de Petropavlovsk-Kamchatski (Kamtchatka)",
"Asia\/Karachi": "heure du Pakistan (Karachi)",
"Asia\/Katmandu": "heure du Népal (Katmandou)",
"Asia\/Khandyga": "heure de Iakoutsk (Khandyga)",
"Asia\/Krasnoyarsk": "heure de Krasnoïarsk",
"Asia\/Kuala_Lumpur": "heure de la Malaisie (Kuala Lumpur)",
"Asia\/Kuching": "heure de la Malaisie (Kuching)",
"Asia\/Kuwait": "heure de l’Arabie (Koweït)",
"Asia\/Macau": "heure de la Chine (Macao)",
"Asia\/Magadan": "heure de Magadan",
"Asia\/Makassar": "heure du Centre indonésien (Macassar)",
"Asia\/Manila": "heure des Philippines (Manille)",
"Asia\/Muscat": "heure du Golfe (Mascate)",
"Asia\/Nicosia": "heure d’Europe de l’Est (Nicosie)",
"Asia\/Novokuznetsk": "heure de Krasnoïarsk (Novokuznetsk)",
"Asia\/Novosibirsk": "heure de Novossibirsk",
"Asia\/Omsk": "heure de Omsk",
"Asia\/Oral": "heure de l’Ouest du Kazakhstan (Ouralsk)",
"Asia\/Phnom_Penh": "heure d’Indochine (Phnom Penh)",
"Asia\/Pontianak": "heure de l’Ouest indonésien (Pontianak)",
"Asia\/Pyongyang": "heure de la Corée (Pyongyang)",
"Asia\/Qatar": "heure de l’Arabie (Qatar)",
"Asia\/Qostanay": "heure de l’Est du Kazakhstan (Kostanaï)",
"Asia\/Qyzylorda": "heure de l’Ouest du Kazakhstan (Kzyl Orda)",
"Asia\/Rangoon": "heure du Myanmar (Rangoun)",
"Asia\/Riyadh": "heure de l’Arabie (Riyad)",
"Asia\/Saigon": "heure d’Indochine (Hô-Chi-Minh-Ville)",
"Asia\/Sakhalin": "heure de Sakhaline",
"Asia\/Samarkand": "heure de l’Ouzbékistan (Samarcande)",
"Asia\/Seoul": "heure de la Corée (Séoul)",
"Asia\/Shanghai": "heure de la Chine (Shanghai)",
"Asia\/Singapore": "heure de Singapour",
"Asia\/Srednekolymsk": "heure de Magadan (Srednekolymsk)",
"Asia\/Taipei": "heure de Taipei",
"Asia\/Tashkent": "heure de l’Ouzbékistan (Tachkent)",
"Asia\/Tbilisi": "heure de la Géorgie (Tbilissi)",
"Asia\/Tehran": "heure de l’Iran (Téhéran)",
"Asia\/Thimphu": "heure du Bhoutan (Thimphu)",
"Asia\/Tokyo": "heure du Japon (Tokyo)",
"Asia\/Tomsk": "heure : Russie (Tomsk)",
"Asia\/Ulaanbaatar": "heure d’Oulan-Bator",
"Asia\/Urumqi": "heure : Chine (Ürümqi)",
"Asia\/Ust-Nera": "heure de Vladivostok (Ust-Nera)",
"Asia\/Vientiane": "heure d’Indochine (Vientiane)",
"Asia\/Vladivostok": "heure de Vladivostok",
"Asia\/Yakutsk": "heure de Iakoutsk",
"Asia\/Yekaterinburg": "heure d’Ekaterinbourg",
"Asia\/Yerevan": "heure de l’Arménie (Erevan)",
"Atlantic\/Azores": "heure des Açores",
"Atlantic\/Bermuda": "heure de l’Atlantique (Bermudes)",
"Atlantic\/Canary": "heure d’Europe de l’Ouest (Îles Canaries)",
"Atlantic\/Cape_Verde": "heure du Cap-Vert",
"Atlantic\/Faeroe": "heure d’Europe de l’Ouest (Féroé)",
"Atlantic\/Madeira": "heure d’Europe de l’Ouest (Madère)",
"Atlantic\/Reykjavik": "heure moyenne de Greenwich (Reykjavik)",
"Atlantic\/South_Georgia": "heure de Géorgie du Sud",
"Atlantic\/St_Helena": "heure moyenne de Greenwich (Sainte-Hélène)",
"Atlantic\/Stanley": "heure des îles Malouines (Stanley)",
"Australia\/Adelaide": "heure du centre de l’Australie (Adélaïde)",
"Australia\/Brisbane": "heure de l’Est de l’Australie (Brisbane)",
"Australia\/Broken_Hill": "heure du centre de l’Australie (Broken Hill)",
"Australia\/Currie": "heure de l’Est de l’Australie (Currie)",
"Australia\/Darwin": "heure du centre de l’Australie (Darwin)",
"Australia\/Eucla": "heure du centre-ouest de l’Australie (Eucla)",
"Australia\/Hobart": "heure de l’Est de l’Australie (Hobart)",
"Australia\/Lindeman": "heure de l’Est de l’Australie (Lindeman)",
"Australia\/Lord_Howe": "heure de Lord Howe",
"Australia\/Melbourne": "heure de l’Est de l’Australie (Melbourne)",
"Australia\/Perth": "heure de l’Ouest de l’Australie (Perth)",
"Australia\/Sydney": "heure de l’Est de l’Australie (Sydney)",
"CST6CDT": "heure du centre nord-américain",
"EST5EDT": "heure de l’Est nord-américain",
"Etc\/GMT": "heure moyenne de Greenwich",
"Etc\/UTC": "Temps universel coordonné",
"Europe\/Amsterdam": "heure d’Europe centrale (Amsterdam)",
"Europe\/Andorra": "heure d’Europe centrale (Andorre)",
"Europe\/Astrakhan": "heure de Moscou (Astrakhan)",
"Europe\/Athens": "heure d’Europe de l’Est (Athènes)",
"Europe\/Belgrade": "heure d’Europe centrale (Belgrade)",
"Europe\/Berlin": "heure d’Europe centrale (Berlin)",
"Europe\/Bratislava": "heure d’Europe centrale (Bratislava)",
"Europe\/Brussels": "heure d’Europe centrale (Bruxelles)",
"Europe\/Bucharest": "heure d’Europe de l’Est (Bucarest)",
"Europe\/Budapest": "heure d’Europe centrale (Budapest)",
"Europe\/Busingen": "heure d’Europe centrale (Büsingen)",
"Europe\/Chisinau": "heure d’Europe de l’Est (Chisinau)",
"Europe\/Copenhagen": "heure d’Europe centrale (Copenhague)",
"Europe\/Dublin": "heure moyenne de Greenwich (Dublin)",
"Europe\/Gibraltar": "heure d’Europe centrale (Gibraltar)",
"Europe\/Guernsey": "heure moyenne de Greenwich (Guernesey)",
"Europe\/Helsinki": "heure d’Europe de l’Est (Helsinki)",
"Europe\/Isle_of_Man": "heure moyenne de Greenwich (Île de Man)",
"Europe\/Istanbul": "heure : Turquie (Istanbul)",
"Europe\/Jersey": "heure moyenne de Greenwich (Jersey)",
"Europe\/Kaliningrad": "heure d’Europe de l’Est (Kaliningrad)",
"Europe\/Kiev": "heure d’Europe de l’Est (Kiev)",
"Europe\/Kirov": "heure : Russie (Kirov)",
"Europe\/Lisbon": "heure d’Europe de l’Ouest (Lisbonne)",
"Europe\/Ljubljana": "heure d’Europe centrale (Ljubljana)",
"Europe\/London": "heure moyenne de Greenwich (Londres)",
"Europe\/Luxembourg": "heure d’Europe centrale (Luxembourg)",
"Europe\/Madrid": "heure d’Europe centrale (Madrid)",
"Europe\/Malta": "heure d’Europe centrale (Malte)",
"Europe\/Mariehamn": "heure d’Europe de l’Est (Mariehamn)",
"Europe\/Minsk": "heure de Moscou (Minsk)",
"Europe\/Monaco": "heure d’Europe centrale (Monaco)",
"Europe\/Moscow": "heure de Moscou",
"Europe\/Oslo": "heure d’Europe centrale (Oslo)",
"Europe\/Paris": "heure d’Europe centrale (Paris)",
"Europe\/Podgorica": "heure d’Europe centrale (Podgorica)",
"Europe\/Prague": "heure d’Europe centrale (Prague)",
"Europe\/Riga": "heure d’Europe de l’Est (Riga)",
"Europe\/Rome": "heure d’Europe centrale (Rome)",
"Europe\/Samara": "heure de Samara",
"Europe\/San_Marino": "heure d’Europe centrale (Saint-Marin)",
"Europe\/Sarajevo": "heure d’Europe centrale (Sarajevo)",
"Europe\/Saratov": "heure de Moscou (Saratov)",
"Europe\/Simferopol": "heure de Moscou (Simferopol)",
"Europe\/Skopje": "heure d’Europe centrale (Skopje)",
"Europe\/Sofia": "heure d’Europe de l’Est (Sofia)",
"Europe\/Stockholm": "heure d’Europe centrale (Stockholm)",
"Europe\/Tallinn": "heure d’Europe de l’Est (Tallinn)",
"Europe\/Tirane": "heure d’Europe centrale (Tirana)",
"Europe\/Ulyanovsk": "heure de Moscou (Oulianovsk)",
"Europe\/Uzhgorod": "heure d’Europe de l’Est (Oujgorod)",
"Europe\/Vaduz": "heure d’Europe centrale (Vaduz)",
"Europe\/Vatican": "heure d’Europe centrale (Le Vatican)",
"Europe\/Vienna": "heure d’Europe centrale (Vienne)",
"Europe\/Vilnius": "heure d’Europe de l’Est (Vilnius)",
"Europe\/Volgograd": "heure de Volgograd",
"Europe\/Warsaw": "heure d’Europe centrale (Varsovie)",
"Europe\/Zagreb": "heure d’Europe centrale (Zagreb)",
"Europe\/Zaporozhye": "heure d’Europe de l’Est (Zaporojie)",
"Europe\/Zurich": "heure d’Europe centrale (Zurich)",
"Indian\/Antananarivo": "heure normale d’Afrique de l’Est (Antananarivo)",
"Indian\/Chagos": "heure de l’Océan Indien (Chagos)",
"Indian\/Christmas": "heure de l’île Christmas",
"Indian\/Cocos": "heure des îles Cocos",
"Indian\/Comoro": "heure normale d’Afrique de l’Est (Comores)",
"Indian\/Kerguelen": "heure des Terres australes et antarctiques françaises (Kerguelen)",
"Indian\/Mahe": "heure des Seychelles (Mahé)",
"Indian\/Maldives": "heure des Maldives",
"Indian\/Mauritius": "heure de Maurice",
"Indian\/Mayotte": "heure normale d’Afrique de l’Est (Mayotte)",
"Indian\/Reunion": "heure de La Réunion",
"MST7MDT": "heure des Rocheuses",
"PST8PDT": "heure du Pacifique nord-américain",
"Pacific\/Apia": "heure d’Apia",
"Pacific\/Auckland": "heure de la Nouvelle-Zélande (Auckland)",
"Pacific\/Bougainville": "heure de la Papouasie-Nouvelle-Guinée (Bougainville)",
"Pacific\/Chatham": "heure des îles Chatham",
"Pacific\/Easter": "heure de l’île de Pâques",
"Pacific\/Efate": "heure du Vanuatu (Éfaté)",
"Pacific\/Enderbury": "heure des îles Phoenix (Enderbury)",
"Pacific\/Fakaofo": "heure de Tokelau (Fakaofo)",
"Pacific\/Fiji": "heure des îles Fidji",
"Pacific\/Funafuti": "heure des Tuvalu (Funafuti)",
"Pacific\/Galapagos": "heure des îles Galápagos",
"Pacific\/Gambier": "heure des îles Gambier",
"Pacific\/Guadalcanal": "heure des îles Salomon (Guadalcanal)",
"Pacific\/Guam": "heure des Chamorro (Guam)",
"Pacific\/Honolulu": "heure d’Hawaii - Aléoutiennes (Honolulu)",
"Pacific\/Johnston": "heure d’Hawaii - Aléoutiennes (Johnston)",
"Pacific\/Kiritimati": "heure des îles de la Ligne (Kiritimati)",
"Pacific\/Kosrae": "heure de Kosrae",
"Pacific\/Kwajalein": "heure des îles Marshall (Kwajalein)",
"Pacific\/Majuro": "heure des îles Marshall (Majuro)",
"Pacific\/Marquesas": "heure des îles Marquises",
"Pacific\/Midway": "heure des Samoa (Midway)",
"Pacific\/Nauru": "heure de Nauru",
"Pacific\/Niue": "heure de Nioué (Niue)",
"Pacific\/Norfolk": "heure de l’île Norfolk",
"Pacific\/Noumea": "heure de la Nouvelle-Calédonie (Nouméa)",
"Pacific\/Pago_Pago": "heure des Samoa (Pago Pago)",
"Pacific\/Palau": "heure des Palaos (Palau)",
"Pacific\/Pitcairn": "heure des îles Pitcairn",
"Pacific\/Ponape": "heure de l’île de Pohnpei",
"Pacific\/Port_Moresby": "heure de la Papouasie-Nouvelle-Guinée (Port Moresby)",
"Pacific\/Rarotonga": "heure des îles Cook (Rarotonga)",
"Pacific\/Saipan": "heure des Chamorro (Saipan)",
"Pacific\/Tahiti": "heure de Tahiti",
"Pacific\/Tarawa": "heure des îles Gilbert (Tarawa)",
"Pacific\/Tongatapu": "heure des Tonga (Tongatapu)",
"Pacific\/Truk": "heure de Chuuk",
"Pacific\/Wake": "heure de l’île Wake",
"Pacific\/Wallis": "heure de Wallis-et-Futuna"
},
"Meta": {
"GmtFormat": "UTC%s",
"HourFormatNeg": "−%02d:%02d"
}
}
|
{
"pile_set_name": "Github"
}
|
# ironpot
-s 4
1
ironpot.bmp [0, 0]
1
1 1
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8" ?>
<ldml>
<identity>
<version number="$Revision: 1.54 $"/>
<generation date="$Date: 2009/05/05 23:06:39 $"/>
<language type="pt"/>
<territory type="BR"/>
</identity>
</ldml>
|
{
"pile_set_name": "Github"
}
|
# AngelCode Bitmap Font Generator configuration file
fileVersion=1
# font settings
fontName=Titillium Web
fontFile=
charSet=0
fontSize=-48
aa=1
scaleH=110
useSmoothing=1
isBold=1
isItalic=0
useUnicode=1
disableBoxChars=1
outputInvalidCharGlyph=0
dontIncludeKerningPairs=0
useHinting=1
renderFromOutline=0
useClearType=0
# character alignment
paddingDown=0
paddingUp=0
paddingRight=0
paddingLeft=0
spacingHoriz=1
spacingVert=1
useFixedHeight=0
forceZero=0
# output file
outWidth=256
outHeight=256
outBitDepth=8
fontDescFormat=0
fourChnlPacked=0
textureFormat=png
textureCompression=0
alphaChnl=1
redChnl=0
greenChnl=0
blueChnl=0
invA=0
invR=0
invG=0
invB=0
# outline
outlineThickness=0
# selected chars
chars=48-57
# imported icon images
|
{
"pile_set_name": "Github"
}
|
import * as fs from 'fs';
import * as path from 'path';
import {
AppAnalyticsConfig,
AppCmsConfig,
AppComponentsConfig,
AppDbConfig,
AppNluConfig,
AppPlatformConfig,
BaseApp,
ExtensibleConfig,
Handler,
Host,
I18NextConfig,
Log,
Logger,
LogLevel,
Middleware,
Project,
} from 'jovo-core';
import { FileDb2 } from 'jovo-db-filedb';
import _merge = require('lodash.merge');
import { BasicLogging, Config as LoggingConfig } from './middleware/logging/BasicLogging';
import { Config as JovoUserConfig, JovoUser } from './middleware/user/JovoUser';
if (process.argv.includes('--port')) {
process.env.JOVO_PORT = process.argv[process.argv.indexOf('--port') + 1].trim();
}
if (process.argv.includes('--log-level')) {
process.env.JOVO_LOG_LEVEL =
Logger.getLogLevelFromString(process.argv[process.argv.indexOf('--log-level') + 1].trim()) + '';
}
if (process.argv.includes('--cwd')) {
process.env.JOVO_CWD = process.argv[process.argv.indexOf('--cwd') + 1].trim();
}
if (process.argv.includes('--config')) {
process.env.JOVO_CONFIG = process.argv[process.argv.indexOf('--config') + 1].trim();
}
if (process.argv.includes('--stage')) {
process.env.JOVO_STAGE = process.argv[process.argv.indexOf('--stage') + 1].trim();
}
if (process.env.JOVO_PERFORMANCE_REPORT || process.argv.includes('--performance-report')) {
const middlewareMap: Record<string, string[]> = {};
const performanceReport = process.argv[process.argv.indexOf('--performance-report') + 1]
? process.argv[process.argv.indexOf('--performance-report') + 1].trim()
: undefined;
function getInstallLocation(stackStr: string, parent: string, middleware: string) {
const stackArray = stackStr.split('\n');
for (let i = 0; i < stackArray.length; i++) {
const stackLine = stackArray[i];
if (stackLine.includes('Middleware.use')) {
const nextStackLine = stackArray[i + 1];
let pluginName = 'Object.<anonymous>';
if (!nextStackLine.includes(pluginName)) {
pluginName = nextStackLine.substring(
nextStackLine.indexOf('at') + 3,
nextStackLine.indexOf('.install'),
);
}
let location =
' - ' +
nextStackLine.substring(nextStackLine.indexOf('(') + 1, nextStackLine.indexOf(')'));
// location = location.substring(process.cwd().length - 3);
location = '';
const middlewareFullKey = `${parent}.${middleware}`;
if (!middlewareMap[middlewareFullKey]) {
middlewareMap[middlewareFullKey] = [];
}
middlewareMap[middlewareFullKey].push(`${pluginName}${location}`);
}
}
}
const oldMiddlewareUse = Middleware.prototype.use;
Middleware.prototype.use = function (fns) {
getInstallLocation(new Error().stack!, this.parent.constructor.name, this.name);
oldMiddlewareUse.call(this, fns);
return this;
};
const oldBaseAppHandle = BaseApp.prototype.handle;
BaseApp.prototype.handle = async function (host) {
Log.info();
Log.infoStart('Handle duration ');
await oldBaseAppHandle.call(this, host);
Log.infoEnd('Handle duration ');
};
const oldMiddlewareRun = Middleware.prototype.run;
Middleware.prototype.run = async function (object, concurrent) {
const start = process.hrtime();
await oldMiddlewareRun.call(this, object, concurrent);
const end = process.hrtime();
// duration of the complete middleware process
let duration = (end[1] - start[1]) / 1000 / 1000; // from nano to ms
if (duration < 0) {
duration = 0;
}
Log.writeToStreams(`\b→ ${this.parent.constructor.name}.${this.name}`, 2, false);
if (duration <= 80) {
// good value
Log.green().info(`+${duration.toFixed(0)}ms`);
} else if (duration > 80 && duration <= 200) {
// ok value
Log.yellow().info(`+${duration.toFixed(0)}ms`);
} else if (duration > 200) {
// bad value
Log.red().info(`+${duration.toFixed(0)}ms`);
}
const middlewareFullKey = `${this.parent.constructor.name}.${this.name}`;
if (middlewareMap[middlewareFullKey]) {
middlewareMap[middlewareFullKey].forEach((impl) => {
if (performanceReport === 'detailed') {
Log.dim().info(`↓ ${impl}`);
}
});
}
};
}
export class App extends BaseApp {
config: Config = {
enabled: true,
inputMap: {},
intentMap: {},
plugin: {},
};
$config: Config;
constructor(config?: Config) {
super(config);
this.$cms = {};
if (config) {
this.config = _merge(this.config, config);
}
Log.verbose();
Log.verbose(Log.header(`Verbose information ${new Date().toISOString()}`));
// sets specific cwd
if (process.env.JOVO_CWD) {
process.chdir(process.env.JOVO_CWD);
}
const pathToConfig = process.env.JOVO_CONFIG || path.join(process.cwd(), 'config.js');
if (fs.existsSync(pathToConfig)) {
const fileConfig = require(pathToConfig) || {};
this.config = _merge(fileConfig, this.config);
Log.verbose('Using ' + pathToConfig);
} else {
if (!config && (!process.env.NODE_ENV || process.env.NODE_ENV !== 'UNIT_TEST')) {
Log.warn(`WARN: Couldn't find default config.js in your project.`);
Log.warn(`WARN: Expected path: ${path.resolve(pathToConfig)}`);
}
}
const stage = process.env.JOVO_STAGE || process.env.STAGE || process.env.NODE_ENV;
if (stage) {
Log.verbose('Stage: ' + stage);
}
if (Logger.isLogLevel(LogLevel.VERBOSE)) {
const pathToPackageJsonInSrc = path.join(process.cwd(), 'package-lock.json');
const pathToPackageJsonInProject = path.join(process.cwd(), '..', 'package-lock.json');
let pathToPackageLockJson: string;
if (fs.existsSync(pathToPackageJsonInSrc)) {
pathToPackageLockJson = pathToPackageJsonInSrc;
}
if (fs.existsSync(pathToPackageJsonInProject)) {
pathToPackageLockJson = pathToPackageJsonInProject;
}
try {
const packageLockJson: any = require(pathToPackageLockJson!); // tslint:disable-line
const dependencies = Object.keys(packageLockJson.dependencies).filter((val) =>
val.startsWith('jovo-'),
);
Log.verbose(Log.header('Jovo dependencies from package-lock.json', 'jovo-framework'));
dependencies.forEach((jovoDependency: string) => {
Log.yellow().verbose(
` ${jovoDependency}@${packageLockJson.dependencies[jovoDependency].version}`,
);
});
} catch (e) {
//
}
}
const pathToStageConfig = path.join(process.cwd(), 'config.' + stage + '.js');
if (fs.existsSync(pathToStageConfig)) {
const fileStageConfig = require(pathToStageConfig) || {};
_merge(this.config, fileStageConfig);
Log.verbose(`Merging stage specific config.js for stage ${stage} `);
} else {
if (stage) {
Log.verbose(`No config file for stage ${stage}. `);
}
}
this.mergePluginConfiguration();
this.initConfig();
Log.verbose(Log.header('App object initialized', 'jovo-framework'));
this.$config = this.config;
this.init();
}
mergePluginConfiguration() {
_merge(this.config.plugin, this.config.platform);
_merge(this.config.plugin, this.config.db);
_merge(this.config.plugin, this.config.cms);
_merge(this.config.plugin, this.config.analytics);
_merge(this.config.plugin, this.config.nlu);
_merge(this.config.plugin, this.config.components);
}
initConfig() {
if (!this.config.plugin) {
this.config.plugin = {};
}
// logging
if (typeof this.config.logging !== 'undefined') {
if (typeof this.config.logging === 'boolean') {
this.config.plugin.BasicLogging = {
logging: this.config.logging,
};
} else {
this.config.plugin.BasicLogging = this.config.logging;
}
}
// user
if (typeof this.config.user !== 'undefined') {
this.config.plugin.JovoUser = this.config.user;
if (this.config.user.metaData) {
if (typeof this.config.user.metaData === 'boolean') {
if (!this.config.plugin.JovoUser.metaData) {
this.config.plugin.JovoUser.metaData = {};
}
this.config.plugin.JovoUser.metaData = {
enabled: this.config.user.metaData,
};
} else {
this.config.plugin.JovoUser.metaData = this.config.user.metaData;
}
}
if (this.config.user.context) {
if (typeof this.config.user.context === 'boolean') {
if (!this.config.plugin.JovoUser.context) {
this.config.plugin.JovoUser.context = {};
}
this.config.plugin.JovoUser.context = {
enabled: this.config.user.context,
};
} else {
this.config.plugin.JovoUser.context = this.config.user.context;
}
}
}
// inputMap
// router (intentMap)
if (this.config.intentMap) {
if (!this.config.plugin.Router) {
this.config.plugin.Router = {};
}
this.config.plugin.Router.intentMap = this.config.intentMap;
}
// router (intentsToSkipUnhandled)
if (this.config.intentsToSkipUnhandled) {
if (!this.config.plugin.Router) {
this.config.plugin.Router = {};
}
this.config.plugin.Router.intentsToSkipUnhandled = this.config.intentsToSkipUnhandled;
}
// i18next
if (this.config.i18n) {
this.config.plugin.I18Next = this.config.i18n;
}
}
init() {
this.use(new BasicLogging());
this.use(new JovoUser());
}
async handle(host: Host) {
if (host.headers && host.headers['jovo-test']) {
let fileDb2Path = './../db/tests';
// tslint:disable-next-line
if (this.$db && this.$db.config && (this.$db.config! as any).pathToFile) {
const dbPath = path.parse((this.$db.config! as any).pathToFile); // tslint:disable-line
fileDb2Path = dbPath.dir + '/tests';
}
if (host.headers['jovo-test'] === 'TestHost') {
fileDb2Path = './db/tests';
}
this.use(
new FileDb2({
path: fileDb2Path,
}),
);
}
await super.handle(host);
}
/**
* @deprecated
* @param config
*/
setConfig(config: Config) {
this.config = _merge(this.config, config);
this.mergePluginConfiguration();
this.initConfig();
this.init();
}
}
export interface Config extends ExtensibleConfig {
keepSessionDataOnSessionEnded?: boolean;
logging?: boolean | LoggingConfig;
inputMap?: { [key: string]: string };
user?: JovoUserConfig | { [key: string]: any; metaData: boolean; context: boolean }; // tslint:disable-line
i18n?: I18NextConfig;
db?: AppDbConfig;
analytics?: AppAnalyticsConfig;
platform?: AppPlatformConfig;
cms?: AppCmsConfig;
nlu?: AppNluConfig;
// components?: AppComponentsConfig;
handlers?: Handler[];
}
|
{
"pile_set_name": "Github"
}
|
var baseCallback = require('../internal/baseCallback'),
isIterateeCall = require('../internal/isIterateeCall'),
isObjectLike = require('../internal/isObjectLike'),
matches = require('./matches');
/**
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and arguments of the created function. If `func` is a property name the
* created callback returns the property value for a given element. If `func`
* is an object the created callback returns `true` for elements that contain
* the equivalent object properties, otherwise it returns `false`.
*
* @static
* @memberOf _
* @alias iteratee
* @category Utility
* @param {*} [func=_.identity] The value to convert to a callback.
* @param {*} [thisArg] The `this` binding of `func`.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Function} Returns the callback.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* // wrap to create custom callback shorthands
* _.callback = _.wrap(_.callback, function(callback, func, thisArg) {
* var match = /^(.+?)__([gl]t)(.+)$/.exec(func);
* if (!match) {
* return callback(func, thisArg);
* }
* return function(object) {
* return match[2] == 'gt'
* ? object[match[1]] > match[3]
* : object[match[1]] < match[3];
* };
* });
*
* _.filter(users, 'age__gt36');
* // => [{ 'user': 'fred', 'age': 40 }]
*/
function callback(func, thisArg, guard) {
if (guard && isIterateeCall(func, thisArg, guard)) {
thisArg = undefined;
}
return isObjectLike(func)
? matches(func)
: baseCallback(func, thisArg);
}
module.exports = callback;
|
{
"pile_set_name": "Github"
}
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/policy/core/common/schema_registry.h"
#include <memory>
#include "components/policy/core/common/policy_namespace.h"
#include "components/policy/core/common/schema.h"
#include "extensions/buildflags/buildflags.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::Mock;
using ::testing::_;
namespace policy {
namespace {
const char kTestSchema[] =
"{"
" \"type\": \"object\","
" \"properties\": {"
" \"string\": { \"type\": \"string\" },"
" \"integer\": { \"type\": \"integer\" },"
" \"boolean\": { \"type\": \"boolean\" },"
" \"null\": { \"type\": \"null\" },"
" \"double\": { \"type\": \"number\" },"
" \"list\": {"
" \"type\": \"array\","
" \"items\": { \"type\": \"string\" }"
" },"
" \"object\": {"
" \"type\": \"object\","
" \"properties\": {"
" \"a\": { \"type\": \"string\" },"
" \"b\": { \"type\": \"integer\" }"
" }"
" }"
" }"
"}";
class MockSchemaRegistryObserver : public SchemaRegistry::Observer {
public:
MockSchemaRegistryObserver() {}
~MockSchemaRegistryObserver() override {}
MOCK_METHOD1(OnSchemaRegistryUpdated, void(bool));
MOCK_METHOD0(OnSchemaRegistryReady, void());
};
bool SchemaMapEquals(const scoped_refptr<SchemaMap>& schema_map1,
const scoped_refptr<SchemaMap>& schema_map2) {
PolicyNamespaceList added;
PolicyNamespaceList removed;
schema_map1->GetChanges(schema_map2, &removed, &added);
return added.empty() && removed.empty();
}
} // namespace
TEST(SchemaRegistryTest, Notifications) {
std::string error;
Schema schema = Schema::Parse(kTestSchema, &error);
ASSERT_TRUE(schema.valid()) << error;
MockSchemaRegistryObserver observer;
SchemaRegistry registry;
registry.AddObserver(&observer);
ASSERT_TRUE(registry.schema_map().get());
EXPECT_FALSE(registry.schema_map()->GetSchema(
PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "abc")));
EXPECT_CALL(observer, OnSchemaRegistryUpdated(true));
registry.RegisterComponent(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "abc"),
schema);
Mock::VerifyAndClearExpectations(&observer);
// Re-register also triggers notifications, because the Schema might have
// changed.
EXPECT_CALL(observer, OnSchemaRegistryUpdated(true));
registry.RegisterComponent(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "abc"),
schema);
Mock::VerifyAndClearExpectations(&observer);
EXPECT_TRUE(registry.schema_map()->GetSchema(
PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "abc")));
EXPECT_CALL(observer, OnSchemaRegistryUpdated(false));
registry.UnregisterComponent(
PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "abc"));
Mock::VerifyAndClearExpectations(&observer);
EXPECT_FALSE(registry.schema_map()->GetSchema(
PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "abc")));
// Registering multiple components at once issues only one notification.
ComponentMap components;
components["abc"] = schema;
components["def"] = schema;
components["xyz"] = schema;
EXPECT_CALL(observer, OnSchemaRegistryUpdated(true));
registry.RegisterComponents(POLICY_DOMAIN_EXTENSIONS, components);
Mock::VerifyAndClearExpectations(&observer);
registry.RemoveObserver(&observer);
}
TEST(SchemaRegistryTest, IsReady) {
SchemaRegistry registry;
MockSchemaRegistryObserver observer;
registry.AddObserver(&observer);
EXPECT_FALSE(registry.IsReady());
#if BUILDFLAG(ENABLE_EXTENSIONS)
EXPECT_CALL(observer, OnSchemaRegistryReady()).Times(0);
registry.SetExtensionsDomainsReady();
Mock::VerifyAndClearExpectations(&observer);
EXPECT_FALSE(registry.IsReady());
#endif
EXPECT_CALL(observer, OnSchemaRegistryReady());
registry.SetDomainReady(POLICY_DOMAIN_CHROME);
Mock::VerifyAndClearExpectations(&observer);
EXPECT_TRUE(registry.IsReady());
EXPECT_CALL(observer, OnSchemaRegistryReady()).Times(0);
registry.SetDomainReady(POLICY_DOMAIN_CHROME);
Mock::VerifyAndClearExpectations(&observer);
EXPECT_TRUE(registry.IsReady());
CombinedSchemaRegistry combined;
EXPECT_TRUE(combined.IsReady());
registry.RemoveObserver(&observer);
}
TEST(SchemaRegistryTest, Combined) {
std::string error;
Schema schema = Schema::Parse(kTestSchema, &error);
ASSERT_TRUE(schema.valid()) << error;
MockSchemaRegistryObserver observer;
std::unique_ptr<SchemaRegistry> registry1(new SchemaRegistry);
std::unique_ptr<SchemaRegistry> registry2(new SchemaRegistry);
CombinedSchemaRegistry combined;
combined.AddObserver(&observer);
EXPECT_CALL(observer, OnSchemaRegistryUpdated(_)).Times(0);
registry1->RegisterComponent(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "abc"),
schema);
Mock::VerifyAndClearExpectations(&observer);
// Starting to track a registry issues notifications when it comes with new
// schemas.
EXPECT_CALL(observer, OnSchemaRegistryUpdated(true));
combined.Track(registry1.get());
Mock::VerifyAndClearExpectations(&observer);
// Adding a new empty registry does not trigger notifications.
EXPECT_CALL(observer, OnSchemaRegistryUpdated(_)).Times(0);
combined.Track(registry2.get());
Mock::VerifyAndClearExpectations(&observer);
// Adding the same component to the combined registry itself triggers
// notifications.
EXPECT_CALL(observer, OnSchemaRegistryUpdated(true));
combined.RegisterComponent(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "abc"),
schema);
Mock::VerifyAndClearExpectations(&observer);
// Adding components to the sub-registries triggers notifications.
EXPECT_CALL(observer, OnSchemaRegistryUpdated(true));
registry2->RegisterComponent(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "def"),
schema);
Mock::VerifyAndClearExpectations(&observer);
// If the same component is published in 2 sub-registries then the combined
// registry publishes one of them.
EXPECT_CALL(observer, OnSchemaRegistryUpdated(true));
registry1->RegisterComponent(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "def"),
schema);
Mock::VerifyAndClearExpectations(&observer);
ASSERT_EQ(1u, combined.schema_map()->GetDomains().size());
ASSERT_TRUE(combined.schema_map()->GetComponents(POLICY_DOMAIN_EXTENSIONS));
ASSERT_EQ(
2u,
combined.schema_map()->GetComponents(POLICY_DOMAIN_EXTENSIONS)->size());
EXPECT_TRUE(combined.schema_map()->GetSchema(
PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "abc")));
EXPECT_TRUE(combined.schema_map()->GetSchema(
PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "def")));
EXPECT_FALSE(combined.schema_map()->GetSchema(
PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "xyz")));
EXPECT_CALL(observer, OnSchemaRegistryUpdated(false));
registry1->UnregisterComponent(
PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "abc"));
Mock::VerifyAndClearExpectations(&observer);
// Still registered at the combined registry.
EXPECT_TRUE(combined.schema_map()->GetSchema(
PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "abc")));
EXPECT_CALL(observer, OnSchemaRegistryUpdated(false));
combined.UnregisterComponent(
PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "abc"));
Mock::VerifyAndClearExpectations(&observer);
// Now it's gone.
EXPECT_FALSE(combined.schema_map()->GetSchema(
PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "abc")));
EXPECT_CALL(observer, OnSchemaRegistryUpdated(false));
registry1->UnregisterComponent(
PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "def"));
Mock::VerifyAndClearExpectations(&observer);
// Still registered at registry2.
EXPECT_TRUE(combined.schema_map()->GetSchema(
PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "def")));
EXPECT_CALL(observer, OnSchemaRegistryUpdated(false));
registry2->UnregisterComponent(
PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "def"));
Mock::VerifyAndClearExpectations(&observer);
// Now it's gone.
EXPECT_FALSE(combined.schema_map()->GetSchema(
PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "def")));
EXPECT_CALL(observer, OnSchemaRegistryUpdated(true)).Times(2);
registry1->RegisterComponent(PolicyNamespace(POLICY_DOMAIN_CHROME, ""),
schema);
registry2->RegisterComponent(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "hij"),
schema);
Mock::VerifyAndClearExpectations(&observer);
// Untracking |registry1| doesn't trigger an update notification, because it
// doesn't contain any components.
EXPECT_CALL(observer, OnSchemaRegistryUpdated(_)).Times(0);
registry1.reset();
Mock::VerifyAndClearExpectations(&observer);
EXPECT_CALL(observer, OnSchemaRegistryUpdated(false));
registry2.reset();
Mock::VerifyAndClearExpectations(&observer);
combined.RemoveObserver(&observer);
}
TEST(SchemaRegistryTest, ForwardingSchemaRegistry) {
std::unique_ptr<SchemaRegistry> registry(new SchemaRegistry);
ForwardingSchemaRegistry forwarding(registry.get());
MockSchemaRegistryObserver observer;
forwarding.AddObserver(&observer);
EXPECT_FALSE(registry->IsReady());
EXPECT_FALSE(forwarding.IsReady());
// They always have the same SchemaMap.
EXPECT_TRUE(SchemaMapEquals(registry->schema_map(), forwarding.schema_map()));
EXPECT_CALL(observer, OnSchemaRegistryUpdated(true));
registry->RegisterComponent(PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "abc"),
Schema());
Mock::VerifyAndClearExpectations(&observer);
EXPECT_TRUE(SchemaMapEquals(registry->schema_map(), forwarding.schema_map()));
EXPECT_CALL(observer, OnSchemaRegistryUpdated(false));
registry->UnregisterComponent(
PolicyNamespace(POLICY_DOMAIN_EXTENSIONS, "abc"));
Mock::VerifyAndClearExpectations(&observer);
EXPECT_TRUE(SchemaMapEquals(registry->schema_map(), forwarding.schema_map()));
// No notifications expected for these calls.
EXPECT_FALSE(registry->IsReady());
EXPECT_FALSE(forwarding.IsReady());
registry->SetExtensionsDomainsReady();
EXPECT_FALSE(registry->IsReady());
EXPECT_FALSE(forwarding.IsReady());
EXPECT_CALL(observer, OnSchemaRegistryReady());
registry->SetDomainReady(POLICY_DOMAIN_CHROME);
EXPECT_TRUE(registry->IsReady());
EXPECT_TRUE(forwarding.IsReady());
Mock::VerifyAndClearExpectations(&observer);
EXPECT_TRUE(SchemaMapEquals(registry->schema_map(), forwarding.schema_map()));
Mock::VerifyAndClearExpectations(&observer);
forwarding.SetExtensionsDomainsReady();
forwarding.SetDomainReady(POLICY_DOMAIN_CHROME);
EXPECT_TRUE(forwarding.IsReady());
// Keep the same SchemaMap when the original registry is gone.
// No notifications are expected in this case either.
scoped_refptr<SchemaMap> schema_map = registry->schema_map();
registry.reset();
EXPECT_TRUE(SchemaMapEquals(schema_map, forwarding.schema_map()));
Mock::VerifyAndClearExpectations(&observer);
forwarding.RemoveObserver(&observer);
}
TEST(SchemaRegistryTest, ForwardingSchemaRegistryReadiness) {
std::unique_ptr<SchemaRegistry> registry(new SchemaRegistry);
ForwardingSchemaRegistry forwarding_1(registry.get());
EXPECT_FALSE(registry->IsReady());
EXPECT_FALSE(forwarding_1.IsReady());
// Once the wrapped registry gets ready, the forwarding schema registry
// becomes ready too.
registry->SetAllDomainsReady();
EXPECT_TRUE(registry->IsReady());
EXPECT_TRUE(forwarding_1.IsReady());
// The wrapped registry was ready at the time when the forwarding registry was
// constructed, so the forwarding registry is immediately ready too.
ForwardingSchemaRegistry forwarding_2(registry.get());
EXPECT_TRUE(forwarding_2.IsReady());
// Destruction of the wrapped registry doesn't change the readiness of the
// forwarding registry.
registry.reset();
EXPECT_TRUE(forwarding_1.IsReady());
EXPECT_TRUE(forwarding_2.IsReady());
}
} // namespace policy
|
{
"pile_set_name": "Github"
}
|
package network
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// DefaultSecurityRulesClient is the network Client
type DefaultSecurityRulesClient struct {
ManagementClient
}
// NewDefaultSecurityRulesClient creates an instance of the DefaultSecurityRulesClient client.
func NewDefaultSecurityRulesClient(subscriptionID string) DefaultSecurityRulesClient {
return NewDefaultSecurityRulesClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewDefaultSecurityRulesClientWithBaseURI creates an instance of the DefaultSecurityRulesClient client.
func NewDefaultSecurityRulesClientWithBaseURI(baseURI string, subscriptionID string) DefaultSecurityRulesClient {
return DefaultSecurityRulesClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Get get the specified default network security rule.
//
// resourceGroupName is the name of the resource group. networkSecurityGroupName is the name of the network security
// group. defaultSecurityRuleName is the name of the default security rule.
func (client DefaultSecurityRulesClient) Get(resourceGroupName string, networkSecurityGroupName string, defaultSecurityRuleName string) (result SecurityRule, err error) {
req, err := client.GetPreparer(resourceGroupName, networkSecurityGroupName, defaultSecurityRuleName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client DefaultSecurityRulesClient) GetPreparer(resourceGroupName string, networkSecurityGroupName string, defaultSecurityRuleName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"defaultSecurityRuleName": autorest.Encode("path", defaultSecurityRuleName),
"networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-09-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/defaultSecurityRules/{defaultSecurityRuleName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare(&http.Request{})
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client DefaultSecurityRulesClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client,
req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client DefaultSecurityRulesClient) GetResponder(resp *http.Response) (result SecurityRule, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List gets all default security rules in a network security group.
//
// resourceGroupName is the name of the resource group. networkSecurityGroupName is the name of the network security
// group.
func (client DefaultSecurityRulesClient) List(resourceGroupName string, networkSecurityGroupName string) (result SecurityRuleListResult, err error) {
req, err := client.ListPreparer(resourceGroupName, networkSecurityGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", resp, "Failure sending request")
return
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client DefaultSecurityRulesClient) ListPreparer(resourceGroupName string, networkSecurityGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-09-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/defaultSecurityRules", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare(&http.Request{})
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client DefaultSecurityRulesClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client,
req,
azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client DefaultSecurityRulesClient) ListResponder(resp *http.Response) (result SecurityRuleListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListNextResults retrieves the next set of results, if any.
func (client DefaultSecurityRulesClient) ListNextResults(lastResults SecurityRuleListResult) (result SecurityRuleListResult, err error) {
req, err := lastResults.SecurityRuleListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", resp, "Failure responding to next results request")
}
return
}
// ListComplete gets all elements from the list without paging.
func (client DefaultSecurityRulesClient) ListComplete(resourceGroupName string, networkSecurityGroupName string, cancel <-chan struct{}) (<-chan SecurityRule, <-chan error) {
resultChan := make(chan SecurityRule)
errChan := make(chan error, 1)
go func() {
defer func() {
close(resultChan)
close(errChan)
}()
list, err := client.List(resourceGroupName, networkSecurityGroupName)
if err != nil {
errChan <- err
return
}
if list.Value != nil {
for _, item := range *list.Value {
select {
case <-cancel:
return
case resultChan <- item:
// Intentionally left blank
}
}
}
for list.NextLink != nil {
list, err = client.ListNextResults(list)
if err != nil {
errChan <- err
return
}
if list.Value != nil {
for _, item := range *list.Value {
select {
case <-cancel:
return
case resultChan <- item:
// Intentionally left blank
}
}
}
}
}()
return resultChan, errChan
}
|
{
"pile_set_name": "Github"
}
|
html,
body {
width: 100%;
height: 100%;
}
body {
color: #cdcccc;
overflow: auto;
margin: 0;
}
#content {
width: 400px;
min-height: 400px;
margin: 0 auto;
background-color: #333333;
text-align: center;
}
#hello_message {
padding-top: 20px;
margin-bottom: 20px;
}
#file_system {
margin: 0 auto;
width: 300px;
padding-bottom: 20px;
text-align: left;
}
.child_desc {
text-decoration: underline;
}
.child_desc:hover{
cursor: pointer;
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.mail.dsn;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import jakarta.activation.*;
import jakarta.mail.*;
import jakarta.mail.internet.*;
import com.sun.mail.util.LineOutputStream; // XXX
import com.sun.mail.util.PropUtil;
import com.sun.mail.util.MailLogger;
/**
* A message/delivery-status message content, as defined in
* <A HREF="http://www.ietf.org/rfc/rfc3464.txt" TARGET="_top">RFC 3464</A>.
*
* @since JavaMail 1.4
*/
public class DeliveryStatus extends Report {
private static MailLogger logger = new MailLogger(
DeliveryStatus.class,
"DEBUG DSN",
PropUtil.getBooleanSystemProperty("mail.dsn.debug", false),
System.out);
/**
* The DSN fields for the message.
*/
protected InternetHeaders messageDSN;
/**
* The DSN fields for each recipient.
*/
protected InternetHeaders[] recipientDSN;
/**
* Construct a delivery status notification with no content.
*
* @exception MessagingException for failures
*/
public DeliveryStatus() throws MessagingException {
super("delivery-status");
messageDSN = new InternetHeaders();
recipientDSN = new InternetHeaders[0];
}
/**
* Construct a delivery status notification by parsing the
* supplied input stream.
*
* @param is the input stream
* @exception IOException for I/O errors reading the stream
* @exception MessagingException for other failures
*/
public DeliveryStatus(InputStream is)
throws MessagingException, IOException {
super("delivery-status");
messageDSN = new InternetHeaders(is);
logger.fine("got messageDSN");
Vector<InternetHeaders> v = new Vector<>();
try {
while (is.available() > 0) {
InternetHeaders h = new InternetHeaders(is);
logger.fine("got recipientDSN");
v.addElement(h);
}
} catch (EOFException ex) {
logger.log(Level.FINE, "got EOFException", ex);
}
if (logger.isLoggable(Level.FINE))
logger.fine("recipientDSN size " + v.size());
recipientDSN = new InternetHeaders[v.size()];
v.copyInto(recipientDSN);
}
/**
* Return all the per-message fields in the delivery status notification.
* The fields are defined as:
*
* <pre>
* per-message-fields =
* [ original-envelope-id-field CRLF ]
* reporting-mta-field CRLF
* [ dsn-gateway-field CRLF ]
* [ received-from-mta-field CRLF ]
* [ arrival-date-field CRLF ]
* *( extension-field CRLF )
* </pre>
*
* @return the per-message DSN fields
*/
// XXX - could parse each of these fields
public InternetHeaders getMessageDSN() {
return messageDSN;
}
/**
* Set the per-message fields in the delivery status notification.
*
* @param messageDSN the per-message DSN fields
*/
public void setMessageDSN(InternetHeaders messageDSN) {
this.messageDSN = messageDSN;
}
/**
* Return the number of recipients for which we have
* per-recipient delivery status notification information.
*
* @return the number of recipients
*/
public int getRecipientDSNCount() {
return recipientDSN.length;
}
/**
* Return the delivery status notification information for
* the specified recipient.
*
* @param n the recipient number
* @return the DSN fields for the recipient
*/
public InternetHeaders getRecipientDSN(int n) {
return recipientDSN[n];
}
/**
* Add deliver status notification information for another
* recipient.
*
* @param h the DSN fields for the recipient
*/
public void addRecipientDSN(InternetHeaders h) {
InternetHeaders[] rh = new InternetHeaders[recipientDSN.length + 1];
System.arraycopy(recipientDSN, 0, rh, 0, recipientDSN.length);
recipientDSN = rh;
recipientDSN[recipientDSN.length - 1] = h;
}
public void writeTo(OutputStream os) throws IOException {
// see if we already have a LOS
LineOutputStream los = null;
if (os instanceof LineOutputStream) {
los = (LineOutputStream) os;
} else {
los = new LineOutputStream(os);
}
writeInternetHeaders(messageDSN, los);
los.writeln();
for (int i = 0; i < recipientDSN.length; i++) {
writeInternetHeaders(recipientDSN[i], los);
los.writeln();
}
}
private static void writeInternetHeaders(InternetHeaders h,
LineOutputStream los) throws IOException {
Enumeration e = h.getAllHeaderLines();
while (e.hasMoreElements())
los.writeln((String)e.nextElement());
}
public String toString() {
return "DeliveryStatus: Reporting-MTA=" +
messageDSN.getHeader("Reporting-MTA", null) + ", #Recipients=" +
recipientDSN.length;
}
}
|
{
"pile_set_name": "Github"
}
|
(**************************************************************************)
(* *)
(* OCaml *)
(* *)
(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
(* *)
(* Copyright 1996 Institut National de Recherche en Informatique et *)
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
(* the GNU Lesser General Public License version 2.1, with the *)
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(***********************************************************************)
(** **)
(** WARNING WARNING WARNING **)
(** **)
(** When you change this file, you must make the parallel change **)
(** in config.mlbuild **)
(** **)
(***********************************************************************)
open Local_store.Compiler
(* The main OCaml version string has moved to ../VERSION *)
let version = Sys.ocaml_version
let exec_magic_number = "Caml1999X011"
and cmi_magic_number = "Caml1999I021"
and cmo_magic_number = "Caml1999O011"
and cma_magic_number = "Caml1999A012"
and cmx_magic_number =
(*if flambda then
"Caml1999Y016"
else*)
"Caml1999Y015"
and cmxa_magic_number =
(*if flambda then
"Caml1999Z015"
else*)
"Caml1999Z014"
and ast_impl_magic_number = "Caml1999M020"
and ast_intf_magic_number = "Caml1999N018"
and cmxs_magic_number = "Caml2007D002"
and cmt_magic_number = "Caml2012T008"
let load_path = srefk ([] : string list)
let interface_suffix = ref ".mli"
let max_tag = 245
let safe_string = false
|
{
"pile_set_name": "Github"
}
|
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "CommonCorePch.h"
#ifdef PROFILE_MEM
#include "Memory/AutoPtr.h"
#include "Core/ProfileMemory.h"
THREAD_LOCAL MemoryProfiler * MemoryProfiler::Instance = nullptr;
CriticalSection MemoryProfiler::s_cs;
AutoPtr<MemoryProfiler, NoCheckHeapAllocator> MemoryProfiler::profilers(nullptr);
MemoryProfiler::MemoryProfiler() :
pageAllocator(nullptr, Js::Configuration::Global.flags,
PageAllocatorType_Max, 0, false
#if ENABLE_BACKGROUND_PAGE_FREEING
, nullptr
#endif
),
alloc(_u("MemoryProfiler"), &pageAllocator, Js::Throw::OutOfMemory),
arenaDataMap(&alloc, 10)
{
threadId = ::GetCurrentThreadId();
memset(&pageMemoryData, 0, sizeof(pageMemoryData));
memset(&recyclerMemoryData, 0, sizeof(recyclerMemoryData));
}
MemoryProfiler::~MemoryProfiler()
{
#if DBG
pageAllocator.SetDisableThreadAccessCheck();
#endif
if (next != nullptr)
{
NoCheckHeapDelete(next);
}
}
MemoryProfiler *
MemoryProfiler::EnsureMemoryProfiler()
{
MemoryProfiler * memoryProfiler = MemoryProfiler::Instance;
if (memoryProfiler == nullptr)
{
memoryProfiler = NoCheckHeapNew(MemoryProfiler);
{
AutoCriticalSection autocs(&s_cs);
memoryProfiler->next = MemoryProfiler::profilers.Detach();
MemoryProfiler::profilers = memoryProfiler;
}
MemoryProfiler::Instance = memoryProfiler;
}
return memoryProfiler;
}
PageMemoryData *
MemoryProfiler::GetPageMemoryData(PageAllocatorType type)
{
if (!Js::Configuration::Global.flags.IsEnabled(Js::TraceMemoryFlag))
{
return nullptr;
}
if (type == PageAllocatorType_Max)
{
return nullptr;
}
MemoryProfiler * memoryProfiler = EnsureMemoryProfiler();
return &memoryProfiler->pageMemoryData[type];
}
RecyclerMemoryData *
MemoryProfiler::GetRecyclerMemoryData()
{
if (!Js::Configuration::Global.flags.IsEnabled(Js::TraceMemoryFlag))
{
return nullptr;
}
MemoryProfiler * memoryProfiler = EnsureMemoryProfiler();
return &memoryProfiler->recyclerMemoryData;
}
ArenaMemoryData *
MemoryProfiler::Begin(LPCWSTR name)
{
if (!Js::Configuration::Global.flags.IsEnabled(Js::TraceMemoryFlag))
{
return nullptr;
}
Assert(name != nullptr);
if (wcscmp(name, _u("MemoryProfiler")) == 0)
{
// Don't profile memory profiler itself
return nullptr;
}
// This is debug only code, we don't care if we catch the right exception
AUTO_NESTED_HANDLED_EXCEPTION_TYPE(ExceptionType_DisableCheck);
MemoryProfiler * memoryProfiler = EnsureMemoryProfiler();
ArenaMemoryDataSummary * arenaTotalMemoryData;
if (!memoryProfiler->arenaDataMap.TryGetValue((LPWSTR)name, &arenaTotalMemoryData))
{
arenaTotalMemoryData = AnewStructZ(&memoryProfiler->alloc, ArenaMemoryDataSummary);
memoryProfiler->arenaDataMap.Add((LPWSTR)name, arenaTotalMemoryData);
}
arenaTotalMemoryData->arenaCount++;
ArenaMemoryData * memoryData = AnewStructZ(&memoryProfiler->alloc, ArenaMemoryData);
if (arenaTotalMemoryData->data == nullptr)
{
arenaTotalMemoryData->data = memoryData;
}
else
{
memoryData->next = arenaTotalMemoryData->data;
arenaTotalMemoryData->data->prev = memoryData;
arenaTotalMemoryData->data = memoryData;
}
memoryData->profiler = memoryProfiler;
return memoryData;
}
void
MemoryProfiler::Reset(LPCWSTR name, ArenaMemoryData * memoryData)
{
MemoryProfiler * memoryProfiler = memoryData->profiler;
ArenaMemoryDataSummary * arenaMemoryDataSummary;
bool hasItem = memoryProfiler->arenaDataMap.TryGetValue((LPWSTR)name, &arenaMemoryDataSummary);
Assert(hasItem);
AccumulateData(arenaMemoryDataSummary, memoryData, true);
memoryData->allocatedBytes = 0;
memoryData->alignmentBytes = 0;
memoryData->requestBytes = 0;
memoryData->requestCount = 0;
memoryData->reuseBytes = 0;
memoryData->reuseCount = 0;
memoryData->freelistBytes = 0;
memoryData->freelistCount = 0;
memoryData->resetCount++;
}
void
MemoryProfiler::End(LPCWSTR name, ArenaMemoryData * memoryData)
{
MemoryProfiler * memoryProfiler = memoryData->profiler;
ArenaMemoryDataSummary * arenaMemoryDataSummary;
bool hasItem = memoryProfiler->arenaDataMap.TryGetValue((LPWSTR)name, &arenaMemoryDataSummary);
Assert(hasItem);
if (memoryData->next != nullptr)
{
memoryData->next->prev = memoryData->prev;
}
if (memoryData->prev != nullptr)
{
memoryData->prev->next = memoryData->next;
}
else
{
Assert(arenaMemoryDataSummary->data == memoryData);
arenaMemoryDataSummary->data = memoryData->next;
}
AccumulateData(arenaMemoryDataSummary, memoryData);
}
void
MemoryProfiler::AccumulateData(ArenaMemoryDataSummary * arenaMemoryDataSummary, ArenaMemoryData * memoryData, bool reset)
{
arenaMemoryDataSummary->total.alignmentBytes += memoryData->alignmentBytes;
arenaMemoryDataSummary->total.allocatedBytes += memoryData->allocatedBytes;
arenaMemoryDataSummary->total.freelistBytes += memoryData->freelistBytes;
arenaMemoryDataSummary->total.freelistCount += memoryData->freelistCount;
arenaMemoryDataSummary->total.requestBytes += memoryData->requestBytes;
arenaMemoryDataSummary->total.requestCount += memoryData->requestCount;
arenaMemoryDataSummary->total.reuseCount += memoryData->reuseCount;
arenaMemoryDataSummary->total.reuseBytes += memoryData->reuseBytes;
if (!reset)
{
arenaMemoryDataSummary->total.resetCount += memoryData->resetCount;
}
arenaMemoryDataSummary->max.alignmentBytes = max(arenaMemoryDataSummary->max.alignmentBytes, memoryData->alignmentBytes);
arenaMemoryDataSummary->max.allocatedBytes = max(arenaMemoryDataSummary->max.allocatedBytes, memoryData->allocatedBytes);
arenaMemoryDataSummary->max.freelistBytes = max(arenaMemoryDataSummary->max.freelistBytes, memoryData->freelistBytes);
arenaMemoryDataSummary->max.freelistCount = max(arenaMemoryDataSummary->max.freelistCount, memoryData->freelistCount);
arenaMemoryDataSummary->max.requestBytes = max(arenaMemoryDataSummary->max.requestBytes, memoryData->requestBytes);
arenaMemoryDataSummary->max.requestCount = max(arenaMemoryDataSummary->max.requestCount, memoryData->requestCount);
arenaMemoryDataSummary->max.reuseCount = max(arenaMemoryDataSummary->max.reuseCount, memoryData->reuseCount);
arenaMemoryDataSummary->max.reuseBytes = max(arenaMemoryDataSummary->max.reuseBytes, memoryData->reuseBytes);
if (!reset)
{
arenaMemoryDataSummary->max.resetCount = max(arenaMemoryDataSummary->max.resetCount, memoryData->resetCount);
}
}
void
MemoryProfiler::PrintPageMemoryData(PageMemoryData const& pageMemoryData, char const * title)
{
if (pageMemoryData.allocSegmentCount != 0)
{
Output::Print(_u("%-10S:%9d %10d | %4d %10d | %4d %10d | %10d | %10d | %10d | %10d\n"), title,
pageMemoryData.currentCommittedPageCount * AutoSystemInfo::PageSize, pageMemoryData.peakCommittedPageCount * AutoSystemInfo::PageSize,
pageMemoryData.allocSegmentCount, pageMemoryData.allocSegmentBytes,
pageMemoryData.releaseSegmentCount, pageMemoryData.releaseSegmentBytes,
pageMemoryData.allocPageCount * AutoSystemInfo::PageSize,
pageMemoryData.releasePageCount * AutoSystemInfo::PageSize,
pageMemoryData.decommitPageCount * AutoSystemInfo::PageSize,
pageMemoryData.recommitPageCount * AutoSystemInfo::PageSize);
}
}
void
MemoryProfiler::Print()
{
Output::Print(_u("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n"));
Output::Print(_u("Allocation for thread 0x%08X\n"), threadId);
Output::Print(_u("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n"));
bool hasData = false;
for (int i = 0; i < PageAllocatorType_Max; i++)
{
if (pageMemoryData[i].allocSegmentCount != 0)
{
hasData = true;
break;
}
}
if (hasData)
{
Output::Print(_u("%-10s:%-20s | %-15s | %-15s | %10s | %10s | %11s | %11s\n"), _u(""), _u(" Current"), _u(" Alloc Seg"), _u(" Free Seg"),
_u("Request"), _u("Released"), _u("Decommitted"), _u("Recommitted"));
Output::Print(_u("%-10s:%9s %10s | %4s %10s | %4s %10s | %10s | %10s | %10s | %10s\n"), _u(""), _u("Bytes"), _u("Peak"), _u("#"), _u("Bytes"), _u("#"), _u("Bytes"),
_u("Bytes"), _u("Bytes"), _u("Bytes"), _u("Bytes"));
Output::Print(_u("------------------------------------------------------------------------------------------------------------------\n"));
#define PAGEALLOCATOR_PRINT(i) PrintPageMemoryData(pageMemoryData[PageAllocatorType_ ## i], STRINGIZE(i));
PAGE_ALLOCATOR_TYPE(PAGEALLOCATOR_PRINT);
Output::Print(_u("------------------------------------------------------------------------------------------------------------------\n"));
}
if (recyclerMemoryData.requestCount != 0)
{
Output::Print(_u("%-10s:%7s %10s %10s %10s\n"),
_u("Recycler"),
_u("#Alloc"),
_u("AllocBytes"),
_u("ReqBytes"),
_u("AlignByte"));
Output::Print(_u("--------------------------------------------------------------------------------------------------------\n"));
Output::Print(_u("%-10s:%7d %10d %10d %10d\n"),
_u(""),
recyclerMemoryData.requestCount,
recyclerMemoryData.requestBytes + recyclerMemoryData.alignmentBytes,
recyclerMemoryData.requestBytes,
recyclerMemoryData.alignmentBytes);
Output::Print(_u("--------------------------------------------------------------------------------------------------------\n"));
}
if (Js::Configuration::Global.flags.TraceMemory.IsEnabled(Js::AllPhase))
{
PrintArena(false);
}
PrintArena(true);
}
void
MemoryProfiler::PrintArenaHeader(char16 const * title)
{
Output::Print(_u("--------------------------------------------------------------------------------------------------------\n"));
Output::Print(_u("%-20s:%7s %9s %9s %9s %6s %9s %6s %9s %5s | %5s\n"),
title,
_u("#Alloc"),
_u("AllocByte"),
_u("ReqBytes"),
_u("AlignByte"),
_u("#Reuse"),
_u("ReuseByte"),
_u("#Free"),
_u("FreeBytes"),
_u("Reset"),
_u("Count"));
Output::Print(_u("--------------------------------------------------------------------------------------------------------\n"));
}
int MemoryProfiler::CreateArenaUsageSummary(ArenaAllocator * alloc, bool liveOnly,
_Outptr_result_buffer_(return) LPWSTR ** name_ptr, _Outptr_result_buffer_(return) ArenaMemoryDataSummary *** summaries_ptr)
{
Assert(alloc);
LPWSTR *& name = *name_ptr;
ArenaMemoryDataSummary **& summaries = *summaries_ptr;
int count = arenaDataMap.Count();
name = AnewArray(alloc, LPWSTR, count);
int i = 0;
arenaDataMap.Map([&i, name](LPWSTR key, ArenaMemoryDataSummary*)
{
name[i++] = key;
});
qsort_s(name, count, sizeof(LPWSTR), [](void*, const void* a, const void* b) { return DefaultComparer<LPWSTR>::Compare(*(LPWSTR*)a, *(LPWSTR*)b); }, nullptr);
summaries = AnewArray(alloc, ArenaMemoryDataSummary *, count);
for (int j = 0; j < count; j++)
{
ArenaMemoryDataSummary * summary = arenaDataMap.Item(name[j]);
ArenaMemoryData * data = summary->data;
ArenaMemoryDataSummary * localSummary;
if (liveOnly)
{
if (data == nullptr)
{
summaries[j] = nullptr;
continue;
}
localSummary = AnewStructZ(alloc, ArenaMemoryDataSummary);
}
else
{
localSummary = Anew(alloc, ArenaMemoryDataSummary, *summary);
}
while (data != nullptr)
{
localSummary->outstandingCount++;
AccumulateData(localSummary, data);
data = data->next;
}
if (liveOnly)
{
localSummary->arenaCount = localSummary->outstandingCount;
}
summaries[j] = localSummary;
}
return count;
}
void
MemoryProfiler::PrintArena(bool liveOnly)
{
WithArenaUsageSummary(liveOnly, [&] (int count, _In_reads_(count) LPWSTR * name, _In_reads_(count) ArenaMemoryDataSummary ** summaries)
{
int i = 0;
if (liveOnly)
{
Output::Print(_u("Arena usage summary (live)\n"));
}
else
{
Output::Print(_u("Arena usage summary (all)\n"));
}
bool header = false;
for (i = 0; i < count; i++)
{
ArenaMemoryDataSummary * data = summaries[i];
if (data == nullptr)
{
continue;
}
if (!header)
{
header = true;
PrintArenaHeader(_u("Arena Size"));
}
Output::Print(_u("%-20s %7d %9d %9d %9d %6d %9d %6d %9d %5d | %5d\n"),
name[i],
data->total.requestCount,
data->total.allocatedBytes,
data->total.requestBytes,
data->total.alignmentBytes,
data->total.reuseCount,
data->total.reuseBytes,
data->total.freelistCount,
data->total.freelistBytes,
data->total.resetCount,
data->arenaCount);
}
header = false;
for (i = 0; i < count; i++)
{
ArenaMemoryDataSummary * data = summaries[i];
if (data == nullptr)
{
continue;
}
if (!header)
{
header = true;
PrintArenaHeader(_u("Arena Max"));
}
Output::Print(_u("%-20s %7d %9d %9d %9d %6d %9d %6d %9d %5d | %5d\n"),
name[i],
data->max.requestCount,
data->max.allocatedBytes,
data->max.requestBytes,
data->max.alignmentBytes,
data->max.reuseCount,
data->max.reuseBytes,
data->max.freelistCount, data->max.freelistBytes,
data->max.resetCount, data->outstandingCount);
}
header = false;
for (i = 0; i < count; i++)
{
ArenaMemoryDataSummary * data = summaries[i];
if (data == nullptr)
{
continue;
}
if (!header)
{
header = true;
PrintArenaHeader(_u("Arena Average"));
}
Output::Print(_u("%-20s %7d %9d %9d %9d %6d %9d %6d %9d %5d\n"), name[i],
data->total.requestCount / data->arenaCount,
data->total.allocatedBytes / data->arenaCount,
data->total.requestBytes / data->arenaCount,
data->total.alignmentBytes / data->arenaCount,
data->total.reuseCount / data->arenaCount,
data->total.reuseBytes / data->arenaCount,
data->total.freelistCount / data->arenaCount,
data->total.freelistBytes / data->arenaCount,
data->total.resetCount / data->arenaCount);
}
Output::Print(_u("--------------------------------------------------------------------------------------------------------\n"));
});
}
void
MemoryProfiler::PrintCurrentThread()
{
MemoryProfiler* instance = NULL;
instance = MemoryProfiler::Instance;
Output::Print(_u("========================================================================================================\n"));
Output::Print(_u("Memory Profile (Current thread)\n"));
if (instance != nullptr)
{
instance->Print();
}
Output::Flush();
}
void
MemoryProfiler::PrintAll()
{
Output::Print(_u("========================================================================================================\n"));
Output::Print(_u("Memory Profile (All threads)\n"));
ForEachProfiler([] (MemoryProfiler * memoryProfiler)
{
memoryProfiler->Print();
});
Output::Flush();
}
bool
MemoryProfiler::IsTraceEnabled(bool isRecycler)
{
if (!Js::Configuration::Global.flags.IsEnabled(Js::TraceMemoryFlag))
{
return false;
}
if (Js::Configuration::Global.flags.TraceMemory.IsEnabled(Js::AllPhase))
{
return true;
}
if (!isRecycler)
{
return (Js::Configuration::Global.flags.TraceMemory.IsEnabled(Js::RunPhase)
|| Js::Configuration::Global.flags.TraceMemory.GetFirstPhase() == Js::InvalidPhase);
}
return Js::Configuration::Global.flags.TraceMemory.IsEnabled(Js::RecyclerPhase);
}
bool
MemoryProfiler::IsEnabled()
{
return Js::Configuration::Global.flags.IsEnabled(Js::ProfileMemoryFlag);
}
bool
MemoryProfiler::DoTrackRecyclerAllocation()
{
return MemoryProfiler::IsEnabled() || MemoryProfiler::IsTraceEnabled(true) || MemoryProfiler::IsTraceEnabled(false);
}
#endif
|
{
"pile_set_name": "Github"
}
|
<?php
/*************************************************************************************
* falcon.php
* ---------------------------------
* Author: billykater (billykater+geshi@gmail.com)
* Copyright: (c) 2010 billykater (http://falconpl.org/)
* Release Version: 1.0.8.10
* Date Started: 2010/06/07
*
* Falcon language file for GeSHi.
*
* CHANGES
* -------
* <2010/8/1> (1.0.8.10)
* - First Release
*
*************************************************************************************
*
* This file is part of GeSHi.
*
* GeSHi 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.
*
* GeSHi 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 GeSHi; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* ************************************************************************************/
$language_data = array (
'LANG_NAME' => 'Falcon',
'COMMENT_SINGLE' => array( 1 => '//' ),
'COMMENT_MULTI' => array( '/*' => '*/' ),
'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE,
'QUOTEMARKS' => array( "'", '"' ),
'ESCAPE_CHAR' => '\\',
'KEYWORDS' => array(
1 => array(
'break','case','catch','class','const','continue','def','default',
'dropping','elif','else','end','enum','for','forfirst','forlast',
'formiddle','from','function','global','if','init','innerfunc',
'launch','loop','object','raise','return','select','state','static',
'switch','try','while'
),
2 => array(
'false','nil','true',
),
3 => array(
'and','as','eq','fself','in','not','notin','or','provides','self','to'
),
4 => array(
'directive','export','import','load','macro'
),
5 => array(
'ArrayType','BooleanType','ClassMethodType','ClassType','DictionaryType',
'FunctionType','MemBufType','MethodType','NilType','NumericType','ObjectType',
'RangeType','StringType','LBindType'
),
6 => array(
"CurrentTime","IOStream","InputStream","MemBufFromPtr","OutputStream",
"PageDict","ParseRFC2822","abs","acos","all",
"allp","any","anyp","argd","argv",
"arrayAdd","arrayBuffer","arrayCompact","arrayDel","arrayDelAll",
"arrayFill","arrayFind","arrayHead","arrayIns","arrayMerge",
"arrayNM","arrayRemove","arrayResize","arrayScan","arraySort",
"arrayTail","asin","assert","atan","atan2",
"attributes","baseClass","beginCritical","bless","brigade",
"broadcast","cascade","ceil","choice","chr",
"className","clone","combinations","compare","consume",
"cos","deg2rad","deoob","derivedFrom","describe",
"deserialize","dictBack","dictBest","dictClear","dictFill",
"dictFind","dictFront","dictGet","dictKeys","dictMerge",
"dictRemove","dictSet","dictValues","dirChange","dirCurrent",
"dirMake","dirMakeLink","dirReadLink","dirRemove","dolist",
"endCritical","epoch","eval","exit","exp",
"factorial","fileChgroup","fileChmod","fileChown","fileCopy",
"fileExt","fileMove","fileName","fileNameMerge","filePath",
"fileRemove","fileType","fileUnit","filter","fint",
"firstOf","floop","floor","fract","getAssert",
"getEnviron","getProperty","getSlot","getSystemEncoding","getenv",
"iff","include","input","inspect","int",
"isBound","isCallable","isoob","lbind","len",
"let","lit","log","map","max",
"metaclass","min","numeric","oob","ord",
"paramCount","paramIsRef","paramSet","parameter","passvp",
"permutations","pow","print","printl","properties",
"rad2deg","random","randomChoice","randomDice","randomGrab",
"randomPick","randomSeed","randomWalk","readURI","reduce",
"retract","round","seconds","serialize","set",
"setProperty","setenv","sin","sleep","stdErr",
"stdErrRaw","stdIn","stdInRaw","stdOut","stdOutRaw",
"strBack","strBackFind","strBackTrim","strBuffer","strCmpIgnoreCase",
"strEndsWith","strEscape","strEsq","strFill","strFind",
"strFromMemBuf","strFront","strFrontTrim","strLower","strMerge",
"strReplace","strReplicate","strSplit","strSplitTrimmed","strStartsWith",
"strToMemBuf","strTrim","strUnescape","strUnesq","strUpper",
"strWildcardMatch","subscribe","systemErrorDescription","tan","times",
"toString","transcodeFrom","transcodeTo","typeOf","unsetenv",
"unsubscribe","valof","vmFalconPath","vmIsMain","vmModuleName",
"vmModuleVersionInfo","vmSearchPath","vmSystemType","vmVersionInfo","vmVersionName",
"writeURI","xmap","yield","yieldOut"
),
7 => array(
"AccessError","Array","BOM","Base64","Class",
"ClassMethod","CloneError","CmdlineParser","CodeError","Continuation",
"Dictionary","Directory","Error","FileStat","Format",
"Function","GarbagePointer","GenericError","Integer","InterruptedError",
"IoError","Iterator","LateBinding","List","MathError",
"MemoryBuffer","MessageError","Method","Numeric","Object",
"ParamError","ParseError","Path","Range","Semaphore",
"Sequence","Set","Stream","String","StringStream",
"SyntaxError","Table","TableError","TimeStamp","TimeZone",
"Tokenizer","TypeError","URI","VMSlot"
),
8 => array(
"args","scriptName","scriptPath"
),
9 => array(
"GC"
),
),
'URLS' => array(
1 => '',
2 => '',
3 => '',
4 => '',
5 => 'http://falconpl.org/project_docs/core/functions.html#typeOf',
6 => 'http://falconpl.org/project_docs/core/functions.html#{FNAME}',
7 => 'http://falconpl.org/project_docs/core/class_{FNAME}.html',
8 => 'http://falconpl.org/project_docs/core/globals.html#{FNAME}',
9 => 'http://falconpl.org/project_docs/core/object_{FNAME}.html)'
),
'CASE_SENSITIVE' => array(
GESHI_COMMENTS => false,
1 => true,
2 => true,
3 => true,
4 => true,
5 => true,
6 => true,
7 => true,
8 => true,
9 => true
),
'SYMBOLS' => array(
'(',')','$','%','&','/','{','[',']','=','}','?','+','-','#','*','@',
'<','>','|',',',':',';','\\','^'
),
'REGEXPS' => array(
0 => array(
GESHI_SEARCH => '(\[)([a-zA-Z_]|\c{C})(?:[a-zA-Z0-9_]|\p{C})*(\])',
GESHI_REPLACE => '\\2',
GESHI_MODIFIERS => '',
GESHI_BEFORE => '\\1',
GESHI_AFTER => '\\3',
),
),
'STRICT_MODE_APPLIES' => GESHI_MAYBE,
'SCRIPT_DELIMITERS' => array(
0 => array( '<?' => '?>' )
),
'HIGHLIGHT_STRICT_BLOCK' => array(
0 => true
),
'STYLES' => array(
'KEYWORDS' => array(
1 => 'color: #000080;font-weight:bold;',
2 => 'color: #800000;font-weight:bold;',
3 => 'color: #800000;font-weight:bold;',
4 => 'color: #000080;font-weight:bold;',
5 => 'color: #000000;font-weight:bold;',
6 => 'font-weight:bold;',
7 => 'font-weight:bold;',
8 => 'font-weight:bold;'
),
'COMMENTS' => array(
1 => 'color: #29B900;',
'MULTI' => 'color: #008080'
),
'STRINGS' => array(
0 => 'color: #800000'
),
'BRACKETS' => array(
0 => 'color: #000000'
),
'ESCAPE_CHAR' => array(
0 => 'color: #800000'
),
'NUMBERS' => array(
0 => 'color: #000000'
),
'METHODS' => array(
0 => 'color: #000000'
),
'SYMBOLS' => array(
0 => 'color: #8B0513'
),
'SCRIPT' => array(
0 => ''
),
'REGEXPS' => array(
0 => 'color: #FF00FF'
)
),
'OOLANG' => true,
'OBJECT_SPLITTERS' => array(
'.'
)
);
?>
|
{
"pile_set_name": "Github"
}
|
// Fountain test script
#pragma version(1)
#pragma rs_fp_relaxed
#pragma rs java_package_name(com.example.android.rs.fountain)
#pragma stateFragment(parent)
#include "rs_graphics.rsh"
static int newPart = 0;
rs_mesh partMesh;
typedef struct __attribute__((packed, aligned(4))) Point {
float2 delta;
float2 position;
uchar4 color;
} Point_t;
Point_t *point;
int root() {
float dt = min(rsGetDt(), 0.1f);
rsgClearColor(0.f, 0.f, 0.f, 1.f);
const float height = rsgGetHeight();
const int size = rsAllocationGetDimX(rsGetAllocation(point));
float dy2 = dt * (10.f);
Point_t * p = point;
for (int ct=0; ct < size; ct++) {
p->delta.y += dy2;
p->position += p->delta;
if ((p->position.y > height) && (p->delta.y > 0)) {
p->delta.y *= -0.3f;
}
p++;
}
rsgDrawMesh(partMesh);
return 1;
}
static float4 partColor[10];
void addParticles(int rate, float x, float y, int index, bool newColor)
{
if (newColor) {
partColor[index].x = rsRand(0.5f, 1.0f);
partColor[index].y = rsRand(1.0f);
partColor[index].z = rsRand(1.0f);
}
float rMax = ((float)rate) * 0.02f;
int size = rsAllocationGetDimX(rsGetAllocation(point));
uchar4 c = rsPackColorTo8888(partColor[index]);
Point_t * np = &point[newPart];
float2 p = {x, y};
while (rate--) {
float angle = rsRand(3.14f * 2.f);
float len = rsRand(rMax);
np->delta.x = len * sin(angle);
np->delta.y = len * cos(angle);
np->position = p;
np->color = c;
newPart++;
np++;
if (newPart >= size) {
newPart = 0;
np = &point[newPart];
}
}
}
|
{
"pile_set_name": "Github"
}
|
/* Copyright© 2000 - 2020 SuperMap Software Co.Ltd. All rights reserved.
* This program are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/
import {SuperMap} from '../SuperMap';
import {Util} from '../commontypes/Util';
/**
* @class SuperMap.FacilityAnalyst3DParameters
* @category iServer FacilityAnalyst3D
* @classdesc 最近设施分析参数基类。最近设施分析是指在网络上给定一个事件点和一组设施点,查找从事件点到设施点(或从设施点到事件点)以最小耗费能到达的最佳路径。
* 设施点一般为学校、超市、加油站等服务设施;事件点为需要服务设施的事件位置。例如事件发生点是一起交通事故,要求查找在 10 分钟内能到达的最近医院,
* 超过 10 分钟能到达的都不予考虑。此例中,事故发生地即是一个事件点,周边的医院则是设施点。最近设施查找实际上也是一种路径分析,因此对路径分析起
* 作用的障碍边、障碍点、转向表、耗费等属性在最近设施分析时同样可设置。
* @param {Object} options - 参数。
* @param {string} options.weightName - 指定的权值字段信息对象的名称。
* @param {number} [options.edgeID] - 指定的弧段 ID,edgeID 与 nodeID 必须指定一个。
* @param {number} [options.nodeID] - 指定的结点 ID,edgeID 与 nodeID 必须指定一个。
* @param {boolean} [options.isUncertainDirectionValid=false] - 指定不确定流向是否有效。指定为 true,表示不确定流向有效,遇到不确定流向时分析继续进行;
* 指定为 false,表示不确定流向无效,遇到不确定流向将停止在该方向上继续查找。
*/
export class FacilityAnalyst3DParameters {
constructor(options) {
/**
* @member {number} [SuperMap.FacilityAnalyst3DParameters.prototype.edgeID]
* @description 指定的弧段 ID,edgeID 与 nodeID 必须指定一个。
*/
this.edgeID = null;
/**
* @member {number} [SuperMap.FacilityAnalyst3DParameters.prototype.nodeID]
* @description 指定的结点 ID,edgeID 与 nodeID 必须指定一个。
*/
this.nodeID = null;
/**
* @member {string} SuperMap.FacilityAnalyst3DParameters.prototype.weightName
* @description 指定的权值字段信息对象的名称。
*/
this.weightName = null;
/**
* @member {boolean} [SuperMap.FacilityAnalyst3DParameters.prototype.isUncertainDirectionValid=false]
* @description 指定不确定流向是否有效。指定为 true,表示不确定流向有效,遇到不确定流向时分析继续进行;
* 指定为 false,表示不确定流向无效,遇到不确定流向将停止在该方向上继续查找
*/
this.isUncertainDirectionValid = false;
Util.extend(this, options);
this.CLASS_NAME = "SuperMap.FacilityAnalyst3DParameters";
}
/**
* @function SuperMap.FacilityAnalyst3DParameters.prototype.destroy
* @override
*/
destroy() {
var me = this;
me.edgeID = null;
me.nodeID = null;
me.weightName = null;
me.isUncertainDirectionValid = null;
}
}
SuperMap.FacilityAnalyst3DParameters = FacilityAnalyst3DParameters;
|
{
"pile_set_name": "Github"
}
|
<?php
namespace Spatie\SchemaOrg\Contracts;
interface MedicalEnumerationContract
{
public function additionalType($additionalType);
public function alternateName($alternateName);
public function description($description);
public function disambiguatingDescription($disambiguatingDescription);
public function identifier($identifier);
public function image($image);
public function mainEntityOfPage($mainEntityOfPage);
public function name($name);
public function potentialAction($potentialAction);
public function sameAs($sameAs);
public function subjectOf($subjectOf);
public function url($url);
}
|
{
"pile_set_name": "Github"
}
|
require 'spec_helper'
require 'bosh/director/models/variable'
module Bosh::Director::Models::Links
describe LinkConsumer do
let(:deployment) {Bosh::Director::Models::Deployment.create(name: 'my-dep')}
describe '#validate' do
it 'validates presence of deployment_id' do
expect {
LinkConsumer.create(
instance_group: 'ig',
name: 'name',
type: 'type'
)
}.to raise_error(Sequel::ValidationFailed, 'deployment_id presence')
end
it 'validates presence of name' do
expect {
LinkConsumer.create(
deployment: deployment,
instance_group: 'ig',
type: 'type'
)
}.to raise_error(Sequel::ValidationFailed, 'name presence')
end
it 'validates presence of value' do
expect {
LinkConsumer.create(
deployment: deployment,
instance_group: 'ig',
name: 'name'
)
}.to raise_error(Sequel::ValidationFailed, 'type presence')
end
end
describe '#find_intent_by_name' do
let(:link_consumer) do
LinkConsumer.create(
deployment: deployment,
instance_group: 'ig',
name: 'name',
type: 'type'
)
end
it 'return the correct intent by name' do
link_consumer_intent = Bosh::Director::Models::Links::LinkConsumerIntent.create(
link_consumer: link_consumer,
original_name: 'meow',
type: 'meow-type'
)
expect(link_consumer.find_intent_by_name('meow')).to eq(link_consumer_intent)
end
end
end
end
|
{
"pile_set_name": "Github"
}
|
package telemetry
import (
"time"
metrics "github.com/armon/go-metrics"
)
// Common metric key constants
const (
MetricKeyBeginBlocker = "begin_blocker"
MetricKeyEndBlocker = "end_blocker"
MetricLabelNameModule = "module"
)
func NewLabel(name, value string) metrics.Label {
return metrics.Label{Name: name, Value: value}
}
// ModuleMeasureSince provides a short hand method for emitting a time measure
// metric for a module with a given set of keys. If any global labels are defined,
// they will be added to the module label.
func ModuleMeasureSince(module string, start time.Time, keys ...string) {
metrics.MeasureSinceWithLabels(
keys,
start.UTC(),
append([]metrics.Label{NewLabel(MetricLabelNameModule, module)}, globalLabels...),
)
}
// ModuleSetGauge provides a short hand method for emitting a gauge metric for a
// module with a given set of keys. If any global labels are defined, they will
// be added to the module label.
func ModuleSetGauge(module string, val float32, keys ...string) {
metrics.SetGaugeWithLabels(
keys,
val,
append([]metrics.Label{NewLabel(MetricLabelNameModule, module)}, globalLabels...),
)
}
// IncrCounter provides a wrapper functionality for emitting a counter metric with
// global labels (if any).
func IncrCounter(val float32, keys ...string) {
metrics.IncrCounterWithLabels(keys, val, globalLabels)
}
// IncrCounterWithLabels provides a wrapper functionality for emitting a counter
// metric with global labels (if any) along with the provided labels.
func IncrCounterWithLabels(keys []string, val float32, labels []metrics.Label) {
metrics.IncrCounterWithLabels(keys, val, append(labels, globalLabels...))
}
// SetGauge provides a wrapper functionality for emitting a gauge metric with
// global labels (if any).
func SetGauge(val float32, keys ...string) {
metrics.SetGaugeWithLabels(keys, val, globalLabels)
}
// SetGaugeWithLabels provides a wrapper functionality for emitting a gauge
// metric with global labels (if any) along with the provided labels.
func SetGaugeWithLabels(keys []string, val float32, labels []metrics.Label) {
metrics.SetGaugeWithLabels(keys, val, append(labels, globalLabels...))
}
// MeasureSince provides a wrapper functionality for emitting a a time measure
// metric with global labels (if any).
func MeasureSince(start time.Time, keys ...string) {
metrics.MeasureSinceWithLabels(keys, start.UTC(), globalLabels)
}
|
{
"pile_set_name": "Github"
}
|
package test
type typeForTest [4][4]string
|
{
"pile_set_name": "Github"
}
|
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/hfsplus/wrapper.c
*
* Copyright (C) 2001
* Brad Boyer (flar@allandria.com)
* (C) 2003 Ardis Technologies <roman@ardistech.com>
*
* Handling of HFS wrappers around HFS+ volumes
*/
#include <linux/fs.h>
#include <linux/blkdev.h>
#include <linux/cdrom.h>
#include <linux/genhd.h>
#include <asm/unaligned.h>
#include "hfsplus_fs.h"
#include "hfsplus_raw.h"
struct hfsplus_wd {
u32 ablk_size;
u16 ablk_start;
u16 embed_start;
u16 embed_count;
};
/**
* hfsplus_submit_bio - Perform block I/O
* @sb: super block of volume for I/O
* @sector: block to read or write, for blocks of HFSPLUS_SECTOR_SIZE bytes
* @buf: buffer for I/O
* @data: output pointer for location of requested data
* @op: direction of I/O
* @op_flags: request op flags
*
* The unit of I/O is hfsplus_min_io_size(sb), which may be bigger than
* HFSPLUS_SECTOR_SIZE, and @buf must be sized accordingly. On reads
* @data will return a pointer to the start of the requested sector,
* which may not be the same location as @buf.
*
* If @sector is not aligned to the bdev logical block size it will
* be rounded down. For writes this means that @buf should contain data
* that starts at the rounded-down address. As long as the data was
* read using hfsplus_submit_bio() and the same buffer is used things
* will work correctly.
*/
int hfsplus_submit_bio(struct super_block *sb, sector_t sector,
void *buf, void **data, int op, int op_flags)
{
struct bio *bio;
int ret = 0;
u64 io_size;
loff_t start;
int offset;
/*
* Align sector to hardware sector size and find offset. We
* assume that io_size is a power of two, which _should_
* be true.
*/
io_size = hfsplus_min_io_size(sb);
start = (loff_t)sector << HFSPLUS_SECTOR_SHIFT;
offset = start & (io_size - 1);
sector &= ~((io_size >> HFSPLUS_SECTOR_SHIFT) - 1);
bio = bio_alloc(GFP_NOIO, 1);
bio->bi_iter.bi_sector = sector;
bio_set_dev(bio, sb->s_bdev);
bio_set_op_attrs(bio, op, op_flags);
if (op != WRITE && data)
*data = (u8 *)buf + offset;
while (io_size > 0) {
unsigned int page_offset = offset_in_page(buf);
unsigned int len = min_t(unsigned int, PAGE_SIZE - page_offset,
io_size);
ret = bio_add_page(bio, virt_to_page(buf), len, page_offset);
if (ret != len) {
ret = -EIO;
goto out;
}
io_size -= len;
buf = (u8 *)buf + len;
}
ret = submit_bio_wait(bio);
out:
bio_put(bio);
return ret < 0 ? ret : 0;
}
static int hfsplus_read_mdb(void *bufptr, struct hfsplus_wd *wd)
{
u32 extent;
u16 attrib;
__be16 sig;
sig = *(__be16 *)(bufptr + HFSP_WRAPOFF_EMBEDSIG);
if (sig != cpu_to_be16(HFSPLUS_VOLHEAD_SIG) &&
sig != cpu_to_be16(HFSPLUS_VOLHEAD_SIGX))
return 0;
attrib = be16_to_cpu(*(__be16 *)(bufptr + HFSP_WRAPOFF_ATTRIB));
if (!(attrib & HFSP_WRAP_ATTRIB_SLOCK) ||
!(attrib & HFSP_WRAP_ATTRIB_SPARED))
return 0;
wd->ablk_size =
be32_to_cpu(*(__be32 *)(bufptr + HFSP_WRAPOFF_ABLKSIZE));
if (wd->ablk_size < HFSPLUS_SECTOR_SIZE)
return 0;
if (wd->ablk_size % HFSPLUS_SECTOR_SIZE)
return 0;
wd->ablk_start =
be16_to_cpu(*(__be16 *)(bufptr + HFSP_WRAPOFF_ABLKSTART));
extent = get_unaligned_be32(bufptr + HFSP_WRAPOFF_EMBEDEXT);
wd->embed_start = (extent >> 16) & 0xFFFF;
wd->embed_count = extent & 0xFFFF;
return 1;
}
static int hfsplus_get_last_session(struct super_block *sb,
sector_t *start, sector_t *size)
{
struct cdrom_device_info *cdi = disk_to_cdi(sb->s_bdev->bd_disk);
/* default values */
*start = 0;
*size = i_size_read(sb->s_bdev->bd_inode) >> 9;
if (HFSPLUS_SB(sb)->session >= 0) {
struct cdrom_tocentry te;
if (!cdi)
return -EINVAL;
te.cdte_track = HFSPLUS_SB(sb)->session;
te.cdte_format = CDROM_LBA;
if (cdrom_read_tocentry(cdi, &te) ||
(te.cdte_ctrl & CDROM_DATA_TRACK) != 4) {
pr_err("invalid session number or type of track\n");
return -EINVAL;
}
*start = (sector_t)te.cdte_addr.lba << 2;
} else if (cdi) {
struct cdrom_multisession ms_info;
ms_info.addr_format = CDROM_LBA;
if (cdrom_multisession(cdi, &ms_info) == 0 && ms_info.xa_flag)
*start = (sector_t)ms_info.addr.lba << 2;
}
return 0;
}
/* Find the volume header and fill in some minimum bits in superblock */
/* Takes in super block, returns true if good data read */
int hfsplus_read_wrapper(struct super_block *sb)
{
struct hfsplus_sb_info *sbi = HFSPLUS_SB(sb);
struct hfsplus_wd wd;
sector_t part_start, part_size;
u32 blocksize;
int error = 0;
error = -EINVAL;
blocksize = sb_min_blocksize(sb, HFSPLUS_SECTOR_SIZE);
if (!blocksize)
goto out;
if (hfsplus_get_last_session(sb, &part_start, &part_size))
goto out;
error = -ENOMEM;
sbi->s_vhdr_buf = kmalloc(hfsplus_min_io_size(sb), GFP_KERNEL);
if (!sbi->s_vhdr_buf)
goto out;
sbi->s_backup_vhdr_buf = kmalloc(hfsplus_min_io_size(sb), GFP_KERNEL);
if (!sbi->s_backup_vhdr_buf)
goto out_free_vhdr;
reread:
error = hfsplus_submit_bio(sb, part_start + HFSPLUS_VOLHEAD_SECTOR,
sbi->s_vhdr_buf, (void **)&sbi->s_vhdr,
REQ_OP_READ, 0);
if (error)
goto out_free_backup_vhdr;
error = -EINVAL;
switch (sbi->s_vhdr->signature) {
case cpu_to_be16(HFSPLUS_VOLHEAD_SIGX):
set_bit(HFSPLUS_SB_HFSX, &sbi->flags);
fallthrough;
case cpu_to_be16(HFSPLUS_VOLHEAD_SIG):
break;
case cpu_to_be16(HFSP_WRAP_MAGIC):
if (!hfsplus_read_mdb(sbi->s_vhdr, &wd))
goto out_free_backup_vhdr;
wd.ablk_size >>= HFSPLUS_SECTOR_SHIFT;
part_start += (sector_t)wd.ablk_start +
(sector_t)wd.embed_start * wd.ablk_size;
part_size = (sector_t)wd.embed_count * wd.ablk_size;
goto reread;
default:
/*
* Check for a partition block.
*
* (should do this only for cdrom/loop though)
*/
if (hfs_part_find(sb, &part_start, &part_size))
goto out_free_backup_vhdr;
goto reread;
}
error = hfsplus_submit_bio(sb, part_start + part_size - 2,
sbi->s_backup_vhdr_buf,
(void **)&sbi->s_backup_vhdr, REQ_OP_READ,
0);
if (error)
goto out_free_backup_vhdr;
error = -EINVAL;
if (sbi->s_backup_vhdr->signature != sbi->s_vhdr->signature) {
pr_warn("invalid secondary volume header\n");
goto out_free_backup_vhdr;
}
blocksize = be32_to_cpu(sbi->s_vhdr->blocksize);
/*
* Block size must be at least as large as a sector and a multiple of 2.
*/
if (blocksize < HFSPLUS_SECTOR_SIZE || ((blocksize - 1) & blocksize))
goto out_free_backup_vhdr;
sbi->alloc_blksz = blocksize;
sbi->alloc_blksz_shift = ilog2(blocksize);
blocksize = min_t(u32, sbi->alloc_blksz, PAGE_SIZE);
/*
* Align block size to block offset.
*/
while (part_start & ((blocksize >> HFSPLUS_SECTOR_SHIFT) - 1))
blocksize >>= 1;
if (sb_set_blocksize(sb, blocksize) != blocksize) {
pr_err("unable to set blocksize to %u!\n", blocksize);
goto out_free_backup_vhdr;
}
sbi->blockoffset =
part_start >> (sb->s_blocksize_bits - HFSPLUS_SECTOR_SHIFT);
sbi->part_start = part_start;
sbi->sect_count = part_size;
sbi->fs_shift = sbi->alloc_blksz_shift - sb->s_blocksize_bits;
return 0;
out_free_backup_vhdr:
kfree(sbi->s_backup_vhdr_buf);
out_free_vhdr:
kfree(sbi->s_vhdr_buf);
out:
return error;
}
|
{
"pile_set_name": "Github"
}
|
fileFormatVersion: 2
guid: 94022b871308e194ca44ae2c0b42db00
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2018 Demerzel Solutions Limited
// This file is part of the Nethermind library.
//
// The Nethermind library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The Nethermind library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the Nethermind. If not, see <http://www.gnu.org/licenses/>.
using System.ComponentModel;
namespace Nethermind.TxPool
{
public static class Metrics
{
[Description("Number of pending transactions broadcasted to peers.")]
public static long PendingTransactionsSent { get; set; }
[Description("Number of pending transactions received from peers.")]
public static long PendingTransactionsReceived { get; set; }
[Description("Number of pending transactions received that were ignored.")]
public static long PendingTransactionsDiscarded { get; set; }
[Description("Number of known pending transactions.")]
public static long PendingTransactionsKnown { get; set; }
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2012
* MIPS Technologies, Inc., California.
*
* 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 MIPS Technologies, Inc., 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 MIPS TECHNOLOGIES, INC. ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE MIPS TECHNOLOGIES, INC. 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.
*
* Author: Bojan Zivkovic (bojan@mips.com)
*
* MPEG Audio decoder optimized for MIPS fixed-point architecture
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Reference: libavcodec/mpegaudiodsp_template.c
*/
#include <string.h>
#include "libavutil/mips/asmdefs.h"
#include "libavcodec/mpegaudiodsp.h"
#if HAVE_INLINE_ASM
#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6
static void ff_mpadsp_apply_window_mips_fixed(int32_t *synth_buf, int32_t *window,
int *dither_state, int16_t *samples, ptrdiff_t incr)
{
register const int32_t *w, *w2, *p;
int j;
int16_t *samples2;
int w_asm, p_asm, w_asm1, p_asm1, w_asm2, p_asm2;
int w2_asm, w2_asm1, *p_temp1, *p_temp2;
int sum1 = 0;
int const min_asm = -32768, max_asm = 32767;
int temp1, temp2 = 0, temp3 = 0;
int64_t sum;
/* copy to avoid wrap */
memcpy(synth_buf + 512, synth_buf, 32 * sizeof(*synth_buf));
samples2 = samples + 31 * incr;
w = window;
w2 = window + 31;
sum = *dither_state;
p = synth_buf + 16;
p_temp1 = synth_buf + 16;
p_temp2 = synth_buf + 48;
temp1 = sum;
/**
* use of round_sample function from the original code is eliminated,
* changed with appropriate assembly instructions.
*/
__asm__ volatile (
"mthi $zero \n\t"
"mtlo %[temp1] \n\t"
"lw %[w_asm], 0(%[w]) \n\t"
"lw %[p_asm], 0(%[p]) \n\t"
"lw %[w_asm1], 64*4(%[w]) \n\t"
"lw %[p_asm1], 64*4(%[p]) \n\t"
"lw %[w_asm2], 128*4(%[w]) \n\t"
"lw %[p_asm2], 128*4(%[p]) \n\t"
"madd %[w_asm], %[p_asm] \n\t"
"madd %[w_asm1], %[p_asm1] \n\t"
"madd %[w_asm2], %[p_asm2] \n\t"
"lw %[w_asm], 192*4(%[w]) \n\t"
"lw %[p_asm], 192*4(%[p]) \n\t"
"lw %[w_asm1], 256*4(%[w]) \n\t"
"lw %[p_asm1], 256*4(%[p]) \n\t"
"lw %[w_asm2], 320*4(%[w]) \n\t"
"lw %[p_asm2], 320*4(%[p]) \n\t"
"madd %[w_asm], %[p_asm] \n\t"
"madd %[w_asm1], %[p_asm1] \n\t"
"madd %[w_asm2], %[p_asm2] \n\t"
"lw %[w_asm], 384*4(%[w]) \n\t"
"lw %[p_asm], 384*4(%[p]) \n\t"
"lw %[w_asm1], 448*4(%[w]) \n\t"
"lw %[p_asm1], 448*4(%[p]) \n\t"
"lw %[w_asm2], 32*4(%[w]) \n\t"
"lw %[p_asm2], 32*4(%[p]) \n\t"
"madd %[w_asm], %[p_asm] \n\t"
"madd %[w_asm1], %[p_asm1] \n\t"
"msub %[w_asm2], %[p_asm2] \n\t"
"lw %[w_asm], 96*4(%[w]) \n\t"
"lw %[p_asm], 96*4(%[p]) \n\t"
"lw %[w_asm1], 160*4(%[w]) \n\t"
"lw %[p_asm1], 160*4(%[p]) \n\t"
"lw %[w_asm2], 224*4(%[w]) \n\t"
"lw %[p_asm2], 224*4(%[p]) \n\t"
"msub %[w_asm], %[p_asm] \n\t"
"msub %[w_asm1], %[p_asm1] \n\t"
"msub %[w_asm2], %[p_asm2] \n\t"
"lw %[w_asm], 288*4(%[w]) \n\t"
"lw %[p_asm], 288*4(%[p]) \n\t"
"lw %[w_asm1], 352*4(%[w]) \n\t"
"lw %[p_asm1], 352*4(%[p]) \n\t"
"msub %[w_asm], %[p_asm] \n\t"
"lw %[w_asm], 480*4(%[w]) \n\t"
"lw %[p_asm], 480*4(%[p]) \n\t"
"lw %[w_asm2], 416*4(%[w]) \n\t"
"lw %[p_asm2], 416*4(%[p]) \n\t"
"msub %[w_asm], %[p_asm] \n\t"
"msub %[w_asm1], %[p_asm1] \n\t"
"msub %[w_asm2], %[p_asm2] \n\t"
/*round_sample function from the original code is eliminated,
* changed with appropriate assembly instructions
* code example:
"extr.w %[sum1],$ac0,24 \n\t"
"mflo %[temp3], $ac0 \n\t"
"and %[temp1], %[temp3], 0x00ffffff \n\t"
"slt %[temp2], %[sum1], %[min_asm] \n\t"
"movn %[sum1], %[min_asm],%[temp2] \n\t"
"slt %[temp2], %[max_asm],%[sum1] \n\t"
"movn %[sum1], %[max_asm],%[temp2] \n\t"
"sh %[sum1], 0(%[samples]) \n\t"
*/
"extr.w %[sum1], $ac0, 24 \n\t"
"mflo %[temp3] \n\t"
PTR_ADDIU "%[w], %[w], 4 \n\t"
"and %[temp1], %[temp3], 0x00ffffff \n\t"
"slt %[temp2], %[sum1], %[min_asm] \n\t"
"movn %[sum1], %[min_asm], %[temp2] \n\t"
"slt %[temp2], %[max_asm], %[sum1] \n\t"
"movn %[sum1], %[max_asm], %[temp2] \n\t"
"sh %[sum1], 0(%[samples]) \n\t"
: [w_asm] "=&r" (w_asm), [p_asm] "=&r" (p_asm), [w_asm1] "=&r" (w_asm1),
[p_asm1] "=&r" (p_asm1), [temp1] "+r" (temp1), [temp2] "+r" (temp2),
[w_asm2] "=&r" (w_asm2), [p_asm2] "=&r" (p_asm2),
[sum1] "+r" (sum1), [w] "+r" (w), [temp3] "+r" (temp3)
: [p] "r" (p), [samples] "r" (samples), [min_asm] "r" (min_asm),
[max_asm] "r" (max_asm)
: "memory", "hi","lo"
);
samples += incr;
/* we calculate two samples at the same time to avoid one memory
access per two sample */
for(j = 1; j < 16; j++) {
__asm__ volatile (
"mthi $0, $ac1 \n\t"
"mtlo $0, $ac1 \n\t"
"mthi $0 \n\t"
"mtlo %[temp1] \n\t"
PTR_ADDIU "%[p_temp1], %[p_temp1], 4 \n\t"
"lw %[w_asm], 0(%[w]) \n\t"
"lw %[p_asm], 0(%[p_temp1]) \n\t"
"lw %[w2_asm], 0(%[w2]) \n\t"
"lw %[w_asm1], 64*4(%[w]) \n\t"
"lw %[p_asm1], 64*4(%[p_temp1]) \n\t"
"lw %[w2_asm1], 64*4(%[w2]) \n\t"
"madd %[w_asm], %[p_asm] \n\t"
"msub $ac1, %[w2_asm], %[p_asm] \n\t"
"madd %[w_asm1], %[p_asm1] \n\t"
"msub $ac1, %[w2_asm1], %[p_asm1] \n\t"
"lw %[w_asm], 128*4(%[w]) \n\t"
"lw %[p_asm], 128*4(%[p_temp1]) \n\t"
"lw %[w2_asm], 128*4(%[w2]) \n\t"
"lw %[w_asm1], 192*4(%[w]) \n\t"
"lw %[p_asm1], 192*4(%[p_temp1]) \n\t"
"lw %[w2_asm1], 192*4(%[w2]) \n\t"
"madd %[w_asm], %[p_asm] \n\t"
"msub $ac1, %[w2_asm], %[p_asm] \n\t"
"madd %[w_asm1], %[p_asm1] \n\t"
"msub $ac1, %[w2_asm1], %[p_asm1] \n\t"
"lw %[w_asm], 256*4(%[w]) \n\t"
"lw %[p_asm], 256*4(%[p_temp1]) \n\t"
"lw %[w2_asm], 256*4(%[w2]) \n\t"
"lw %[w_asm1], 320*4(%[w]) \n\t"
"lw %[p_asm1], 320*4(%[p_temp1]) \n\t"
"lw %[w2_asm1], 320*4(%[w2]) \n\t"
"madd %[w_asm], %[p_asm] \n\t"
"msub $ac1, %[w2_asm], %[p_asm] \n\t"
"madd %[w_asm1], %[p_asm1] \n\t"
"msub $ac1, %[w2_asm1], %[p_asm1] \n\t"
"lw %[w_asm], 384*4(%[w]) \n\t"
"lw %[p_asm], 384*4(%[p_temp1]) \n\t"
"lw %[w2_asm], 384*4(%[w2]) \n\t"
"lw %[w_asm1], 448*4(%[w]) \n\t"
"lw %[p_asm1], 448*4(%[p_temp1]) \n\t"
"lw %[w2_asm1], 448*4(%[w2]) \n\t"
"madd %[w_asm], %[p_asm] \n\t"
"msub $ac1, %[w2_asm], %[p_asm] \n\t"
"madd %[w_asm1], %[p_asm1] \n\t"
"msub $ac1, %[w2_asm1], %[p_asm1] \n\t"
PTR_ADDIU "%[p_temp2], %[p_temp2], -4 \n\t"
"lw %[w_asm], 32*4(%[w]) \n\t"
"lw %[p_asm], 0(%[p_temp2]) \n\t"
"lw %[w2_asm], 32*4(%[w2]) \n\t"
"lw %[w_asm1], 96*4(%[w]) \n\t"
"lw %[p_asm1], 64*4(%[p_temp2]) \n\t"
"lw %[w2_asm1], 96*4(%[w2]) \n\t"
"msub %[w_asm], %[p_asm] \n\t"
"msub $ac1, %[w2_asm], %[p_asm] \n\t"
"msub %[w_asm1], %[p_asm1] \n\t"
"msub $ac1, %[w2_asm1], %[p_asm1] \n\t"
"lw %[w_asm], 160*4(%[w]) \n\t"
"lw %[p_asm], 128*4(%[p_temp2]) \n\t"
"lw %[w2_asm], 160*4(%[w2]) \n\t"
"lw %[w_asm1], 224*4(%[w]) \n\t"
"lw %[p_asm1], 192*4(%[p_temp2]) \n\t"
"lw %[w2_asm1], 224*4(%[w2]) \n\t"
"msub %[w_asm], %[p_asm] \n\t"
"msub $ac1, %[w2_asm], %[p_asm] \n\t"
"msub %[w_asm1], %[p_asm1] \n\t"
"msub $ac1, %[w2_asm1], %[p_asm1] \n\t"
"lw %[w_asm], 288*4(%[w]) \n\t"
"lw %[p_asm], 256*4(%[p_temp2]) \n\t"
"lw %[w2_asm], 288*4(%[w2]) \n\t"
"lw %[w_asm1], 352*4(%[w]) \n\t"
"lw %[p_asm1], 320*4(%[p_temp2]) \n\t"
"lw %[w2_asm1], 352*4(%[w2]) \n\t"
"msub %[w_asm], %[p_asm] \n\t"
"msub $ac1, %[w2_asm], %[p_asm] \n\t"
"msub %[w_asm1], %[p_asm1] \n\t"
"msub $ac1, %[w2_asm1], %[p_asm1] \n\t"
"lw %[w_asm], 416*4(%[w]) \n\t"
"lw %[p_asm], 384*4(%[p_temp2]) \n\t"
"lw %[w2_asm], 416*4(%[w2]) \n\t"
"lw %[w_asm1], 480*4(%[w]) \n\t"
"lw %[p_asm1], 448*4(%[p_temp2]) \n\t"
"lw %[w2_asm1], 480*4(%[w2]) \n\t"
"msub %[w_asm], %[p_asm] \n\t"
"msub %[w_asm1], %[p_asm1] \n\t"
"msub $ac1, %[w2_asm], %[p_asm] \n\t"
"msub $ac1, %[w2_asm1], %[p_asm1] \n\t"
PTR_ADDIU "%[w], %[w], 4 \n\t"
PTR_ADDIU "%[w2], %[w2], -4 \n\t"
"mflo %[temp2] \n\t"
"extr.w %[sum1], $ac0, 24 \n\t"
"li %[temp3], 1 \n\t"
"and %[temp1], %[temp2], 0x00ffffff \n\t"
"madd $ac1, %[temp1], %[temp3] \n\t"
"slt %[temp2], %[sum1], %[min_asm] \n\t"
"movn %[sum1], %[min_asm], %[temp2] \n\t"
"slt %[temp2], %[max_asm], %[sum1] \n\t"
"movn %[sum1], %[max_asm], %[temp2] \n\t"
"sh %[sum1], 0(%[samples]) \n\t"
"mflo %[temp3], $ac1 \n\t"
"extr.w %[sum1], $ac1, 24 \n\t"
"and %[temp1], %[temp3], 0x00ffffff \n\t"
"slt %[temp2], %[sum1], %[min_asm] \n\t"
"movn %[sum1], %[min_asm], %[temp2] \n\t"
"slt %[temp2], %[max_asm], %[sum1] \n\t"
"movn %[sum1], %[max_asm], %[temp2] \n\t"
"sh %[sum1], 0(%[samples2]) \n\t"
: [w_asm] "=&r" (w_asm), [p_asm] "=&r" (p_asm), [w_asm1] "=&r" (w_asm1),
[p_asm1] "=&r" (p_asm1), [w2_asm1] "=&r" (w2_asm1),
[w2_asm] "=&r" (w2_asm), [temp1] "+r" (temp1), [temp2] "+r" (temp2),
[p_temp1] "+r" (p_temp1), [p_temp2] "+r" (p_temp2), [sum1] "+r" (sum1),
[w] "+r" (w), [w2] "+r" (w2), [samples] "+r" (samples),
[samples2] "+r" (samples2), [temp3] "+r" (temp3)
: [min_asm] "r" (min_asm), [max_asm] "r" (max_asm)
: "memory", "hi", "lo", "$ac1hi", "$ac1lo"
);
samples += incr;
samples2 -= incr;
}
p = synth_buf + 32;
__asm__ volatile (
"mthi $0 \n\t"
"mtlo %[temp1] \n\t"
"lw %[w_asm], 32*4(%[w]) \n\t"
"lw %[p_asm], 0(%[p]) \n\t"
"lw %[w_asm1], 96*4(%[w]) \n\t"
"lw %[p_asm1], 64*4(%[p]) \n\t"
"lw %[w_asm2], 160*4(%[w]) \n\t"
"lw %[p_asm2], 128*4(%[p]) \n\t"
"msub %[w_asm], %[p_asm] \n\t"
"msub %[w_asm1], %[p_asm1] \n\t"
"msub %[w_asm2], %[p_asm2] \n\t"
"lw %[w_asm], 224*4(%[w]) \n\t"
"lw %[p_asm], 192*4(%[p]) \n\t"
"lw %[w_asm1], 288*4(%[w]) \n\t"
"lw %[p_asm1], 256*4(%[p]) \n\t"
"lw %[w_asm2], 352*4(%[w]) \n\t"
"lw %[p_asm2], 320*4(%[p]) \n\t"
"msub %[w_asm], %[p_asm] \n\t"
"msub %[w_asm1], %[p_asm1] \n\t"
"msub %[w_asm2], %[p_asm2] \n\t"
"lw %[w_asm], 416*4(%[w]) \n\t"
"lw %[p_asm], 384*4(%[p]) \n\t"
"lw %[w_asm1], 480*4(%[w]) \n\t"
"lw %[p_asm1], 448*4(%[p]) \n\t"
"msub %[w_asm], %[p_asm] \n\t"
"msub %[w_asm1], %[p_asm1] \n\t"
"extr.w %[sum1], $ac0, 24 \n\t"
"mflo %[temp2] \n\t"
"and %[temp1], %[temp2], 0x00ffffff \n\t"
"slt %[temp2], %[sum1], %[min_asm] \n\t"
"movn %[sum1], %[min_asm], %[temp2] \n\t"
"slt %[temp2], %[max_asm], %[sum1] \n\t"
"movn %[sum1], %[max_asm], %[temp2] \n\t"
"sh %[sum1], 0(%[samples]) \n\t"
: [w_asm] "=&r" (w_asm), [p_asm] "=&r" (p_asm), [w_asm1] "=&r" (w_asm1),
[p_asm1] "=&r" (p_asm1), [temp1] "+r" (temp1), [temp2] "+r" (temp2),
[w_asm2] "=&r" (w_asm2), [p_asm2] "=&r" (p_asm2), [sum1] "+r" (sum1)
: [w] "r" (w), [p] "r" (p), [samples] "r" (samples), [min_asm] "r" (min_asm),
[max_asm] "r" (max_asm)
: "memory", "hi", "lo", "$ac1hi", "$ac1lo"
);
*dither_state= temp1;
}
static void imdct36_mips_fixed(int *out, int *buf, int *in, int *win)
{
int j;
int t0, t1, t2, t3, s0, s1, s2, s3;
int tmp[18], *tmp1, *in1;
/* temporary variables */
int temp_reg1, temp_reg2, temp_reg3, temp_reg4, temp_reg5, temp_reg6;
int t4, t5, t6, t8, t7;
/* values defined in macros and tables are
* eliminated - they are directly loaded in appropriate variables
*/
int const C_1 = 4229717092; /* cos(pi*1/18)*2 */
int const C_2 = 4035949074; /* cos(pi*2/18)*2 */
int const C_3 = 575416510; /* -cos(pi*3/18)*2 */
int const C_3A = 3719550786; /* cos(pi*3/18)*2 */
int const C_4 = 1004831466; /* -cos(pi*4/18)*2 */
int const C_5 = 1534215534; /* -cos(pi*5/18)*2 */
int const C_7 = -1468965330; /* -cos(pi*7/18)*2 */
int const C_8 = -745813244; /* -cos(pi*8/18)*2 */
/*
* instructions of the first two loops are reorganized and loops are unrolled,
* in order to eliminate unnecessary readings and writings in array
*/
__asm__ volatile (
"lw %[t1], 17*4(%[in]) \n\t"
"lw %[t2], 16*4(%[in]) \n\t"
"lw %[t3], 15*4(%[in]) \n\t"
"lw %[t4], 14*4(%[in]) \n\t"
"addu %[t1], %[t1], %[t2] \n\t"
"addu %[t2], %[t2], %[t3] \n\t"
"addu %[t3], %[t3], %[t4] \n\t"
"lw %[t5], 13*4(%[in]) \n\t"
"addu %[t1], %[t1], %[t3] \n\t"
"sw %[t2], 16*4(%[in]) \n\t"
"lw %[t6], 12*4(%[in]) \n\t"
"sw %[t1], 17*4(%[in]) \n\t"
"addu %[t4], %[t4], %[t5] \n\t"
"addu %[t5], %[t5], %[t6] \n\t"
"lw %[t7], 11*4(%[in]) \n\t"
"addu %[t3], %[t3], %[t5] \n\t"
"sw %[t4], 14*4(%[in]) \n\t"
"lw %[t8], 10*4(%[in]) \n\t"
"sw %[t3], 15*4(%[in]) \n\t"
"addu %[t6], %[t6], %[t7] \n\t"
"addu %[t7], %[t7], %[t8] \n\t"
"sw %[t6], 12*4(%[in]) \n\t"
"addu %[t5], %[t5], %[t7] \n\t"
"lw %[t1], 9*4(%[in]) \n\t"
"lw %[t2], 8*4(%[in]) \n\t"
"sw %[t5], 13*4(%[in]) \n\t"
"addu %[t8], %[t8], %[t1] \n\t"
"addu %[t1], %[t1], %[t2] \n\t"
"sw %[t8], 10*4(%[in]) \n\t"
"addu %[t7], %[t7], %[t1] \n\t"
"lw %[t3], 7*4(%[in]) \n\t"
"lw %[t4], 6*4(%[in]) \n\t"
"sw %[t7], 11*4(%[in]) \n\t"
"addu %[t2], %[t2], %[t3] \n\t"
"addu %[t3], %[t3], %[t4] \n\t"
"sw %[t2], 8*4(%[in]) \n\t"
"addu %[t1], %[t1], %[t3] \n\t"
"lw %[t5], 5*4(%[in]) \n\t"
"lw %[t6], 4*4(%[in]) \n\t"
"sw %[t1], 9*4(%[in]) \n\t"
"addu %[t4], %[t4], %[t5] \n\t"
"addu %[t5], %[t5], %[t6] \n\t"
"sw %[t4], 6*4(%[in]) \n\t"
"addu %[t3], %[t3], %[t5] \n\t"
"lw %[t7], 3*4(%[in]) \n\t"
"lw %[t8], 2*4(%[in]) \n\t"
"sw %[t3], 7*4(%[in]) \n\t"
"addu %[t6], %[t6], %[t7] \n\t"
"addu %[t7], %[t7], %[t8] \n\t"
"sw %[t6], 4*4(%[in]) \n\t"
"addu %[t5], %[t5], %[t7] \n\t"
"lw %[t1], 1*4(%[in]) \n\t"
"lw %[t2], 0*4(%[in]) \n\t"
"sw %[t5], 5*4(%[in]) \n\t"
"addu %[t8], %[t8], %[t1] \n\t"
"addu %[t1], %[t1], %[t2] \n\t"
"sw %[t8], 2*4(%[in]) \n\t"
"addu %[t7], %[t7], %[t1] \n\t"
"sw %[t7], 3*4(%[in]) \n\t"
"sw %[t1], 1*4(%[in]) \n\t"
: [in] "+r" (in), [t1] "=&r" (t1), [t2] "=&r" (t2), [t3] "=&r" (t3),
[t4] "=&r" (t4), [t5] "=&r" (t5), [t6] "=&r" (t6),
[t7] "=&r" (t7), [t8] "=&r" (t8)
:
: "memory"
);
for(j = 0; j < 2; j++) {
tmp1 = tmp + j;
in1 = in + j;
/**
* Original constants are multiplied by two in advanced
* for assembly optimization (e.g. C_2 = 2 * C2).
* That can lead to overflow in operations where they are used.
*
* Example of the solution:
*
* in original code:
* t0 = ((int64_t)(in1[2*2] + in1[2*4]) * (int64_t)(2*C2))>>32
*
* in assembly:
* C_2 = 2 * C2;
* .
* .
* "lw %[t7], 4*4(%[in1]) \n\t"
* "lw %[t8], 8*4(%[in1]) \n\t"
* "addu %[temp_reg2],%[t7], %[t8] \n\t"
* "multu %[C_2], %[temp_reg2] \n\t"
* "mfhi %[temp_reg1] \n\t"
* "sra %[temp_reg2],%[temp_reg2],31 \n\t"
* "move %[t0], $0 \n\t"
* "movn %[t0], %[C_2], %[temp_reg2] \n\t"
* "sub %[t0], %[temp_reg1],%[t0] \n\t"
*/
__asm__ volatile (
"lw %[t7], 4*4(%[in1]) \n\t"
"lw %[t8], 8*4(%[in1]) \n\t"
"lw %[t6], 16*4(%[in1]) \n\t"
"lw %[t4], 0*4(%[in1]) \n\t"
"addu %[temp_reg2], %[t7], %[t8] \n\t"
"addu %[t2], %[t6], %[t8] \n\t"
"multu %[C_2], %[temp_reg2] \n\t"
"lw %[t5], 12*4(%[in1]) \n\t"
"sub %[t2], %[t2], %[t7] \n\t"
"sub %[t1], %[t4], %[t5] \n\t"
"sra %[t3], %[t5], 1 \n\t"
"sra %[temp_reg1], %[t2], 1 \n\t"
"addu %[t3], %[t3], %[t4] \n\t"
"sub %[temp_reg1], %[t1], %[temp_reg1] \n\t"
"sra %[temp_reg2], %[temp_reg2], 31 \n\t"
"sw %[temp_reg1], 6*4(%[tmp1]) \n\t"
"move %[t0], $0 \n\t"
"movn %[t0], %[C_2], %[temp_reg2] \n\t"
"mfhi %[temp_reg1] \n\t"
"addu %[t1], %[t1], %[t2] \n\t"
"sw %[t1], 16*4(%[tmp1]) \n\t"
"sub %[temp_reg4], %[t8], %[t6] \n\t"
"add %[temp_reg2], %[t7], %[t6] \n\t"
"mult $ac1, %[C_8], %[temp_reg4] \n\t"
"multu $ac2, %[C_4], %[temp_reg2] \n\t"
"sub %[t0], %[temp_reg1], %[t0] \n\t"
"sra %[temp_reg1], %[temp_reg2], 31 \n\t"
"move %[t2], $0 \n\t"
"movn %[t2], %[C_4], %[temp_reg1] \n\t"
"mfhi %[t1], $ac1 \n\t"
"mfhi %[temp_reg1], $ac2 \n\t"
"lw %[t6], 10*4(%[in1]) \n\t"
"lw %[t8], 14*4(%[in1]) \n\t"
"lw %[t7], 2*4(%[in1]) \n\t"
"lw %[t4], 6*4(%[in1]) \n\t"
"sub %[temp_reg3], %[t3], %[t0] \n\t"
"add %[temp_reg4], %[t3], %[t0] \n\t"
"sub %[temp_reg1], %[temp_reg1], %[temp_reg2] \n\t"
"add %[temp_reg4], %[temp_reg4], %[t1] \n\t"
"sub %[t2], %[temp_reg1], %[t2] \n\t"
"sw %[temp_reg4], 2*4(%[tmp1]) \n\t"
"sub %[temp_reg3], %[temp_reg3], %[t2] \n\t"
"add %[temp_reg1], %[t3], %[t2] \n\t"
"sw %[temp_reg3], 10*4(%[tmp1]) \n\t"
"sub %[temp_reg1], %[temp_reg1], %[t1] \n\t"
"addu %[temp_reg2], %[t6], %[t8] \n\t"
"sw %[temp_reg1], 14*4(%[tmp1]) \n\t"
"sub %[temp_reg2], %[temp_reg2], %[t7] \n\t"
"addu %[temp_reg3], %[t7], %[t6] \n\t"
"multu $ac3, %[C_3], %[temp_reg2] \n\t"
"multu %[C_1], %[temp_reg3] \n\t"
"sra %[temp_reg1], %[temp_reg2], 31 \n\t"
"move %[t1], $0 \n\t"
"sra %[temp_reg3], %[temp_reg3], 31 \n\t"
"movn %[t1], %[C_3], %[temp_reg1] \n\t"
"mfhi %[temp_reg1], $ac3 \n\t"
"mfhi %[temp_reg4] \n\t"
"move %[t2], $0 \n\t"
"movn %[t2], %[C_1], %[temp_reg3] \n\t"
"sub %[temp_reg3], %[t6], %[t8] \n\t"
"sub %[t2], %[temp_reg4], %[t2] \n\t"
"multu $ac1, %[C_7], %[temp_reg3] \n\t"
"sub %[temp_reg1], %[temp_reg1], %[temp_reg2] \n\t"
"sra %[temp_reg4], %[temp_reg3], 31 \n\t"
"sub %[t1], %[temp_reg1], %[t1] \n\t"
"move %[t3], $0 \n\t"
"sw %[t1], 4*4(%[tmp1]) \n\t"
"movn %[t3], %[C_7], %[temp_reg4] \n\t"
"multu $ac2, %[C_3A], %[t4] \n\t"
"add %[temp_reg2], %[t7], %[t8] \n\t"
"move %[t1], $0 \n\t"
"mfhi %[temp_reg4], $ac1 \n\t"
"multu $ac3,%[C_5], %[temp_reg2] \n\t"
"move %[t0], $0 \n\t"
"sra %[temp_reg1], %[temp_reg2], 31 \n\t"
"movn %[t1],%[C_5], %[temp_reg1] \n\t"
"sub %[temp_reg4], %[temp_reg4], %[temp_reg3] \n\t"
"mfhi %[temp_reg1], $ac3 \n\t"
"sra %[temp_reg3], %[t4], 31 \n\t"
"movn %[t0], %[C_3A], %[temp_reg3] \n\t"
"mfhi %[temp_reg3], $ac2 \n\t"
"sub %[t3], %[temp_reg4], %[t3] \n\t"
"add %[temp_reg4], %[t3], %[t2] \n\t"
"sub %[temp_reg1], %[temp_reg1], %[temp_reg2] \n\t"
"sub %[t1], %[temp_reg1], %[t1] \n\t"
"sub %[t0], %[temp_reg3], %[t0] \n\t"
"add %[temp_reg1], %[t2], %[t1] \n\t"
"add %[temp_reg4], %[temp_reg4], %[t0] \n\t"
"sub %[temp_reg2], %[t3], %[t1] \n\t"
"sw %[temp_reg4], 0*4(%[tmp1]) \n\t"
"sub %[temp_reg1], %[temp_reg1], %[t0] \n\t"
"sub %[temp_reg2], %[temp_reg2], %[t0] \n\t"
"sw %[temp_reg1], 12*4(%[tmp1]) \n\t"
"sw %[temp_reg2], 8*4(%[tmp1]) \n\t"
: [t7] "=&r" (t7), [temp_reg1] "=&r" (temp_reg1),
[temp_reg2] "=&r" (temp_reg2), [temp_reg4] "=&r" (temp_reg4),
[temp_reg3] "=&r" (temp_reg3), [t8] "=&r" (t8), [t0] "=&r" (t0),
[t4] "=&r" (t4), [t5] "=&r" (t5), [t6] "=&r"(t6), [t2] "=&r" (t2),
[t3] "=&r" (t3), [t1] "=&r" (t1)
: [C_2] "r" (C_2), [in1] "r" (in1), [tmp1] "r" (tmp1), [C_8] "r" (C_8),
[C_4] "r" (C_4), [C_3] "r" (C_3), [C_1] "r" (C_1), [C_7] "r" (C_7),
[C_3A] "r" (C_3A), [C_5] "r" (C_5)
: "memory", "hi", "lo", "$ac1hi", "$ac1lo", "$ac2hi", "$ac2lo",
"$ac3hi", "$ac3lo"
);
}
/**
* loop is unrolled four times
*
* values defined in tables(icos36[] and icos36h[]) are not loaded from
* these tables - they are directly loaded in appropriate registers
*
*/
__asm__ volatile (
"lw %[t2], 1*4(%[tmp]) \n\t"
"lw %[t3], 3*4(%[tmp]) \n\t"
"lw %[t0], 0*4(%[tmp]) \n\t"
"lw %[t1], 2*4(%[tmp]) \n\t"
"addu %[temp_reg1], %[t3], %[t2] \n\t"
"li %[temp_reg2], 0x807D2B1E \n\t"
"move %[s1], $0 \n\t"
"multu %[temp_reg2], %[temp_reg1] \n\t"
"sra %[temp_reg1], %[temp_reg1], 31 \n\t"
"movn %[s1], %[temp_reg2], %[temp_reg1] \n\t"
"sub %[temp_reg3], %[t3], %[t2] \n\t"
"li %[temp_reg4], 0x2de5151 \n\t"
"mfhi %[temp_reg2] \n\t"
"addu %[s0], %[t1], %[t0] \n\t"
"lw %[temp_reg5], 9*4(%[win]) \n\t"
"mult $ac1, %[temp_reg4], %[temp_reg3] \n\t"
"lw %[temp_reg6], 4*9*4(%[buf]) \n\t"
"sub %[s2], %[t1], %[t0] \n\t"
"lw %[temp_reg3], 29*4(%[win]) \n\t"
"subu %[s1], %[temp_reg2], %[s1] \n\t"
"lw %[temp_reg4], 28*4(%[win]) \n\t"
"add %[t0], %[s0], %[s1] \n\t"
"extr.w %[s3], $ac1,23 \n\t"
"mult $ac2, %[t0], %[temp_reg3] \n\t"
"sub %[t1], %[s0], %[s1] \n\t"
"lw %[temp_reg1], 4*8*4(%[buf]) \n\t"
"mult %[t1], %[temp_reg5] \n\t"
"lw %[temp_reg2], 8*4(%[win]) \n\t"
"mfhi %[temp_reg3], $ac2 \n\t"
"mult $ac3, %[t0], %[temp_reg4] \n\t"
"add %[t0], %[s2], %[s3] \n\t"
"mfhi %[temp_reg5] \n\t"
"mult $ac1, %[t1], %[temp_reg2] \n\t"
"sub %[t1], %[s2], %[s3] \n\t"
"sw %[temp_reg3], 4*9*4(%[buf]) \n\t"
"mfhi %[temp_reg4], $ac3 \n\t"
"lw %[temp_reg3], 37*4(%[win]) \n\t"
"mfhi %[temp_reg2], $ac1 \n\t"
"add %[temp_reg5], %[temp_reg5], %[temp_reg6] \n\t"
"lw %[temp_reg6], 17*4(%[win]) \n\t"
"sw %[temp_reg5], 32*9*4(%[out]) \n\t"
"sw %[temp_reg4], 4*8*4(%[buf]) \n\t"
"mult %[t1], %[temp_reg6] \n\t"
"add %[temp_reg1], %[temp_reg1], %[temp_reg2] \n\t"
"lw %[temp_reg2], 0*4(%[win]) \n\t"
"lw %[temp_reg5], 4*17*4(%[buf]) \n\t"
"sw %[temp_reg1], 8*32*4(%[out]) \n\t"
"mfhi %[temp_reg6] \n\t"
"mult $ac1, %[t1], %[temp_reg2] \n\t"
"lw %[temp_reg4], 20*4(%[win]) \n\t"
"lw %[temp_reg1], 0(%[buf]) \n\t"
"mult $ac2, %[t0], %[temp_reg3] \n\t"
"mult %[t0], %[temp_reg4] \n\t"
"mfhi %[temp_reg2], $ac1 \n\t"
"lw %[t0], 4*4(%[tmp]) \n\t"
"add %[temp_reg5], %[temp_reg5], %[temp_reg6] \n\t"
"mfhi %[temp_reg3], $ac2 \n\t"
"mfhi %[temp_reg4] \n\t"
"sw %[temp_reg5], 17*32*4(%[out]) \n\t"
"lw %[t1], 6*4(%[tmp]) \n\t"
"add %[temp_reg1], %[temp_reg1], %[temp_reg2] \n\t"
"lw %[t2], 5*4(%[tmp]) \n\t"
"sw %[temp_reg1], 0*32*4(%[out]) \n\t"
"addu %[s0], %[t1], %[t0] \n\t"
"sw %[temp_reg3], 4*17*4(%[buf]) \n\t"
"lw %[t3], 7*4(%[tmp]) \n\t"
"sub %[s2], %[t1], %[t0] \n\t"
"sw %[temp_reg4], 0(%[buf]) \n\t"
"addu %[temp_reg5], %[t3], %[t2] \n\t"
"li %[temp_reg6], 0x8483EE0C \n\t"
"move %[s1], $0 \n\t"
"multu %[temp_reg6], %[temp_reg5] \n\t"
"sub %[temp_reg1], %[t3], %[t2] \n\t"
"li %[temp_reg2], 0xf746ea \n\t"
"sra %[temp_reg5], %[temp_reg5], 31 \n\t"
"mult $ac1, %[temp_reg2], %[temp_reg1] \n\t"
"movn %[s1], %[temp_reg6], %[temp_reg5] \n\t"
"mfhi %[temp_reg5] \n\t"
"lw %[temp_reg3], 10*4(%[win]) \n\t"
"lw %[temp_reg4], 4*10*4(%[buf]) \n\t"
"extr.w %[s3], $ac1, 23 \n\t"
"lw %[temp_reg1], 4*7*4(%[buf]) \n\t"
"lw %[temp_reg2], 7*4(%[win]) \n\t"
"lw %[temp_reg6], 30*4(%[win]) \n\t"
"subu %[s1], %[temp_reg5], %[s1] \n\t"
"sub %[t1], %[s0], %[s1] \n\t"
"add %[t0], %[s0], %[s1] \n\t"
"mult $ac2, %[t1], %[temp_reg3] \n\t"
"mult $ac3, %[t1], %[temp_reg2] \n\t"
"mult %[t0], %[temp_reg6] \n\t"
"lw %[temp_reg5], 27*4(%[win]) \n\t"
"mult $ac1, %[t0], %[temp_reg5] \n\t"
"mfhi %[temp_reg3], $ac2 \n\t"
"mfhi %[temp_reg2], $ac3 \n\t"
"mfhi %[temp_reg6] \n\t"
"add %[t0], %[s2], %[s3] \n\t"
"sub %[t1], %[s2], %[s3] \n\t"
"add %[temp_reg3], %[temp_reg3], %[temp_reg4] \n\t"
"lw %[temp_reg4], 16*4(%[win]) \n\t"
"mfhi %[temp_reg5], $ac1 \n\t"
"sw %[temp_reg3], 32*10*4(%[out]) \n\t"
"add %[temp_reg1], %[temp_reg1], %[temp_reg2] \n\t"
"lw %[temp_reg3], 4*16*4(%[buf]) \n\t"
"sw %[temp_reg6], 4*10*4(%[buf]) \n\t"
"sw %[temp_reg1], 7*32*4(%[out]) \n\t"
"mult $ac2, %[t1], %[temp_reg4] \n\t"
"sw %[temp_reg5], 4*7*4(%[buf]) \n\t"
"lw %[temp_reg6], 1*4(%[win]) \n\t"
"lw %[temp_reg5], 4*1*4(%[buf]) \n\t"
"lw %[temp_reg1], 36*4(%[win]) \n\t"
"mult $ac3, %[t1], %[temp_reg6] \n\t"
"lw %[temp_reg2], 21*4(%[win]) \n\t"
"mfhi %[temp_reg4], $ac2 \n\t"
"mult %[t0], %[temp_reg1] \n\t"
"mult $ac1, %[t0],%[temp_reg2] \n\t"
"lw %[t0], 8*4(%[tmp]) \n\t"
"mfhi %[temp_reg6], $ac3 \n\t"
"lw %[t1], 10*4(%[tmp]) \n\t"
"lw %[t3], 11*4(%[tmp]) \n\t"
"mfhi %[temp_reg1] \n\t"
"add %[temp_reg3], %[temp_reg3], %[temp_reg4] \n\t"
"lw %[t2], 9*4(%[tmp]) \n\t"
"mfhi %[temp_reg2], $ac1 \n\t"
"add %[temp_reg5], %[temp_reg5], %[temp_reg6] \n\t"
"sw %[temp_reg3], 16*32*4(%[out]) \n\t"
"sw %[temp_reg5], 1*32*4(%[out]) \n\t"
"sw %[temp_reg1], 4*16*4(%[buf]) \n\t"
"addu %[temp_reg3], %[t3], %[t2] \n\t"
"li %[temp_reg4], 0x8D3B7CD6 \n\t"
"sw %[temp_reg2], 4*1*4(%[buf]) \n\t"
"multu %[temp_reg4],%[temp_reg3] \n\t"
"sra %[temp_reg3], %[temp_reg3], 31 \n\t"
"move %[s1], $0 \n\t"
"movn %[s1], %[temp_reg4], %[temp_reg3] \n\t"
"addu %[s0], %[t1], %[t0] \n\t"
"mfhi %[temp_reg3] \n\t"
"sub %[s2], %[t1], %[t0] \n\t"
"sub %[temp_reg5], %[t3], %[t2] \n\t"
"li %[temp_reg6], 0x976fd9 \n\t"
"lw %[temp_reg2], 11*4(%[win]) \n\t"
"lw %[temp_reg1], 4*11*4(%[buf]) \n\t"
"mult $ac1, %[temp_reg6], %[temp_reg5] \n\t"
"subu %[s1], %[temp_reg3], %[s1] \n\t"
"lw %[temp_reg5], 31*4(%[win]) \n\t"
"sub %[t1], %[s0], %[s1] \n\t"
"add %[t0], %[s0], %[s1] \n\t"
"mult $ac2, %[t1], %[temp_reg2] \n\t"
"mult %[t0], %[temp_reg5] \n\t"
"lw %[temp_reg4], 6*4(%[win]) \n\t"
"extr.w %[s3], $ac1, 23 \n\t"
"lw %[temp_reg3], 4*6*4(%[buf]) \n\t"
"mfhi %[temp_reg2], $ac2 \n\t"
"lw %[temp_reg6], 26*4(%[win]) \n\t"
"mfhi %[temp_reg5] \n\t"
"mult $ac3, %[t1], %[temp_reg4] \n\t"
"mult $ac1, %[t0], %[temp_reg6] \n\t"
"add %[t0], %[s2], %[s3] \n\t"
"sub %[t1], %[s2], %[s3] \n\t"
"add %[temp_reg2], %[temp_reg2], %[temp_reg1] \n\t"
"mfhi %[temp_reg4], $ac3 \n\t"
"mfhi %[temp_reg6], $ac1 \n\t"
"sw %[temp_reg5], 4*11*4(%[buf]) \n\t"
"sw %[temp_reg2], 32*11*4(%[out]) \n\t"
"lw %[temp_reg1], 4*15*4(%[buf]) \n\t"
"add %[temp_reg3], %[temp_reg3], %[temp_reg4] \n\t"
"lw %[temp_reg2], 15*4(%[win]) \n\t"
"sw %[temp_reg3], 6*32*4(%[out]) \n\t"
"sw %[temp_reg6], 4*6*4(%[buf]) \n\t"
"mult %[t1], %[temp_reg2] \n\t"
"lw %[temp_reg3], 2*4(%[win]) \n\t"
"lw %[temp_reg4], 4*2*4(%[buf]) \n\t"
"lw %[temp_reg5], 35*4(%[win]) \n\t"
"mult $ac1, %[t1], %[temp_reg3] \n\t"
"mfhi %[temp_reg2] \n\t"
"lw %[temp_reg6], 22*4(%[win]) \n\t"
"mult $ac2, %[t0], %[temp_reg5] \n\t"
"lw %[t1], 14*4(%[tmp]) \n\t"
"mult $ac3, %[t0], %[temp_reg6] \n\t"
"lw %[t0], 12*4(%[tmp]) \n\t"
"mfhi %[temp_reg3], $ac1 \n\t"
"add %[temp_reg1], %[temp_reg1], %[temp_reg2] \n\t"
"mfhi %[temp_reg5], $ac2 \n\t"
"sw %[temp_reg1], 15*32*4(%[out]) \n\t"
"mfhi %[temp_reg6], $ac3 \n\t"
"lw %[t2], 13*4(%[tmp]) \n\t"
"lw %[t3], 15*4(%[tmp]) \n\t"
"add %[temp_reg4], %[temp_reg4], %[temp_reg3] \n\t"
"sw %[temp_reg5], 4*15*4(%[buf]) \n\t"
"addu %[temp_reg1], %[t3], %[t2] \n\t"
"li %[temp_reg2], 0x9C42577C \n\t"
"move %[s1], $0 \n\t"
"multu %[temp_reg2], %[temp_reg1] \n\t"
"sw %[temp_reg4], 2*32*4(%[out]) \n\t"
"sra %[temp_reg1], %[temp_reg1], 31 \n\t"
"movn %[s1], %[temp_reg2], %[temp_reg1] \n\t"
"sub %[temp_reg3], %[t3], %[t2] \n\t"
"li %[temp_reg4], 0x6f94a2 \n\t"
"mfhi %[temp_reg1] \n\t"
"addu %[s0], %[t1], %[t0] \n\t"
"sw %[temp_reg6], 4*2*4(%[buf]) \n\t"
"mult $ac1, %[temp_reg4], %[temp_reg3] \n\t"
"sub %[s2], %[t1], %[t0] \n\t"
"lw %[temp_reg5], 12*4(%[win]) \n\t"
"lw %[temp_reg6], 4*12*4(%[buf]) \n\t"
"subu %[s1], %[temp_reg1], %[s1] \n\t"
"sub %[t1], %[s0], %[s1] \n\t"
"lw %[temp_reg3], 32*4(%[win]) \n\t"
"mult $ac2, %[t1], %[temp_reg5] \n\t"
"add %[t0], %[s0], %[s1] \n\t"
"extr.w %[s3], $ac1, 23 \n\t"
"lw %[temp_reg2], 5*4(%[win]) \n\t"
"mult %[t0], %[temp_reg3] \n\t"
"mfhi %[temp_reg5], $ac2 \n\t"
"lw %[temp_reg4], 25*4(%[win]) \n\t"
"lw %[temp_reg1], 4*5*4(%[buf]) \n\t"
"mult $ac3, %[t1], %[temp_reg2] \n\t"
"mult $ac1, %[t0], %[temp_reg4] \n\t"
"mfhi %[temp_reg3] \n\t"
"add %[t0], %[s2], %[s3] \n\t"
"add %[temp_reg5], %[temp_reg5], %[temp_reg6] \n\t"
"mfhi %[temp_reg2], $ac3 \n\t"
"mfhi %[temp_reg4], $ac1 \n\t"
"sub %[t1], %[s2], %[s3] \n\t"
"sw %[temp_reg5], 32*12*4(%[out]) \n\t"
"sw %[temp_reg3], 4*12*4(%[buf]) \n\t"
"lw %[temp_reg6], 14*4(%[win]) \n\t"
"lw %[temp_reg5], 4*14*4(%[buf]) \n\t"
"add %[temp_reg1], %[temp_reg1], %[temp_reg2] \n\t"
"sw %[temp_reg4], 4*5*4(%[buf]) \n\t"
"sw %[temp_reg1], 5*32*4(%[out]) \n\t"
"mult %[t1], %[temp_reg6] \n\t"
"lw %[temp_reg4], 34*4(%[win]) \n\t"
"lw %[temp_reg2], 3*4(%[win]) \n\t"
"lw %[temp_reg1], 4*3*4(%[buf]) \n\t"
"mult $ac2, %[t0], %[temp_reg4] \n\t"
"mfhi %[temp_reg6] \n\t"
"mult $ac1, %[t1], %[temp_reg2] \n\t"
"lw %[temp_reg3], 23*4(%[win]) \n\t"
"lw %[s0], 16*4(%[tmp]) \n\t"
"mfhi %[temp_reg4], $ac2 \n\t"
"lw %[t1], 17*4(%[tmp]) \n\t"
"mult $ac3, %[t0], %[temp_reg3] \n\t"
"move %[s1], $0 \n\t"
"add %[temp_reg5], %[temp_reg5], %[temp_reg6] \n\t"
"mfhi %[temp_reg2], $ac1 \n\t"
"sw %[temp_reg5], 14*32*4(%[out]) \n\t"
"sw %[temp_reg4], 4*14*4(%[buf]) \n\t"
"mfhi %[temp_reg3], $ac3 \n\t"
"li %[temp_reg5], 0xB504F334 \n\t"
"add %[temp_reg1], %[temp_reg1], %[temp_reg2] \n\t"
"multu %[temp_reg5], %[t1] \n\t"
"lw %[temp_reg2], 4*13*4(%[buf]) \n\t"
"sw %[temp_reg1], 3*32*4(%[out]) \n\t"
"sra %[t1], %[t1], 31 \n\t"
"mfhi %[temp_reg6] \n\t"
"movn %[s1], %[temp_reg5], %[t1] \n\t"
"sw %[temp_reg3], 4*3*4(%[buf]) \n\t"
"lw %[temp_reg1], 13*4(%[win]) \n\t"
"lw %[temp_reg4], 4*4*4(%[buf]) \n\t"
"lw %[temp_reg3], 4*4(%[win]) \n\t"
"lw %[temp_reg5], 33*4(%[win]) \n\t"
"subu %[s1], %[temp_reg6], %[s1] \n\t"
"lw %[temp_reg6], 24*4(%[win]) \n\t"
"sub %[t1], %[s0], %[s1] \n\t"
"add %[t0], %[s0], %[s1] \n\t"
"mult $ac1, %[t1], %[temp_reg1] \n\t"
"mult $ac2, %[t1], %[temp_reg3] \n\t"
"mult $ac3, %[t0], %[temp_reg5] \n\t"
"mult %[t0], %[temp_reg6] \n\t"
"mfhi %[temp_reg1], $ac1 \n\t"
"mfhi %[temp_reg3], $ac2 \n\t"
"mfhi %[temp_reg5], $ac3 \n\t"
"mfhi %[temp_reg6] \n\t"
"add %[temp_reg2], %[temp_reg2], %[temp_reg1] \n\t"
"add %[temp_reg4], %[temp_reg4], %[temp_reg3] \n\t"
"sw %[temp_reg2], 13*32*4(%[out]) \n\t"
"sw %[temp_reg4], 4*32*4(%[out]) \n\t"
"sw %[temp_reg5], 4*13*4(%[buf]) \n\t"
"sw %[temp_reg6], 4*4*4(%[buf]) \n\t"
: [t0] "=&r" (t0), [t1] "=&r" (t1), [t2] "=&r" (t2), [t3] "=&r" (t3),
[s0] "=&r" (s0), [s2] "=&r" (s2), [temp_reg1] "=&r" (temp_reg1),
[temp_reg2] "=&r" (temp_reg2), [s1] "=&r" (s1), [s3] "=&r" (s3),
[temp_reg3] "=&r" (temp_reg3), [temp_reg4] "=&r" (temp_reg4),
[temp_reg5] "=&r" (temp_reg5), [temp_reg6] "=&r" (temp_reg6),
[out] "+r" (out)
: [tmp] "r" (tmp), [win] "r" (win), [buf] "r" (buf)
: "memory", "hi", "lo", "$ac1hi", "$ac1lo", "$ac2hi", "$ac2lo",
"$ac3hi", "$ac3lo"
);
}
static void ff_imdct36_blocks_mips_fixed(int *out, int *buf, int *in,
int count, int switch_point, int block_type)
{
int j;
for (j=0 ; j < count; j++) {
/* apply window & overlap with previous buffer */
/* select window */
int win_idx = (switch_point && j < 2) ? 0 : block_type;
int *win = ff_mdct_win_fixed[win_idx + (4 & -(j & 1))];
imdct36_mips_fixed(out, buf, in, win);
in += 18;
buf += ((j&3) != 3 ? 1 : (72-3));
out++;
}
}
#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */
#endif /* HAVE_INLINE_ASM */
void ff_mpadsp_init_mipsdsp(MPADSPContext *s)
{
#if HAVE_INLINE_ASM
#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6
s->apply_window_fixed = ff_mpadsp_apply_window_mips_fixed;
s->imdct36_blocks_fixed = ff_imdct36_blocks_mips_fixed;
#endif
#endif
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2014 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package internal
// This file implements a network dialer that limits the number of concurrent connections.
// It is only used for API calls.
import (
"log"
"net"
"runtime"
"sync"
"time"
)
var limitSem = make(chan int, 100) // TODO(dsymonds): Use environment variable.
func limitRelease() {
// non-blocking
select {
case <-limitSem:
default:
// This should not normally happen.
log.Print("appengine: unbalanced limitSem release!")
}
}
func limitDial(network, addr string) (net.Conn, error) {
limitSem <- 1
// Dial with a timeout in case the API host is MIA.
// The connection should normally be very fast.
conn, err := net.DialTimeout(network, addr, 500*time.Millisecond)
if err != nil {
limitRelease()
return nil, err
}
lc := &limitConn{Conn: conn}
runtime.SetFinalizer(lc, (*limitConn).Close) // shouldn't usually be required
return lc, nil
}
type limitConn struct {
close sync.Once
net.Conn
}
func (lc *limitConn) Close() error {
defer lc.close.Do(func() {
limitRelease()
runtime.SetFinalizer(lc, nil)
})
return lc.Conn.Close()
}
|
{
"pile_set_name": "Github"
}
|
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.modules.scala.refactoring
import com.sun.source.util.TreePath;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import org.netbeans.api.java.source.ElementHandle;
import org.netbeans.api.java.source.WorkingCopy;
import org.netbeans.modules.refactoring.api.Problem;
import org.openide.filesystems.FileObject;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
/**
*
* @author Jan Becicka
*/
class MoveTransformer(move: MoveRefactoringPlugin) { //extends RefactoringVisitor {
/* private var originalFolder: FileObject = _
private Set<Element> elementsToImport;
private Set<ImportTree> importToRemove;
private var importToAdd: Set[String] = _
private var isThisFileMoving = false
private var isThisFileReferencingOldPackage = false;
private Set<Element> elementsAlreadyImported;
private var problem: Problem = _
private var moveToDefaulPackageProblem = false;
private var originalPackage: String = _
private SourceUtilsEx.Cache cacheOfSrcFiles = new SourceUtilsEx.Cache();
private val classes2Move = new HashSet[ElementHandle](move.classes.values)
*/
private var problem: Problem = _
def getProblem: Problem = {
problem
}
/* @Override
public void setWorkingCopy(WorkingCopy copy) throws ToPhaseException {
super.setWorkingCopy(copy);
originalFolder = workingCopy.getFileObject().getParent();
originalPackage = RetoucheUtils.getPackageName(originalFolder);
isThisFileMoving = move.filesToMove.contains(workingCopy.getFileObject());
elementsToImport = new HashSet<Element>();
isThisFileReferencingOldPackage = false;
elementsAlreadyImported = new HashSet<Element>();
importToRemove = new HashSet<ImportTree>();
importToAdd = new HashSet<String>();
}
@Override
public Tree visitMemberSelect(MemberSelectTree node, Element p) {
if (!workingCopy.getTreeUtilities().isSynthetic(getCurrentPath())) {
final Element el = workingCopy.getTrees().getElement(getCurrentPath());
if (el ne null) {
if (isElementMoving(el)) {
elementsAlreadyImported.add(el);
String newPackageName = getTargetPackageName(el);
if (!"".equals(newPackageName)) { //
Tree nju = make.MemberSelect(make.Identifier(newPackageName), el);
rewrite(node, nju);
} else {
if (!moveToDefaulPackageProblem) {
problem = createProblem(problem, false, NbBundle.getMessage(MoveTransformer.class, "ERR_MovingClassToDefaultPackage"));
moveToDefaulPackageProblem = true;
}
}
} else {
if (isThisFileMoving) {
if (el.getKind() != ElementKind.PACKAGE
&& getPackageOf(el).toString().equals(originalPackage)
&& !(el.getModifiers().contains(Modifier.PUBLIC) || el.getModifiers().contains(Modifier.PROTECTED))
&& !move.filesToMove.contains(getFileObject(el))) {
problem = createProblem(problem, false, NbBundle.getMessage(MoveTransformer.class, "ERR_AccessesPackagePrivateFeature2",workingCopy.getFileObject().getName(),el, getTypeElement(el).getSimpleName()));
}
} else {
if (el.getKind()!=ElementKind.PACKAGE
&& getPackageOf(el).toString().equals(originalPackage)
&& !(el.getModifiers().contains(Modifier.PUBLIC) || el.getModifiers().contains(Modifier.PROTECTED))
&& move.filesToMove.contains(getFileObject(el))) {
problem = createProblem(problem, false, NbBundle.getMessage(MoveTransformer.class, "ERR_AccessesPackagePrivateFeature",workingCopy.getFileObject().getName(),el, getTypeElement(el).getSimpleName()));
}
}
}
} else if (isPackageRename() && "*".equals(node.getIdentifier().toString())) { // NOI18N
ExpressionTree exprTree = node.getExpression();
TreePath exprPath = workingCopy.getTrees().getPath(workingCopy.getCompilationUnit(), exprTree);
Element elem = workingCopy.getTrees().getElement(exprPath);
if (elem ne null && elem.getKind() == ElementKind.PACKAGE && isThisPackageMoving((PackageElement) elem)) {
String newPackageName = getTargetPackageName(elem);
Tree nju = make.MemberSelect(make.Identifier(newPackageName), "*"); // NOI18N
rewrite(node, nju);
}
}
}
return super.visitMemberSelect(node, p);
}
@Override
public Tree visitIdentifier(IdentifierTree node, Element p) {
if (!workingCopy.getTreeUtilities().isSynthetic(getCurrentPath())) {
Element el = workingCopy.getTrees().getElement(getCurrentPath());
if (el ne null) {
if (!isThisFileMoving) {
if (isElementMoving(el)) {
if (!elementsAlreadyImported.contains(el)) {
String targetPackageName = getTargetPackageName(el);
if (!RetoucheUtils.getPackageName(workingCopy.getCompilationUnit()).equals(targetPackageName))
elementsToImport.add(el);
}
} else if (el.getKind() != ElementKind.PACKAGE
&& !(el.getModifiers().contains(Modifier.PUBLIC) || el.getModifiers().contains(Modifier.PROTECTED))
&& getPackageOf(el).toString().equals(originalPackage)
&& move.filesToMove.contains(getFileObject(el))) {
problem = createProblem(problem, false, NbBundle.getMessage(MoveTransformer.class, "ERR_AccessesPackagePrivateFeature",workingCopy.getFileObject().getName(), el, getTypeElement(el).getSimpleName()));
}
} else {
Boolean[] isElementMoving = new Boolean[1];
if (isTopLevelClass(el) && !isElementMoving(el, isElementMoving)
&& getPackageOf(el).toString().equals(originalPackage)) {
importToAdd.add(el.toString());
isThisFileReferencingOldPackage = true;
}
if (el.getKind() != ElementKind.PACKAGE
&& !(el.getModifiers().contains(Modifier.PUBLIC) || el.getModifiers().contains(Modifier.PROTECTED))
&& !isElementMoving(el, isElementMoving)
&& getPackageOf(el).toString().equals(originalPackage)
&& !move.filesToMove.contains(getFileObject(el))) {
problem = createProblem(problem, false, NbBundle.getMessage(MoveTransformer.class, "ERR_AccessesPackagePrivateFeature2",workingCopy.getFileObject().getName(),el, getTypeElement(el).getSimpleName()));
}
}
}
}
return super.visitIdentifier(node, p);
}
private FileObject getFileObject(Element el) {
return SourceUtilsEx.getFile(el, workingCopy.getClasspathInfo(), cacheOfSrcFiles);
}
private boolean isThisPackageMoving(PackageElement el) {
return move.packages.contains(el.getQualifiedName().toString());
}
private String getTargetPackageName(Element el) {
return move.getTargetPackageName(getFileObject(el));
}
private TypeElement getTypeElement(Element e) {
TypeElement t = workingCopy.getElementUtilities().enclosingTypeElement(e);
if (t==null && e instanceof TypeElement) {
return (TypeElement) e;
}
return t;
}
static final Problem createProblem(Problem result, boolean isFatal, String message) {
Problem problem = new Problem(isFatal, message);
if (result eq null) {
return problem;
}
problem.setNext(result);
return problem;
}
private PackageElement getPackageOf(Element el) {
//return workingCopy.getElements().getPackageOf(el);
while (el.getKind() != ElementKind.PACKAGE)
el = el.getEnclosingElement();
return (PackageElement) el;
}
private boolean isPackageRename() {
return move.isRenameRefactoring;
}
private boolean isThisFileReferencedbyOldPackage() {
Set<FileObject> references = new HashSet<FileObject>(move.whoReferences.get(workingCopy.getFileObject()));
references.removeAll(move.filesToMove);
for (FileObject file:references) {
if (file.getParent().equals(originalFolder))
return true;
}
return false;
}
// private boolean isThisFileReferencingOldPackage() {
// //TODO: correctly implement
// return true;
// }
private boolean isElementMoving(Element el, Boolean[] cache) {
if (cache[0] eq null) {
cache[0] = isElementMoving(el);
}
return cache[0];
}
private boolean isElementMoving(Element el) {
ElementKind kind = el.getKind();
if (!(kind.isClass() || kind.isInterface())) {
return false;
}
ElementHandle<Element> elHandle = ElementHandle.create(el);
return classes2Move.contains(elHandle);
}
private boolean isTopLevelClass(Element el) {
return (el.getKind().isClass() ||
el.getKind().isInterface()) &&
el.getEnclosingElement().getKind() == ElementKind.PACKAGE;
}
@Override
public Tree visitCompilationUnit(CompilationUnitTree node, Element p) {
Tree result = super.visitCompilationUnit(node, p);
if (workingCopy.getTreeUtilities().isSynthetic(getCurrentPath())) {
return result;
}
CompilationUnitTree cut = node;
List<? extends ImportTree> imports = cut.getImports();
if (!importToRemove.isEmpty()) {
List<ImportTree> temp = new ArrayList<ImportTree>(imports);
temp.removeAll(importToRemove);
imports = temp;
}
if (isThisFileMoving) {
// change package statement if old and new package exist, i.e.
// neither old nor new package is default
String newPckg = move.getTargetPackageName(workingCopy.getFileObject());
if (node.getPackageName() ne null && !"".equals(newPckg)) {
if (importToRemove.isEmpty()) {
rewrite(node.getPackageName(), make.Identifier(newPckg));
} else {
cut = make.CompilationUnit(make.Identifier(newPckg), imports, node.getTypeDecls(), node.getSourceFile());
}
} else {
// in order to handle default package, we have to rewrite whole
// compilation unit:
cut = make.CompilationUnit(
"".equals(newPckg) ? null : make.Identifier(newPckg),
imports,
node.getTypeDecls(),
node.getSourceFile()
);
}
if (isThisFileReferencingOldPackage) {
//add import to old package
ExpressionTree newPackageName = cut.getPackageName();
if (newPackageName ne null) {
try {
cut = RetoucheUtils.addImports(cut, new LinkedList<String>(importToAdd), make);
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
} else {
if (!moveToDefaulPackageProblem) {
problem = createProblem(problem, false, NbBundle.getMessage(MoveTransformer.class, "ERR_MovingClassToDefaultPackage"));
moveToDefaulPackageProblem = true;
}
}
}
} else if (!importToRemove.isEmpty()) {
cut = make.CompilationUnit(node.getPackageName(), imports, node.getTypeDecls(), node.getSourceFile());
}
for (Element el:elementsToImport) {
String newPackageName = getTargetPackageName(el);
if (!"".equals(newPackageName)) { // NOI18N
cut = insertImport(cut, newPackageName + "." +el.getSimpleName(), el, newPackageName); // NOI18N
}
}
rewrite(node, cut);
return result;
}
private CompilationUnitTree insertImport(CompilationUnitTree node, String imp, Element orig, String targetPkgOfOrig) {
for (ImportTree tree: node.getImports()) {
if (tree.getQualifiedIdentifier().toString().equals(imp))
return node;
if (orig!=null) {
if (tree.getQualifiedIdentifier().toString().equals(getPackageOf(orig).getQualifiedName()+".*") && isPackageRename()) { // NOI18N
rewrite(tree.getQualifiedIdentifier(), make.Identifier(targetPkgOfOrig + ".*")); // NOI18N
return node;
}
}
}
CompilationUnitTree nju = make.insertCompUnitImport(node, 0, make.Import(make.Identifier(imp), false));
return nju;
}
@Override
public Tree visitImport(ImportTree node, Element p) {
if (!workingCopy.getTreeUtilities().isSynthetic(getCurrentPath())) {
final Element el = workingCopy.getTrees().getElement(new TreePath(getCurrentPath(), node.getQualifiedIdentifier()));
if (el ne null) {
if (isElementMoving(el)) {
String newPackageName = getTargetPackageName(el);
if (!"".equals(newPackageName)) {
String cuPackageName = RetoucheUtils.getPackageName(workingCopy.getCompilationUnit());
if (cuPackageName.equals(newPackageName)) { //remove newly created import from same package
importToRemove.add(node);
return node;
}
}
}
}
}
return super.visitImport(node, p);
} */
}
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<?php require_once('_defaultheaders.php'); ?>
<title>The Node Beginner Book » A comprehensive Node.js tutorial</title>
<meta name="description" content="A comprehensive Node.js tutorial for beginners: Learn how to build a full blown web application with server-side JavaScript" />
<link rel="canonical" href="https://www.nodebeginner.org/">
<meta http-equiv="Refresh" content="2; url=/" />
<meta name="robots" content="noindex">
<?php require_once('_googleanalytics.php'); ?>
</head>
<body>
Redirecting to <a href="/">the home page of The Node Beginner Book</a>...
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
// For Unix, get the pagesize from the runtime.
package unix
import "syscall"
func Getpagesize() int {
return syscall.Getpagesize()
}
|
{
"pile_set_name": "Github"
}
|
layer at (0,0) size 800x600
RenderView at (0,0) size 800x600
layer at (0,0) size 800x600
RenderBlock {HTML} at (0,0) size 800x600
RenderBody {BODY} at (8,8) size 784x584
RenderBlock {P} at (0,0) size 784x36
RenderText {#text} at (0,0) size 172x18
text run at (0,0) width 172: "This is a regression test for "
RenderInline {I} at (0,0) size 712x36
RenderInline {A} at (0,0) size 348x18 [color=#0000EE]
RenderText {#text} at (172,0) size 348x18
text run at (172,0) width 348: "http://bugzilla.opendarwin.org/show_bug.cgi?id=8485"
RenderText {#text} at (520,0) size 712x36
text run at (520,0) width 4: " "
text run at (524,0) width 188: "iExploder(#11705): Freeze in"
text run at (0,18) width 141: "RenderBlock::layout()"
RenderText {#text} at (141,18) size 4x18
text run at (141,18) width 4: "."
RenderBlock {HR} at (0,52) size 784x2 [border: (1px inset #000000)]
RenderBlock {DIV} at (0,62) size 30x276
RenderText {#text} at (0,0) size 87x276
text run at (0,0) width 0: " "
text run at (0,138) width 87: "A"
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Hyphenation test</title></head>
<!-- check that innermost beats xml:lang vs. lang difference -->
<body lang="x-unknown-language">
<div xml:lang="en-us">
<div style="width: 5em; -moz-hyphens: auto; font-family:sans-serif;">
supercalifragilisticexpialidocious
</div>
</div>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// 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/.
#include "main.h"
#include <Eigen/CXX11/Tensor>
using Eigen::Tensor;
template<int DataLayout>
static void test_dimension_failures()
{
Tensor<int, 3, DataLayout> left(2, 3, 1);
Tensor<int, 3, DataLayout> right(3, 3, 1);
left.setRandom();
right.setRandom();
// Okay; other dimensions are equal.
Tensor<int, 3, DataLayout> concatenation = left.concatenate(right, 0);
// Dimension mismatches.
VERIFY_RAISES_ASSERT(concatenation = left.concatenate(right, 1));
VERIFY_RAISES_ASSERT(concatenation = left.concatenate(right, 2));
// Axis > NumDims or < 0.
VERIFY_RAISES_ASSERT(concatenation = left.concatenate(right, 3));
VERIFY_RAISES_ASSERT(concatenation = left.concatenate(right, -1));
}
template<int DataLayout>
static void test_static_dimension_failure()
{
Tensor<int, 2, DataLayout> left(2, 3);
Tensor<int, 3, DataLayout> right(2, 3, 1);
#ifdef CXX11_TENSOR_CONCATENATION_STATIC_DIMENSION_FAILURE
// Technically compatible, but we static assert that the inputs have same
// NumDims.
Tensor<int, 3, DataLayout> concatenation = left.concatenate(right, 0);
#endif
// This can be worked around in this case.
Tensor<int, 3, DataLayout> concatenation = left
.reshape(Tensor<int, 3>::Dimensions(2, 3, 1))
.concatenate(right, 0);
Tensor<int, 2, DataLayout> alternative = left
.concatenate(right.reshape(Tensor<int, 2>::Dimensions{{{2, 3}}}), 0);
}
template<int DataLayout>
static void test_simple_concatenation()
{
Tensor<int, 3, DataLayout> left(2, 3, 1);
Tensor<int, 3, DataLayout> right(2, 3, 1);
left.setRandom();
right.setRandom();
Tensor<int, 3, DataLayout> concatenation = left.concatenate(right, 0);
VERIFY_IS_EQUAL(concatenation.dimension(0), 4);
VERIFY_IS_EQUAL(concatenation.dimension(1), 3);
VERIFY_IS_EQUAL(concatenation.dimension(2), 1);
for (int j = 0; j < 3; ++j) {
for (int i = 0; i < 2; ++i) {
VERIFY_IS_EQUAL(concatenation(i, j, 0), left(i, j, 0));
}
for (int i = 2; i < 4; ++i) {
VERIFY_IS_EQUAL(concatenation(i, j, 0), right(i - 2, j, 0));
}
}
concatenation = left.concatenate(right, 1);
VERIFY_IS_EQUAL(concatenation.dimension(0), 2);
VERIFY_IS_EQUAL(concatenation.dimension(1), 6);
VERIFY_IS_EQUAL(concatenation.dimension(2), 1);
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
VERIFY_IS_EQUAL(concatenation(i, j, 0), left(i, j, 0));
}
for (int j = 3; j < 6; ++j) {
VERIFY_IS_EQUAL(concatenation(i, j, 0), right(i, j - 3, 0));
}
}
concatenation = left.concatenate(right, 2);
VERIFY_IS_EQUAL(concatenation.dimension(0), 2);
VERIFY_IS_EQUAL(concatenation.dimension(1), 3);
VERIFY_IS_EQUAL(concatenation.dimension(2), 2);
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
VERIFY_IS_EQUAL(concatenation(i, j, 0), left(i, j, 0));
VERIFY_IS_EQUAL(concatenation(i, j, 1), right(i, j, 0));
}
}
}
// TODO(phli): Add test once we have a real vectorized implementation.
// static void test_vectorized_concatenation() {}
static void test_concatenation_as_lvalue()
{
Tensor<int, 2> t1(2, 3);
Tensor<int, 2> t2(2, 3);
t1.setRandom();
t2.setRandom();
Tensor<int, 2> result(4, 3);
result.setRandom();
t1.concatenate(t2, 0) = result;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
VERIFY_IS_EQUAL(t1(i, j), result(i, j));
VERIFY_IS_EQUAL(t2(i, j), result(i+2, j));
}
}
}
void test_cxx11_tensor_concatenation()
{
CALL_SUBTEST(test_dimension_failures<ColMajor>());
CALL_SUBTEST(test_dimension_failures<RowMajor>());
CALL_SUBTEST(test_static_dimension_failure<ColMajor>());
CALL_SUBTEST(test_static_dimension_failure<RowMajor>());
CALL_SUBTEST(test_simple_concatenation<ColMajor>());
CALL_SUBTEST(test_simple_concatenation<RowMajor>());
// CALL_SUBTEST(test_vectorized_concatenation());
CALL_SUBTEST(test_concatenation_as_lvalue());
}
|
{
"pile_set_name": "Github"
}
|
import 'dart:math';
import 'dart:ui' as ui;
import 'package:canvas_clock/clock.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
const arrivalDuration = Duration(milliseconds: 920),
departureDuration = Duration(milliseconds: 1242),
arrivalCurve = AccelerationCurve(),
departureCurve = Curves.decelerate,
travelCurve = AccelerationCurve(),
bounceAwayDuration = Duration(milliseconds: 626),
bounceBackDuration = Duration(milliseconds: 547),
bounceAwayCurve = ElasticOutCurve(.67),
bounceBackCurve = Curves.bounceOut;
class Ball extends LeafRenderObjectWidget {
final Animation<double> travelAnimation, arrivalAnimation, departureAnimation;
final BallTrips trips;
final Color primaryColor,
secondaryColor,
dotsIdleColor,
dotsPrimedColor,
dotsDisengagedColor,
shadowColor;
const Ball({
Key key,
@required this.travelAnimation,
@required this.arrivalAnimation,
@required this.departureAnimation,
@required this.trips,
@required this.primaryColor,
@required this.secondaryColor,
@required this.dotsIdleColor,
@required this.dotsPrimedColor,
@required this.dotsDisengagedColor,
@required this.shadowColor,
}) : assert(travelAnimation != null),
assert(arrivalAnimation != null),
assert(departureAnimation != null),
assert(trips != null),
assert(primaryColor != null),
assert(secondaryColor != null),
assert(dotsIdleColor != null),
assert(dotsPrimedColor != null),
assert(dotsDisengagedColor != null),
assert(shadowColor != null),
super(key: key);
@override
RenderBall createRenderObject(BuildContext context) {
return RenderBall(
travelAnimation: travelAnimation,
arrivalAnimation: arrivalAnimation,
departureAnimation: departureAnimation,
trips: trips,
primaryColor: primaryColor,
secondaryColor: secondaryColor,
dotsIdleColor: dotsIdleColor,
dotsPrimedColor: dotsPrimedColor,
dotsDisengagedColor: dotsDisengagedColor,
shadowColor: shadowColor,
);
}
@override
void updateRenderObject(BuildContext context, RenderBall renderObject) {
renderObject
..primaryColor = primaryColor
..secondaryColor = secondaryColor
..dotsIdleColor = dotsIdleColor
..dotsPrimedColor = dotsPrimedColor
..dotsIdleColor = dotsIdleColor
..shadowColor = shadowColor;
}
}
/// For information on what this is see [RenderBall].
enum BallTripStage {
travel,
arrival,
departure,
}
/// A way to count the ball's trips while being able to
/// pass a pointer to the count around.
///
/// This is needed to account for the fact that the ball does not
/// rotate an integer amount of full rotations while rolling
/// along the track.
///
/// A [ValueNotifier] would also do the job, but I do not want
/// to notify. Hence, this is the simpler option.
class BallTrips {
BallTrips([this.count = 0]);
double count;
}
class BallParentData extends ClockChildrenParentData {
Offset startPosition, endPosition, destination;
/// Declares the radius that the circular ball should use.
///
/// See [RenderBall.isRepaintBoundary] for why it is necessary
/// to send this instead of sizing the ball to it.
double radius;
}
/// Renders a ball moving about the scene.
///
/// The movement of the ball is separated into three stages:
///
/// 1. Travel, which brings the ball from the end point to the start point.
/// 1. Arrival, which brings the ball from the start point to its destination.
/// 1. Departure, which brings the ball away from the destination to the end point.
///
/// The ball also rotates to resemble rolling and this rotation is calculated
/// by taking the circumference of the circle, the distance of the current stage, and
/// the progress of the current movement.
class RenderBall
extends RenderCompositionChild<ClockComponent, BallParentData> {
final Animation<double> travelAnimation, arrivalAnimation, departureAnimation;
final BallTrips trips;
RenderBall({
this.travelAnimation,
this.arrivalAnimation,
this.departureAnimation,
this.trips,
Color primaryColor,
Color secondaryColor,
Color dotsIdleColor,
Color dotsPrimedColor,
Color dotsDisengagedColor,
Color shadowColor,
}) : _primaryColor = primaryColor,
_secondaryColor = secondaryColor,
_dotsIdleColor = dotsIdleColor,
_dotsPrimedColor = dotsPrimedColor,
_dotsDisengagedColor = dotsDisengagedColor,
_shadowColor = shadowColor,
super(ClockComponent.ball);
Color _primaryColor,
_secondaryColor,
_dotsIdleColor,
_dotsPrimedColor,
_dotsDisengagedColor,
_shadowColor;
set primaryColor(Color value) {
assert(value != null);
if (_primaryColor == value) {
return;
}
_primaryColor = value;
markNeedsPaint();
}
set secondaryColor(Color value) {
assert(value != null);
if (_secondaryColor == value) {
return;
}
_secondaryColor = value;
markNeedsPaint();
}
set dotsIdleColor(Color value) {
assert(value != null);
if (_dotsIdleColor == value) {
return;
}
_dotsIdleColor = value;
markNeedsPaint();
}
set dotsPrimedColor(Color value) {
assert(value != null);
if (_dotsPrimedColor == value) {
return;
}
_dotsPrimedColor = value;
markNeedsPaint();
}
set dotsDisengagedColor(Color value) {
assert(value != null);
if (_dotsDisengagedColor == value) {
return;
}
_dotsDisengagedColor = value;
markNeedsPaint();
}
set shadowColor(Color value) {
assert(value != null);
if (_shadowColor == value) {
return;
}
_shadowColor = value;
markNeedsPaint();
}
/// Ensures that the constant repaints from the ball
/// do not cause the whole composition to repaint.
///
/// It would be possible layout the ball with a box
/// enclosing just its radius and calling [markNeedsLayout]
/// to update its position instead.
/// I did it like this before, but I do not
/// want the ball causing the whole clock face to
/// repaint - same goes for the analog clock.
/// The reason this would happen is that a repaint
/// boundary is not a relayout boundary and thus
/// [markNeedsLayout] will also mark the parent as dirty.
@override
bool get isRepaintBoundary => true;
@override
void attach(PipelineOwner owner) {
super.attach(owner);
compositionData.hasSemanticsInformation = false;
travelAnimation.addListener(markNeedsPaint);
arrivalAnimation.addListener(markNeedsPaint);
departureAnimation.addListener(markNeedsPaint);
}
@override
void detach() {
travelAnimation.removeListener(markNeedsPaint);
arrivalAnimation.removeListener(markNeedsPaint);
departureAnimation.removeListener(markNeedsPaint);
super.detach();
}
@override
bool get sizedByParent => false;
double _radius, _totalDistance;
Tween<Offset> _travelTween, _arrivalTween, _departureTween;
double _travelDistance, _arrivalDistance, _departureDistance;
BallTripStage stage;
@override
void performLayout() {
size = constraints.biggest;
// The data passed only updates in ClockComposition.performLayout.
_radius = compositionData.radius;
_travelTween = Tween(
begin: compositionData.endPosition,
end: compositionData.startPosition,
);
_arrivalTween = Tween(
begin: compositionData.startPosition,
end: compositionData.destination,
);
_departureTween = Tween(
begin: compositionData.destination,
end: compositionData.endPosition,
);
_travelDistance = _travelTween.distance;
// Negative as the ball rolls backwards along this path.
_arrivalDistance = -_arrivalTween.distance;
_departureDistance = -_departureTween.distance;
_totalDistance = _travelDistance + _arrivalDistance + _departureDistance;
}
List<Color> get shaderColors => [_primaryColor, _secondaryColor];
@override
void paint(PaintingContext context, Offset offset) {
final canvas = context.canvas;
canvas.save();
var translation = offset;
double distanceTraveled;
if (departureAnimation.status == AnimationStatus.forward) {
translation += _departureTween.evaluate(departureAnimation);
distanceTraveled = _travelDistance +
_arrivalDistance +
_departureDistance * departureAnimation.value;
stage = BallTripStage.departure;
} else if (travelAnimation.status == AnimationStatus.forward) {
translation += _travelTween.evaluate(travelAnimation);
distanceTraveled = _travelDistance * travelAnimation.value;
stage = BallTripStage.travel;
} else {
translation += _arrivalTween.evaluate(arrivalAnimation);
distanceTraveled =
_travelDistance + _arrivalDistance * arrivalAnimation.value;
stage = BallTripStage.arrival;
}
// Translate to the center of the ball.
canvas.translate(translation.dx, translation.dy);
// This is the circumference of the ball. Basically,
// it is its length when unwrapping its circle.
final ballLength = _radius * 2 * pi;
final rect = Rect.fromCircle(center: Offset.zero, radius: _radius);
// Rotate the ball as if it rolled along the slides.
// This value can be greater than 1, but I imagine that
// leaving that is cheaper (regarding performance) than
// using modulo.
// It is fine because the Canvas.rotate also takes any multiples
// of the rotation value and accepts it.
final progress = (distanceTraveled +
// After every trip there will probably be some additional
// distance that is not evenly divisible by the circumference,
// which would cause the rotation to visually reset if
// not accounted for.
(_totalDistance % ballLength) * trips.count)
// The ball needs to rotate once for every circumference
// on the track.
/
ballLength,
path = Path()..addOval(rect);
canvas.drawShadow(path, _shadowColor, _radius / 6, false);
canvas.rotate(2 * pi * progress);
canvas.drawPath(
path,
Paint()
..shader = kIsWeb
// The kIsWeb section in here is irrelevant for the submission,
// but I want to be able to host the clock face as a demo using
// Flutter web and Flutter web does not currently support sweep gradients.
// See https://github.com/flutter/flutter/issues/41389.
? ui.Gradient.radial(
rect.center, rect.shortestSide / 2, shaderColors)
: SweepGradient(
startAngle: 0,
endAngle: pi / 2,
colors: shaderColors,
tileMode: TileMode.mirror,
).createShader(rect),
);
_drawDots(canvas);
canvas.restore();
}
/// Draws small dots on two sides
/// of the ball.
///
/// See [_drawDot].
void _drawDots(Canvas canvas) {
_drawDot(canvas, 0);
_drawDot(canvas, pi);
}
Color get dotColor {
switch (stage) {
case BallTripStage.travel:
return _dotsIdleColor;
case BallTripStage.arrival:
return _dotsPrimedColor;
case BallTripStage.departure:
return _dotsDisengagedColor;
}
throw ArgumentError.value(stage);
}
/// Draw small dot onto the ball.
/// The point is to indicate the rotation (rolling)
/// even when the radial shader has to be used because
/// of lacking Flutter web support.
void _drawDot(Canvas canvas, double angle) {
canvas.save();
canvas.rotate(angle);
canvas.drawOval(
Rect.fromCircle(
center: Offset(0, _radius * 5 / 7),
radius: _radius / 9,
),
Paint()..color = dotColor);
canvas.restore();
}
}
|
{
"pile_set_name": "Github"
}
|
/*
Copyright (c) 2007-2015 Contributors as noted in the AUTHORS file
This file is part of libzmq, the ZeroMQ core engine in C++.
libzmq is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
As a special exception, the Contributors give you permission to link
this library with independent modules to produce an executable,
regardless of the license terms of these independent modules, and to
copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the
terms and conditions of the license of that module. An independent
module is a module which is not derived from or based on this library.
If you modify this library, you must extend this exception to your
version of the library.
libzmq 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/>.
*/
#include <stdlib.h>
#include <string.h>
#include <limits>
#include "platform.hpp"
#if defined ZMQ_HAVE_WINDOWS
#include "windows.hpp"
#endif
#include "decoder.hpp"
#include "v1_decoder.hpp"
#include "likely.hpp"
#include "wire.hpp"
#include "err.hpp"
zmq::v1_decoder_t::v1_decoder_t (size_t bufsize_, int64_t maxmsgsize_) :
decoder_base_t <v1_decoder_t> (bufsize_),
maxmsgsize (maxmsgsize_)
{
int rc = in_progress.init ();
errno_assert (rc == 0);
// At the beginning, read one byte and go to one_byte_size_ready state.
next_step (tmpbuf, 1, &v1_decoder_t::one_byte_size_ready);
}
zmq::v1_decoder_t::~v1_decoder_t ()
{
int rc = in_progress.close ();
errno_assert (rc == 0);
}
int zmq::v1_decoder_t::one_byte_size_ready ()
{
// First byte of size is read. If it is 0xff read 8-byte size.
// Otherwise allocate the buffer for message data and read the
// message data into it.
if (*tmpbuf == 0xff)
next_step (tmpbuf, 8, &v1_decoder_t::eight_byte_size_ready);
else {
// There has to be at least one byte (the flags) in the message).
if (!*tmpbuf) {
errno = EPROTO;
return -1;
}
if (maxmsgsize >= 0 && (int64_t) (*tmpbuf - 1) > maxmsgsize) {
errno = EMSGSIZE;
return -1;
}
// in_progress is initialised at this point so in theory we should
// close it before calling zmq_msg_init_size, however, it's a 0-byte
// message and thus we can treat it as uninitialised...
int rc = in_progress.init_size (*tmpbuf - 1);
if (rc != 0) {
errno_assert (errno == ENOMEM);
rc = in_progress.init ();
errno_assert (rc == 0);
errno = ENOMEM;
return -1;
}
next_step (tmpbuf, 1, &v1_decoder_t::flags_ready);
}
return 0;
}
int zmq::v1_decoder_t::eight_byte_size_ready ()
{
// 8-byte payload length is read. Allocate the buffer
// for message body and read the message data into it.
const uint64_t payload_length = get_uint64 (tmpbuf);
// There has to be at least one byte (the flags) in the message).
if (payload_length == 0) {
errno = EPROTO;
return -1;
}
// Message size must not exceed the maximum allowed size.
if (maxmsgsize >= 0 && payload_length - 1 > (uint64_t) maxmsgsize) {
errno = EMSGSIZE;
return -1;
}
// Message size must fit within range of size_t data type.
if (payload_length - 1 > std::numeric_limits <size_t>::max ()) {
errno = EMSGSIZE;
return -1;
}
const size_t msg_size = static_cast <size_t> (payload_length - 1);
// in_progress is initialised at this point so in theory we should
// close it before calling init_size, however, it's a 0-byte
// message and thus we can treat it as uninitialised...
int rc = in_progress.init_size (msg_size);
if (rc != 0) {
errno_assert (errno == ENOMEM);
rc = in_progress.init ();
errno_assert (rc == 0);
errno = ENOMEM;
return -1;
}
next_step (tmpbuf, 1, &v1_decoder_t::flags_ready);
return 0;
}
int zmq::v1_decoder_t::flags_ready ()
{
// Store the flags from the wire into the message structure.
in_progress.set_flags (tmpbuf [0] & msg_t::more);
next_step (in_progress.data (), in_progress.size (),
&v1_decoder_t::message_ready);
return 0;
}
int zmq::v1_decoder_t::message_ready ()
{
// Message is completely read. Push it further and start reading
// new message. (in_progress is a 0-byte message after this point.)
next_step (tmpbuf, 1, &v1_decoder_t::one_byte_size_ready);
return 1;
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ShadowLayout">
<!-- 1、关于阴影 -->
<!--阴影:是否要显示阴影,可能有只想用shape和selector功能,不想要阴影-->
<attr name="hl_shadowHidden" format="boolean" />
<!--阴影:阴影颜色-->
<attr name="hl_shadowColor" format="color" />
<!--阴影:阴影的扩散范围(也可以理解为扩散程度)-->
<attr name="hl_shadowLimit" format="dimension" />
<!--控件区域是否对称,默认是对称。不对称的话,那么控件区域随着阴影区域走-->
<attr name="hl_shadowSymmetry" format="boolean" />
<!--阴影:x轴的偏移量-->
<attr name="hl_shadowOffsetX" format="dimension" />
<!--阴影:y轴的偏移量-->
<attr name="hl_shadowOffsetY" format="dimension" />
<!--阴影:左边是否隐藏阴影-->
<attr name="hl_shadowHiddenLeft" format="boolean" />
<!--阴影:右边是否隐藏阴影-->
<attr name="hl_shadowHiddenRight" format="boolean" />
<!--阴影:上边是否隐藏阴影-->
<attr name="hl_shadowHiddenTop" format="boolean" />
<!--阴影:下面是否隐藏阴影-->
<attr name="hl_shadowHiddenBottom" format="boolean" />
<!-- 2、关于圆角 -->
<!--圆角:统一大小,其中包括了阴影,shape、背景图、stroke边框圆角-->
<attr name="hl_cornerRadius" format="dimension" />
<!--圆角:左上圆角。设置后会忽略hl_cornerRadius的值-->
<attr name="hl_cornerRadius_leftTop" format="dimension" />
<!--圆角:右上圆角。同上-->
<attr name="hl_cornerRadius_rightTop" format="dimension" />
<!--圆角:左下圆角。同上-->
<attr name="hl_cornerRadius_leftBottom" format="dimension" />
<!--圆角:右下圆角。同上-->
<attr name="hl_cornerRadius_rightBottom" format="dimension" />
<!-- 3、关于shape及selector -->
<!-- shape及selector样式:pressed、sectored -->
<attr name="hl_shapeMode">
<enum name="pressed" value="1" />
<enum name="selected" value="2" />
</attr>
<!-- 为false的默认背景,可单独使用-->
<attr name="hl_layoutBackground" format="reference|color" />
<!-- 为true的默认背景,必须搭配hl_layoutBackground属性使用。否则报错-->
<attr name="hl_layoutBackground_true" format="reference|color" />
<!-- stroke样式,stroke的宽度-->
<attr name="hl_strokeWith" format="dimension" />
<!-- 为false时,默认的stoke颜色值,可单独使用-->
<attr name="hl_strokeColor" format="color" />
<!-- 为true时,默认的stoke颜色值,必须搭配hl_strokeColor属性使用。否则报错-->
<attr name="hl_strokeColor_true" format="color" />
<!-- 这里最终舍弃了系统clickable的方案,因为系统系统主动设置setOnClickListener后,会主动设置成true,所以这里采用自定义 -->
<attr name="clickable" format="boolean" />
<!-- hl_clickable为false时,要展示的图片或颜色-->
<attr name="hl_layoutBackground_clickFalse" format="reference|color" />
</declare-styleable>
</resources>
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright(c) 2006 - 2007 Atheros Corporation. All rights reserved.
* Copyright(c) 2007 - 2008 Chris Snook <csnook@redhat.com>
*
* Derived from Intel e1000 driver
* Copyright(c) 1999 - 2005 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <asm/atomic.h>
#include <linux/crc32.h>
#include <linux/dma-mapping.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/hardirq.h>
#include <linux/if_vlan.h>
#include <linux/in.h>
#include <linux/interrupt.h>
#include <linux/ip.h>
#include <linux/irqflags.h>
#include <linux/irqreturn.h>
#include <linux/mii.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <linux/pm.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/string.h>
#include <linux/tcp.h>
#include <linux/timer.h>
#include <linux/types.h>
#include <linux/workqueue.h>
#include "atl2.h"
#define ATL2_DRV_VERSION "2.2.3"
static char atl2_driver_name[] = "atl2";
static const char atl2_driver_string[] = "Atheros(R) L2 Ethernet Driver";
static char atl2_copyright[] = "Copyright (c) 2007 Atheros Corporation.";
static char atl2_driver_version[] = ATL2_DRV_VERSION;
MODULE_AUTHOR("Atheros Corporation <xiong.huang@atheros.com>, Chris Snook <csnook@redhat.com>");
MODULE_DESCRIPTION("Atheros Fast Ethernet Network Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(ATL2_DRV_VERSION);
/*
* atl2_pci_tbl - PCI Device ID Table
*/
static DEFINE_PCI_DEVICE_TABLE(atl2_pci_tbl) = {
{PCI_DEVICE(PCI_VENDOR_ID_ATTANSIC, PCI_DEVICE_ID_ATTANSIC_L2)},
/* required last entry */
{0,}
};
MODULE_DEVICE_TABLE(pci, atl2_pci_tbl);
static void atl2_set_ethtool_ops(struct net_device *netdev);
static void atl2_check_options(struct atl2_adapter *adapter);
/*
* atl2_sw_init - Initialize general software structures (struct atl2_adapter)
* @adapter: board private structure to initialize
*
* atl2_sw_init initializes the Adapter private data structure.
* Fields are initialized based on PCI device information and
* OS network device settings (MTU size).
*/
static int __devinit atl2_sw_init(struct atl2_adapter *adapter)
{
struct atl2_hw *hw = &adapter->hw;
struct pci_dev *pdev = adapter->pdev;
/* PCI config space info */
hw->vendor_id = pdev->vendor;
hw->device_id = pdev->device;
hw->subsystem_vendor_id = pdev->subsystem_vendor;
hw->subsystem_id = pdev->subsystem_device;
pci_read_config_byte(pdev, PCI_REVISION_ID, &hw->revision_id);
pci_read_config_word(pdev, PCI_COMMAND, &hw->pci_cmd_word);
adapter->wol = 0;
adapter->ict = 50000; /* ~100ms */
adapter->link_speed = SPEED_0; /* hardware init */
adapter->link_duplex = FULL_DUPLEX;
hw->phy_configured = false;
hw->preamble_len = 7;
hw->ipgt = 0x60;
hw->min_ifg = 0x50;
hw->ipgr1 = 0x40;
hw->ipgr2 = 0x60;
hw->retry_buf = 2;
hw->max_retry = 0xf;
hw->lcol = 0x37;
hw->jam_ipg = 7;
hw->fc_rxd_hi = 0;
hw->fc_rxd_lo = 0;
hw->max_frame_size = adapter->netdev->mtu;
spin_lock_init(&adapter->stats_lock);
set_bit(__ATL2_DOWN, &adapter->flags);
return 0;
}
/*
* atl2_set_multi - Multicast and Promiscuous mode set
* @netdev: network interface device structure
*
* The set_multi entry point is called whenever the multicast address
* list or the network interface flags are updated. This routine is
* responsible for configuring the hardware for proper multicast,
* promiscuous mode, and all-multi behavior.
*/
static void atl2_set_multi(struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
struct netdev_hw_addr *ha;
u32 rctl;
u32 hash_value;
/* Check for Promiscuous and All Multicast modes */
rctl = ATL2_READ_REG(hw, REG_MAC_CTRL);
if (netdev->flags & IFF_PROMISC) {
rctl |= MAC_CTRL_PROMIS_EN;
} else if (netdev->flags & IFF_ALLMULTI) {
rctl |= MAC_CTRL_MC_ALL_EN;
rctl &= ~MAC_CTRL_PROMIS_EN;
} else
rctl &= ~(MAC_CTRL_PROMIS_EN | MAC_CTRL_MC_ALL_EN);
ATL2_WRITE_REG(hw, REG_MAC_CTRL, rctl);
/* clear the old settings from the multicast hash table */
ATL2_WRITE_REG(hw, REG_RX_HASH_TABLE, 0);
ATL2_WRITE_REG_ARRAY(hw, REG_RX_HASH_TABLE, 1, 0);
/* comoute mc addresses' hash value ,and put it into hash table */
netdev_for_each_mc_addr(ha, netdev) {
hash_value = atl2_hash_mc_addr(hw, ha->addr);
atl2_hash_set(hw, hash_value);
}
}
static void init_ring_ptrs(struct atl2_adapter *adapter)
{
/* Read / Write Ptr Initialize: */
adapter->txd_write_ptr = 0;
atomic_set(&adapter->txd_read_ptr, 0);
adapter->rxd_read_ptr = 0;
adapter->rxd_write_ptr = 0;
atomic_set(&adapter->txs_write_ptr, 0);
adapter->txs_next_clear = 0;
}
/*
* atl2_configure - Configure Transmit&Receive Unit after Reset
* @adapter: board private structure
*
* Configure the Tx /Rx unit of the MAC after a reset.
*/
static int atl2_configure(struct atl2_adapter *adapter)
{
struct atl2_hw *hw = &adapter->hw;
u32 value;
/* clear interrupt status */
ATL2_WRITE_REG(&adapter->hw, REG_ISR, 0xffffffff);
/* set MAC Address */
value = (((u32)hw->mac_addr[2]) << 24) |
(((u32)hw->mac_addr[3]) << 16) |
(((u32)hw->mac_addr[4]) << 8) |
(((u32)hw->mac_addr[5]));
ATL2_WRITE_REG(hw, REG_MAC_STA_ADDR, value);
value = (((u32)hw->mac_addr[0]) << 8) |
(((u32)hw->mac_addr[1]));
ATL2_WRITE_REG(hw, (REG_MAC_STA_ADDR+4), value);
/* HI base address */
ATL2_WRITE_REG(hw, REG_DESC_BASE_ADDR_HI,
(u32)((adapter->ring_dma & 0xffffffff00000000ULL) >> 32));
/* LO base address */
ATL2_WRITE_REG(hw, REG_TXD_BASE_ADDR_LO,
(u32)(adapter->txd_dma & 0x00000000ffffffffULL));
ATL2_WRITE_REG(hw, REG_TXS_BASE_ADDR_LO,
(u32)(adapter->txs_dma & 0x00000000ffffffffULL));
ATL2_WRITE_REG(hw, REG_RXD_BASE_ADDR_LO,
(u32)(adapter->rxd_dma & 0x00000000ffffffffULL));
/* element count */
ATL2_WRITE_REGW(hw, REG_TXD_MEM_SIZE, (u16)(adapter->txd_ring_size/4));
ATL2_WRITE_REGW(hw, REG_TXS_MEM_SIZE, (u16)adapter->txs_ring_size);
ATL2_WRITE_REGW(hw, REG_RXD_BUF_NUM, (u16)adapter->rxd_ring_size);
/* config Internal SRAM */
/*
ATL2_WRITE_REGW(hw, REG_SRAM_TXRAM_END, sram_tx_end);
ATL2_WRITE_REGW(hw, REG_SRAM_TXRAM_END, sram_rx_end);
*/
/* config IPG/IFG */
value = (((u32)hw->ipgt & MAC_IPG_IFG_IPGT_MASK) <<
MAC_IPG_IFG_IPGT_SHIFT) |
(((u32)hw->min_ifg & MAC_IPG_IFG_MIFG_MASK) <<
MAC_IPG_IFG_MIFG_SHIFT) |
(((u32)hw->ipgr1 & MAC_IPG_IFG_IPGR1_MASK) <<
MAC_IPG_IFG_IPGR1_SHIFT)|
(((u32)hw->ipgr2 & MAC_IPG_IFG_IPGR2_MASK) <<
MAC_IPG_IFG_IPGR2_SHIFT);
ATL2_WRITE_REG(hw, REG_MAC_IPG_IFG, value);
/* config Half-Duplex Control */
value = ((u32)hw->lcol & MAC_HALF_DUPLX_CTRL_LCOL_MASK) |
(((u32)hw->max_retry & MAC_HALF_DUPLX_CTRL_RETRY_MASK) <<
MAC_HALF_DUPLX_CTRL_RETRY_SHIFT) |
MAC_HALF_DUPLX_CTRL_EXC_DEF_EN |
(0xa << MAC_HALF_DUPLX_CTRL_ABEBT_SHIFT) |
(((u32)hw->jam_ipg & MAC_HALF_DUPLX_CTRL_JAMIPG_MASK) <<
MAC_HALF_DUPLX_CTRL_JAMIPG_SHIFT);
ATL2_WRITE_REG(hw, REG_MAC_HALF_DUPLX_CTRL, value);
/* set Interrupt Moderator Timer */
ATL2_WRITE_REGW(hw, REG_IRQ_MODU_TIMER_INIT, adapter->imt);
ATL2_WRITE_REG(hw, REG_MASTER_CTRL, MASTER_CTRL_ITIMER_EN);
/* set Interrupt Clear Timer */
ATL2_WRITE_REGW(hw, REG_CMBDISDMA_TIMER, adapter->ict);
/* set MTU */
ATL2_WRITE_REG(hw, REG_MTU, adapter->netdev->mtu +
ENET_HEADER_SIZE + VLAN_SIZE + ETHERNET_FCS_SIZE);
/* 1590 */
ATL2_WRITE_REG(hw, REG_TX_CUT_THRESH, 0x177);
/* flow control */
ATL2_WRITE_REGW(hw, REG_PAUSE_ON_TH, hw->fc_rxd_hi);
ATL2_WRITE_REGW(hw, REG_PAUSE_OFF_TH, hw->fc_rxd_lo);
/* Init mailbox */
ATL2_WRITE_REGW(hw, REG_MB_TXD_WR_IDX, (u16)adapter->txd_write_ptr);
ATL2_WRITE_REGW(hw, REG_MB_RXD_RD_IDX, (u16)adapter->rxd_read_ptr);
/* enable DMA read/write */
ATL2_WRITE_REGB(hw, REG_DMAR, DMAR_EN);
ATL2_WRITE_REGB(hw, REG_DMAW, DMAW_EN);
value = ATL2_READ_REG(&adapter->hw, REG_ISR);
if ((value & ISR_PHY_LINKDOWN) != 0)
value = 1; /* config failed */
else
value = 0;
/* clear all interrupt status */
ATL2_WRITE_REG(&adapter->hw, REG_ISR, 0x3fffffff);
ATL2_WRITE_REG(&adapter->hw, REG_ISR, 0);
return value;
}
/*
* atl2_setup_ring_resources - allocate Tx / RX descriptor resources
* @adapter: board private structure
*
* Return 0 on success, negative on failure
*/
static s32 atl2_setup_ring_resources(struct atl2_adapter *adapter)
{
struct pci_dev *pdev = adapter->pdev;
int size;
u8 offset = 0;
/* real ring DMA buffer */
adapter->ring_size = size =
adapter->txd_ring_size * 1 + 7 + /* dword align */
adapter->txs_ring_size * 4 + 7 + /* dword align */
adapter->rxd_ring_size * 1536 + 127; /* 128bytes align */
adapter->ring_vir_addr = pci_alloc_consistent(pdev, size,
&adapter->ring_dma);
if (!adapter->ring_vir_addr)
return -ENOMEM;
memset(adapter->ring_vir_addr, 0, adapter->ring_size);
/* Init TXD Ring */
adapter->txd_dma = adapter->ring_dma ;
offset = (adapter->txd_dma & 0x7) ? (8 - (adapter->txd_dma & 0x7)) : 0;
adapter->txd_dma += offset;
adapter->txd_ring = (struct tx_pkt_header *) (adapter->ring_vir_addr +
offset);
/* Init TXS Ring */
adapter->txs_dma = adapter->txd_dma + adapter->txd_ring_size;
offset = (adapter->txs_dma & 0x7) ? (8 - (adapter->txs_dma & 0x7)) : 0;
adapter->txs_dma += offset;
adapter->txs_ring = (struct tx_pkt_status *)
(((u8 *)adapter->txd_ring) + (adapter->txd_ring_size + offset));
/* Init RXD Ring */
adapter->rxd_dma = adapter->txs_dma + adapter->txs_ring_size * 4;
offset = (adapter->rxd_dma & 127) ?
(128 - (adapter->rxd_dma & 127)) : 0;
if (offset > 7)
offset -= 8;
else
offset += (128 - 8);
adapter->rxd_dma += offset;
adapter->rxd_ring = (struct rx_desc *) (((u8 *)adapter->txs_ring) +
(adapter->txs_ring_size * 4 + offset));
/*
* Read / Write Ptr Initialize:
* init_ring_ptrs(adapter);
*/
return 0;
}
/*
* atl2_irq_enable - Enable default interrupt generation settings
* @adapter: board private structure
*/
static inline void atl2_irq_enable(struct atl2_adapter *adapter)
{
ATL2_WRITE_REG(&adapter->hw, REG_IMR, IMR_NORMAL_MASK);
ATL2_WRITE_FLUSH(&adapter->hw);
}
/*
* atl2_irq_disable - Mask off interrupt generation on the NIC
* @adapter: board private structure
*/
static inline void atl2_irq_disable(struct atl2_adapter *adapter)
{
ATL2_WRITE_REG(&adapter->hw, REG_IMR, 0);
ATL2_WRITE_FLUSH(&adapter->hw);
synchronize_irq(adapter->pdev->irq);
}
#ifdef NETIF_F_HW_VLAN_TX
static void atl2_vlan_rx_register(struct net_device *netdev,
struct vlan_group *grp)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
u32 ctrl;
atl2_irq_disable(adapter);
adapter->vlgrp = grp;
if (grp) {
/* enable VLAN tag insert/strip */
ctrl = ATL2_READ_REG(&adapter->hw, REG_MAC_CTRL);
ctrl |= MAC_CTRL_RMV_VLAN;
ATL2_WRITE_REG(&adapter->hw, REG_MAC_CTRL, ctrl);
} else {
/* disable VLAN tag insert/strip */
ctrl = ATL2_READ_REG(&adapter->hw, REG_MAC_CTRL);
ctrl &= ~MAC_CTRL_RMV_VLAN;
ATL2_WRITE_REG(&adapter->hw, REG_MAC_CTRL, ctrl);
}
atl2_irq_enable(adapter);
}
static void atl2_restore_vlan(struct atl2_adapter *adapter)
{
atl2_vlan_rx_register(adapter->netdev, adapter->vlgrp);
}
#endif
static void atl2_intr_rx(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct rx_desc *rxd;
struct sk_buff *skb;
do {
rxd = adapter->rxd_ring+adapter->rxd_write_ptr;
if (!rxd->status.update)
break; /* end of tx */
/* clear this flag at once */
rxd->status.update = 0;
if (rxd->status.ok && rxd->status.pkt_size >= 60) {
int rx_size = (int)(rxd->status.pkt_size - 4);
/* alloc new buffer */
skb = netdev_alloc_skb_ip_align(netdev, rx_size);
if (NULL == skb) {
printk(KERN_WARNING
"%s: Mem squeeze, deferring packet.\n",
netdev->name);
/*
* Check that some rx space is free. If not,
* free one and mark stats->rx_dropped++.
*/
netdev->stats.rx_dropped++;
break;
}
memcpy(skb->data, rxd->packet, rx_size);
skb_put(skb, rx_size);
skb->protocol = eth_type_trans(skb, netdev);
#ifdef NETIF_F_HW_VLAN_TX
if (adapter->vlgrp && (rxd->status.vlan)) {
u16 vlan_tag = (rxd->status.vtag>>4) |
((rxd->status.vtag&7) << 13) |
((rxd->status.vtag&8) << 9);
vlan_hwaccel_rx(skb, adapter->vlgrp, vlan_tag);
} else
#endif
netif_rx(skb);
netdev->stats.rx_bytes += rx_size;
netdev->stats.rx_packets++;
} else {
netdev->stats.rx_errors++;
if (rxd->status.ok && rxd->status.pkt_size <= 60)
netdev->stats.rx_length_errors++;
if (rxd->status.mcast)
netdev->stats.multicast++;
if (rxd->status.crc)
netdev->stats.rx_crc_errors++;
if (rxd->status.align)
netdev->stats.rx_frame_errors++;
}
/* advance write ptr */
if (++adapter->rxd_write_ptr == adapter->rxd_ring_size)
adapter->rxd_write_ptr = 0;
} while (1);
/* update mailbox? */
adapter->rxd_read_ptr = adapter->rxd_write_ptr;
ATL2_WRITE_REGW(&adapter->hw, REG_MB_RXD_RD_IDX, adapter->rxd_read_ptr);
}
static void atl2_intr_tx(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
u32 txd_read_ptr;
u32 txs_write_ptr;
struct tx_pkt_status *txs;
struct tx_pkt_header *txph;
int free_hole = 0;
do {
txs_write_ptr = (u32) atomic_read(&adapter->txs_write_ptr);
txs = adapter->txs_ring + txs_write_ptr;
if (!txs->update)
break; /* tx stop here */
free_hole = 1;
txs->update = 0;
if (++txs_write_ptr == adapter->txs_ring_size)
txs_write_ptr = 0;
atomic_set(&adapter->txs_write_ptr, (int)txs_write_ptr);
txd_read_ptr = (u32) atomic_read(&adapter->txd_read_ptr);
txph = (struct tx_pkt_header *)
(((u8 *)adapter->txd_ring) + txd_read_ptr);
if (txph->pkt_size != txs->pkt_size) {
struct tx_pkt_status *old_txs = txs;
printk(KERN_WARNING
"%s: txs packet size not consistent with txd"
" txd_:0x%08x, txs_:0x%08x!\n",
adapter->netdev->name,
*(u32 *)txph, *(u32 *)txs);
printk(KERN_WARNING
"txd read ptr: 0x%x\n",
txd_read_ptr);
txs = adapter->txs_ring + txs_write_ptr;
printk(KERN_WARNING
"txs-behind:0x%08x\n",
*(u32 *)txs);
if (txs_write_ptr < 2) {
txs = adapter->txs_ring +
(adapter->txs_ring_size +
txs_write_ptr - 2);
} else {
txs = adapter->txs_ring + (txs_write_ptr - 2);
}
printk(KERN_WARNING
"txs-before:0x%08x\n",
*(u32 *)txs);
txs = old_txs;
}
/* 4for TPH */
txd_read_ptr += (((u32)(txph->pkt_size) + 7) & ~3);
if (txd_read_ptr >= adapter->txd_ring_size)
txd_read_ptr -= adapter->txd_ring_size;
atomic_set(&adapter->txd_read_ptr, (int)txd_read_ptr);
/* tx statistics: */
if (txs->ok) {
netdev->stats.tx_bytes += txs->pkt_size;
netdev->stats.tx_packets++;
}
else
netdev->stats.tx_errors++;
if (txs->defer)
netdev->stats.collisions++;
if (txs->abort_col)
netdev->stats.tx_aborted_errors++;
if (txs->late_col)
netdev->stats.tx_window_errors++;
if (txs->underun)
netdev->stats.tx_fifo_errors++;
} while (1);
if (free_hole) {
if (netif_queue_stopped(adapter->netdev) &&
netif_carrier_ok(adapter->netdev))
netif_wake_queue(adapter->netdev);
}
}
static void atl2_check_for_link(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
u16 phy_data = 0;
spin_lock(&adapter->stats_lock);
atl2_read_phy_reg(&adapter->hw, MII_BMSR, &phy_data);
atl2_read_phy_reg(&adapter->hw, MII_BMSR, &phy_data);
spin_unlock(&adapter->stats_lock);
/* notify upper layer link down ASAP */
if (!(phy_data & BMSR_LSTATUS)) { /* Link Down */
if (netif_carrier_ok(netdev)) { /* old link state: Up */
printk(KERN_INFO "%s: %s NIC Link is Down\n",
atl2_driver_name, netdev->name);
adapter->link_speed = SPEED_0;
netif_carrier_off(netdev);
netif_stop_queue(netdev);
}
}
schedule_work(&adapter->link_chg_task);
}
static inline void atl2_clear_phy_int(struct atl2_adapter *adapter)
{
u16 phy_data;
spin_lock(&adapter->stats_lock);
atl2_read_phy_reg(&adapter->hw, 19, &phy_data);
spin_unlock(&adapter->stats_lock);
}
/*
* atl2_intr - Interrupt Handler
* @irq: interrupt number
* @data: pointer to a network interface device structure
* @pt_regs: CPU registers structure
*/
static irqreturn_t atl2_intr(int irq, void *data)
{
struct atl2_adapter *adapter = netdev_priv(data);
struct atl2_hw *hw = &adapter->hw;
u32 status;
status = ATL2_READ_REG(hw, REG_ISR);
if (0 == status)
return IRQ_NONE;
/* link event */
if (status & ISR_PHY)
atl2_clear_phy_int(adapter);
/* clear ISR status, and Enable CMB DMA/Disable Interrupt */
ATL2_WRITE_REG(hw, REG_ISR, status | ISR_DIS_INT);
/* check if PCIE PHY Link down */
if (status & ISR_PHY_LINKDOWN) {
if (netif_running(adapter->netdev)) { /* reset MAC */
ATL2_WRITE_REG(hw, REG_ISR, 0);
ATL2_WRITE_REG(hw, REG_IMR, 0);
ATL2_WRITE_FLUSH(hw);
schedule_work(&adapter->reset_task);
return IRQ_HANDLED;
}
}
/* check if DMA read/write error? */
if (status & (ISR_DMAR_TO_RST | ISR_DMAW_TO_RST)) {
ATL2_WRITE_REG(hw, REG_ISR, 0);
ATL2_WRITE_REG(hw, REG_IMR, 0);
ATL2_WRITE_FLUSH(hw);
schedule_work(&adapter->reset_task);
return IRQ_HANDLED;
}
/* link event */
if (status & (ISR_PHY | ISR_MANUAL)) {
adapter->netdev->stats.tx_carrier_errors++;
atl2_check_for_link(adapter);
}
/* transmit event */
if (status & ISR_TX_EVENT)
atl2_intr_tx(adapter);
/* rx exception */
if (status & ISR_RX_EVENT)
atl2_intr_rx(adapter);
/* re-enable Interrupt */
ATL2_WRITE_REG(&adapter->hw, REG_ISR, 0);
return IRQ_HANDLED;
}
static int atl2_request_irq(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int flags, err = 0;
flags = IRQF_SHARED;
adapter->have_msi = true;
err = pci_enable_msi(adapter->pdev);
if (err)
adapter->have_msi = false;
if (adapter->have_msi)
flags &= ~IRQF_SHARED;
return request_irq(adapter->pdev->irq, atl2_intr, flags, netdev->name,
netdev);
}
/*
* atl2_free_ring_resources - Free Tx / RX descriptor Resources
* @adapter: board private structure
*
* Free all transmit software resources
*/
static void atl2_free_ring_resources(struct atl2_adapter *adapter)
{
struct pci_dev *pdev = adapter->pdev;
pci_free_consistent(pdev, adapter->ring_size, adapter->ring_vir_addr,
adapter->ring_dma);
}
/*
* atl2_open - Called when a network interface is made active
* @netdev: network interface device structure
*
* Returns 0 on success, negative value on failure
*
* The open entry point is called when a network interface is made
* active by the system (IFF_UP). At this point all resources needed
* for transmit and receive operations are allocated, the interrupt
* handler is registered with the OS, the watchdog timer is started,
* and the stack is notified that the interface is ready.
*/
static int atl2_open(struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
int err;
u32 val;
/* disallow open during test */
if (test_bit(__ATL2_TESTING, &adapter->flags))
return -EBUSY;
/* allocate transmit descriptors */
err = atl2_setup_ring_resources(adapter);
if (err)
return err;
err = atl2_init_hw(&adapter->hw);
if (err) {
err = -EIO;
goto err_init_hw;
}
/* hardware has been reset, we need to reload some things */
atl2_set_multi(netdev);
init_ring_ptrs(adapter);
#ifdef NETIF_F_HW_VLAN_TX
atl2_restore_vlan(adapter);
#endif
if (atl2_configure(adapter)) {
err = -EIO;
goto err_config;
}
err = atl2_request_irq(adapter);
if (err)
goto err_req_irq;
clear_bit(__ATL2_DOWN, &adapter->flags);
mod_timer(&adapter->watchdog_timer, round_jiffies(jiffies + 4*HZ));
val = ATL2_READ_REG(&adapter->hw, REG_MASTER_CTRL);
ATL2_WRITE_REG(&adapter->hw, REG_MASTER_CTRL,
val | MASTER_CTRL_MANUAL_INT);
atl2_irq_enable(adapter);
return 0;
err_init_hw:
err_req_irq:
err_config:
atl2_free_ring_resources(adapter);
atl2_reset_hw(&adapter->hw);
return err;
}
static void atl2_down(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
/* signal that we're down so the interrupt handler does not
* reschedule our watchdog timer */
set_bit(__ATL2_DOWN, &adapter->flags);
netif_tx_disable(netdev);
/* reset MAC to disable all RX/TX */
atl2_reset_hw(&adapter->hw);
msleep(1);
atl2_irq_disable(adapter);
del_timer_sync(&adapter->watchdog_timer);
del_timer_sync(&adapter->phy_config_timer);
clear_bit(0, &adapter->cfg_phy);
netif_carrier_off(netdev);
adapter->link_speed = SPEED_0;
adapter->link_duplex = -1;
}
static void atl2_free_irq(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
free_irq(adapter->pdev->irq, netdev);
#ifdef CONFIG_PCI_MSI
if (adapter->have_msi)
pci_disable_msi(adapter->pdev);
#endif
}
/*
* atl2_close - Disables a network interface
* @netdev: network interface device structure
*
* Returns 0, this is not allowed to fail
*
* The close entry point is called when an interface is de-activated
* by the OS. The hardware is still under the drivers control, but
* needs to be disabled. A global MAC reset is issued to stop the
* hardware, and all transmit and receive resources are freed.
*/
static int atl2_close(struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
WARN_ON(test_bit(__ATL2_RESETTING, &adapter->flags));
atl2_down(adapter);
atl2_free_irq(adapter);
atl2_free_ring_resources(adapter);
return 0;
}
static inline int TxsFreeUnit(struct atl2_adapter *adapter)
{
u32 txs_write_ptr = (u32) atomic_read(&adapter->txs_write_ptr);
return (adapter->txs_next_clear >= txs_write_ptr) ?
(int) (adapter->txs_ring_size - adapter->txs_next_clear +
txs_write_ptr - 1) :
(int) (txs_write_ptr - adapter->txs_next_clear - 1);
}
static inline int TxdFreeBytes(struct atl2_adapter *adapter)
{
u32 txd_read_ptr = (u32)atomic_read(&adapter->txd_read_ptr);
return (adapter->txd_write_ptr >= txd_read_ptr) ?
(int) (adapter->txd_ring_size - adapter->txd_write_ptr +
txd_read_ptr - 1) :
(int) (txd_read_ptr - adapter->txd_write_ptr - 1);
}
static netdev_tx_t atl2_xmit_frame(struct sk_buff *skb,
struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct tx_pkt_header *txph;
u32 offset, copy_len;
int txs_unused;
int txbuf_unused;
if (test_bit(__ATL2_DOWN, &adapter->flags)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
if (unlikely(skb->len <= 0)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
txs_unused = TxsFreeUnit(adapter);
txbuf_unused = TxdFreeBytes(adapter);
if (skb->len + sizeof(struct tx_pkt_header) + 4 > txbuf_unused ||
txs_unused < 1) {
/* not enough resources */
netif_stop_queue(netdev);
return NETDEV_TX_BUSY;
}
offset = adapter->txd_write_ptr;
txph = (struct tx_pkt_header *) (((u8 *)adapter->txd_ring) + offset);
*(u32 *)txph = 0;
txph->pkt_size = skb->len;
offset += 4;
if (offset >= adapter->txd_ring_size)
offset -= adapter->txd_ring_size;
copy_len = adapter->txd_ring_size - offset;
if (copy_len >= skb->len) {
memcpy(((u8 *)adapter->txd_ring) + offset, skb->data, skb->len);
offset += ((u32)(skb->len + 3) & ~3);
} else {
memcpy(((u8 *)adapter->txd_ring)+offset, skb->data, copy_len);
memcpy((u8 *)adapter->txd_ring, skb->data+copy_len,
skb->len-copy_len);
offset = ((u32)(skb->len-copy_len + 3) & ~3);
}
#ifdef NETIF_F_HW_VLAN_TX
if (adapter->vlgrp && vlan_tx_tag_present(skb)) {
u16 vlan_tag = vlan_tx_tag_get(skb);
vlan_tag = (vlan_tag << 4) |
(vlan_tag >> 13) |
((vlan_tag >> 9) & 0x8);
txph->ins_vlan = 1;
txph->vlan = vlan_tag;
}
#endif
if (offset >= adapter->txd_ring_size)
offset -= adapter->txd_ring_size;
adapter->txd_write_ptr = offset;
/* clear txs before send */
adapter->txs_ring[adapter->txs_next_clear].update = 0;
if (++adapter->txs_next_clear == adapter->txs_ring_size)
adapter->txs_next_clear = 0;
ATL2_WRITE_REGW(&adapter->hw, REG_MB_TXD_WR_IDX,
(adapter->txd_write_ptr >> 2));
mmiowb();
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
/*
* atl2_change_mtu - Change the Maximum Transfer Unit
* @netdev: network interface device structure
* @new_mtu: new value for maximum frame size
*
* Returns 0 on success, negative on failure
*/
static int atl2_change_mtu(struct net_device *netdev, int new_mtu)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
if ((new_mtu < 40) || (new_mtu > (ETH_DATA_LEN + VLAN_SIZE)))
return -EINVAL;
/* set MTU */
if (hw->max_frame_size != new_mtu) {
netdev->mtu = new_mtu;
ATL2_WRITE_REG(hw, REG_MTU, new_mtu + ENET_HEADER_SIZE +
VLAN_SIZE + ETHERNET_FCS_SIZE);
}
return 0;
}
/*
* atl2_set_mac - Change the Ethernet Address of the NIC
* @netdev: network interface device structure
* @p: pointer to an address structure
*
* Returns 0 on success, negative on failure
*/
static int atl2_set_mac(struct net_device *netdev, void *p)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct sockaddr *addr = p;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
if (netif_running(netdev))
return -EBUSY;
memcpy(netdev->dev_addr, addr->sa_data, netdev->addr_len);
memcpy(adapter->hw.mac_addr, addr->sa_data, netdev->addr_len);
atl2_set_mac_addr(&adapter->hw);
return 0;
}
/*
* atl2_mii_ioctl -
* @netdev:
* @ifreq:
* @cmd:
*/
static int atl2_mii_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct mii_ioctl_data *data = if_mii(ifr);
unsigned long flags;
switch (cmd) {
case SIOCGMIIPHY:
data->phy_id = 0;
break;
case SIOCGMIIREG:
spin_lock_irqsave(&adapter->stats_lock, flags);
if (atl2_read_phy_reg(&adapter->hw,
data->reg_num & 0x1F, &data->val_out)) {
spin_unlock_irqrestore(&adapter->stats_lock, flags);
return -EIO;
}
spin_unlock_irqrestore(&adapter->stats_lock, flags);
break;
case SIOCSMIIREG:
if (data->reg_num & ~(0x1F))
return -EFAULT;
spin_lock_irqsave(&adapter->stats_lock, flags);
if (atl2_write_phy_reg(&adapter->hw, data->reg_num,
data->val_in)) {
spin_unlock_irqrestore(&adapter->stats_lock, flags);
return -EIO;
}
spin_unlock_irqrestore(&adapter->stats_lock, flags);
break;
default:
return -EOPNOTSUPP;
}
return 0;
}
/*
* atl2_ioctl -
* @netdev:
* @ifreq:
* @cmd:
*/
static int atl2_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
switch (cmd) {
case SIOCGMIIPHY:
case SIOCGMIIREG:
case SIOCSMIIREG:
return atl2_mii_ioctl(netdev, ifr, cmd);
#ifdef ETHTOOL_OPS_COMPAT
case SIOCETHTOOL:
return ethtool_ioctl(ifr);
#endif
default:
return -EOPNOTSUPP;
}
}
/*
* atl2_tx_timeout - Respond to a Tx Hang
* @netdev: network interface device structure
*/
static void atl2_tx_timeout(struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
/* Do the reset outside of interrupt context */
schedule_work(&adapter->reset_task);
}
/*
* atl2_watchdog - Timer Call-back
* @data: pointer to netdev cast into an unsigned long
*/
static void atl2_watchdog(unsigned long data)
{
struct atl2_adapter *adapter = (struct atl2_adapter *) data;
if (!test_bit(__ATL2_DOWN, &adapter->flags)) {
u32 drop_rxd, drop_rxs;
unsigned long flags;
spin_lock_irqsave(&adapter->stats_lock, flags);
drop_rxd = ATL2_READ_REG(&adapter->hw, REG_STS_RXD_OV);
drop_rxs = ATL2_READ_REG(&adapter->hw, REG_STS_RXS_OV);
spin_unlock_irqrestore(&adapter->stats_lock, flags);
adapter->netdev->stats.rx_over_errors += drop_rxd + drop_rxs;
/* Reset the timer */
mod_timer(&adapter->watchdog_timer,
round_jiffies(jiffies + 4 * HZ));
}
}
/*
* atl2_phy_config - Timer Call-back
* @data: pointer to netdev cast into an unsigned long
*/
static void atl2_phy_config(unsigned long data)
{
struct atl2_adapter *adapter = (struct atl2_adapter *) data;
struct atl2_hw *hw = &adapter->hw;
unsigned long flags;
spin_lock_irqsave(&adapter->stats_lock, flags);
atl2_write_phy_reg(hw, MII_ADVERTISE, hw->mii_autoneg_adv_reg);
atl2_write_phy_reg(hw, MII_BMCR, MII_CR_RESET | MII_CR_AUTO_NEG_EN |
MII_CR_RESTART_AUTO_NEG);
spin_unlock_irqrestore(&adapter->stats_lock, flags);
clear_bit(0, &adapter->cfg_phy);
}
static int atl2_up(struct atl2_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int err = 0;
u32 val;
/* hardware has been reset, we need to reload some things */
err = atl2_init_hw(&adapter->hw);
if (err) {
err = -EIO;
return err;
}
atl2_set_multi(netdev);
init_ring_ptrs(adapter);
#ifdef NETIF_F_HW_VLAN_TX
atl2_restore_vlan(adapter);
#endif
if (atl2_configure(adapter)) {
err = -EIO;
goto err_up;
}
clear_bit(__ATL2_DOWN, &adapter->flags);
val = ATL2_READ_REG(&adapter->hw, REG_MASTER_CTRL);
ATL2_WRITE_REG(&adapter->hw, REG_MASTER_CTRL, val |
MASTER_CTRL_MANUAL_INT);
atl2_irq_enable(adapter);
err_up:
return err;
}
static void atl2_reinit_locked(struct atl2_adapter *adapter)
{
WARN_ON(in_interrupt());
while (test_and_set_bit(__ATL2_RESETTING, &adapter->flags))
msleep(1);
atl2_down(adapter);
atl2_up(adapter);
clear_bit(__ATL2_RESETTING, &adapter->flags);
}
static void atl2_reset_task(struct work_struct *work)
{
struct atl2_adapter *adapter;
adapter = container_of(work, struct atl2_adapter, reset_task);
atl2_reinit_locked(adapter);
}
static void atl2_setup_mac_ctrl(struct atl2_adapter *adapter)
{
u32 value;
struct atl2_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
/* Config MAC CTRL Register */
value = MAC_CTRL_TX_EN | MAC_CTRL_RX_EN | MAC_CTRL_MACLP_CLK_PHY;
/* duplex */
if (FULL_DUPLEX == adapter->link_duplex)
value |= MAC_CTRL_DUPLX;
/* flow control */
value |= (MAC_CTRL_TX_FLOW | MAC_CTRL_RX_FLOW);
/* PAD & CRC */
value |= (MAC_CTRL_ADD_CRC | MAC_CTRL_PAD);
/* preamble length */
value |= (((u32)adapter->hw.preamble_len & MAC_CTRL_PRMLEN_MASK) <<
MAC_CTRL_PRMLEN_SHIFT);
/* vlan */
if (adapter->vlgrp)
value |= MAC_CTRL_RMV_VLAN;
/* filter mode */
value |= MAC_CTRL_BC_EN;
if (netdev->flags & IFF_PROMISC)
value |= MAC_CTRL_PROMIS_EN;
else if (netdev->flags & IFF_ALLMULTI)
value |= MAC_CTRL_MC_ALL_EN;
/* half retry buffer */
value |= (((u32)(adapter->hw.retry_buf &
MAC_CTRL_HALF_LEFT_BUF_MASK)) << MAC_CTRL_HALF_LEFT_BUF_SHIFT);
ATL2_WRITE_REG(hw, REG_MAC_CTRL, value);
}
static int atl2_check_link(struct atl2_adapter *adapter)
{
struct atl2_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
int ret_val;
u16 speed, duplex, phy_data;
int reconfig = 0;
/* MII_BMSR must read twise */
atl2_read_phy_reg(hw, MII_BMSR, &phy_data);
atl2_read_phy_reg(hw, MII_BMSR, &phy_data);
if (!(phy_data&BMSR_LSTATUS)) { /* link down */
if (netif_carrier_ok(netdev)) { /* old link state: Up */
u32 value;
/* disable rx */
value = ATL2_READ_REG(hw, REG_MAC_CTRL);
value &= ~MAC_CTRL_RX_EN;
ATL2_WRITE_REG(hw, REG_MAC_CTRL, value);
adapter->link_speed = SPEED_0;
netif_carrier_off(netdev);
netif_stop_queue(netdev);
}
return 0;
}
/* Link Up */
ret_val = atl2_get_speed_and_duplex(hw, &speed, &duplex);
if (ret_val)
return ret_val;
switch (hw->MediaType) {
case MEDIA_TYPE_100M_FULL:
if (speed != SPEED_100 || duplex != FULL_DUPLEX)
reconfig = 1;
break;
case MEDIA_TYPE_100M_HALF:
if (speed != SPEED_100 || duplex != HALF_DUPLEX)
reconfig = 1;
break;
case MEDIA_TYPE_10M_FULL:
if (speed != SPEED_10 || duplex != FULL_DUPLEX)
reconfig = 1;
break;
case MEDIA_TYPE_10M_HALF:
if (speed != SPEED_10 || duplex != HALF_DUPLEX)
reconfig = 1;
break;
}
/* link result is our setting */
if (reconfig == 0) {
if (adapter->link_speed != speed ||
adapter->link_duplex != duplex) {
adapter->link_speed = speed;
adapter->link_duplex = duplex;
atl2_setup_mac_ctrl(adapter);
printk(KERN_INFO "%s: %s NIC Link is Up<%d Mbps %s>\n",
atl2_driver_name, netdev->name,
adapter->link_speed,
adapter->link_duplex == FULL_DUPLEX ?
"Full Duplex" : "Half Duplex");
}
if (!netif_carrier_ok(netdev)) { /* Link down -> Up */
netif_carrier_on(netdev);
netif_wake_queue(netdev);
}
return 0;
}
/* change original link status */
if (netif_carrier_ok(netdev)) {
u32 value;
/* disable rx */
value = ATL2_READ_REG(hw, REG_MAC_CTRL);
value &= ~MAC_CTRL_RX_EN;
ATL2_WRITE_REG(hw, REG_MAC_CTRL, value);
adapter->link_speed = SPEED_0;
netif_carrier_off(netdev);
netif_stop_queue(netdev);
}
/* auto-neg, insert timer to re-config phy
* (if interval smaller than 5 seconds, something strange) */
if (!test_bit(__ATL2_DOWN, &adapter->flags)) {
if (!test_and_set_bit(0, &adapter->cfg_phy))
mod_timer(&adapter->phy_config_timer,
round_jiffies(jiffies + 5 * HZ));
}
return 0;
}
/*
* atl2_link_chg_task - deal with link change event Out of interrupt context
* @netdev: network interface device structure
*/
static void atl2_link_chg_task(struct work_struct *work)
{
struct atl2_adapter *adapter;
unsigned long flags;
adapter = container_of(work, struct atl2_adapter, link_chg_task);
spin_lock_irqsave(&adapter->stats_lock, flags);
atl2_check_link(adapter);
spin_unlock_irqrestore(&adapter->stats_lock, flags);
}
static void atl2_setup_pcicmd(struct pci_dev *pdev)
{
u16 cmd;
pci_read_config_word(pdev, PCI_COMMAND, &cmd);
if (cmd & PCI_COMMAND_INTX_DISABLE)
cmd &= ~PCI_COMMAND_INTX_DISABLE;
if (cmd & PCI_COMMAND_IO)
cmd &= ~PCI_COMMAND_IO;
if (0 == (cmd & PCI_COMMAND_MEMORY))
cmd |= PCI_COMMAND_MEMORY;
if (0 == (cmd & PCI_COMMAND_MASTER))
cmd |= PCI_COMMAND_MASTER;
pci_write_config_word(pdev, PCI_COMMAND, cmd);
/*
* some motherboards BIOS(PXE/EFI) driver may set PME
* while they transfer control to OS (Windows/Linux)
* so we should clear this bit before NIC work normally
*/
pci_write_config_dword(pdev, REG_PM_CTRLSTAT, 0);
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void atl2_poll_controller(struct net_device *netdev)
{
disable_irq(netdev->irq);
atl2_intr(netdev->irq, netdev);
enable_irq(netdev->irq);
}
#endif
static const struct net_device_ops atl2_netdev_ops = {
.ndo_open = atl2_open,
.ndo_stop = atl2_close,
.ndo_start_xmit = atl2_xmit_frame,
.ndo_set_multicast_list = atl2_set_multi,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = atl2_set_mac,
.ndo_change_mtu = atl2_change_mtu,
.ndo_do_ioctl = atl2_ioctl,
.ndo_tx_timeout = atl2_tx_timeout,
.ndo_vlan_rx_register = atl2_vlan_rx_register,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = atl2_poll_controller,
#endif
};
/*
* atl2_probe - Device Initialization Routine
* @pdev: PCI device information struct
* @ent: entry in atl2_pci_tbl
*
* Returns 0 on success, negative on failure
*
* atl2_probe initializes an adapter identified by a pci_dev structure.
* The OS initialization, configuring of the adapter private structure,
* and a hardware reset occur.
*/
static int __devinit atl2_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct net_device *netdev;
struct atl2_adapter *adapter;
static int cards_found;
unsigned long mmio_start;
int mmio_len;
int err;
cards_found = 0;
err = pci_enable_device(pdev);
if (err)
return err;
/*
* atl2 is a shared-high-32-bit device, so we're stuck with 32-bit DMA
* until the kernel has the proper infrastructure to support 64-bit DMA
* on these devices.
*/
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) &&
pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) {
printk(KERN_ERR "atl2: No usable DMA configuration, aborting\n");
goto err_dma;
}
/* Mark all PCI regions associated with PCI device
* pdev as being reserved by owner atl2_driver_name */
err = pci_request_regions(pdev, atl2_driver_name);
if (err)
goto err_pci_reg;
/* Enables bus-mastering on the device and calls
* pcibios_set_master to do the needed arch specific settings */
pci_set_master(pdev);
err = -ENOMEM;
netdev = alloc_etherdev(sizeof(struct atl2_adapter));
if (!netdev)
goto err_alloc_etherdev;
SET_NETDEV_DEV(netdev, &pdev->dev);
pci_set_drvdata(pdev, netdev);
adapter = netdev_priv(netdev);
adapter->netdev = netdev;
adapter->pdev = pdev;
adapter->hw.back = adapter;
mmio_start = pci_resource_start(pdev, 0x0);
mmio_len = pci_resource_len(pdev, 0x0);
adapter->hw.mem_rang = (u32)mmio_len;
adapter->hw.hw_addr = ioremap(mmio_start, mmio_len);
if (!adapter->hw.hw_addr) {
err = -EIO;
goto err_ioremap;
}
atl2_setup_pcicmd(pdev);
netdev->netdev_ops = &atl2_netdev_ops;
atl2_set_ethtool_ops(netdev);
netdev->watchdog_timeo = 5 * HZ;
strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1);
netdev->mem_start = mmio_start;
netdev->mem_end = mmio_start + mmio_len;
adapter->bd_number = cards_found;
adapter->pci_using_64 = false;
/* setup the private structure */
err = atl2_sw_init(adapter);
if (err)
goto err_sw_init;
err = -EIO;
#ifdef NETIF_F_HW_VLAN_TX
netdev->features |= (NETIF_F_HW_VLAN_TX | NETIF_F_HW_VLAN_RX);
#endif
/* Init PHY as early as possible due to power saving issue */
atl2_phy_init(&adapter->hw);
/* reset the controller to
* put the device in a known good starting state */
if (atl2_reset_hw(&adapter->hw)) {
err = -EIO;
goto err_reset;
}
/* copy the MAC address out of the EEPROM */
atl2_read_mac_addr(&adapter->hw);
memcpy(netdev->dev_addr, adapter->hw.mac_addr, netdev->addr_len);
#ifdef ETHTOOL_GPERMADDR
memcpy(netdev->perm_addr, adapter->hw.mac_addr, netdev->addr_len);
if (!is_valid_ether_addr(netdev->perm_addr)) {
#else
if (!is_valid_ether_addr(netdev->dev_addr)) {
#endif
err = -EIO;
goto err_eeprom;
}
atl2_check_options(adapter);
init_timer(&adapter->watchdog_timer);
adapter->watchdog_timer.function = &atl2_watchdog;
adapter->watchdog_timer.data = (unsigned long) adapter;
init_timer(&adapter->phy_config_timer);
adapter->phy_config_timer.function = &atl2_phy_config;
adapter->phy_config_timer.data = (unsigned long) adapter;
INIT_WORK(&adapter->reset_task, atl2_reset_task);
INIT_WORK(&adapter->link_chg_task, atl2_link_chg_task);
strcpy(netdev->name, "eth%d"); /* ?? */
err = register_netdev(netdev);
if (err)
goto err_register;
/* assume we have no link for now */
netif_carrier_off(netdev);
netif_stop_queue(netdev);
cards_found++;
return 0;
err_reset:
err_register:
err_sw_init:
err_eeprom:
iounmap(adapter->hw.hw_addr);
err_ioremap:
free_netdev(netdev);
err_alloc_etherdev:
pci_release_regions(pdev);
err_pci_reg:
err_dma:
pci_disable_device(pdev);
return err;
}
/*
* atl2_remove - Device Removal Routine
* @pdev: PCI device information struct
*
* atl2_remove is called by the PCI subsystem to alert the driver
* that it should release a PCI device. The could be caused by a
* Hot-Plug event, or because the driver is going to be removed from
* memory.
*/
static void __devexit atl2_remove(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct atl2_adapter *adapter = netdev_priv(netdev);
/* flush_scheduled work may reschedule our watchdog task, so
* explicitly disable watchdog tasks from being rescheduled */
set_bit(__ATL2_DOWN, &adapter->flags);
del_timer_sync(&adapter->watchdog_timer);
del_timer_sync(&adapter->phy_config_timer);
flush_scheduled_work();
unregister_netdev(netdev);
atl2_force_ps(&adapter->hw);
iounmap(adapter->hw.hw_addr);
pci_release_regions(pdev);
free_netdev(netdev);
pci_disable_device(pdev);
}
static int atl2_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
u16 speed, duplex;
u32 ctrl = 0;
u32 wufc = adapter->wol;
#ifdef CONFIG_PM
int retval = 0;
#endif
netif_device_detach(netdev);
if (netif_running(netdev)) {
WARN_ON(test_bit(__ATL2_RESETTING, &adapter->flags));
atl2_down(adapter);
}
#ifdef CONFIG_PM
retval = pci_save_state(pdev);
if (retval)
return retval;
#endif
atl2_read_phy_reg(hw, MII_BMSR, (u16 *)&ctrl);
atl2_read_phy_reg(hw, MII_BMSR, (u16 *)&ctrl);
if (ctrl & BMSR_LSTATUS)
wufc &= ~ATLX_WUFC_LNKC;
if (0 != (ctrl & BMSR_LSTATUS) && 0 != wufc) {
u32 ret_val;
/* get current link speed & duplex */
ret_val = atl2_get_speed_and_duplex(hw, &speed, &duplex);
if (ret_val) {
printk(KERN_DEBUG
"%s: get speed&duplex error while suspend\n",
atl2_driver_name);
goto wol_dis;
}
ctrl = 0;
/* turn on magic packet wol */
if (wufc & ATLX_WUFC_MAG)
ctrl |= (WOL_MAGIC_EN | WOL_MAGIC_PME_EN);
/* ignore Link Chg event when Link is up */
ATL2_WRITE_REG(hw, REG_WOL_CTRL, ctrl);
/* Config MAC CTRL Register */
ctrl = MAC_CTRL_RX_EN | MAC_CTRL_MACLP_CLK_PHY;
if (FULL_DUPLEX == adapter->link_duplex)
ctrl |= MAC_CTRL_DUPLX;
ctrl |= (MAC_CTRL_ADD_CRC | MAC_CTRL_PAD);
ctrl |= (((u32)adapter->hw.preamble_len &
MAC_CTRL_PRMLEN_MASK) << MAC_CTRL_PRMLEN_SHIFT);
ctrl |= (((u32)(adapter->hw.retry_buf &
MAC_CTRL_HALF_LEFT_BUF_MASK)) <<
MAC_CTRL_HALF_LEFT_BUF_SHIFT);
if (wufc & ATLX_WUFC_MAG) {
/* magic packet maybe Broadcast&multicast&Unicast */
ctrl |= MAC_CTRL_BC_EN;
}
ATL2_WRITE_REG(hw, REG_MAC_CTRL, ctrl);
/* pcie patch */
ctrl = ATL2_READ_REG(hw, REG_PCIE_PHYMISC);
ctrl |= PCIE_PHYMISC_FORCE_RCV_DET;
ATL2_WRITE_REG(hw, REG_PCIE_PHYMISC, ctrl);
ctrl = ATL2_READ_REG(hw, REG_PCIE_DLL_TX_CTRL1);
ctrl |= PCIE_DLL_TX_CTRL1_SEL_NOR_CLK;
ATL2_WRITE_REG(hw, REG_PCIE_DLL_TX_CTRL1, ctrl);
pci_enable_wake(pdev, pci_choose_state(pdev, state), 1);
goto suspend_exit;
}
if (0 == (ctrl&BMSR_LSTATUS) && 0 != (wufc&ATLX_WUFC_LNKC)) {
/* link is down, so only LINK CHG WOL event enable */
ctrl |= (WOL_LINK_CHG_EN | WOL_LINK_CHG_PME_EN);
ATL2_WRITE_REG(hw, REG_WOL_CTRL, ctrl);
ATL2_WRITE_REG(hw, REG_MAC_CTRL, 0);
/* pcie patch */
ctrl = ATL2_READ_REG(hw, REG_PCIE_PHYMISC);
ctrl |= PCIE_PHYMISC_FORCE_RCV_DET;
ATL2_WRITE_REG(hw, REG_PCIE_PHYMISC, ctrl);
ctrl = ATL2_READ_REG(hw, REG_PCIE_DLL_TX_CTRL1);
ctrl |= PCIE_DLL_TX_CTRL1_SEL_NOR_CLK;
ATL2_WRITE_REG(hw, REG_PCIE_DLL_TX_CTRL1, ctrl);
hw->phy_configured = false; /* re-init PHY when resume */
pci_enable_wake(pdev, pci_choose_state(pdev, state), 1);
goto suspend_exit;
}
wol_dis:
/* WOL disabled */
ATL2_WRITE_REG(hw, REG_WOL_CTRL, 0);
/* pcie patch */
ctrl = ATL2_READ_REG(hw, REG_PCIE_PHYMISC);
ctrl |= PCIE_PHYMISC_FORCE_RCV_DET;
ATL2_WRITE_REG(hw, REG_PCIE_PHYMISC, ctrl);
ctrl = ATL2_READ_REG(hw, REG_PCIE_DLL_TX_CTRL1);
ctrl |= PCIE_DLL_TX_CTRL1_SEL_NOR_CLK;
ATL2_WRITE_REG(hw, REG_PCIE_DLL_TX_CTRL1, ctrl);
atl2_force_ps(hw);
hw->phy_configured = false; /* re-init PHY when resume */
pci_enable_wake(pdev, pci_choose_state(pdev, state), 0);
suspend_exit:
if (netif_running(netdev))
atl2_free_irq(adapter);
pci_disable_device(pdev);
pci_set_power_state(pdev, pci_choose_state(pdev, state));
return 0;
}
#ifdef CONFIG_PM
static int atl2_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct atl2_adapter *adapter = netdev_priv(netdev);
u32 err;
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
err = pci_enable_device(pdev);
if (err) {
printk(KERN_ERR
"atl2: Cannot enable PCI device from suspend\n");
return err;
}
pci_set_master(pdev);
ATL2_READ_REG(&adapter->hw, REG_WOL_CTRL); /* clear WOL status */
pci_enable_wake(pdev, PCI_D3hot, 0);
pci_enable_wake(pdev, PCI_D3cold, 0);
ATL2_WRITE_REG(&adapter->hw, REG_WOL_CTRL, 0);
if (netif_running(netdev)) {
err = atl2_request_irq(adapter);
if (err)
return err;
}
atl2_reset_hw(&adapter->hw);
if (netif_running(netdev))
atl2_up(adapter);
netif_device_attach(netdev);
return 0;
}
#endif
static void atl2_shutdown(struct pci_dev *pdev)
{
atl2_suspend(pdev, PMSG_SUSPEND);
}
static struct pci_driver atl2_driver = {
.name = atl2_driver_name,
.id_table = atl2_pci_tbl,
.probe = atl2_probe,
.remove = __devexit_p(atl2_remove),
/* Power Managment Hooks */
.suspend = atl2_suspend,
#ifdef CONFIG_PM
.resume = atl2_resume,
#endif
.shutdown = atl2_shutdown,
};
/*
* atl2_init_module - Driver Registration Routine
*
* atl2_init_module is the first routine called when the driver is
* loaded. All it does is register with the PCI subsystem.
*/
static int __init atl2_init_module(void)
{
printk(KERN_INFO "%s - version %s\n", atl2_driver_string,
atl2_driver_version);
printk(KERN_INFO "%s\n", atl2_copyright);
return pci_register_driver(&atl2_driver);
}
module_init(atl2_init_module);
/*
* atl2_exit_module - Driver Exit Cleanup Routine
*
* atl2_exit_module is called just before the driver is removed
* from memory.
*/
static void __exit atl2_exit_module(void)
{
pci_unregister_driver(&atl2_driver);
}
module_exit(atl2_exit_module);
static void atl2_read_pci_cfg(struct atl2_hw *hw, u32 reg, u16 *value)
{
struct atl2_adapter *adapter = hw->back;
pci_read_config_word(adapter->pdev, reg, value);
}
static void atl2_write_pci_cfg(struct atl2_hw *hw, u32 reg, u16 *value)
{
struct atl2_adapter *adapter = hw->back;
pci_write_config_word(adapter->pdev, reg, *value);
}
static int atl2_get_settings(struct net_device *netdev,
struct ethtool_cmd *ecmd)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
ecmd->supported = (SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full |
SUPPORTED_100baseT_Half |
SUPPORTED_100baseT_Full |
SUPPORTED_Autoneg |
SUPPORTED_TP);
ecmd->advertising = ADVERTISED_TP;
ecmd->advertising |= ADVERTISED_Autoneg;
ecmd->advertising |= hw->autoneg_advertised;
ecmd->port = PORT_TP;
ecmd->phy_address = 0;
ecmd->transceiver = XCVR_INTERNAL;
if (adapter->link_speed != SPEED_0) {
ecmd->speed = adapter->link_speed;
if (adapter->link_duplex == FULL_DUPLEX)
ecmd->duplex = DUPLEX_FULL;
else
ecmd->duplex = DUPLEX_HALF;
} else {
ecmd->speed = -1;
ecmd->duplex = -1;
}
ecmd->autoneg = AUTONEG_ENABLE;
return 0;
}
static int atl2_set_settings(struct net_device *netdev,
struct ethtool_cmd *ecmd)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
while (test_and_set_bit(__ATL2_RESETTING, &adapter->flags))
msleep(1);
if (ecmd->autoneg == AUTONEG_ENABLE) {
#define MY_ADV_MASK (ADVERTISE_10_HALF | \
ADVERTISE_10_FULL | \
ADVERTISE_100_HALF| \
ADVERTISE_100_FULL)
if ((ecmd->advertising & MY_ADV_MASK) == MY_ADV_MASK) {
hw->MediaType = MEDIA_TYPE_AUTO_SENSOR;
hw->autoneg_advertised = MY_ADV_MASK;
} else if ((ecmd->advertising & MY_ADV_MASK) ==
ADVERTISE_100_FULL) {
hw->MediaType = MEDIA_TYPE_100M_FULL;
hw->autoneg_advertised = ADVERTISE_100_FULL;
} else if ((ecmd->advertising & MY_ADV_MASK) ==
ADVERTISE_100_HALF) {
hw->MediaType = MEDIA_TYPE_100M_HALF;
hw->autoneg_advertised = ADVERTISE_100_HALF;
} else if ((ecmd->advertising & MY_ADV_MASK) ==
ADVERTISE_10_FULL) {
hw->MediaType = MEDIA_TYPE_10M_FULL;
hw->autoneg_advertised = ADVERTISE_10_FULL;
} else if ((ecmd->advertising & MY_ADV_MASK) ==
ADVERTISE_10_HALF) {
hw->MediaType = MEDIA_TYPE_10M_HALF;
hw->autoneg_advertised = ADVERTISE_10_HALF;
} else {
clear_bit(__ATL2_RESETTING, &adapter->flags);
return -EINVAL;
}
ecmd->advertising = hw->autoneg_advertised |
ADVERTISED_TP | ADVERTISED_Autoneg;
} else {
clear_bit(__ATL2_RESETTING, &adapter->flags);
return -EINVAL;
}
/* reset the link */
if (netif_running(adapter->netdev)) {
atl2_down(adapter);
atl2_up(adapter);
} else
atl2_reset_hw(&adapter->hw);
clear_bit(__ATL2_RESETTING, &adapter->flags);
return 0;
}
static u32 atl2_get_tx_csum(struct net_device *netdev)
{
return (netdev->features & NETIF_F_HW_CSUM) != 0;
}
static u32 atl2_get_msglevel(struct net_device *netdev)
{
return 0;
}
/*
* It's sane for this to be empty, but we might want to take advantage of this.
*/
static void atl2_set_msglevel(struct net_device *netdev, u32 data)
{
}
static int atl2_get_regs_len(struct net_device *netdev)
{
#define ATL2_REGS_LEN 42
return sizeof(u32) * ATL2_REGS_LEN;
}
static void atl2_get_regs(struct net_device *netdev,
struct ethtool_regs *regs, void *p)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
u32 *regs_buff = p;
u16 phy_data;
memset(p, 0, sizeof(u32) * ATL2_REGS_LEN);
regs->version = (1 << 24) | (hw->revision_id << 16) | hw->device_id;
regs_buff[0] = ATL2_READ_REG(hw, REG_VPD_CAP);
regs_buff[1] = ATL2_READ_REG(hw, REG_SPI_FLASH_CTRL);
regs_buff[2] = ATL2_READ_REG(hw, REG_SPI_FLASH_CONFIG);
regs_buff[3] = ATL2_READ_REG(hw, REG_TWSI_CTRL);
regs_buff[4] = ATL2_READ_REG(hw, REG_PCIE_DEV_MISC_CTRL);
regs_buff[5] = ATL2_READ_REG(hw, REG_MASTER_CTRL);
regs_buff[6] = ATL2_READ_REG(hw, REG_MANUAL_TIMER_INIT);
regs_buff[7] = ATL2_READ_REG(hw, REG_IRQ_MODU_TIMER_INIT);
regs_buff[8] = ATL2_READ_REG(hw, REG_PHY_ENABLE);
regs_buff[9] = ATL2_READ_REG(hw, REG_CMBDISDMA_TIMER);
regs_buff[10] = ATL2_READ_REG(hw, REG_IDLE_STATUS);
regs_buff[11] = ATL2_READ_REG(hw, REG_MDIO_CTRL);
regs_buff[12] = ATL2_READ_REG(hw, REG_SERDES_LOCK);
regs_buff[13] = ATL2_READ_REG(hw, REG_MAC_CTRL);
regs_buff[14] = ATL2_READ_REG(hw, REG_MAC_IPG_IFG);
regs_buff[15] = ATL2_READ_REG(hw, REG_MAC_STA_ADDR);
regs_buff[16] = ATL2_READ_REG(hw, REG_MAC_STA_ADDR+4);
regs_buff[17] = ATL2_READ_REG(hw, REG_RX_HASH_TABLE);
regs_buff[18] = ATL2_READ_REG(hw, REG_RX_HASH_TABLE+4);
regs_buff[19] = ATL2_READ_REG(hw, REG_MAC_HALF_DUPLX_CTRL);
regs_buff[20] = ATL2_READ_REG(hw, REG_MTU);
regs_buff[21] = ATL2_READ_REG(hw, REG_WOL_CTRL);
regs_buff[22] = ATL2_READ_REG(hw, REG_SRAM_TXRAM_END);
regs_buff[23] = ATL2_READ_REG(hw, REG_DESC_BASE_ADDR_HI);
regs_buff[24] = ATL2_READ_REG(hw, REG_TXD_BASE_ADDR_LO);
regs_buff[25] = ATL2_READ_REG(hw, REG_TXD_MEM_SIZE);
regs_buff[26] = ATL2_READ_REG(hw, REG_TXS_BASE_ADDR_LO);
regs_buff[27] = ATL2_READ_REG(hw, REG_TXS_MEM_SIZE);
regs_buff[28] = ATL2_READ_REG(hw, REG_RXD_BASE_ADDR_LO);
regs_buff[29] = ATL2_READ_REG(hw, REG_RXD_BUF_NUM);
regs_buff[30] = ATL2_READ_REG(hw, REG_DMAR);
regs_buff[31] = ATL2_READ_REG(hw, REG_TX_CUT_THRESH);
regs_buff[32] = ATL2_READ_REG(hw, REG_DMAW);
regs_buff[33] = ATL2_READ_REG(hw, REG_PAUSE_ON_TH);
regs_buff[34] = ATL2_READ_REG(hw, REG_PAUSE_OFF_TH);
regs_buff[35] = ATL2_READ_REG(hw, REG_MB_TXD_WR_IDX);
regs_buff[36] = ATL2_READ_REG(hw, REG_MB_RXD_RD_IDX);
regs_buff[38] = ATL2_READ_REG(hw, REG_ISR);
regs_buff[39] = ATL2_READ_REG(hw, REG_IMR);
atl2_read_phy_reg(hw, MII_BMCR, &phy_data);
regs_buff[40] = (u32)phy_data;
atl2_read_phy_reg(hw, MII_BMSR, &phy_data);
regs_buff[41] = (u32)phy_data;
}
static int atl2_get_eeprom_len(struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
if (!atl2_check_eeprom_exist(&adapter->hw))
return 512;
else
return 0;
}
static int atl2_get_eeprom(struct net_device *netdev,
struct ethtool_eeprom *eeprom, u8 *bytes)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
u32 *eeprom_buff;
int first_dword, last_dword;
int ret_val = 0;
int i;
if (eeprom->len == 0)
return -EINVAL;
if (atl2_check_eeprom_exist(hw))
return -EINVAL;
eeprom->magic = hw->vendor_id | (hw->device_id << 16);
first_dword = eeprom->offset >> 2;
last_dword = (eeprom->offset + eeprom->len - 1) >> 2;
eeprom_buff = kmalloc(sizeof(u32) * (last_dword - first_dword + 1),
GFP_KERNEL);
if (!eeprom_buff)
return -ENOMEM;
for (i = first_dword; i < last_dword; i++) {
if (!atl2_read_eeprom(hw, i*4, &(eeprom_buff[i-first_dword]))) {
ret_val = -EIO;
goto free;
}
}
memcpy(bytes, (u8 *)eeprom_buff + (eeprom->offset & 3),
eeprom->len);
free:
kfree(eeprom_buff);
return ret_val;
}
static int atl2_set_eeprom(struct net_device *netdev,
struct ethtool_eeprom *eeprom, u8 *bytes)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
u32 *eeprom_buff;
u32 *ptr;
int max_len, first_dword, last_dword, ret_val = 0;
int i;
if (eeprom->len == 0)
return -EOPNOTSUPP;
if (eeprom->magic != (hw->vendor_id | (hw->device_id << 16)))
return -EFAULT;
max_len = 512;
first_dword = eeprom->offset >> 2;
last_dword = (eeprom->offset + eeprom->len - 1) >> 2;
eeprom_buff = kmalloc(max_len, GFP_KERNEL);
if (!eeprom_buff)
return -ENOMEM;
ptr = (u32 *)eeprom_buff;
if (eeprom->offset & 3) {
/* need read/modify/write of first changed EEPROM word */
/* only the second byte of the word is being modified */
if (!atl2_read_eeprom(hw, first_dword*4, &(eeprom_buff[0])))
return -EIO;
ptr++;
}
if (((eeprom->offset + eeprom->len) & 3)) {
/*
* need read/modify/write of last changed EEPROM word
* only the first byte of the word is being modified
*/
if (!atl2_read_eeprom(hw, last_dword * 4,
&(eeprom_buff[last_dword - first_dword])))
return -EIO;
}
/* Device's eeprom is always little-endian, word addressable */
memcpy(ptr, bytes, eeprom->len);
for (i = 0; i < last_dword - first_dword + 1; i++) {
if (!atl2_write_eeprom(hw, ((first_dword+i)*4), eeprom_buff[i]))
return -EIO;
}
kfree(eeprom_buff);
return ret_val;
}
static void atl2_get_drvinfo(struct net_device *netdev,
struct ethtool_drvinfo *drvinfo)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
strncpy(drvinfo->driver, atl2_driver_name, 32);
strncpy(drvinfo->version, atl2_driver_version, 32);
strncpy(drvinfo->fw_version, "L2", 32);
strncpy(drvinfo->bus_info, pci_name(adapter->pdev), 32);
drvinfo->n_stats = 0;
drvinfo->testinfo_len = 0;
drvinfo->regdump_len = atl2_get_regs_len(netdev);
drvinfo->eedump_len = atl2_get_eeprom_len(netdev);
}
static void atl2_get_wol(struct net_device *netdev,
struct ethtool_wolinfo *wol)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
wol->supported = WAKE_MAGIC;
wol->wolopts = 0;
if (adapter->wol & ATLX_WUFC_EX)
wol->wolopts |= WAKE_UCAST;
if (adapter->wol & ATLX_WUFC_MC)
wol->wolopts |= WAKE_MCAST;
if (adapter->wol & ATLX_WUFC_BC)
wol->wolopts |= WAKE_BCAST;
if (adapter->wol & ATLX_WUFC_MAG)
wol->wolopts |= WAKE_MAGIC;
if (adapter->wol & ATLX_WUFC_LNKC)
wol->wolopts |= WAKE_PHY;
}
static int atl2_set_wol(struct net_device *netdev, struct ethtool_wolinfo *wol)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
if (wol->wolopts & (WAKE_ARP | WAKE_MAGICSECURE))
return -EOPNOTSUPP;
if (wol->wolopts & (WAKE_UCAST | WAKE_BCAST | WAKE_MCAST))
return -EOPNOTSUPP;
/* these settings will always override what we currently have */
adapter->wol = 0;
if (wol->wolopts & WAKE_MAGIC)
adapter->wol |= ATLX_WUFC_MAG;
if (wol->wolopts & WAKE_PHY)
adapter->wol |= ATLX_WUFC_LNKC;
return 0;
}
static int atl2_nway_reset(struct net_device *netdev)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
if (netif_running(netdev))
atl2_reinit_locked(adapter);
return 0;
}
static const struct ethtool_ops atl2_ethtool_ops = {
.get_settings = atl2_get_settings,
.set_settings = atl2_set_settings,
.get_drvinfo = atl2_get_drvinfo,
.get_regs_len = atl2_get_regs_len,
.get_regs = atl2_get_regs,
.get_wol = atl2_get_wol,
.set_wol = atl2_set_wol,
.get_msglevel = atl2_get_msglevel,
.set_msglevel = atl2_set_msglevel,
.nway_reset = atl2_nway_reset,
.get_link = ethtool_op_get_link,
.get_eeprom_len = atl2_get_eeprom_len,
.get_eeprom = atl2_get_eeprom,
.set_eeprom = atl2_set_eeprom,
.get_tx_csum = atl2_get_tx_csum,
.get_sg = ethtool_op_get_sg,
.set_sg = ethtool_op_set_sg,
#ifdef NETIF_F_TSO
.get_tso = ethtool_op_get_tso,
#endif
};
static void atl2_set_ethtool_ops(struct net_device *netdev)
{
SET_ETHTOOL_OPS(netdev, &atl2_ethtool_ops);
}
#define LBYTESWAP(a) ((((a) & 0x00ff00ff) << 8) | \
(((a) & 0xff00ff00) >> 8))
#define LONGSWAP(a) ((LBYTESWAP(a) << 16) | (LBYTESWAP(a) >> 16))
#define SHORTSWAP(a) (((a) << 8) | ((a) >> 8))
/*
* Reset the transmit and receive units; mask and clear all interrupts.
*
* hw - Struct containing variables accessed by shared code
* return : 0 or idle status (if error)
*/
static s32 atl2_reset_hw(struct atl2_hw *hw)
{
u32 icr;
u16 pci_cfg_cmd_word;
int i;
atl2_read_pci_cfg(hw, PCI_REG_COMMAND, &pci_cfg_cmd_word);
if ((pci_cfg_cmd_word &
(CMD_IO_SPACE|CMD_MEMORY_SPACE|CMD_BUS_MASTER)) !=
(CMD_IO_SPACE|CMD_MEMORY_SPACE|CMD_BUS_MASTER)) {
pci_cfg_cmd_word |=
(CMD_IO_SPACE|CMD_MEMORY_SPACE|CMD_BUS_MASTER);
atl2_write_pci_cfg(hw, PCI_REG_COMMAND, &pci_cfg_cmd_word);
}
/* Clear Interrupt mask to stop board from generating
* interrupts & Clear any pending interrupt events
*/
/* ATL2_WRITE_REG(hw, REG_IMR, 0); */
/* ATL2_WRITE_REG(hw, REG_ISR, 0xffffffff); */
/* Issue Soft Reset to the MAC. This will reset the chip's
* transmit, receive, DMA. It will not effect
* the current PCI configuration. The global reset bit is self-
* clearing, and should clear within a microsecond.
*/
ATL2_WRITE_REG(hw, REG_MASTER_CTRL, MASTER_CTRL_SOFT_RST);
wmb();
msleep(1); /* delay about 1ms */
/* Wait at least 10ms for All module to be Idle */
for (i = 0; i < 10; i++) {
icr = ATL2_READ_REG(hw, REG_IDLE_STATUS);
if (!icr)
break;
msleep(1); /* delay 1 ms */
cpu_relax();
}
if (icr)
return icr;
return 0;
}
#define CUSTOM_SPI_CS_SETUP 2
#define CUSTOM_SPI_CLK_HI 2
#define CUSTOM_SPI_CLK_LO 2
#define CUSTOM_SPI_CS_HOLD 2
#define CUSTOM_SPI_CS_HI 3
static struct atl2_spi_flash_dev flash_table[] =
{
/* MFR WRSR READ PROGRAM WREN WRDI RDSR RDID SECTOR_ERASE CHIP_ERASE */
{"Atmel", 0x0, 0x03, 0x02, 0x06, 0x04, 0x05, 0x15, 0x52, 0x62 },
{"SST", 0x01, 0x03, 0x02, 0x06, 0x04, 0x05, 0x90, 0x20, 0x60 },
{"ST", 0x01, 0x03, 0x02, 0x06, 0x04, 0x05, 0xAB, 0xD8, 0xC7 },
};
static bool atl2_spi_read(struct atl2_hw *hw, u32 addr, u32 *buf)
{
int i;
u32 value;
ATL2_WRITE_REG(hw, REG_SPI_DATA, 0);
ATL2_WRITE_REG(hw, REG_SPI_ADDR, addr);
value = SPI_FLASH_CTRL_WAIT_READY |
(CUSTOM_SPI_CS_SETUP & SPI_FLASH_CTRL_CS_SETUP_MASK) <<
SPI_FLASH_CTRL_CS_SETUP_SHIFT |
(CUSTOM_SPI_CLK_HI & SPI_FLASH_CTRL_CLK_HI_MASK) <<
SPI_FLASH_CTRL_CLK_HI_SHIFT |
(CUSTOM_SPI_CLK_LO & SPI_FLASH_CTRL_CLK_LO_MASK) <<
SPI_FLASH_CTRL_CLK_LO_SHIFT |
(CUSTOM_SPI_CS_HOLD & SPI_FLASH_CTRL_CS_HOLD_MASK) <<
SPI_FLASH_CTRL_CS_HOLD_SHIFT |
(CUSTOM_SPI_CS_HI & SPI_FLASH_CTRL_CS_HI_MASK) <<
SPI_FLASH_CTRL_CS_HI_SHIFT |
(0x1 & SPI_FLASH_CTRL_INS_MASK) << SPI_FLASH_CTRL_INS_SHIFT;
ATL2_WRITE_REG(hw, REG_SPI_FLASH_CTRL, value);
value |= SPI_FLASH_CTRL_START;
ATL2_WRITE_REG(hw, REG_SPI_FLASH_CTRL, value);
for (i = 0; i < 10; i++) {
msleep(1);
value = ATL2_READ_REG(hw, REG_SPI_FLASH_CTRL);
if (!(value & SPI_FLASH_CTRL_START))
break;
}
if (value & SPI_FLASH_CTRL_START)
return false;
*buf = ATL2_READ_REG(hw, REG_SPI_DATA);
return true;
}
/*
* get_permanent_address
* return 0 if get valid mac address,
*/
static int get_permanent_address(struct atl2_hw *hw)
{
u32 Addr[2];
u32 i, Control;
u16 Register;
u8 EthAddr[NODE_ADDRESS_SIZE];
bool KeyValid;
if (is_valid_ether_addr(hw->perm_mac_addr))
return 0;
Addr[0] = 0;
Addr[1] = 0;
if (!atl2_check_eeprom_exist(hw)) { /* eeprom exists */
Register = 0;
KeyValid = false;
/* Read out all EEPROM content */
i = 0;
while (1) {
if (atl2_read_eeprom(hw, i + 0x100, &Control)) {
if (KeyValid) {
if (Register == REG_MAC_STA_ADDR)
Addr[0] = Control;
else if (Register ==
(REG_MAC_STA_ADDR + 4))
Addr[1] = Control;
KeyValid = false;
} else if ((Control & 0xff) == 0x5A) {
KeyValid = true;
Register = (u16) (Control >> 16);
} else {
/* assume data end while encount an invalid KEYWORD */
break;
}
} else {
break; /* read error */
}
i += 4;
}
*(u32 *) &EthAddr[2] = LONGSWAP(Addr[0]);
*(u16 *) &EthAddr[0] = SHORTSWAP(*(u16 *) &Addr[1]);
if (is_valid_ether_addr(EthAddr)) {
memcpy(hw->perm_mac_addr, EthAddr, NODE_ADDRESS_SIZE);
return 0;
}
return 1;
}
/* see if SPI flash exists? */
Addr[0] = 0;
Addr[1] = 0;
Register = 0;
KeyValid = false;
i = 0;
while (1) {
if (atl2_spi_read(hw, i + 0x1f000, &Control)) {
if (KeyValid) {
if (Register == REG_MAC_STA_ADDR)
Addr[0] = Control;
else if (Register == (REG_MAC_STA_ADDR + 4))
Addr[1] = Control;
KeyValid = false;
} else if ((Control & 0xff) == 0x5A) {
KeyValid = true;
Register = (u16) (Control >> 16);
} else {
break; /* data end */
}
} else {
break; /* read error */
}
i += 4;
}
*(u32 *) &EthAddr[2] = LONGSWAP(Addr[0]);
*(u16 *) &EthAddr[0] = SHORTSWAP(*(u16 *)&Addr[1]);
if (is_valid_ether_addr(EthAddr)) {
memcpy(hw->perm_mac_addr, EthAddr, NODE_ADDRESS_SIZE);
return 0;
}
/* maybe MAC-address is from BIOS */
Addr[0] = ATL2_READ_REG(hw, REG_MAC_STA_ADDR);
Addr[1] = ATL2_READ_REG(hw, REG_MAC_STA_ADDR + 4);
*(u32 *) &EthAddr[2] = LONGSWAP(Addr[0]);
*(u16 *) &EthAddr[0] = SHORTSWAP(*(u16 *) &Addr[1]);
if (is_valid_ether_addr(EthAddr)) {
memcpy(hw->perm_mac_addr, EthAddr, NODE_ADDRESS_SIZE);
return 0;
}
return 1;
}
/*
* Reads the adapter's MAC address from the EEPROM
*
* hw - Struct containing variables accessed by shared code
*/
static s32 atl2_read_mac_addr(struct atl2_hw *hw)
{
u16 i;
if (get_permanent_address(hw)) {
/* for test */
hw->perm_mac_addr[0] = 0x00;
hw->perm_mac_addr[1] = 0x13;
hw->perm_mac_addr[2] = 0x74;
hw->perm_mac_addr[3] = 0x00;
hw->perm_mac_addr[4] = 0x5c;
hw->perm_mac_addr[5] = 0x38;
}
for (i = 0; i < NODE_ADDRESS_SIZE; i++)
hw->mac_addr[i] = hw->perm_mac_addr[i];
return 0;
}
/*
* Hashes an address to determine its location in the multicast table
*
* hw - Struct containing variables accessed by shared code
* mc_addr - the multicast address to hash
*
* atl2_hash_mc_addr
* purpose
* set hash value for a multicast address
* hash calcu processing :
* 1. calcu 32bit CRC for multicast address
* 2. reverse crc with MSB to LSB
*/
static u32 atl2_hash_mc_addr(struct atl2_hw *hw, u8 *mc_addr)
{
u32 crc32, value;
int i;
value = 0;
crc32 = ether_crc_le(6, mc_addr);
for (i = 0; i < 32; i++)
value |= (((crc32 >> i) & 1) << (31 - i));
return value;
}
/*
* Sets the bit in the multicast table corresponding to the hash value.
*
* hw - Struct containing variables accessed by shared code
* hash_value - Multicast address hash value
*/
static void atl2_hash_set(struct atl2_hw *hw, u32 hash_value)
{
u32 hash_bit, hash_reg;
u32 mta;
/* The HASH Table is a register array of 2 32-bit registers.
* It is treated like an array of 64 bits. We want to set
* bit BitArray[hash_value]. So we figure out what register
* the bit is in, read it, OR in the new bit, then write
* back the new value. The register is determined by the
* upper 7 bits of the hash value and the bit within that
* register are determined by the lower 5 bits of the value.
*/
hash_reg = (hash_value >> 31) & 0x1;
hash_bit = (hash_value >> 26) & 0x1F;
mta = ATL2_READ_REG_ARRAY(hw, REG_RX_HASH_TABLE, hash_reg);
mta |= (1 << hash_bit);
ATL2_WRITE_REG_ARRAY(hw, REG_RX_HASH_TABLE, hash_reg, mta);
}
/*
* atl2_init_pcie - init PCIE module
*/
static void atl2_init_pcie(struct atl2_hw *hw)
{
u32 value;
value = LTSSM_TEST_MODE_DEF;
ATL2_WRITE_REG(hw, REG_LTSSM_TEST_MODE, value);
value = PCIE_DLL_TX_CTRL1_DEF;
ATL2_WRITE_REG(hw, REG_PCIE_DLL_TX_CTRL1, value);
}
static void atl2_init_flash_opcode(struct atl2_hw *hw)
{
if (hw->flash_vendor >= ARRAY_SIZE(flash_table))
hw->flash_vendor = 0; /* ATMEL */
/* Init OP table */
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_PROGRAM,
flash_table[hw->flash_vendor].cmdPROGRAM);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_SC_ERASE,
flash_table[hw->flash_vendor].cmdSECTOR_ERASE);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_CHIP_ERASE,
flash_table[hw->flash_vendor].cmdCHIP_ERASE);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_RDID,
flash_table[hw->flash_vendor].cmdRDID);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_WREN,
flash_table[hw->flash_vendor].cmdWREN);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_RDSR,
flash_table[hw->flash_vendor].cmdRDSR);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_WRSR,
flash_table[hw->flash_vendor].cmdWRSR);
ATL2_WRITE_REGB(hw, REG_SPI_FLASH_OP_READ,
flash_table[hw->flash_vendor].cmdREAD);
}
/********************************************************************
* Performs basic configuration of the adapter.
*
* hw - Struct containing variables accessed by shared code
* Assumes that the controller has previously been reset and is in a
* post-reset uninitialized state. Initializes multicast table,
* and Calls routines to setup link
* Leaves the transmit and receive units disabled and uninitialized.
********************************************************************/
static s32 atl2_init_hw(struct atl2_hw *hw)
{
u32 ret_val = 0;
atl2_init_pcie(hw);
/* Zero out the Multicast HASH table */
/* clear the old settings from the multicast hash table */
ATL2_WRITE_REG(hw, REG_RX_HASH_TABLE, 0);
ATL2_WRITE_REG_ARRAY(hw, REG_RX_HASH_TABLE, 1, 0);
atl2_init_flash_opcode(hw);
ret_val = atl2_phy_init(hw);
return ret_val;
}
/*
* Detects the current speed and duplex settings of the hardware.
*
* hw - Struct containing variables accessed by shared code
* speed - Speed of the connection
* duplex - Duplex setting of the connection
*/
static s32 atl2_get_speed_and_duplex(struct atl2_hw *hw, u16 *speed,
u16 *duplex)
{
s32 ret_val;
u16 phy_data;
/* Read PHY Specific Status Register (17) */
ret_val = atl2_read_phy_reg(hw, MII_ATLX_PSSR, &phy_data);
if (ret_val)
return ret_val;
if (!(phy_data & MII_ATLX_PSSR_SPD_DPLX_RESOLVED))
return ATLX_ERR_PHY_RES;
switch (phy_data & MII_ATLX_PSSR_SPEED) {
case MII_ATLX_PSSR_100MBS:
*speed = SPEED_100;
break;
case MII_ATLX_PSSR_10MBS:
*speed = SPEED_10;
break;
default:
return ATLX_ERR_PHY_SPEED;
break;
}
if (phy_data & MII_ATLX_PSSR_DPLX)
*duplex = FULL_DUPLEX;
else
*duplex = HALF_DUPLEX;
return 0;
}
/*
* Reads the value from a PHY register
* hw - Struct containing variables accessed by shared code
* reg_addr - address of the PHY register to read
*/
static s32 atl2_read_phy_reg(struct atl2_hw *hw, u16 reg_addr, u16 *phy_data)
{
u32 val;
int i;
val = ((u32)(reg_addr & MDIO_REG_ADDR_MASK)) << MDIO_REG_ADDR_SHIFT |
MDIO_START |
MDIO_SUP_PREAMBLE |
MDIO_RW |
MDIO_CLK_25_4 << MDIO_CLK_SEL_SHIFT;
ATL2_WRITE_REG(hw, REG_MDIO_CTRL, val);
wmb();
for (i = 0; i < MDIO_WAIT_TIMES; i++) {
udelay(2);
val = ATL2_READ_REG(hw, REG_MDIO_CTRL);
if (!(val & (MDIO_START | MDIO_BUSY)))
break;
wmb();
}
if (!(val & (MDIO_START | MDIO_BUSY))) {
*phy_data = (u16)val;
return 0;
}
return ATLX_ERR_PHY;
}
/*
* Writes a value to a PHY register
* hw - Struct containing variables accessed by shared code
* reg_addr - address of the PHY register to write
* data - data to write to the PHY
*/
static s32 atl2_write_phy_reg(struct atl2_hw *hw, u32 reg_addr, u16 phy_data)
{
int i;
u32 val;
val = ((u32)(phy_data & MDIO_DATA_MASK)) << MDIO_DATA_SHIFT |
(reg_addr & MDIO_REG_ADDR_MASK) << MDIO_REG_ADDR_SHIFT |
MDIO_SUP_PREAMBLE |
MDIO_START |
MDIO_CLK_25_4 << MDIO_CLK_SEL_SHIFT;
ATL2_WRITE_REG(hw, REG_MDIO_CTRL, val);
wmb();
for (i = 0; i < MDIO_WAIT_TIMES; i++) {
udelay(2);
val = ATL2_READ_REG(hw, REG_MDIO_CTRL);
if (!(val & (MDIO_START | MDIO_BUSY)))
break;
wmb();
}
if (!(val & (MDIO_START | MDIO_BUSY)))
return 0;
return ATLX_ERR_PHY;
}
/*
* Configures PHY autoneg and flow control advertisement settings
*
* hw - Struct containing variables accessed by shared code
*/
static s32 atl2_phy_setup_autoneg_adv(struct atl2_hw *hw)
{
s32 ret_val;
s16 mii_autoneg_adv_reg;
/* Read the MII Auto-Neg Advertisement Register (Address 4). */
mii_autoneg_adv_reg = MII_AR_DEFAULT_CAP_MASK;
/* Need to parse autoneg_advertised and set up
* the appropriate PHY registers. First we will parse for
* autoneg_advertised software override. Since we can advertise
* a plethora of combinations, we need to check each bit
* individually.
*/
/* First we clear all the 10/100 mb speed bits in the Auto-Neg
* Advertisement Register (Address 4) and the 1000 mb speed bits in
* the 1000Base-T Control Register (Address 9). */
mii_autoneg_adv_reg &= ~MII_AR_SPEED_MASK;
/* Need to parse MediaType and setup the
* appropriate PHY registers. */
switch (hw->MediaType) {
case MEDIA_TYPE_AUTO_SENSOR:
mii_autoneg_adv_reg |=
(MII_AR_10T_HD_CAPS |
MII_AR_10T_FD_CAPS |
MII_AR_100TX_HD_CAPS|
MII_AR_100TX_FD_CAPS);
hw->autoneg_advertised =
ADVERTISE_10_HALF |
ADVERTISE_10_FULL |
ADVERTISE_100_HALF|
ADVERTISE_100_FULL;
break;
case MEDIA_TYPE_100M_FULL:
mii_autoneg_adv_reg |= MII_AR_100TX_FD_CAPS;
hw->autoneg_advertised = ADVERTISE_100_FULL;
break;
case MEDIA_TYPE_100M_HALF:
mii_autoneg_adv_reg |= MII_AR_100TX_HD_CAPS;
hw->autoneg_advertised = ADVERTISE_100_HALF;
break;
case MEDIA_TYPE_10M_FULL:
mii_autoneg_adv_reg |= MII_AR_10T_FD_CAPS;
hw->autoneg_advertised = ADVERTISE_10_FULL;
break;
default:
mii_autoneg_adv_reg |= MII_AR_10T_HD_CAPS;
hw->autoneg_advertised = ADVERTISE_10_HALF;
break;
}
/* flow control fixed to enable all */
mii_autoneg_adv_reg |= (MII_AR_ASM_DIR | MII_AR_PAUSE);
hw->mii_autoneg_adv_reg = mii_autoneg_adv_reg;
ret_val = atl2_write_phy_reg(hw, MII_ADVERTISE, mii_autoneg_adv_reg);
if (ret_val)
return ret_val;
return 0;
}
/*
* Resets the PHY and make all config validate
*
* hw - Struct containing variables accessed by shared code
*
* Sets bit 15 and 12 of the MII Control regiser (for F001 bug)
*/
static s32 atl2_phy_commit(struct atl2_hw *hw)
{
s32 ret_val;
u16 phy_data;
phy_data = MII_CR_RESET | MII_CR_AUTO_NEG_EN | MII_CR_RESTART_AUTO_NEG;
ret_val = atl2_write_phy_reg(hw, MII_BMCR, phy_data);
if (ret_val) {
u32 val;
int i;
/* pcie serdes link may be down ! */
for (i = 0; i < 25; i++) {
msleep(1);
val = ATL2_READ_REG(hw, REG_MDIO_CTRL);
if (!(val & (MDIO_START | MDIO_BUSY)))
break;
}
if (0 != (val & (MDIO_START | MDIO_BUSY))) {
printk(KERN_ERR "atl2: PCIe link down for at least 25ms !\n");
return ret_val;
}
}
return 0;
}
static s32 atl2_phy_init(struct atl2_hw *hw)
{
s32 ret_val;
u16 phy_val;
if (hw->phy_configured)
return 0;
/* Enable PHY */
ATL2_WRITE_REGW(hw, REG_PHY_ENABLE, 1);
ATL2_WRITE_FLUSH(hw);
msleep(1);
/* check if the PHY is in powersaving mode */
atl2_write_phy_reg(hw, MII_DBG_ADDR, 0);
atl2_read_phy_reg(hw, MII_DBG_DATA, &phy_val);
/* 024E / 124E 0r 0274 / 1274 ? */
if (phy_val & 0x1000) {
phy_val &= ~0x1000;
atl2_write_phy_reg(hw, MII_DBG_DATA, phy_val);
}
msleep(1);
/*Enable PHY LinkChange Interrupt */
ret_val = atl2_write_phy_reg(hw, 18, 0xC00);
if (ret_val)
return ret_val;
/* setup AutoNeg parameters */
ret_val = atl2_phy_setup_autoneg_adv(hw);
if (ret_val)
return ret_val;
/* SW.Reset & En-Auto-Neg to restart Auto-Neg */
ret_val = atl2_phy_commit(hw);
if (ret_val)
return ret_val;
hw->phy_configured = true;
return ret_val;
}
static void atl2_set_mac_addr(struct atl2_hw *hw)
{
u32 value;
/* 00-0B-6A-F6-00-DC
* 0: 6AF600DC 1: 000B
* low dword */
value = (((u32)hw->mac_addr[2]) << 24) |
(((u32)hw->mac_addr[3]) << 16) |
(((u32)hw->mac_addr[4]) << 8) |
(((u32)hw->mac_addr[5]));
ATL2_WRITE_REG_ARRAY(hw, REG_MAC_STA_ADDR, 0, value);
/* hight dword */
value = (((u32)hw->mac_addr[0]) << 8) |
(((u32)hw->mac_addr[1]));
ATL2_WRITE_REG_ARRAY(hw, REG_MAC_STA_ADDR, 1, value);
}
/*
* check_eeprom_exist
* return 0 if eeprom exist
*/
static int atl2_check_eeprom_exist(struct atl2_hw *hw)
{
u32 value;
value = ATL2_READ_REG(hw, REG_SPI_FLASH_CTRL);
if (value & SPI_FLASH_CTRL_EN_VPD) {
value &= ~SPI_FLASH_CTRL_EN_VPD;
ATL2_WRITE_REG(hw, REG_SPI_FLASH_CTRL, value);
}
value = ATL2_READ_REGW(hw, REG_PCIE_CAP_LIST);
return ((value & 0xFF00) == 0x6C00) ? 0 : 1;
}
static bool atl2_write_eeprom(struct atl2_hw *hw, u32 offset, u32 value)
{
return true;
}
static bool atl2_read_eeprom(struct atl2_hw *hw, u32 Offset, u32 *pValue)
{
int i;
u32 Control;
if (Offset & 0x3)
return false; /* address do not align */
ATL2_WRITE_REG(hw, REG_VPD_DATA, 0);
Control = (Offset & VPD_CAP_VPD_ADDR_MASK) << VPD_CAP_VPD_ADDR_SHIFT;
ATL2_WRITE_REG(hw, REG_VPD_CAP, Control);
for (i = 0; i < 10; i++) {
msleep(2);
Control = ATL2_READ_REG(hw, REG_VPD_CAP);
if (Control & VPD_CAP_VPD_FLAG)
break;
}
if (Control & VPD_CAP_VPD_FLAG) {
*pValue = ATL2_READ_REG(hw, REG_VPD_DATA);
return true;
}
return false; /* timeout */
}
static void atl2_force_ps(struct atl2_hw *hw)
{
u16 phy_val;
atl2_write_phy_reg(hw, MII_DBG_ADDR, 0);
atl2_read_phy_reg(hw, MII_DBG_DATA, &phy_val);
atl2_write_phy_reg(hw, MII_DBG_DATA, phy_val | 0x1000);
atl2_write_phy_reg(hw, MII_DBG_ADDR, 2);
atl2_write_phy_reg(hw, MII_DBG_DATA, 0x3000);
atl2_write_phy_reg(hw, MII_DBG_ADDR, 3);
atl2_write_phy_reg(hw, MII_DBG_DATA, 0);
}
/* This is the only thing that needs to be changed to adjust the
* maximum number of ports that the driver can manage.
*/
#define ATL2_MAX_NIC 4
#define OPTION_UNSET -1
#define OPTION_DISABLED 0
#define OPTION_ENABLED 1
/* All parameters are treated the same, as an integer array of values.
* This macro just reduces the need to repeat the same declaration code
* over and over (plus this helps to avoid typo bugs).
*/
#define ATL2_PARAM_INIT {[0 ... ATL2_MAX_NIC] = OPTION_UNSET}
#ifndef module_param_array
/* Module Parameters are always initialized to -1, so that the driver
* can tell the difference between no user specified value or the
* user asking for the default value.
* The true default values are loaded in when atl2_check_options is called.
*
* This is a GCC extension to ANSI C.
* See the item "Labeled Elements in Initializers" in the section
* "Extensions to the C Language Family" of the GCC documentation.
*/
#define ATL2_PARAM(X, desc) \
static const int __devinitdata X[ATL2_MAX_NIC + 1] = ATL2_PARAM_INIT; \
MODULE_PARM(X, "1-" __MODULE_STRING(ATL2_MAX_NIC) "i"); \
MODULE_PARM_DESC(X, desc);
#else
#define ATL2_PARAM(X, desc) \
static int __devinitdata X[ATL2_MAX_NIC+1] = ATL2_PARAM_INIT; \
static unsigned int num_##X; \
module_param_array_named(X, X, int, &num_##X, 0); \
MODULE_PARM_DESC(X, desc);
#endif
/*
* Transmit Memory Size
* Valid Range: 64-2048
* Default Value: 128
*/
#define ATL2_MIN_TX_MEMSIZE 4 /* 4KB */
#define ATL2_MAX_TX_MEMSIZE 64 /* 64KB */
#define ATL2_DEFAULT_TX_MEMSIZE 8 /* 8KB */
ATL2_PARAM(TxMemSize, "Bytes of Transmit Memory");
/*
* Receive Memory Block Count
* Valid Range: 16-512
* Default Value: 128
*/
#define ATL2_MIN_RXD_COUNT 16
#define ATL2_MAX_RXD_COUNT 512
#define ATL2_DEFAULT_RXD_COUNT 64
ATL2_PARAM(RxMemBlock, "Number of receive memory block");
/*
* User Specified MediaType Override
*
* Valid Range: 0-5
* - 0 - auto-negotiate at all supported speeds
* - 1 - only link at 1000Mbps Full Duplex
* - 2 - only link at 100Mbps Full Duplex
* - 3 - only link at 100Mbps Half Duplex
* - 4 - only link at 10Mbps Full Duplex
* - 5 - only link at 10Mbps Half Duplex
* Default Value: 0
*/
ATL2_PARAM(MediaType, "MediaType Select");
/*
* Interrupt Moderate Timer in units of 2048 ns (~2 us)
* Valid Range: 10-65535
* Default Value: 45000(90ms)
*/
#define INT_MOD_DEFAULT_CNT 100 /* 200us */
#define INT_MOD_MAX_CNT 65000
#define INT_MOD_MIN_CNT 50
ATL2_PARAM(IntModTimer, "Interrupt Moderator Timer");
/*
* FlashVendor
* Valid Range: 0-2
* 0 - Atmel
* 1 - SST
* 2 - ST
*/
ATL2_PARAM(FlashVendor, "SPI Flash Vendor");
#define AUTONEG_ADV_DEFAULT 0x2F
#define AUTONEG_ADV_MASK 0x2F
#define FLOW_CONTROL_DEFAULT FLOW_CONTROL_FULL
#define FLASH_VENDOR_DEFAULT 0
#define FLASH_VENDOR_MIN 0
#define FLASH_VENDOR_MAX 2
struct atl2_option {
enum { enable_option, range_option, list_option } type;
char *name;
char *err;
int def;
union {
struct { /* range_option info */
int min;
int max;
} r;
struct { /* list_option info */
int nr;
struct atl2_opt_list { int i; char *str; } *p;
} l;
} arg;
};
static int __devinit atl2_validate_option(int *value, struct atl2_option *opt)
{
int i;
struct atl2_opt_list *ent;
if (*value == OPTION_UNSET) {
*value = opt->def;
return 0;
}
switch (opt->type) {
case enable_option:
switch (*value) {
case OPTION_ENABLED:
printk(KERN_INFO "%s Enabled\n", opt->name);
return 0;
break;
case OPTION_DISABLED:
printk(KERN_INFO "%s Disabled\n", opt->name);
return 0;
break;
}
break;
case range_option:
if (*value >= opt->arg.r.min && *value <= opt->arg.r.max) {
printk(KERN_INFO "%s set to %i\n", opt->name, *value);
return 0;
}
break;
case list_option:
for (i = 0; i < opt->arg.l.nr; i++) {
ent = &opt->arg.l.p[i];
if (*value == ent->i) {
if (ent->str[0] != '\0')
printk(KERN_INFO "%s\n", ent->str);
return 0;
}
}
break;
default:
BUG();
}
printk(KERN_INFO "Invalid %s specified (%i) %s\n",
opt->name, *value, opt->err);
*value = opt->def;
return -1;
}
/*
* atl2_check_options - Range Checking for Command Line Parameters
* @adapter: board private structure
*
* This routine checks all command line parameters for valid user
* input. If an invalid value is given, or if no user specified
* value exists, a default value is used. The final value is stored
* in a variable in the adapter structure.
*/
static void __devinit atl2_check_options(struct atl2_adapter *adapter)
{
int val;
struct atl2_option opt;
int bd = adapter->bd_number;
if (bd >= ATL2_MAX_NIC) {
printk(KERN_NOTICE "Warning: no configuration for board #%i\n",
bd);
printk(KERN_NOTICE "Using defaults for all values\n");
#ifndef module_param_array
bd = ATL2_MAX_NIC;
#endif
}
/* Bytes of Transmit Memory */
opt.type = range_option;
opt.name = "Bytes of Transmit Memory";
opt.err = "using default of " __MODULE_STRING(ATL2_DEFAULT_TX_MEMSIZE);
opt.def = ATL2_DEFAULT_TX_MEMSIZE;
opt.arg.r.min = ATL2_MIN_TX_MEMSIZE;
opt.arg.r.max = ATL2_MAX_TX_MEMSIZE;
#ifdef module_param_array
if (num_TxMemSize > bd) {
#endif
val = TxMemSize[bd];
atl2_validate_option(&val, &opt);
adapter->txd_ring_size = ((u32) val) * 1024;
#ifdef module_param_array
} else
adapter->txd_ring_size = ((u32)opt.def) * 1024;
#endif
/* txs ring size: */
adapter->txs_ring_size = adapter->txd_ring_size / 128;
if (adapter->txs_ring_size > 160)
adapter->txs_ring_size = 160;
/* Receive Memory Block Count */
opt.type = range_option;
opt.name = "Number of receive memory block";
opt.err = "using default of " __MODULE_STRING(ATL2_DEFAULT_RXD_COUNT);
opt.def = ATL2_DEFAULT_RXD_COUNT;
opt.arg.r.min = ATL2_MIN_RXD_COUNT;
opt.arg.r.max = ATL2_MAX_RXD_COUNT;
#ifdef module_param_array
if (num_RxMemBlock > bd) {
#endif
val = RxMemBlock[bd];
atl2_validate_option(&val, &opt);
adapter->rxd_ring_size = (u32)val;
/* ((u16)val)&~1; */ /* even number */
#ifdef module_param_array
} else
adapter->rxd_ring_size = (u32)opt.def;
#endif
/* init RXD Flow control value */
adapter->hw.fc_rxd_hi = (adapter->rxd_ring_size / 8) * 7;
adapter->hw.fc_rxd_lo = (ATL2_MIN_RXD_COUNT / 8) >
(adapter->rxd_ring_size / 12) ? (ATL2_MIN_RXD_COUNT / 8) :
(adapter->rxd_ring_size / 12);
/* Interrupt Moderate Timer */
opt.type = range_option;
opt.name = "Interrupt Moderate Timer";
opt.err = "using default of " __MODULE_STRING(INT_MOD_DEFAULT_CNT);
opt.def = INT_MOD_DEFAULT_CNT;
opt.arg.r.min = INT_MOD_MIN_CNT;
opt.arg.r.max = INT_MOD_MAX_CNT;
#ifdef module_param_array
if (num_IntModTimer > bd) {
#endif
val = IntModTimer[bd];
atl2_validate_option(&val, &opt);
adapter->imt = (u16) val;
#ifdef module_param_array
} else
adapter->imt = (u16)(opt.def);
#endif
/* Flash Vendor */
opt.type = range_option;
opt.name = "SPI Flash Vendor";
opt.err = "using default of " __MODULE_STRING(FLASH_VENDOR_DEFAULT);
opt.def = FLASH_VENDOR_DEFAULT;
opt.arg.r.min = FLASH_VENDOR_MIN;
opt.arg.r.max = FLASH_VENDOR_MAX;
#ifdef module_param_array
if (num_FlashVendor > bd) {
#endif
val = FlashVendor[bd];
atl2_validate_option(&val, &opt);
adapter->hw.flash_vendor = (u8) val;
#ifdef module_param_array
} else
adapter->hw.flash_vendor = (u8)(opt.def);
#endif
/* MediaType */
opt.type = range_option;
opt.name = "Speed/Duplex Selection";
opt.err = "using default of " __MODULE_STRING(MEDIA_TYPE_AUTO_SENSOR);
opt.def = MEDIA_TYPE_AUTO_SENSOR;
opt.arg.r.min = MEDIA_TYPE_AUTO_SENSOR;
opt.arg.r.max = MEDIA_TYPE_10M_HALF;
#ifdef module_param_array
if (num_MediaType > bd) {
#endif
val = MediaType[bd];
atl2_validate_option(&val, &opt);
adapter->hw.MediaType = (u16) val;
#ifdef module_param_array
} else
adapter->hw.MediaType = (u16)(opt.def);
#endif
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="Ydg-fD-yQy"/>
<viewControllerLayoutGuide type="bottom" id="xbc-2k-c8Z"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<imageView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" image="LaunchImage" translatesAutoresizingMaskIntoConstraints="NO" id="YRO-k0-Ey4">
</imageView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="YRO-k0-Ey4" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="1a2-6s-vTC"/>
<constraint firstItem="YRO-k0-Ey4" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="4X2-HB-R7a"/>
</constraints>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
<resources>
<image name="LaunchImage" width="168" height="185"/>
</resources>
</document>
|
{
"pile_set_name": "Github"
}
|
package terraform
import "github.com/hashicorp/terraform-plugin-sdk/internal/dag"
// GraphDot returns the dot formatting of a visual representation of
// the given Terraform graph.
func GraphDot(g *Graph, opts *dag.DotOpts) (string, error) {
return string(g.Dot(opts)), nil
}
|
{
"pile_set_name": "Github"
}
|
TK_CONST_DATA_ALIGN(const unsigned char ui_stroke_gradient[]) = {
0x04,0x00,0x01,0x01,0x4e,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x73,0x74,0x72,0x6f,0x6b,0x65,0x5f,0x67,
0x72,0x61,0x64,0x69,0x65,0x6e,0x74,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x12,0x12,0x22,0x11,0x77,0x69,0x6e,0x64,0x6f,0x77,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x61,0x6e,0x69,0x6d,
0x5f,0x68,0x69,0x6e,0x74,0x00,0x68,0x74,0x72,0x61,0x6e,0x73,0x6c,0x61,0x74,0x65,0x00,0x00,0x63,0x61,
0x6e,0x76,0x61,0x73,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x64,0x00,
0x00,0x00,0x64,0x00,0x00,0x00,0x73,0x65,0x6c,0x66,0x5f,0x6c,0x61,0x79,0x6f,0x75,0x74,0x00,0x64,0x65,
0x66,0x61,0x75,0x6c,0x74,0x28,0x78,0x3d,0x30,0x2c,0x79,0x3d,0x30,0x2c,0x77,0x3d,0x31,0x30,0x30,0x25,
0x2c,0x68,0x3d,0x31,0x30,0x30,0x25,0x29,0x00,0x6e,0x61,0x6d,0x65,0x00,0x70,0x61,0x69,0x6e,0x74,0x5f,
0x73,0x74,0x72,0x6f,0x6b,0x65,0x5f,0x67,0x72,0x61,0x64,0x69,0x65,0x6e,0x74,0x00,0x00,0x00,0x62,0x75,
0x74,0x74,0x6f,0x6e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x6e,0x61,0x6d,0x65,0x00,0x63,0x6c,0x6f,0x73,0x65,0x00,0x73,0x65,0x6c,
0x66,0x5f,0x6c,0x61,0x79,0x6f,0x75,0x74,0x00,0x64,0x65,0x66,0x61,0x75,0x6c,0x74,0x28,0x78,0x3d,0x63,
0x65,0x6e,0x74,0x65,0x72,0x2c,0x79,0x3d,0x62,0x6f,0x74,0x74,0x6f,0x6d,0x3a,0x35,0x30,0x2c,0x77,0x3d,
0x35,0x30,0x25,0x2c,0x68,0x3d,0x33,0x30,0x29,0x00,0x66,0x6c,0x6f,0x61,0x74,0x69,0x6e,0x67,0x00,0x74,
0x72,0x75,0x65,0x00,0x74,0x65,0x78,0x74,0x00,0x43,0x6c,0x6f,0x73,0x65,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,};/*382*/
|
{
"pile_set_name": "Github"
}
|
#ifdef HAVE_CONFIG_H
/* For PARALLEL_MARK */
# include "config.h"
#endif
#ifndef GC_THREADS
# define GC_THREADS
#endif
#include "gc.h"
#ifdef PARALLEL_MARK
# define AO_REQUIRE_CAS
#endif
#include "atomic_ops.h"
#include <stdio.h>
#ifdef AO_HAVE_fetch_and_add
#ifdef GC_PTHREADS
# include <pthread.h>
#else
# include <windows.h>
#endif
#include <stdlib.h>
#include <string.h>
#ifndef MAX_SUBTHREAD_DEPTH
# define INITIAL_THREAD_COUNT 31
# define MAX_ALIVE_THREAD_COUNT 55
# define MAX_SUBTHREAD_DEPTH 7
# define MAX_SUBTHREAD_COUNT 200
#endif
#ifndef DECAY_NUMER
# define DECAY_NUMER 15
# define DECAY_DENOM 16
#endif
volatile AO_t thread_created_cnt = 0;
volatile AO_t thread_ended_cnt = 0;
#ifdef GC_PTHREADS
void *entry(void *arg)
#else
DWORD WINAPI entry(LPVOID arg)
#endif
{
int thread_num = AO_fetch_and_add(&thread_created_cnt, 1);
GC_word my_depth = (GC_word)arg + 1;
if (my_depth <= MAX_SUBTHREAD_DEPTH
&& thread_num < MAX_SUBTHREAD_COUNT
&& (thread_num % DECAY_DENOM) < DECAY_NUMER
&& (int)(thread_num - AO_load(&thread_ended_cnt))
<= MAX_ALIVE_THREAD_COUNT) {
# ifdef GC_PTHREADS
int err;
pthread_t th;
err = pthread_create(&th, NULL, entry, (void *)my_depth);
if (err) {
fprintf(stderr, "Thread #%d creation failed: %s", thread_num,
strerror(err));
exit(2);
}
# else
HANDLE th;
DWORD thread_id;
th = CreateThread(NULL, 0, entry, (LPVOID)my_depth, 0, &thread_id);
if (th == NULL) {
fprintf(stderr, "Thread #%d creation failed: %d\n", thread_num,
(int)GetLastError());
exit(2);
}
CloseHandle(th);
# endif
}
AO_fetch_and_add(&thread_ended_cnt, 1);
return 0;
}
int main(void)
{
int i;
# ifdef GC_PTHREADS
int err;
pthread_t th[INITIAL_THREAD_COUNT];
# else
HANDLE th[INITIAL_THREAD_COUNT];
# endif
GC_INIT();
for (i = 0; i < INITIAL_THREAD_COUNT; ++i) {
# ifdef GC_PTHREADS
err = pthread_create(&th[i], NULL, entry, 0);
if (err) {
fprintf(stderr, "Thread creation failed: %s", strerror(err));
exit(1);
}
# else
DWORD thread_id;
th[i] = CreateThread(NULL, 0, entry, 0, 0, &thread_id);
if (th[i] == NULL) {
fprintf(stderr, "Thread creation failed: %d\n",
(int)GetLastError());
exit(1);
}
# endif
}
for (i = 0; i < INITIAL_THREAD_COUNT; ++i) {
# ifdef GC_PTHREADS
void *res;
err = pthread_join(th[i], &res);
if (err) {
fprintf(stderr, "Failed to join thread: %s", strerror(err));
exit(1);
}
# else
if (WaitForSingleObject(th[i], INFINITE) != WAIT_OBJECT_0) {
fprintf(stderr, "Failed to join thread: %d\n",
(int)GetLastError());
CloseHandle(th[i]);
exit(1);
}
CloseHandle(th[i]);
# endif
}
printf("subthread_create: created %d threads (%d ended)\n",
(int)AO_load(&thread_created_cnt), (int)AO_load(&thread_ended_cnt));
return 0;
}
#else
int main(void)
{
printf("subthread_create test skipped\n");
return 0;
}
#endif /* !AO_HAVE_fetch_and_add */
|
{
"pile_set_name": "Github"
}
|
package main
import (
"flag"
"fmt"
"math/rand"
"time"
"github.com/Shopify/sarama"
)
var (
topic *string = flag.String("topic", "logstream1", "the topic of VDL")
broker *string = flag.String("broker", "127.0.0.1:8181", "broker ip:port")
messageSize *int = flag.Int("message_size", 500, "The size of message")
messageCount *int = flag.Int("message count", 32, "each send")
)
const testLetterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
// create size = n random string
func testRandStringBytes(n int) string {
if n <= 0 {
n = 1
}
b := make([]byte, n)
for i := range b {
b[i] = testLetterBytes[rand.Intn(len(testLetterBytes))]
}
return string(b)
}
func main() {
flag.Parse()
config := sarama.NewConfig()
config.Producer.RequiredAcks = sarama.WaitForAll
config.Producer.Return.Successes = true
config.Producer.Flush.Bytes = 16384 //batch.size
//config.Producer.Return.Errors = true
brokers := make([]string, 0, 1)
brokers = append(brokers, *broker)
producer, _ := sarama.NewSyncProducer(brokers, config)
for {
msgs := make([]*sarama.ProducerMessage, *messageCount)
for i := 0; i < *messageCount; i++ {
msg := &sarama.ProducerMessage{
Topic: *topic,
Partition: 0,
Key: sarama.StringEncoder(""),
Value: sarama.ByteEncoder([]byte(testRandStringBytes(*messageSize))),
}
msgs[i] = msg
}
<-time.After(time.Second)
startTime := time.Now()
err := producer.SendMessages(msgs)
if err != nil {
panic(err)
}
perDuration := time.Since(startTime)
fmt.Printf("send used %v \n", perDuration)
}
}
|
{
"pile_set_name": "Github"
}
|
body.sharks_page_index {
$text_color: #282d33;
$main_font: "Century Gothic", CenturyGothic, AppleGothic, sans-serif;
$header_links_color: #ccc;
font-family: $main_font;
text-align: center;
overflow-y: scroll;
color: $text_color;
letter-spacing: 1px;
background: #000000;
background: -moz-radial-gradient(center, ellipse cover, #000000 0%, #111214 5%, #0e1014 100%);
background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(0%,#000000), color-stop(5%,#111214), color-stop(100%,#0e1014));
background: -webkit-radial-gradient(center, ellipse cover, #000000 0%,#111214 5%,#0e1014 100%);
background: -o-radial-gradient(center, ellipse cover, #000000 0%,#111214 5%,#0e1014 100%);
background: -ms-radial-gradient(center, ellipse cover, #000000 0%,#111214 5%,#0e1014 100%);
background: radial-gradient(ellipse at center, #000000 0%,#111214 5%,#0e1014 100%);
header {
position: absolute;
top: 0;
left: 0;
right: 0;
padding: 10px 20px;
margin-bottom: 30px;
}
#logo a {
float: left;
line-height: 20px;
font-size: 14px;
text-decoration: none;
color: $header_links_color;
}
#links_container {
float: right;
}
#links_container a {
font-size: 11px;
line-height: 20px;
text-decoration: none;
color: $header_links_color;
margin-left: 15px;
}
#links_container a:visited {
color: $header_links_color;
}
#links_container a:hover {
color: $text_color;
}
.clear {
clear: both;
}
canvas {
display: inline-block;
vertical-align: top;
}
}
|
{
"pile_set_name": "Github"
}
|
# https://www.kaggle.com/c/home-depot-product-search-relevance/forums/t/18967/data-preparation
COLOR_LIST = [
"white",
"black",
"brown",
"gray",
"chrome",
"stainless steel",
"whites",
"red",
"browns / tans",
"bronze",
"silver",
"blacks",
"beige",
"stainless",
"blue",
"nickel",
"metallics",
"clear",
"grays",
"green",
"multi",
"beige / cream",
"tan",
"greens",
"yellow",
"wood",
"blues",
"reds / pinks",
"brushed nickel",
"orange",
"metallic",
"brass",
"yellows / golds",
"oil rubbed bronze",
"polished chrome",
"almond",
"multi-colored",
"dark brown wood",
"primed white",
"beige/bisque",
"biscuit",
"ivory",
"oranges / peaches",
"grey",
"unfinished wood",
"light brown wood",
"wood grain",
"silver metallic",
"copper",
"medium brown wood",
"soft white",
"gold",
"satin nickel",
"cherry",
"bright white",
"red/orange",
"teal",
"natural",
"oak",
"mahogany",
"aluminum",
"espresso",
"unfinished",
"purples / lavenders",
"brown/tan",
"steel",
"venetian bronze",
"slate",
"warm white",
"bone",
"pink",
"stainless look",
"reddish brown wood",
"solid colors",
"off-white",
"walnut",
"chocolate",
"light almond",
"vibrant brushed nickel",
"satin white",
"polished brass",
"linen",
"white primer",
"purple",
"charcoal",
"color",
"oil-rubbed bronze",
"melamine white",
"turquoises / aquas",
"blue/purple",
"primed",
"bisque",
"browns/tans",
"assorted colors",
"java",
"pewter",
"chestnut",
"yellow/gold",
"taupe",
"pacific white",
"cedar",
"monochromatic stainless steel",
"other",
"platinum",
"mocha",
"cream",
"sand",
"daylight",
"brushed stainless steel",
"powder-coat white",
]
|
{
"pile_set_name": "Github"
}
|
var mr = require('npm-registry-mock')
var test = require('tap').test
var common = require('../common-tap.js')
var server
var cache = {
'_id': 'cond',
'_rev': '19-d458a706de1740662cd7728d7d7ddf07',
'name': 'cond',
'time': {
'modified': '2015-02-13T07:33:58.120Z',
'created': '2014-03-16T20:52:52.236Z',
'0.0.0': '2014-03-16T20:52:52.236Z',
'0.0.1': '2014-03-16T21:12:33.393Z',
'0.0.2': '2014-03-16T21:15:25.430Z'
},
'versions': {
'0.0.0': {},
'0.0.1': {},
'0.0.2': {}
},
'dist-tags': {
'latest': '0.0.2'
},
'description': 'Restartable error handling system',
'license': 'CC0'
}
test('setup', function (t) {
mr({port: common.port}, function (err, s) {
t.ifError(err, 'registry mocked successfully')
server = s
t.ok(true)
t.end()
})
})
test('npm deprecate an unscoped package', function (t) {
var deprecated = JSON.parse(JSON.stringify(cache))
deprecated.versions = {
'0.0.0': {},
'0.0.1': { deprecated: 'make it dead' },
'0.0.2': {}
}
server.get('/cond?write=true').reply(200, cache)
server.put('/cond', deprecated).reply(201, { deprecated: true })
common.npm([
'deprecate',
'cond@0.0.1',
'make it dead',
'--registry', common.registry,
'--loglevel', 'silent'
], {},
function (er, code, stdout, stderr) {
t.ifError(er, 'npm deprecate')
t.equal(stderr, '', 'no error output')
t.equal(code, 0, 'exited OK')
t.end()
})
})
test('npm deprecate a scoped package', function (t) {
var cacheCopy = JSON.parse(JSON.stringify(cache))
cacheCopy.name = '@scope/cond'
cacheCopy._id = '@scope/cond'
var deprecated = JSON.parse(JSON.stringify(cacheCopy))
deprecated.versions = {
'0.0.0': {},
'0.0.1': { deprecated: 'make it dead' },
'0.0.2': {}
}
server.get('/@scope%2fcond?write=true').reply(200, cacheCopy)
server.put('/@scope%2fcond', deprecated).reply(201, { deprecated: true })
common.npm([
'deprecate',
'@scope/cond@0.0.1',
'make it dead',
'--registry', common.registry,
'--loglevel', 'silent'
], {},
function (er, code, stdout, stderr) {
t.ifError(er, 'npm deprecate')
t.equal(stderr, '', 'no error output')
t.equal(code, 0, 'exited OK')
t.end()
})
})
test('npm deprecate semver range', function (t) {
var deprecated = JSON.parse(JSON.stringify(cache))
deprecated.versions = {
'0.0.0': { deprecated: 'make it dead' },
'0.0.1': { deprecated: 'make it dead' },
'0.0.2': {}
}
server.get('/cond?write=true').reply(200, cache)
server.put('/cond', deprecated).reply(201, { deprecated: true })
common.npm([
'deprecate',
'cond@<0.0.2',
'make it dead',
'--registry', common.registry,
'--loglevel', 'silent'
], {},
function (er, code, stdout, stderr) {
t.ifError(er, 'npm deprecate')
t.equal(stderr, '', 'no error output')
t.equal(code, 0, 'exited OK')
t.end()
})
})
test('npm deprecate bad semver range', function (t) {
common.npm([
'deprecate',
'cond@-9001',
'make it dead',
'--registry', common.registry
], {},
function (er, code, stdout, stderr) {
t.equal(code, 1, 'errored')
t.match(stderr, /invalid version range/, 'bad semver')
t.end()
})
})
test('npm deprecate a package with no semver range', function (t) {
var deprecated = JSON.parse(JSON.stringify(cache))
deprecated.versions = {
'0.0.0': { deprecated: 'make it dead' },
'0.0.1': { deprecated: 'make it dead' },
'0.0.2': { deprecated: 'make it dead' }
}
server.get('/cond?write=true').reply(200, cache)
server.put('/cond', deprecated).reply(201, { deprecated: true })
common.npm([
'deprecate',
'cond',
'make it dead',
'--registry', common.registry,
'--loglevel', 'silent'
], {},
function (er, code, stdout, stderr) {
t.ifError(er, 'npm deprecate')
t.equal(stderr, '', 'no error output')
t.equal(code, 0, 'exited OK')
t.end()
})
})
test('cleanup', function (t) {
server.close()
t.ok(true)
t.end()
})
|
{
"pile_set_name": "Github"
}
|
package tarsum // import "github.com/docker/docker/pkg/tarsum"
// BuilderContext is an interface extending TarSum by adding the Remove method.
// In general there was concern about adding this method to TarSum itself
// so instead it is being added just to "BuilderContext" which will then
// only be used during the .dockerignore file processing
// - see builder/evaluator.go
type BuilderContext interface {
TarSum
Remove(string)
}
func (bc *tarSum) Remove(filename string) {
for i, fis := range bc.sums {
if fis.Name() == filename {
bc.sums = append(bc.sums[:i], bc.sums[i+1:]...)
// Note, we don't just return because there could be
// more than one with this name
}
}
}
|
{
"pile_set_name": "Github"
}
|
true
true
|
{
"pile_set_name": "Github"
}
|
// RUN: %clang_cc1 -triple %itanium_abi_triple -emit-pch -o %t.1.ast %S/Inputs/exprs1.c
// RUN: %clang_cc1 -triple %itanium_abi_triple -emit-pch -o %t.2.ast %S/Inputs/exprs2.c
// RUN: %clang_cc1 -triple %itanium_abi_triple -emit-obj -o /dev/null -ast-merge %t.1.ast -ast-merge %t.2.ast -fsyntax-only -verify %s
// expected-no-diagnostics
|
{
"pile_set_name": "Github"
}
|
====
---- QUERY: TPCH-Q5
# Q5 - Local Supplier Volume Query
select
n_name,
sum(l_extendedprice * (1 - l_discount)) as revenue
from
customer,
orders,
lineitem,
supplier,
nation,
region
where
c_custkey = o_custkey
and l_orderkey = o_orderkey
and l_suppkey = s_suppkey
and c_nationkey = s_nationkey
and s_nationkey = n_nationkey
and n_regionkey = r_regionkey
and r_name = 'ASIA'
and o_orderdate >= '1994-01-01'
and o_orderdate < '1995-01-01'
group by
n_name
order by
revenue desc
---- RESULTS
'INDONESIA',55502041.1697
'VIETNAM',55295086.9967
'CHINA',53724494.2566
'INDIA',52035512.0002
'JAPAN',45410175.6954
---- TYPES
string, decimal
====
|
{
"pile_set_name": "Github"
}
|
fileFormatVersion: 2
guid: dcebde38c75fc8c44b9bc29f72ae803a
timeCreated: 1452127717
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
|
{
"pile_set_name": "Github"
}
|
%% Copyright (c) 2013-2015, Michael Santos <michael.santos@gmail.com>
%% 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 the author nor the names of its contributors
%% may be used to endorse or promote products derived from this software
%% without specific prior written permission.
%%
%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
%% "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
%% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
%% FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
%% COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
%% INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
%% BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
%% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
%% CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
%% LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
%% ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
%% POSSIBILITY OF SUCH DAMAGE.
-module(pkt_ipv6_ah).
%% RFC 4302: IP Authentication Header
-include("pkt_ipproto.hrl").
-include("pkt_ipv6.hrl").
-export([codec/1]).
codec(
<<Next:8, Len:8, Res:16, SPI:32, Seq:32, Rest/binary>>
) ->
% the length of AH in 32-bit words (4-byte units), minus "2"
% Next + Len + Res = 32 bits
% SPI = 32 bits
% The length is the 32-bit sequence number + the ICV
%
% XXX for IPv6, must be a multiple of 8-octets
ICVLen = ((Len - 1) * 4),
<<ICV:ICVLen/bytes, Payload/binary>> = Rest,
{#ipv6_ah{
next = Next,
len = Len,
res = Res,
spi = SPI,
seq = Seq,
icv = ICV
}, Payload};
codec(#ipv6_ah{
next = Next,
len = Len,
res = Res,
spi = SPI,
seq = Seq,
icv = ICV
}) ->
<<Next:8, Len:8, Res:16, SPI:32, Seq:32, ICV/binary>>.
|
{
"pile_set_name": "Github"
}
|
define([
'dojo/_base/declare',
'JBrowse/Component'
],
function( declare, Component ) {
return declare( Component,
{
constructor: function( args ) {
this.name = args.name;
this.cssLoaded = args.cssLoaded;
this._finalizeConfig( args.config );
},
_defaultConfig: function() {
return {
baseUrl: '/plugins/'+this.name
};
}
});
});
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns = "http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
</ApplicationInsights>
|
{
"pile_set_name": "Github"
}
|
// generated by gotemplate
package opt
import (
"fmt"
"github.com/mailru/easyjson/jlexer"
"github.com/mailru/easyjson/jwriter"
)
// template type Optional(A)
// A 'gotemplate'-based type for providing optional semantics without using pointers.
type Bool struct {
V bool
Defined bool
}
// Creates an optional type with a given value.
func OBool(v bool) Bool {
return Bool{V: v, Defined: true}
}
// Get returns the value or given default in the case the value is undefined.
func (v Bool) Get(deflt bool) bool {
if !v.Defined {
return deflt
}
return v.V
}
// MarshalEasyJSON does JSON marshaling using easyjson interface.
func (v Bool) MarshalEasyJSON(w *jwriter.Writer) {
if v.Defined {
w.Bool(v.V)
} else {
w.RawString("null")
}
}
// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface.
func (v *Bool) UnmarshalEasyJSON(l *jlexer.Lexer) {
if l.IsNull() {
l.Skip()
*v = Bool{}
} else {
v.V = l.Bool()
v.Defined = true
}
}
// MarshalJSON implements a standard json marshaler interface.
func (v Bool) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
v.MarshalEasyJSON(&w)
return w.Buffer.BuildBytes(), w.Error
}
// UnmarshalJSON implements a standard json unmarshaler interface.
func (v *Bool) UnmarshalJSON(data []byte) error {
l := jlexer.Lexer{Data: data}
v.UnmarshalEasyJSON(&l)
return l.Error()
}
// IsDefined returns whether the value is defined, a function is required so that it can
// be used in an interface.
func (v Bool) IsDefined() bool {
return v.Defined
}
// String implements a stringer interface using fmt.Sprint for the value.
func (v Bool) String() string {
if !v.Defined {
return "<undefined>"
}
return fmt.Sprint(v.V)
}
|
{
"pile_set_name": "Github"
}
|
from functools import wraps
import numpy as np
import tensorflow as tf
from keras import backend as K
from keras.layers import Conv2D, Add, ZeroPadding2D, UpSampling2D, Concatenate, MaxPooling2D
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.normalization import BatchNormalization
from keras.models import Model
from keras.regularizers import l2
from nets.darknet53 import darknet_body
from utils.utils import compose
#--------------------------------------------------#
# 单次卷积
#--------------------------------------------------#
@wraps(Conv2D)
def DarknetConv2D(*args, **kwargs):
darknet_conv_kwargs = {'kernel_regularizer': l2(5e-4)}
darknet_conv_kwargs['padding'] = 'valid' if kwargs.get('strides')==(2,2) else 'same'
darknet_conv_kwargs.update(kwargs)
return Conv2D(*args, **darknet_conv_kwargs)
#---------------------------------------------------#
# 卷积块
# DarknetConv2D + BatchNormalization + LeakyReLU
#---------------------------------------------------#
def DarknetConv2D_BN_Leaky(*args, **kwargs):
no_bias_kwargs = {'use_bias': False}
no_bias_kwargs.update(kwargs)
return compose(
DarknetConv2D(*args, **no_bias_kwargs),
BatchNormalization(),
LeakyReLU(alpha=0.1))
#---------------------------------------------------#
# 特征层->最后的输出
#---------------------------------------------------#
def make_last_layers(x, num_filters, out_filters):
# 五次卷积
x = DarknetConv2D_BN_Leaky(num_filters, (1,1))(x)
x = DarknetConv2D_BN_Leaky(num_filters*2, (3,3))(x)
x = DarknetConv2D_BN_Leaky(num_filters, (1,1))(x)
x = DarknetConv2D_BN_Leaky(num_filters*2, (3,3))(x)
x = DarknetConv2D_BN_Leaky(num_filters, (1,1))(x)
# 将最后的通道数调整为outfilter
y = DarknetConv2D_BN_Leaky(num_filters*2, (3,3))(x)
y = DarknetConv2D(out_filters, (1,1))(y)
return x, y
#---------------------------------------------------#
# 特征层->最后的输出
#---------------------------------------------------#
def yolo_body(inputs, num_anchors, num_classes):
# 生成darknet53的主干模型
feat1,feat2,feat3 = darknet_body(inputs)
darknet = Model(inputs, feat3)
# 第一个特征层
# y1=(batch_size,13,13,3,85)
x, y1 = make_last_layers(darknet.output, 512, num_anchors*(num_classes+5))
x = compose(
DarknetConv2D_BN_Leaky(256, (1,1)),
UpSampling2D(2))(x)
x = Concatenate()([x,feat2])
# 第二个特征层
# y2=(batch_size,26,26,3,85)
x, y2 = make_last_layers(x, 256, num_anchors*(num_classes+5))
x = compose(
DarknetConv2D_BN_Leaky(128, (1,1)),
UpSampling2D(2))(x)
x = Concatenate()([x,feat1])
# 第三个特征层
# y3=(batch_size,52,52,3,85)
x, y3 = make_last_layers(x, 128, num_anchors*(num_classes+5))
return Model(inputs, [y1,y2,y3])
#---------------------------------------------------#
# 将预测值的每个特征层调成真实值
#---------------------------------------------------#
def yolo_head(feats, anchors, num_classes, input_shape, calc_loss=False):
num_anchors = len(anchors)
# [1, 1, 1, num_anchors, 2]
anchors_tensor = K.reshape(K.constant(anchors), [1, 1, 1, num_anchors, 2])
# 获得x,y的网格
# (13, 13, 1, 2)
grid_shape = K.shape(feats)[1:3] # height, width
grid_y = K.tile(K.reshape(K.arange(0, stop=grid_shape[0]), [-1, 1, 1, 1]),
[1, grid_shape[1], 1, 1])
grid_x = K.tile(K.reshape(K.arange(0, stop=grid_shape[1]), [1, -1, 1, 1]),
[grid_shape[0], 1, 1, 1])
grid = K.concatenate([grid_x, grid_y])
grid = K.cast(grid, K.dtype(feats))
# (batch_size,13,13,3,85)
feats = K.reshape(feats, [-1, grid_shape[0], grid_shape[1], num_anchors, num_classes + 5])
# 将预测值调成真实值
# box_xy对应框的中心点
# box_wh对应框的宽和高
box_xy = (K.sigmoid(feats[..., :2]) + grid) / K.cast(grid_shape[::-1], K.dtype(feats))
box_wh = K.exp(feats[..., 2:4]) * anchors_tensor / K.cast(input_shape[::-1], K.dtype(feats))
box_confidence = K.sigmoid(feats[..., 4:5])
box_class_probs = K.sigmoid(feats[..., 5:])
# 在计算loss的时候返回如下参数
if calc_loss == True:
return grid, feats, box_xy, box_wh
return box_xy, box_wh, box_confidence, box_class_probs
#---------------------------------------------------#
# 对box进行调整,使其符合真实图片的样子
#---------------------------------------------------#
def yolo_correct_boxes(box_xy, box_wh, input_shape, image_shape):
box_yx = box_xy[..., ::-1]
box_hw = box_wh[..., ::-1]
input_shape = K.cast(input_shape, K.dtype(box_yx))
image_shape = K.cast(image_shape, K.dtype(box_yx))
new_shape = K.round(image_shape * K.min(input_shape/image_shape))
offset = (input_shape-new_shape)/2./input_shape
scale = input_shape/new_shape
box_yx = (box_yx - offset) * scale
box_hw *= scale
box_mins = box_yx - (box_hw / 2.)
box_maxes = box_yx + (box_hw / 2.)
boxes = K.concatenate([
box_mins[..., 0:1], # y_min
box_mins[..., 1:2], # x_min
box_maxes[..., 0:1], # y_max
box_maxes[..., 1:2] # x_max
])
boxes *= K.concatenate([image_shape, image_shape])
return boxes
#---------------------------------------------------#
# 获取每个box和它的得分
#---------------------------------------------------#
def yolo_boxes_and_scores(feats, anchors, num_classes, input_shape, image_shape):
# 将预测值调成真实值
# box_xy对应框的中心点
# box_wh对应框的宽和高
# -1,13,13,3,2; -1,13,13,3,2; -1,13,13,3,1; -1,13,13,3,80
box_xy, box_wh, box_confidence, box_class_probs = yolo_head(feats, anchors, num_classes, input_shape)
# 将box_xy、和box_wh调节成y_min,y_max,xmin,xmax
boxes = yolo_correct_boxes(box_xy, box_wh, input_shape, image_shape)
# 获得得分和box
boxes = K.reshape(boxes, [-1, 4])
box_scores = box_confidence * box_class_probs
box_scores = K.reshape(box_scores, [-1, num_classes])
return boxes, box_scores
#---------------------------------------------------#
# 图片预测
#---------------------------------------------------#
def yolo_eval(yolo_outputs,
anchors,
num_classes,
image_shape,
max_boxes=20,
score_threshold=.6,
iou_threshold=.5):
# 获得特征层的数量
num_layers = len(yolo_outputs)
# 特征层1对应的anchor是678
# 特征层2对应的anchor是345
# 特征层3对应的anchor是012
anchor_mask = [[6,7,8], [3,4,5], [0,1,2]]
input_shape = K.shape(yolo_outputs[0])[1:3] * 32
boxes = []
box_scores = []
# 对每个特征层进行处理
for l in range(num_layers):
_boxes, _box_scores = yolo_boxes_and_scores(yolo_outputs[l], anchors[anchor_mask[l]], num_classes, input_shape, image_shape)
boxes.append(_boxes)
box_scores.append(_box_scores)
# 将每个特征层的结果进行堆叠
boxes = K.concatenate(boxes, axis=0)
box_scores = K.concatenate(box_scores, axis=0)
mask = box_scores >= score_threshold
max_boxes_tensor = K.constant(max_boxes, dtype='int32')
boxes_ = []
scores_ = []
classes_ = []
for c in range(num_classes):
# 取出所有box_scores >= score_threshold的框,和成绩
class_boxes = tf.boolean_mask(boxes, mask[:, c])
class_box_scores = tf.boolean_mask(box_scores[:, c], mask[:, c])
# 非极大抑制,去掉box重合程度高的那一些
nms_index = tf.image.non_max_suppression(
class_boxes, class_box_scores, max_boxes_tensor, iou_threshold=iou_threshold)
# 获取非极大抑制后的结果
# 下列三个分别是
# 框的位置,得分与种类
class_boxes = K.gather(class_boxes, nms_index)
class_box_scores = K.gather(class_box_scores, nms_index)
classes = K.ones_like(class_box_scores, 'int32') * c
boxes_.append(class_boxes)
scores_.append(class_box_scores)
classes_.append(classes)
boxes_ = K.concatenate(boxes_, axis=0)
scores_ = K.concatenate(scores_, axis=0)
classes_ = K.concatenate(classes_, axis=0)
return boxes_, scores_, classes_
|
{
"pile_set_name": "Github"
}
|
/* ###
* IP: GHIDRA
*
* 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 ghidra.app.plugin.core.memory;
import static org.junit.Assert.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.junit.*;
import ghidra.app.plugin.core.memory.AddBlockModel.InitializedType;
import ghidra.framework.plugintool.PluginTool;
import ghidra.program.database.ProgramBuilder;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressSpace;
import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.MemoryBlock;
import ghidra.program.model.mem.MemoryBlockType;
import ghidra.test.AbstractGhidraHeadedIntegrationTest;
import ghidra.test.TestEnv;
/**
*
* Test the add memory block model.
*
*/
public class AddBlockModelTest extends AbstractGhidraHeadedIntegrationTest
implements ChangeListener {
private Program program;
private PluginTool tool;
private TestEnv env;
private AddBlockModel model;
/**
* Constructor for AddBlockModelTest.
* @param name
*/
public AddBlockModelTest() {
super();
}
private Program buildProgram(String programName) throws Exception {
ProgramBuilder builder = new ProgramBuilder(programName, ProgramBuilder._TOY);
builder.createMemory(".data", Long.toHexString(0x1001000), 0x6000);
return builder.getProgram();
}
/*
* @see TestCase#setUp()
*/
@Before
public void setUp() throws Exception {
env = new TestEnv();
tool = env.getTool();
program = buildProgram("notepad");
model = new AddBlockModel(tool, program);
model.setChangeListener(this);
}
/*
* @see TestCase#tearDown()
*/
@After
public void tearDown() throws Exception {
env.release(program);
env.dispose();
}
@Test
public void testSetFieldsForInitializedBlock() {
model.setBlockName(".test");
assertTrue(!model.isValidInfo());
model.setStartAddress(getAddr(0x100));
assertTrue(!model.isValidInfo());
model.setLength(100);
assertTrue(model.isValidInfo());
model.setBlockType(MemoryBlockType.DEFAULT);
assertTrue(model.isValidInfo());
model.setInitialValue(0xa);
assertTrue(model.isValidInfo());
}
@Test
public void testSetFieldsForUninitializedBlock() {
model.setBlockName(".test");
assertTrue(!model.isValidInfo());
model.setStartAddress(getAddr(0x200));
assertTrue(!model.isValidInfo());
model.setLength(100);
assertTrue(model.isValidInfo());
model.setBlockType(MemoryBlockType.DEFAULT);
assertTrue(model.isValidInfo());
}
@Test
public void testSetFieldsForBitBlock() {
model.setBlockName(".test");
assertTrue(!model.isValidInfo());
model.setStartAddress(getAddr(0x200));
assertTrue(!model.isValidInfo());
model.setLength(100);
assertTrue(model.isValidInfo());
model.setBlockType(MemoryBlockType.BIT_MAPPED);
assertTrue(!model.isValidInfo());
model.setBaseAddress(getAddr(0x2000));
assertTrue(model.isValidInfo());
}
@Test
public void testSetFieldsForOverlayBlock() {
model.setBlockName(".test");
assertTrue(!model.isValidInfo());
model.setStartAddress(getAddr(0x200));
assertTrue(!model.isValidInfo());
model.setLength(100);
assertTrue(model.isValidInfo());
model.setBlockType(MemoryBlockType.DEFAULT);
assertTrue(model.isValidInfo());
model.setOverlay(true);
assertTrue(model.isValidInfo());
model.setBaseAddress(getAddr(0x2000));
assertTrue(model.isValidInfo());
}
@Test
public void testBadName() {
model.setBlockName(">/== test");
assertTrue(!model.isValidInfo());
assertTrue(model.getMessage().length() > 0);
}
@Test
public void testExecute() throws Exception {
model.setBlockName(".test");
model.setStartAddress(getAddr(0x100));
model.setLength(100);
model.setBlockType(MemoryBlockType.DEFAULT);
model.setInitializedType(InitializedType.INITIALIZED_FROM_VALUE);
model.setInitialValue(0xa);
model.setComment("Test");
model.setRead(true);
model.setWrite(true);
model.setExecute(true);
assertTrue(model.execute());
MemoryBlock block = program.getMemory().getBlock(getAddr(0x100));
assertNotNull(block);
assertEquals((byte) 0xa, block.getByte(getAddr(0x100)));
}
@Test
public void testCreateOverlayBlock() throws Exception {
model.setBlockName(".test");
model.setStartAddress(getAddr(0x100));
model.setLength(100);
model.setBlockType(MemoryBlockType.DEFAULT);
model.setOverlay(true);
model.setInitializedType(InitializedType.INITIALIZED_FROM_VALUE);
model.setInitialValue(0xa);
assertTrue(model.execute());
MemoryBlock block = null;
AddressSpace[] spaces = program.getAddressFactory().getAddressSpaces();
AddressSpace ovSpace = null;
for (AddressSpace space : spaces) {
if (space.isOverlaySpace()) {
ovSpace = space;
Address blockAddr = space.getAddress(0x100);
block = program.getMemory().getBlock(blockAddr);
break;
}
}
assertNotNull(block);
assertEquals((byte) 0xa, block.getByte(ovSpace.getAddress(0x100)));
}
@Test
public void testCreateOverlayBlock2() throws Exception {
model.setBlockName(".test");
model.setStartAddress(getAddr(0x01001000));
model.setLength(100);
model.setBlockType(MemoryBlockType.DEFAULT);
model.setOverlay(true);
model.setInitializedType(InitializedType.INITIALIZED_FROM_VALUE);
model.setInitialValue(0xa);
assertTrue(model.execute());
MemoryBlock block = null;
AddressSpace[] spaces = program.getAddressFactory().getAddressSpaces();
AddressSpace ovSpace = null;
for (AddressSpace space : spaces) {
if (space.isOverlaySpace()) {
ovSpace = space;
Address blockAddr = space.getAddress(0x1001000);
block = program.getMemory().getBlock(blockAddr);
break;
}
}
assertNotNull(block);
assertEquals((byte) 0xa, block.getByte(ovSpace.getAddress(0x1001000)));
}
@Test
public void testCreateBitMappedBlock() throws Exception {
model.setBlockName(".test");
model.setStartAddress(getAddr(0x100));
model.setLength(100);
model.setBlockType(MemoryBlockType.BIT_MAPPED);
assertEquals(InitializedType.UNITIALIZED, model.getInitializedType());
model.setBaseAddress(getAddr(0x2000));
assertTrue(model.execute());
MemoryBlock block = program.getMemory().getBlock(getAddr(0x100));
assertNotNull(block);
assertEquals(MemoryBlockType.BIT_MAPPED, block.getType());
}
@Test
public void testCreateByteMappedBlock() throws Exception {
model.setBlockName(".test");
model.setStartAddress(getAddr(0x100));
model.setLength(100);
model.setBlockType(MemoryBlockType.BYTE_MAPPED);
assertEquals(InitializedType.UNITIALIZED, model.getInitializedType());
model.setBaseAddress(getAddr(0x2000));
assertTrue(model.execute());
MemoryBlock block = program.getMemory().getBlock(getAddr(0x100));
assertNotNull(block);
assertEquals(MemoryBlockType.BYTE_MAPPED, block.getType());
}
@Test
public void testDuplicateNameSetting() {
model.setBlockName(".data");
assertTrue(!model.isValidInfo());
assertTrue(model.getMessage().length() > 0);
}
@Test
public void testDuplicateName() {
model.setBlockName(".data");
model.setStartAddress(getAddr(0x100));
model.setLength(100);
model.setBlockType(MemoryBlockType.DEFAULT);
model.setInitialValue(0xa);
assertFalse(model.execute());
}
@Test
public void testStartAddress() throws Exception {
int transactionID = program.startTransaction("test");
try {
program.setImageBase(getAddr(0x3000100), true);
}
finally {
program.endTransaction(transactionID, true);
}
model = new AddBlockModel(tool, program);
assertEquals(program.getImageBase(), model.getStartAddress());
}
/**
* @see javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent)
*/
@Override
public void stateChanged(ChangeEvent e) {
}
private Address getAddr(int offset) {
return program.getMinAddress().getNewAddress(offset);
}
}
|
{
"pile_set_name": "Github"
}
|
<?php
namespace Stripe;
class CollectionTest extends TestCase
{
private function pageableModelResponse($ids, $hasMore)
{
$data = array();
foreach ($ids as $id) {
array_push($data, array(
'id' => $id,
'object' => 'pageablemodel'
));
}
return array(
'object' => 'list',
'url' => '/v1/pageablemodels',
'data' => $data,
'has_more' => $hasMore
);
}
public function testAutoPagingOnePage()
{
$collection = Collection::constructFrom(
$this->pageableModelResponse(array('pm_123', 'pm_124'), false),
new Util\RequestOptions()
);
$seen = array();
foreach ($collection->autoPagingIterator() as $item) {
array_push($seen, $item['id']);
}
$this->assertSame($seen, array('pm_123', 'pm_124'));
}
public function testAutoPagingThreePages()
{
$collection = Collection::constructFrom(
$this->pageableModelResponse(array('pm_123', 'pm_124'), true),
new Util\RequestOptions()
);
$collection->setRequestParams(array('foo' => 'bar'));
$this->mockRequest(
'GET',
'/v1/pageablemodels',
array(
'foo' => 'bar',
'starting_after' => 'pm_124'
),
$this->pageableModelResponse(array('pm_125', 'pm_126'), true)
);
$this->mockRequest(
'GET',
'/v1/pageablemodels',
array(
'foo' => 'bar',
'starting_after' => 'pm_126'
),
$this->pageableModelResponse(array('pm_127'), false)
);
$seen = array();
foreach ($collection->autoPagingIterator() as $item) {
array_push($seen, $item['id']);
}
$this->assertSame($seen, array('pm_123', 'pm_124', 'pm_125', 'pm_126', 'pm_127'));
}
public function testIteratorToArray()
{
$collection = Collection::constructFrom(
$this->pageableModelResponse(array('pm_123', 'pm_124'), true),
new Util\RequestOptions()
);
$this->mockRequest(
'GET',
'/v1/pageablemodels',
array(
'starting_after' => 'pm_124'
),
$this->pageableModelResponse(array('pm_125', 'pm_126'), true)
);
$this->mockRequest(
'GET',
'/v1/pageablemodels',
array(
'starting_after' => 'pm_126'
),
$this->pageableModelResponse(array('pm_127'), false)
);
$seen = array();
foreach (iterator_to_array($collection->autoPagingIterator()) as $item) {
array_push($seen, $item['id']);
}
$this->assertSame($seen, array('pm_123', 'pm_124', 'pm_125', 'pm_126', 'pm_127'));
}
}
|
{
"pile_set_name": "Github"
}
|
using System;
using System.Runtime.Serialization;
using System.Security;
using System.Xml.Serialization;
using EasyConnect.Common;
namespace EasyConnect.Protocols.Rdp
{
/// <summary>
/// Connection class for connecting to Microsoft Remote Desktop (RDP) servers.
/// </summary>
[Serializable]
public class RdpConnection : BaseConnection
{
/// <summary>
/// Default constructor; initializes various connection parameters to default values.
/// </summary>
public RdpConnection()
{
Port = 3389;
AudioMode = AudioMode.Locally;
KeyboardMode = KeyboardMode.Remotely;
VisualStyles = true;
PersistentBitmapCaching = true;
ConnectClipboard = true;
ConnectSmartCards = true;
ConnectPrinters = true;
RecordingMode = RecordingMode.RecordFromThisComputer;
}
/// <summary>
/// Serialization constructor required for <see cref="ISerializable"/>; reads connection data from <paramref name="info"/>.
/// </summary>
/// <param name="info">Serialization store that we are going to read our data from.</param>
/// <param name="context">Streaming context to use during the deserialization process.</param>
protected RdpConnection(SerializationInfo info, StreamingContext context)
: base(info, context)
{
Animations = info.GetBoolean("Animations");
AudioMode = info.GetValue<AudioMode>("AudioMode");
ColorDepth = info.GetInt32("ColorDepth");
ConnectClipboard = info.GetBoolean("ConnectClipboard");
ConnectSmartCards = info.GetBoolean("ConnectSmartCards");
ConnectDrives = info.GetBoolean("ConnectDrives");
ConnectPrinters = info.GetBoolean("ConnectPrinters");
DesktopBackground = info.GetBoolean("DesktopBackground");
DesktopComposition = info.GetBoolean("DesktopComposition");
DesktopHeight = info.GetInt32("DesktopHeight");
DesktopWidth = info.GetInt32("DesktopWidth");
FontSmoothing = info.GetBoolean("FontSmoothing");
KeyboardMode = info.GetValue<KeyboardMode>("KeyboardMode");
PersistentBitmapCaching = info.GetBoolean("PersistentBitmapCaching");
RecordingMode = info.GetValue<RecordingMode>("RecordingMode");
VisualStyles = info.GetBoolean("VisualStyles");
WindowContentsWhileDragging = info.GetBoolean("WindowContentsWhileDragging");
ConnectToAdminChannel = info.GetBoolean("ConnectToAdminChannel");
UseTSProxy = info.GetBoolean("UseTSProxy");
ProxyName = info.GetString("ProxyName");
ProxyUserName = info.GetString("ProxyUserName");
Port = info.GetInt32("Port");
string encryptedProxyPassword = info.GetString("ProxyPassword");
if (!String.IsNullOrEmpty(encryptedProxyPassword))
{
EncryptedPassword = encryptedProxyPassword;
}
}
/// <summary>
/// Width of the resulting desktop. 0 means that it should fill the available window space.
/// </summary>
public int DesktopWidth
{
get;
set;
}
/// <summary>
/// Height of the resulting desktop. 0 means that it should fill the available window space.
/// </summary>
public int DesktopHeight
{
get;
set;
}
/// <summary>
/// Color depth (16, 24, or 32) of the resulting desktop.
/// </summary>
public int ColorDepth
{
get;
set;
}
/// <summary>
/// Where sounds originating from the remote server should be played (locally or remotely).
/// </summary>
public AudioMode AudioMode
{
get;
set;
}
/// <summary>
/// When recording in the remote system, this indicates where (locally or remotely) the recording source should be.
/// </summary>
public RecordingMode RecordingMode
{
get;
set;
}
/// <summary>
/// Which system (locally or remotely) Windows shortcut keys like Alt+Tab should be directed to.
/// </summary>
public KeyboardMode KeyboardMode
{
get;
set;
}
/// <summary>
/// Flag indicating whether the remote system should connect to local printers.
/// </summary>
public bool ConnectPrinters
{
get;
set;
}
/// <summary>
/// Flag indicating whether the remote session should use the local clipboard.
/// </summary>
public bool ConnectClipboard
{
get;
set;
}
/// <summary>
/// Flag indicating whether the remote session should redirect smart cards.
/// </summary>
public bool ConnectSmartCards
{
get;
set;
}
/// <summary>
/// Flag indicating whether the remote system should map network drives to the user's local hard drive instances.
/// </summary>
public bool ConnectDrives
{
get;
set;
}
/// <summary>
/// Flag indicating whether we should display the remote desktop background.
/// </summary>
public bool DesktopBackground
{
get;
set;
}
/// <summary>
/// Flag indicating whether we should use font smoothing when rendering text from the remote system.
/// </summary>
public bool FontSmoothing
{
get;
set;
}
/// <summary>
/// Flag indicating whether advanced visual effects like Aero Glass should be enabled.
/// </summary>
public bool DesktopComposition
{
get;
set;
}
/// <summary>
/// Flag indicating whether a window's contents should be displayed while it is being dragged around the screen.
/// </summary>
public bool WindowContentsWhileDragging
{
get;
set;
}
/// <summary>
/// Flag indicating whether we should animate the showing and hiding of menus.
/// </summary>
public bool Animations
{
get;
set;
}
/// <summary>
/// Flag indicating whether the Windows Basic theme should be used when displaying the user's desktop.
/// </summary>
public bool VisualStyles
{
get;
set;
}
/// <summary>
/// Flag indicating whether we should use bitmap caching during the rendering process.
/// </summary>
public bool PersistentBitmapCaching
{
get;
set;
}
/// <summary>
/// Flag indicating whether we should connect to the admin channel (the local, physical desktop display) when establishing a connection.
/// </summary>
public bool ConnectToAdminChannel
{
get;
set;
}
/// <summary>
/// Flag indicating whether we should connect via a TS proxy.
/// </summary>
public bool UseTSProxy
{
get;
set;
}
/// <summary>
/// The name for the proxy server.
/// </summary>
public string ProxyName
{
get;
set;
}
/// <summary>
/// The user name for the proxy server.
/// </summary>
public string ProxyUserName
{
get;
set;
}
/// <summary>
/// Encrypted and Base64-encoded password for the proxy server.
/// </summary>
[XmlElement("ProxyPassword")]
public string EncryptedProxyPassword
{
get
{
if (ProxyPassword == null || ProxyPassword.Length == 0)
return null;
return Convert.ToBase64String(ConnectionFactory.Encrypt(ProxyPassword));
}
set
{
if (String.IsNullOrEmpty(value))
{
ProxyPassword = null;
return;
}
// Decrypt the password and put it into a secure string
SecureString password = new SecureString();
byte[] decryptedPassword = ConnectionFactory.Decrypt(Convert.FromBase64String(value));
for (int i = 0; i < decryptedPassword.Length; i++)
{
if (decryptedPassword[i] == 0)
break;
password.AppendChar((char)decryptedPassword[i]);
decryptedPassword[i] = 0;
}
ProxyPassword = password;
}
}
/// <summary>
/// The raw text of the password for the proxy server.
/// </summary>
[XmlIgnore]
public SecureString ProxyPassword
{
get;
set;
}
public int Port
{
get;
set;
}
/// <summary>
/// Method required for <see cref="ISerializable"/>; serializes the connection data to <paramref name="info"/>.
/// </summary>
/// <param name="info">Serialization store that the connection's data will be written to.</param>
/// <param name="context">Streaming context to use during the serialization process.</param>
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("Animations", Animations);
info.AddValue("AudioMode", AudioMode);
info.AddValue("ColorDepth", ColorDepth);
info.AddValue("ConnectClipboard", ConnectClipboard);
info.AddValue("ConnectSmartCards", ConnectSmartCards);
info.AddValue("ConnectDrives", ConnectDrives);
info.AddValue("ConnectPrinters", ConnectPrinters);
info.AddValue("DesktopBackground", DesktopBackground);
info.AddValue("DesktopComposition", DesktopComposition);
info.AddValue("DesktopHeight", DesktopHeight);
info.AddValue("DesktopWidth", DesktopWidth);
info.AddValue("FontSmoothing", FontSmoothing);
info.AddValue("KeyboardMode", KeyboardMode);
info.AddValue("PersistentBitmapCaching", PersistentBitmapCaching);
info.AddValue("RecordingMode", RecordingMode);
info.AddValue("VisualStyles", VisualStyles);
info.AddValue("WindowContentsWhileDragging", WindowContentsWhileDragging);
info.AddValue("ConnectToAdminChannel", ConnectToAdminChannel);
info.AddValue("Port", Port);
info.AddValue("UseTSProxy", UseTSProxy);
info.AddValue("ProxyName", ProxyName);
info.AddValue("ProxyUserName", ProxyUserName);
info.AddValue(
"ProxyPassword", ProxyPassword == null
? null
: EncryptedProxyPassword);
}
}
}
|
{
"pile_set_name": "Github"
}
|
/**
* @file
* @author zdying
*/
'use strict';
var glob = require('../../helpers/glob');
module.exports = function (ctx, next) {
var config = ctx.args;
var logger = ctx.log;
var hostsPattern = config.hostsFile;
var rewritePattern = config.rewriteFile;
var dir = this.dir;
// TODO 添加对应的option到CLI中
if (String(config.autoFindConf) !== 'false') {
if (hostsPattern == null) {
hostsPattern = ['./*/hosts', './hosts'];
}
if (rewritePattern == null) {
rewritePattern = ['./*/rewrite', './rewrite'];
}
var hostsFiles = glob(hostsPattern, dir);
var rewriteFiles = glob(rewritePattern, dir);
logger.debug('add hosts [', hostsFiles.join(', ').bold.green, ']');
logger.debug('add rewrites [', (rewriteFiles.join(', ')).bold.green, ']');
// 将找到的Hosts文件解析并加入缓存
this.addHostsFile(hostsFiles);
// 将找到的rewrite文件解析并加入缓存
this.addRewriteFile(rewriteFiles);
// 添加内置的rewrite规则
this.rewrite.addRule([
'domain hi.proxy {',
' location / {',
' proxy_pass http://127.0.0.1:' + (config.port || 5525) + '/;',
' }',
'}'
].join('\n'), 'hiproxy-internal-rewrite');
}
next();
};
|
{
"pile_set_name": "Github"
}
|
/*
Copyright 2015 The Kubernetes Authors.
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 jsonpath
import (
"testing"
)
type parserTest struct {
name string
text string
nodes []Node
shouldError bool
}
var parserTests = []parserTest{
{"plain", `hello jsonpath`, []Node{newText("hello jsonpath")}, false},
{"variable", `hello {.jsonpath}`,
[]Node{newText("hello "), newList(), newField("jsonpath")}, false},
{"arrayfiled", `hello {['jsonpath']}`,
[]Node{newText("hello "), newList(), newField("jsonpath")}, false},
{"quote", `{"{"}`, []Node{newList(), newText("{")}, false},
{"array", `{[1:3]}`, []Node{newList(),
newArray([3]ParamsEntry{{1, true, false}, {3, true, false}, {0, false, false}})}, false},
{"allarray", `{.book[*].author}`,
[]Node{newList(), newField("book"),
newArray([3]ParamsEntry{{0, false, false}, {0, false, false}, {0, false, false}}), newField("author")}, false},
{"wildcard", `{.bicycle.*}`,
[]Node{newList(), newField("bicycle"), newWildcard()}, false},
{"filter", `{[?(@.price<3)]}`,
[]Node{newList(), newFilter(newList(), newList(), "<"),
newList(), newField("price"), newList(), newInt(3)}, false},
{"recursive", `{..}`, []Node{newList(), newRecursive()}, false},
{"recurField", `{..price}`,
[]Node{newList(), newRecursive(), newField("price")}, false},
{"arraydict", `{['book.price']}`, []Node{newList(),
newField("book"), newField("price"),
}, false},
{"union", `{['bicycle.price', 3, 'book.price']}`, []Node{newList(), newUnion([]*ListNode{}),
newList(), newField("bicycle"), newField("price"),
newList(), newArray([3]ParamsEntry{{3, true, false}, {4, true, true}, {0, false, false}}),
newList(), newField("book"), newField("price"),
}, false},
{"range", `{range .items}{.name},{end}`, []Node{
newList(), newIdentifier("range"), newField("items"),
newList(), newField("name"), newText(","),
newList(), newIdentifier("end"),
}, false},
{"malformat input", `{\\\}`, []Node{}, true},
{"paired parentheses in quotes", `{[?(@.status.nodeInfo.osImage == "()")]}`,
[]Node{newList(), newFilter(newList(), newList(), "=="), newList(), newField("status"), newField("nodeInfo"), newField("osImage"), newList(), newText("()")}, false},
{"paired parentheses in double quotes and with double quotes escape", `{[?(@.status.nodeInfo.osImage == "(\"\")")]}`,
[]Node{newList(), newFilter(newList(), newList(), "=="), newList(), newField("status"), newField("nodeInfo"), newField("osImage"), newList(), newText("(\"\")")}, false},
{"unregular parentheses in double quotes", `{[?(@.test == "())(")]}`,
[]Node{newList(), newFilter(newList(), newList(), "=="), newList(), newField("test"), newList(), newText("())(")}, false},
{"plain text in single quotes", `{[?(@.status.nodeInfo.osImage == 'Linux')]}`,
[]Node{newList(), newFilter(newList(), newList(), "=="), newList(), newField("status"), newField("nodeInfo"), newField("osImage"), newList(), newText("Linux")}, false},
{"test filter suffix", `{[?(@.status.nodeInfo.osImage == "{[()]}")]}`,
[]Node{newList(), newFilter(newList(), newList(), "=="), newList(), newField("status"), newField("nodeInfo"), newField("osImage"), newList(), newText("{[()]}")}, false},
{"double inside single", `{[?(@.status.nodeInfo.osImage == "''")]}`,
[]Node{newList(), newFilter(newList(), newList(), "=="), newList(), newField("status"), newField("nodeInfo"), newField("osImage"), newList(), newText("''")}, false},
{"single inside double", `{[?(@.status.nodeInfo.osImage == '""')]}`,
[]Node{newList(), newFilter(newList(), newList(), "=="), newList(), newField("status"), newField("nodeInfo"), newField("osImage"), newList(), newText("\"\"")}, false},
{"single containing escaped single", `{[?(@.status.nodeInfo.osImage == '\\\'')]}`,
[]Node{newList(), newFilter(newList(), newList(), "=="), newList(), newField("status"), newField("nodeInfo"), newField("osImage"), newList(), newText("\\'")}, false},
{"negative index slice, equals a[len-5] to a[len-1]", `{[-5:]}`, []Node{newList(),
newArray([3]ParamsEntry{{-5, true, false}, {0, false, false}, {0, false, false}})}, false},
{"negative index slice, equals a[len-1]", `{[-1]}`, []Node{newList(),
newArray([3]ParamsEntry{{-1, true, false}, {0, true, true}, {0, false, false}})}, false},
{"negative index slice, equals a[1] to a[len-1]", `{[1:-1]}`, []Node{newList(),
newArray([3]ParamsEntry{{1, true, false}, {-1, true, false}, {0, false, false}})}, false},
}
func collectNode(nodes []Node, cur Node) []Node {
nodes = append(nodes, cur)
switch cur.Type() {
case NodeList:
for _, node := range cur.(*ListNode).Nodes {
nodes = collectNode(nodes, node)
}
case NodeFilter:
nodes = collectNode(nodes, cur.(*FilterNode).Left)
nodes = collectNode(nodes, cur.(*FilterNode).Right)
case NodeUnion:
for _, node := range cur.(*UnionNode).Nodes {
nodes = collectNode(nodes, node)
}
}
return nodes
}
func TestParser(t *testing.T) {
for _, test := range parserTests {
parser, err := Parse(test.name, test.text)
if test.shouldError {
if err == nil {
t.Errorf("unexpected non-error when parsing %s", test.name)
}
continue
}
if err != nil {
t.Errorf("parse %s error %v", test.name, err)
}
result := collectNode([]Node{}, parser.Root)[1:]
if len(result) != len(test.nodes) {
t.Errorf("in %s, expect to get %d nodes, got %d nodes", test.name, len(test.nodes), len(result))
t.Error(result)
}
for i, expect := range test.nodes {
if result[i].String() != expect.String() {
t.Errorf("in %s, %dth node, expect %v, got %v", test.name, i, expect, result[i])
}
}
}
}
type failParserTest struct {
name string
text string
err string
}
func TestFailParser(t *testing.T) {
failParserTests := []failParserTest{
{"unclosed action", "{.hello", "unclosed action"},
{"unrecognized character", "{*}", "unrecognized character in action: U+002A '*'"},
{"invalid number", "{+12.3.0}", "cannot parse number +12.3.0"},
{"unterminated array", "{[1}", "unterminated array"},
{"unterminated filter", "{[?(.price]}", "unterminated filter"},
{"invalid multiple recursive descent", "{........}", "invalid multiple recursive descent"},
}
for _, test := range failParserTests {
_, err := Parse(test.name, test.text)
var out string
if err == nil {
out = "nil"
} else {
out = err.Error()
}
if out != test.err {
t.Errorf("in %s, expect to get error %v, got %v", test.name, test.err, out)
}
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) Internet Systems Consortium, Inc. ("ISC")
*
* 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/.
*
* See the COPYRIGHT file distributed with this work for additional
* information regarding copyright ownership.
*/
/*
* This is just a random selection of configuration options.
*/
dnssec-policy "kasp" {
dnskey-ttl 200;
keys {
csk key-directory lifetime P1Y algorithm 13;
ksk key-directory lifetime P1Y algorithm 8;
zsk key-directory lifetime P30D algorithm 8 1024;
zsk key-directory lifetime P6M algorithm 8 2000;
};
};
|
{
"pile_set_name": "Github"
}
|
[
{
"model": "hardware.Manufacturer",
"pk": 1,
"fields": {
"name": "Ubiquiti Networks",
"url": "http://www.ubnt.com/",
"image": "manufacturers/ubiquiti.png"
}
},
{
"model": "hardware.Manufacturer",
"pk": 2,
"fields": {
"name": "Mikrotik",
"url": "http://www.mikrotik.com/",
"image": "manufacturers/mikrotic.png"
}
},
{
"model": "hardware.Manufacturer",
"pk": 3,
"fields": {
"name": "D-Link",
"url": "http://www.dlink.com/",
"image": "manufacturers/dlink.jpg"
}
},
{
"model": "hardware.Manufacturer",
"pk": 4,
"fields": {
"name": "TP-Link",
"url": "http://www.tp-link.com/",
"image": "manufacturers/tplink.png"
}
}
]
|
{
"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.hadoop.net;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.TreeMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.util.ReflectionUtils;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
/** The class represents a cluster of computer with a tree hierarchical
* network topology.
* For example, a cluster may be consists of many data centers filled
* with racks of computers.
* In a network topology, leaves represent data nodes (computers) and inner
* nodes represent switches/routers that manage traffic in/out of data centers
* or racks.
*
*/
@InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"})
@InterfaceStability.Unstable
public class NetworkTopology {
public final static String DEFAULT_RACK = "/default-rack";
public final static int DEFAULT_HOST_LEVEL = 2;
public static final Log LOG =
LogFactory.getLog(NetworkTopology.class);
public static class InvalidTopologyException extends RuntimeException {
private static final long serialVersionUID = 1L;
public InvalidTopologyException(String msg) {
super(msg);
}
}
/**
* Get an instance of NetworkTopology based on the value of the configuration
* parameter net.topology.impl.
*
* @param conf the configuration to be used
* @return an instance of NetworkTopology
*/
public static NetworkTopology getInstance(Configuration conf){
return ReflectionUtils.newInstance(
conf.getClass(CommonConfigurationKeysPublic.NET_TOPOLOGY_IMPL_KEY,
NetworkTopology.class, NetworkTopology.class), conf);
}
/** InnerNode represents a switch/router of a data center or rack.
* Different from a leaf node, it has non-null children.
*/
static class InnerNode extends NodeBase {
protected List<Node> children=new ArrayList<Node>();
private int numOfLeaves;
/** Construct an InnerNode from a path-like string */
InnerNode(String path) {
super(path);
}
/** Construct an InnerNode from its name and its network location */
InnerNode(String name, String location) {
super(name, location);
}
/** Construct an InnerNode
* from its name, its network location, its parent, and its level */
InnerNode(String name, String location, InnerNode parent, int level) {
super(name, location, parent, level);
}
/** @return its children */
List<Node> getChildren() {return children;}
/** @return the number of children this node has */
int getNumOfChildren() {
return children.size();
}
/** Judge if this node represents a rack
* @return true if it has no child or its children are not InnerNodes
*/
boolean isRack() {
if (children.isEmpty()) {
return true;
}
Node firstChild = children.get(0);
if (firstChild instanceof InnerNode) {
return false;
}
return true;
}
/** Judge if this node is an ancestor of node <i>n</i>
*
* @param n a node
* @return true if this node is an ancestor of <i>n</i>
*/
boolean isAncestor(Node n) {
return getPath(this).equals(NodeBase.PATH_SEPARATOR_STR) ||
(n.getNetworkLocation()+NodeBase.PATH_SEPARATOR_STR).
startsWith(getPath(this)+NodeBase.PATH_SEPARATOR_STR);
}
/** Judge if this node is the parent of node <i>n</i>
*
* @param n a node
* @return true if this node is the parent of <i>n</i>
*/
boolean isParent(Node n) {
return n.getNetworkLocation().equals(getPath(this));
}
/* Return a child name of this node who is an ancestor of node <i>n</i> */
private String getNextAncestorName(Node n) {
if (!isAncestor(n)) {
throw new IllegalArgumentException(
this + "is not an ancestor of " + n);
}
String name = n.getNetworkLocation().substring(getPath(this).length());
if (name.charAt(0) == PATH_SEPARATOR) {
name = name.substring(1);
}
int index=name.indexOf(PATH_SEPARATOR);
if (index !=-1)
name = name.substring(0, index);
return name;
}
/** Add node <i>n</i> to the subtree of this node
* @param n node to be added
* @return true if the node is added; false otherwise
*/
boolean add(Node n) {
if (!isAncestor(n))
throw new IllegalArgumentException(n.getName()+", which is located at "
+n.getNetworkLocation()+", is not a decendent of "
+getPath(this));
if (isParent(n)) {
// this node is the parent of n; add n directly
n.setParent(this);
n.setLevel(this.level+1);
for(int i=0; i<children.size(); i++) {
if (children.get(i).getName().equals(n.getName())) {
children.set(i, n);
return false;
}
}
children.add(n);
numOfLeaves++;
return true;
} else {
// find the next ancestor node
String parentName = getNextAncestorName(n);
InnerNode parentNode = null;
for(int i=0; i<children.size(); i++) {
if (children.get(i).getName().equals(parentName)) {
parentNode = (InnerNode)children.get(i);
break;
}
}
if (parentNode == null) {
// create a new InnerNode
parentNode = createParentNode(parentName);
children.add(parentNode);
}
// add n to the subtree of the next ancestor node
if (parentNode.add(n)) {
numOfLeaves++;
return true;
} else {
return false;
}
}
}
/**
* Creates a parent node to be added to the list of children.
* Creates a node using the InnerNode four argument constructor specifying
* the name, location, parent, and level of this node.
*
* <p>To be overridden in subclasses for specific InnerNode implementations,
* as alternative to overriding the full {@link #add(Node)} method.
*
* @param parentName The name of the parent node
* @return A new inner node
* @see InnerNode#InnerNode(String, String, InnerNode, int)
*/
protected InnerNode createParentNode(String parentName) {
return new InnerNode(parentName, getPath(this), this, this.getLevel()+1);
}
/** Remove node <i>n</i> from the subtree of this node
* @param n node to be deleted
* @return true if the node is deleted; false otherwise
*/
boolean remove(Node n) {
String parent = n.getNetworkLocation();
String currentPath = getPath(this);
if (!isAncestor(n))
throw new IllegalArgumentException(n.getName()
+", which is located at "
+parent+", is not a descendent of "+currentPath);
if (isParent(n)) {
// this node is the parent of n; remove n directly
for(int i=0; i<children.size(); i++) {
if (children.get(i).getName().equals(n.getName())) {
children.remove(i);
numOfLeaves--;
n.setParent(null);
return true;
}
}
return false;
} else {
// find the next ancestor node: the parent node
String parentName = getNextAncestorName(n);
InnerNode parentNode = null;
int i;
for(i=0; i<children.size(); i++) {
if (children.get(i).getName().equals(parentName)) {
parentNode = (InnerNode)children.get(i);
break;
}
}
if (parentNode==null) {
return false;
}
// remove n from the parent node
boolean isRemoved = parentNode.remove(n);
// if the parent node has no children, remove the parent node too
if (isRemoved) {
if (parentNode.getNumOfChildren() == 0) {
children.remove(i);
}
numOfLeaves--;
}
return isRemoved;
}
} // end of remove
/** Given a node's string representation, return a reference to the node
* @param loc string location of the form /rack/node
* @return null if the node is not found or the childnode is there but
* not an instance of {@link InnerNode}
*/
private Node getLoc(String loc) {
if (loc == null || loc.length() == 0) return this;
String[] path = loc.split(PATH_SEPARATOR_STR, 2);
Node childnode = null;
for(int i=0; i<children.size(); i++) {
if (children.get(i).getName().equals(path[0])) {
childnode = children.get(i);
}
}
if (childnode == null) return null; // non-existing node
if (path.length == 1) return childnode;
if (childnode instanceof InnerNode) {
return ((InnerNode)childnode).getLoc(path[1]);
} else {
return null;
}
}
/** get <i>leafIndex</i> leaf of this subtree
* if it is not in the <i>excludedNode</i>
*
* @param leafIndex an indexed leaf of the node
* @param excludedNode an excluded node (can be null)
* @return
*/
Node getLeaf(int leafIndex, Node excludedNode) {
int count=0;
// check if the excluded node a leaf
boolean isLeaf =
excludedNode == null || !(excludedNode instanceof InnerNode);
// calculate the total number of excluded leaf nodes
int numOfExcludedLeaves =
isLeaf ? 1 : ((InnerNode)excludedNode).getNumOfLeaves();
if (isLeafParent()) { // children are leaves
if (isLeaf) { // excluded node is a leaf node
int excludedIndex = children.indexOf(excludedNode);
if (excludedIndex != -1 && leafIndex >= 0) {
// excluded node is one of the children so adjust the leaf index
leafIndex = leafIndex>=excludedIndex ? leafIndex+1 : leafIndex;
}
}
// range check
if (leafIndex<0 || leafIndex>=this.getNumOfChildren()) {
return null;
}
return children.get(leafIndex);
} else {
for(int i=0; i<children.size(); i++) {
InnerNode child = (InnerNode)children.get(i);
if (excludedNode == null || excludedNode != child) {
// not the excludedNode
int numOfLeaves = child.getNumOfLeaves();
if (excludedNode != null && child.isAncestor(excludedNode)) {
numOfLeaves -= numOfExcludedLeaves;
}
if (count+numOfLeaves > leafIndex) {
// the leaf is in the child subtree
return child.getLeaf(leafIndex-count, excludedNode);
} else {
// go to the next child
count = count+numOfLeaves;
}
} else { // it is the excluededNode
// skip it and set the excludedNode to be null
excludedNode = null;
}
}
return null;
}
}
protected boolean isLeafParent() {
return isRack();
}
/**
* Determine if children a leaves, default implementation calls {@link #isRack()}
* <p>To be overridden in subclasses for specific InnerNode implementations,
* as alternative to overriding the full {@link #getLeaf(int, Node)} method.
*
* @return true if children are leaves, false otherwise
*/
protected boolean areChildrenLeaves() {
return isRack();
}
/**
* Get number of leaves.
*/
int getNumOfLeaves() {
return numOfLeaves;
}
} // end of InnerNode
/**
* the root cluster map
*/
InnerNode clusterMap;
/** Depth of all leaf nodes */
private int depthOfAllLeaves = -1;
/** rack counter */
protected int numOfRacks = 0;
/** the lock used to manage access */
protected ReadWriteLock netlock = new ReentrantReadWriteLock();
public NetworkTopology() {
clusterMap = new InnerNode(InnerNode.ROOT);
}
/** Add a leaf node
* Update node counter & rack counter if necessary
* @param node node to be added; can be null
* @exception IllegalArgumentException if add a node to a leave
or node to be added is not a leaf
*/
public void add(Node node) {
if (node==null) return;
String oldTopoStr = this.toString();
if( node instanceof InnerNode ) {
throw new IllegalArgumentException(
"Not allow to add an inner node: "+NodeBase.getPath(node));
}
int newDepth = NodeBase.locationToDepth(node.getNetworkLocation()) + 1;
netlock.writeLock().lock();
try {
if ((depthOfAllLeaves != -1) && (depthOfAllLeaves != newDepth)) {
LOG.error("Error: can't add leaf node " + NodeBase.getPath(node) +
" at depth " + newDepth + " to topology:\n" + oldTopoStr);
throw new InvalidTopologyException("Failed to add " + NodeBase.getPath(node) +
": You cannot have a rack and a non-rack node at the same " +
"level of the network topology.");
}
Node rack = getNodeForNetworkLocation(node);
if (rack != null && !(rack instanceof InnerNode)) {
throw new IllegalArgumentException("Unexpected data node "
+ node.toString()
+ " at an illegal network location");
}
if (clusterMap.add(node)) {
LOG.info("Adding a new node: "+NodeBase.getPath(node));
if (rack == null) {
numOfRacks++;
}
if (!(node instanceof InnerNode)) {
if (depthOfAllLeaves == -1) {
depthOfAllLeaves = node.getLevel();
}
}
}
if(LOG.isDebugEnabled()) {
LOG.debug("NetworkTopology became:\n" + this.toString());
}
} finally {
netlock.writeLock().unlock();
}
}
/**
* Return a reference to the node given its string representation.
* Default implementation delegates to {@link #getNode(String)}.
*
* <p>To be overridden in subclasses for specific NetworkTopology
* implementations, as alternative to overriding the full {@link #add(Node)}
* method.
*
* @param node The string representation of this node's network location is
* used to retrieve a Node object.
* @return a reference to the node; null if the node is not in the tree
*
* @see #add(Node)
* @see #getNode(String)
*/
protected Node getNodeForNetworkLocation(Node node) {
return getNode(node.getNetworkLocation());
}
/**
* Given a string representation of a rack, return its children
* @param loc a path-like string representation of a rack
* @return a newly allocated list with all the node's children
*/
public List<Node> getDatanodesInRack(String loc) {
netlock.readLock().lock();
try {
loc = NodeBase.normalize(loc);
if (!NodeBase.ROOT.equals(loc)) {
loc = loc.substring(1);
}
InnerNode rack = (InnerNode) clusterMap.getLoc(loc);
if (rack == null) {
return null;
}
return new ArrayList<Node>(rack.getChildren());
} finally {
netlock.readLock().unlock();
}
}
/** Remove a node
* Update node counter and rack counter if necessary
* @param node node to be removed; can be null
*/
public void remove(Node node) {
if (node==null) return;
if( node instanceof InnerNode ) {
throw new IllegalArgumentException(
"Not allow to remove an inner node: "+NodeBase.getPath(node));
}
LOG.info("Removing a node: "+NodeBase.getPath(node));
netlock.writeLock().lock();
try {
if (clusterMap.remove(node)) {
InnerNode rack = (InnerNode)getNode(node.getNetworkLocation());
if (rack == null) {
numOfRacks--;
}
}
if(LOG.isDebugEnabled()) {
LOG.debug("NetworkTopology became:\n" + this.toString());
}
} finally {
netlock.writeLock().unlock();
}
}
/** Check if the tree contains node <i>node</i>
*
* @param node a node
* @return true if <i>node</i> is already in the tree; false otherwise
*/
public boolean contains(Node node) {
if (node == null) return false;
netlock.readLock().lock();
try {
Node parent = node.getParent();
for (int level = node.getLevel(); parent != null && level > 0;
parent = parent.getParent(), level--) {
if (parent == clusterMap) {
return true;
}
}
} finally {
netlock.readLock().unlock();
}
return false;
}
/** Given a string representation of a node, return its reference
*
* @param loc
* a path-like string representation of a node
* @return a reference to the node; null if the node is not in the tree
*/
public Node getNode(String loc) {
netlock.readLock().lock();
try {
loc = NodeBase.normalize(loc);
if (!NodeBase.ROOT.equals(loc))
loc = loc.substring(1);
return clusterMap.getLoc(loc);
} finally {
netlock.readLock().unlock();
}
}
/** Given a string representation of a rack for a specific network
* location
*
* To be overridden in subclasses for specific NetworkTopology
* implementations, as alternative to overriding the full
* {@link #getRack(String)} method.
* @param loc
* a path-like string representation of a network location
* @return a rack string
*/
public String getRack(String loc) {
return loc;
}
/** @return the total number of racks */
public int getNumOfRacks() {
netlock.readLock().lock();
try {
return numOfRacks;
} finally {
netlock.readLock().unlock();
}
}
/** @return the total number of leaf nodes */
public int getNumOfLeaves() {
netlock.readLock().lock();
try {
return clusterMap.getNumOfLeaves();
} finally {
netlock.readLock().unlock();
}
}
/** Return the distance between two nodes
* It is assumed that the distance from one node to its parent is 1
* The distance between two nodes is calculated by summing up their distances
* to their closest common ancestor.
* @param node1 one node
* @param node2 another node
* @return the distance between node1 and node2 which is zero if they are the same
* or {@link Integer#MAX_VALUE} if node1 or node2 do not belong to the cluster
*/
public int getDistance(Node node1, Node node2) {
if (node1 == node2) {
return 0;
}
Node n1=node1, n2=node2;
int dis = 0;
netlock.readLock().lock();
try {
int level1=node1.getLevel(), level2=node2.getLevel();
while(n1!=null && level1>level2) {
n1 = n1.getParent();
level1--;
dis++;
}
while(n2!=null && level2>level1) {
n2 = n2.getParent();
level2--;
dis++;
}
while(n1!=null && n2!=null && n1.getParent()!=n2.getParent()) {
n1=n1.getParent();
n2=n2.getParent();
dis+=2;
}
} finally {
netlock.readLock().unlock();
}
if (n1==null) {
LOG.warn("The cluster does not contain node: "+NodeBase.getPath(node1));
return Integer.MAX_VALUE;
}
if (n2==null) {
LOG.warn("The cluster does not contain node: "+NodeBase.getPath(node2));
return Integer.MAX_VALUE;
}
return dis+2;
}
/** Check if two nodes are on the same rack
* @param node1 one node (can be null)
* @param node2 another node (can be null)
* @return true if node1 and node2 are on the same rack; false otherwise
* @exception IllegalArgumentException when either node1 or node2 is null, or
* node1 or node2 do not belong to the cluster
*/
public boolean isOnSameRack( Node node1, Node node2) {
if (node1 == null || node2 == null) {
return false;
}
netlock.readLock().lock();
try {
return isSameParents(node1, node2);
} finally {
netlock.readLock().unlock();
}
}
/**
* Check if network topology is aware of NodeGroup
*/
public boolean isNodeGroupAware() {
return false;
}
/**
* Return false directly as not aware of NodeGroup, to be override in sub-class
*/
public boolean isOnSameNodeGroup(Node node1, Node node2) {
return false;
}
/**
* Compare the parents of each node for equality
*
* <p>To be overridden in subclasses for specific NetworkTopology
* implementations, as alternative to overriding the full
* {@link #isOnSameRack(Node, Node)} method.
*
* @param node1 the first node to compare
* @param node2 the second node to compare
* @return true if their parents are equal, false otherwise
*
* @see #isOnSameRack(Node, Node)
*/
protected boolean isSameParents(Node node1, Node node2) {
return node1.getParent()==node2.getParent();
}
private static final ThreadLocal<Random> r = new ThreadLocal<Random>();
/**
* Getter for thread-local Random, which provides better performance than
* a shared Random (even though Random is thread-safe).
*
* @return Thread-local Random.
*/
protected Random getRandom() {
Random rand = r.get();
if (rand == null) {
rand = new Random();
r.set(rand);
}
return rand;
}
/** randomly choose one node from <i>scope</i>
* if scope starts with ~, choose one from the all nodes except for the
* ones in <i>scope</i>; otherwise, choose one from <i>scope</i>
* @param scope range of nodes from which a node will be chosen
* @return the chosen node
*/
public Node chooseRandom(String scope) {
netlock.readLock().lock();
try {
if (scope.startsWith("~")) {
return chooseRandom(NodeBase.ROOT, scope.substring(1));
} else {
return chooseRandom(scope, null);
}
} finally {
netlock.readLock().unlock();
}
}
private Node chooseRandom(String scope, String excludedScope){
if (excludedScope != null) {
if (scope.startsWith(excludedScope)) {
return null;
}
if (!excludedScope.startsWith(scope)) {
excludedScope = null;
}
}
Node node = getNode(scope);
if (!(node instanceof InnerNode)) {
return node;
}
InnerNode innerNode = (InnerNode)node;
int numOfDatanodes = innerNode.getNumOfLeaves();
if (excludedScope == null) {
node = null;
} else {
node = getNode(excludedScope);
if (!(node instanceof InnerNode)) {
numOfDatanodes -= 1;
} else {
numOfDatanodes -= ((InnerNode)node).getNumOfLeaves();
}
}
if (numOfDatanodes == 0) {
throw new InvalidTopologyException(
"Failed to find datanode (scope=\"" + String.valueOf(scope) +
"\" excludedScope=\"" + String.valueOf(excludedScope) + "\").");
}
int leaveIndex = getRandom().nextInt(numOfDatanodes);
return innerNode.getLeaf(leaveIndex, node);
}
/** return leaves in <i>scope</i>
* @param scope a path string
* @return leaves nodes under specific scope
*/
public List<Node> getLeaves(String scope) {
Node node = getNode(scope);
List<Node> leafNodes = new ArrayList<Node>();
if (!(node instanceof InnerNode)) {
leafNodes.add(node);
} else {
InnerNode innerNode = (InnerNode) node;
for (int i=0;i<innerNode.getNumOfLeaves();i++) {
leafNodes.add(innerNode.getLeaf(i, null));
}
}
return leafNodes;
}
/** return the number of leaves in <i>scope</i> but not in <i>excludedNodes</i>
* if scope starts with ~, return the number of nodes that are not
* in <i>scope</i> and <i>excludedNodes</i>;
* @param scope a path string that may start with ~
* @param excludedNodes a list of nodes
* @return number of available nodes
*/
public int countNumOfAvailableNodes(String scope,
Collection<Node> excludedNodes) {
boolean isExcluded=false;
if (scope.startsWith("~")) {
isExcluded=true;
scope=scope.substring(1);
}
scope = NodeBase.normalize(scope);
int count=0; // the number of nodes in both scope & excludedNodes
netlock.readLock().lock();
try {
for(Node node:excludedNodes) {
if ((NodeBase.getPath(node)+NodeBase.PATH_SEPARATOR_STR).
startsWith(scope+NodeBase.PATH_SEPARATOR_STR)) {
count++;
}
}
Node n=getNode(scope);
int scopeNodeCount=1;
if (n instanceof InnerNode) {
scopeNodeCount=((InnerNode)n).getNumOfLeaves();
}
if (isExcluded) {
return clusterMap.getNumOfLeaves()-
scopeNodeCount-excludedNodes.size()+count;
} else {
return scopeNodeCount-count;
}
} finally {
netlock.readLock().unlock();
}
}
/** convert a network tree to a string */
@Override
public String toString() {
// print the number of racks
StringBuilder tree = new StringBuilder();
tree.append("Number of racks: ");
tree.append(numOfRacks);
tree.append("\n");
// print the number of leaves
int numOfLeaves = getNumOfLeaves();
tree.append("Expected number of leaves:");
tree.append(numOfLeaves);
tree.append("\n");
// print nodes
for(int i=0; i<numOfLeaves; i++) {
tree.append(NodeBase.getPath(clusterMap.getLeaf(i, null)));
tree.append("\n");
}
return tree.toString();
}
/**
* Divide networklocation string into two parts by last separator, and get
* the first part here.
*
* @param networkLocation
* @return
*/
public static String getFirstHalf(String networkLocation) {
int index = networkLocation.lastIndexOf(NodeBase.PATH_SEPARATOR_STR);
return networkLocation.substring(0, index);
}
/**
* Divide networklocation string into two parts by last separator, and get
* the second part here.
*
* @param networkLocation
* @return
*/
public static String getLastHalf(String networkLocation) {
int index = networkLocation.lastIndexOf(NodeBase.PATH_SEPARATOR_STR);
return networkLocation.substring(index);
}
/**
* Returns an integer weight which specifies how far away {node} is away from
* {reader}. A lower value signifies that a node is closer.
*
* @param reader Node where data will be read
* @param node Replica of data
* @return weight
*/
protected int getWeight(Node reader, Node node) {
// 0 is local, 1 is same rack, 2 is off rack
// Start off by initializing to off rack
int weight = 2;
if (reader != null) {
if (reader == node) {
weight = 0;
} else if (isOnSameRack(reader, node)) {
weight = 1;
}
}
return weight;
}
/**
* Sort nodes array by network distance to <i>reader</i>.
* <p/>
* In a three-level topology, a node can be either local, on the same rack, or
* on a different rack from the reader. Sorting the nodes based on network
* distance from the reader reduces network traffic and improves performance.
* <p/>
* As an additional twist, we also randomize the nodes at each network
* distance using the provided random seed. This helps with load balancing
* when there is data skew.
*
* @param reader Node where data will be read
* @param nodes Available replicas with the requested data
* @param seed Used to seed the pseudo-random generator that randomizes the
* set of nodes at each network distance.
*/
public void sortByDistance(Node reader, Node[] nodes, int activeLen,
long seed, boolean randomizeBlockLocationsPerBlock) {
/** Sort weights for the nodes array */
int[] weights = new int[activeLen];
for (int i=0; i<activeLen; i++) {
weights[i] = getWeight(reader, nodes[i]);
}
// Add weight/node pairs to a TreeMap to sort
TreeMap<Integer, List<Node>> tree = new TreeMap<Integer, List<Node>>();
for (int i=0; i<activeLen; i++) {
int weight = weights[i];
Node node = nodes[i];
List<Node> list = tree.get(weight);
if (list == null) {
list = Lists.newArrayListWithExpectedSize(1);
tree.put(weight, list);
}
list.add(node);
}
// Seed is normally the block id
// This means we use the same pseudo-random order for each block, for
// potentially better page cache usage.
// Seed is not used if we want to randomize block location for every block
Random rand = getRandom();
if (!randomizeBlockLocationsPerBlock) {
rand.setSeed(seed);
}
int idx = 0;
for (List<Node> list: tree.values()) {
if (list != null) {
Collections.shuffle(list, rand);
for (Node n: list) {
nodes[idx] = n;
idx++;
}
}
}
Preconditions.checkState(idx == activeLen,
"Sorted the wrong number of nodes!");
}
}
|
{
"pile_set_name": "Github"
}
|
#include <QtScript/QScriptValue>
#include <QtScript/QScriptEngine>
QScriptValue qtscript_create_QGLFramebufferObjectFormat_class(QScriptEngine *engine);
QScriptValue qtscript_create_QGLContext_class(QScriptEngine *engine);
QScriptValue qtscript_create_QGLColormap_class(QScriptEngine *engine);
QScriptValue qtscript_create_QGLShader_class(QScriptEngine *engine);
QScriptValue qtscript_create_QGLPixelBuffer_class(QScriptEngine *engine);
QScriptValue qtscript_create_QGLFramebufferObject_class(QScriptEngine *engine);
QScriptValue qtscript_create_QGLShaderProgram_class(QScriptEngine *engine);
QScriptValue qtscript_create_QGLWidget_class(QScriptEngine *engine);
static const char * const qtscript_com_trolltech_qt_opengl_class_names[] = {
"QGLFramebufferObjectFormat"
, "QGLContext"
, "QGLColormap"
, "QGLShader"
, "QGLPixelBuffer"
, "QGLFramebufferObject"
, "QGLShaderProgram"
, "QGLWidget"
};
typedef QScriptValue (*QtBindingCreator)(QScriptEngine *engine);
static const QtBindingCreator qtscript_com_trolltech_qt_opengl_class_functions[] = {
qtscript_create_QGLFramebufferObjectFormat_class
, qtscript_create_QGLContext_class
, qtscript_create_QGLColormap_class
, qtscript_create_QGLShader_class
, qtscript_create_QGLPixelBuffer_class
, qtscript_create_QGLFramebufferObject_class
, qtscript_create_QGLShaderProgram_class
, qtscript_create_QGLWidget_class
};
void qtscript_initialize_com_trolltech_qt_opengl_bindings(QScriptValue &extensionObject)
{
QScriptEngine *engine = extensionObject.engine();
for (int i = 0; i < 8; ++i) {
extensionObject.setProperty(qtscript_com_trolltech_qt_opengl_class_names[i],
qtscript_com_trolltech_qt_opengl_class_functions[i](engine),
QScriptValue::SkipInEnumeration);
}
}
|
{
"pile_set_name": "Github"
}
|
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrmTest
{
public class Demo6_Queue
{
public static void Init()
{
Console.WriteLine("");
Console.WriteLine("#### Queue Start ####");
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
DbType = DbType.SqlServer,
ConnectionString = Config.ConnectionString,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true,
AopEvents = new AopEvents
{
OnLogExecuting = (sql, p) =>
{
Console.WriteLine(sql);
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
}
}
});
db.Insertable<Order>(new Order() { Name = "a" }).AddQueue();
db.Insertable<Order>(new Order() { Name = "b" }).AddQueue();
db.SaveQueues();
db.Insertable<Order>(new Order() { Name = "a" }).AddQueue();
db.Insertable<Order>(new Order() { Name = "b" }).AddQueue();
db.Insertable<Order>(new Order() { Name = "c" }).AddQueue();
db.Insertable<Order>(new Order() { Name = "d" }).AddQueue();
var ar = db.SaveQueuesAsync();
ar.Wait();
db.Queryable<Order>().AddQueue();
db.Queryable<Order>().AddQueue();
db.AddQueue("select * from [Order] where id=@id", new { id = 10000 });
var result2 = db.SaveQueues<Order, Order, Order>();
Console.WriteLine("#### Queue End ####");
}
}
}
|
{
"pile_set_name": "Github"
}
|
import React from 'react';
import { expect } from 'chai';
import SkinDeep from 'skin-deep';
import FormTitle from '../../../src/js/components/FormTitle';
describe('Schemaform <FormTitle>', () => {
it('should render', () => {
const tree = SkinDeep.shallowRender(
<FormTitle title="My title" subTitle="My subtitle" />,
);
expect(tree.text()).to.contain('My title');
expect(tree.text()).to.contain('My subtitle');
});
});
|
{
"pile_set_name": "Github"
}
|
# minimist
parse argument options
This module is the guts of optimist's argument parser without all the
fanciful decoration.
[](http://ci.testling.com/substack/minimist)
[](http://travis-ci.org/substack/minimist)
# example
``` js
var argv = require('minimist')(process.argv.slice(2));
console.dir(argv);
```
```
$ node example/parse.js -a beep -b boop
{ _: [], a: 'beep', b: 'boop' }
```
```
$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz
{ _: [ 'foo', 'bar', 'baz' ],
x: 3,
y: 4,
n: 5,
a: true,
b: true,
c: true,
beep: 'boop' }
```
# methods
``` js
var parseArgs = require('minimist')
```
## var argv = parseArgs(args, opts={})
Return an argument object `argv` populated with the array arguments from `args`.
`argv._` contains all the arguments that didn't have an option associated with
them.
Numeric-looking arguments will be returned as numbers unless `opts.string` or
`opts.boolean` is set for that argument name.
Any arguments after `'--'` will not be parsed and will end up in `argv._`.
options can be:
* `opts.string` - a string or array of strings argument names to always treat as
strings
* `opts.boolean` - a string or array of strings to always treat as booleans
* `opts.alias` - an object mapping string names to strings or arrays of string
argument names to use as aliases
* `opts.default` - an object mapping string argument names to default values
# install
With [npm](https://npmjs.org) do:
```
npm install minimist
```
# license
MIT
|
{
"pile_set_name": "Github"
}
|
--TEST--
Bug #42976 (Crash when constructor for newInstance() or newInstanceArgs() fails)
--FILE--
<?php
Class C {
function __construct(&$x) {
$x = "x.changed";
}
}
$x = "x.original";
new C($x); // OK
var_dump($x);
$rc = new ReflectionClass('C');
$x = "x.original";
$rc->newInstance($x); // causes crash
var_dump($x);
$x = "x.original";
$rc->newInstanceArgs(array($x)); // causes crash
var_dump($x);
echo "Done\n";
?>
--EXPECTF--
string(9) "x.changed"
Warning: Parameter 1 to C::__construct() expected to be a reference, value given in %sbug42976.php on line 15
Warning: ReflectionClass::newInstance(): Invocation of C's constructor failed in %sbug42976.php on line 15
string(10) "x.original"
Warning: Parameter 1 to C::__construct() expected to be a reference, value given in %sbug42976.php on line 18
Warning: ReflectionClass::newInstanceArgs(): Invocation of C's constructor failed in %sbug42976.php on line 18
string(10) "x.original"
Done
|
{
"pile_set_name": "Github"
}
|
package rpckids.demo;
public class ExpResponse {
private long value;
private long costInNanos;
public ExpResponse() {
}
public ExpResponse(long value, long costInNanos) {
this.value = value;
this.costInNanos = costInNanos;
}
public long getValue() {
return value;
}
public void setValue(long value) {
this.value = value;
}
public long getCostInNanos() {
return costInNanos;
}
public void setCostInNanos(long costInNanos) {
this.costInNanos = costInNanos;
}
}
|
{
"pile_set_name": "Github"
}
|
# -*- coding: utf-8 -*-
"""
generator.py is a simple script that creates a sqlite database of Android
device models and its corresponding user-friendly names, e.g.:
SM-N910W8, Samsung Galaxy Note4.
This is part of AndroidDeviceNames library:
https://github.com/tslamic/AndroidDeviceNames
:copyright: (c) 2017 by Tadej Slamic (github.com/tslamic)
:license: Apache 2.0
"""
import StringIO
import csv
import os
import re
import sqlite3
import sys
import zipfile
try:
import requests
requests.packages.urllib3.disable_warnings() # No sensitive data.
except ImportError:
sys.exit("'requests' library required")
SQL_CREATE = '''
DROP TABLE IF EXISTS adn;
CREATE TABLE adn (
_id INTEGER PRIMARY KEY,
name TEXT,
model TEXT UNIQUE
);
CREATE INDEX model_index ON adn (model);
'''
SQL_INSERT = '''
INSERT OR IGNORE INTO adn (name, model) VALUES (?, ?)
'''
SQL_COUNT = '''
SELECT Count(*) FROM adn
'''
RE_WHITESPACE = re.compile('\s+')
def _sanitize(string):
""" Removes or replaces unsupported chars from a given string. """
s = string.strip().replace('_', ' ')
s = RE_WHITESPACE.sub(' ', s)
return s
def _log(message):
print message
def _zip(filename):
destination = '{}.zip'.format(filename)
with zipfile.ZipFile(destination, 'w', zipfile.ZIP_DEFLATED) as f:
f.write(filename)
def _main():
gen = Generator(CorcoranGithubEngine(), GooglePlayEngine())
database = gen.create_database()
_zip(database)
class Generator(object):
def __init__(self, *engines):
"""
Constructs a new Generator instance using the list of provided
Engines.
Returns the created database path.
"""
super(Generator, self).__init__()
self.engines = engines
def create_database(self, database_path=None):
if database_path is None:
database_path = os.path.join(os.getcwd(), 'dn.db')
with sqlite3.connect(database_path) as db:
db.executescript(SQL_CREATE)
for engine in self.engines:
devices = engine.devices()
_log("engine {} found {} devices"
.format(engine.__class__.__name__, len(devices)))
db.executemany(SQL_INSERT, devices)
count = db.execute(SQL_COUNT).fetchone()[0]
_log("total devices in the database: {}".format(count))
return database_path
class Engine(object):
def devices(self):
"""
Returns a list of (name, model) tuples representing
various devices.
"""
raise NotImplementedError()
class GooglePlayEngine(Engine):
""" Google Play supported devices. """
ENCODING = 'UTF-16'
URL = 'http://storage.googleapis.com/play_public/supported_devices.csv'
def devices(self):
tuple_list = []
r = requests.get(self.URL, stream=True)
r.raise_for_status()
content = r.content.decode(self.ENCODING)
reader = csv.reader(StringIO.StringIO(content), delimiter=',')
next(reader) # Skip header.
for row in reader:
name = _sanitize('%s %s' % (row[0], row[1]))
model = row[3]
if name and model:
tuple_list.append((name, model,))
return tuple_list
class CorcoranGithubEngine(Engine):
""" Jeff Corcoran GitHub device list. """
DELIMITER = ' = '
URL = "https://raw.githubusercontent.com/corcoran" \
"/android-device-names-registry/master/parsed.devices"
def devices(self):
tuple_list = []
r = requests.get(self.URL)
r.raise_for_status()
content = r.content
lines = content.split(os.linesep)
for line in lines:
if self.DELIMITER in line:
model, name = line.split(self.DELIMITER)
tuple_list.append((_sanitize(name), model,))
return tuple_list
if __name__ == '__main__':
_main()
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/perl -T
use lib '.'; use lib 't';
use SATest; sa_t_init("autolearn");
use constant HAS_DB_FILE => eval { require DB_File; };
use Test::More;
plan skip_all => 'Need DB_File for this test' unless HAS_DB_FILE;
plan tests => 2;
# ---------------------------------------------------------------------------
%patterns = (
q{ autolearn=spam } => 'autolearned as spam'
);
%anti_patterns = (
);
tstprefs ('
body AUTOLEARNTEST_BODY /EVOLUTION PREVIEW RELEASE/
score AUTOLEARNTEST_BODY 1.5
body AUTOLEARNTEST_BODY2 /GET SOURCE CODE/
score AUTOLEARNTEST_BODY2 1.5
body AUTOLEARNTEST_BODY3 /RELEASE NOTES/
score AUTOLEARNTEST_BODY3 1.5
header AUTOLEARNTEST_HEAD From =~ /@/
score AUTOLEARNTEST_HEAD 1.5
header AUTOLEARNTEST_HEAD2 Subject =~ /HC Announce/
score AUTOLEARNTEST_HEAD2 1.5
header AUTOLEARNTEST_HEAD3 Precedence =~ /bulk/
score AUTOLEARNTEST_HEAD3 1.5
use_bayes 1
bayes_auto_learn 1
bayes_auto_learn_threshold_spam 6.0
');
ok (sarun ("-L -t < data/nice/001", \&patterns_run_cb));
ok_all_patterns();
|
{
"pile_set_name": "Github"
}
|
--TEST--
Test gmdate() function : usage variation - Passing predefined constants to format argument.
--FILE--
<?php
/* Prototype : string gmdate(string format [, long timestamp])
* Description: Format a GMT date/time
* Source code: ext/date/php_date.c
*/
echo "*** Testing gmdate() : usage variation ***\n";
// Initialise all required variables
date_default_timezone_set('UTC');
$timestamp = mktime(8, 8, 8, 8, 8, 2008);
//array of values to iterate over
$inputs = array(
// Predefined Date constants
'DATE_ATOM Constant' => DATE_ATOM,
'DATE_COOKIE Constant' => DATE_COOKIE,
'DATE_RFC822 Constant' => DATE_RFC822,
'DATE_RFC850 Constant' => DATE_RFC850,
'DATE_RFC1036 Constant' => DATE_RFC1036,
'DATE_RFC1123 Constant' => DATE_RFC1123,
'DATE_RFC2822 Constant' => DATE_RFC2822,
'DATE_RFC3339 Constant' => DATE_RFC3339,
'DATE_RSS Constant' => DATE_RSS,
'DATE_W3C Constant' => DATE_W3C,
);
// loop through each element of the array for format
foreach($inputs as $key =>$value) {
echo "\n--$key--\n";
var_dump( gmdate($value, $timestamp) );
var_dump( gmdate($value) );
};
?>
===DONE===
--EXPECTF--
*** Testing gmdate() : usage variation ***
--DATE_ATOM Constant--
string(25) "2008-08-08T08:08:08+00:00"
string(%d) "%s"
--DATE_COOKIE Constant--
string(30) "Friday, 08-Aug-08 08:08:08 GMT"
string(%d) "%s"
--DATE_RFC822 Constant--
string(29) "Fri, 08 Aug 08 08:08:08 +0000"
string(%d) "%s"
--DATE_RFC850 Constant--
string(30) "Friday, 08-Aug-08 08:08:08 GMT"
string(%d) "%s"
--DATE_RFC1036 Constant--
string(29) "Fri, 08 Aug 08 08:08:08 +0000"
string(%d) "%s"
--DATE_RFC1123 Constant--
string(31) "Fri, 08 Aug 2008 08:08:08 +0000"
string(%d) "%s"
--DATE_RFC2822 Constant--
string(31) "Fri, 08 Aug 2008 08:08:08 +0000"
string(%d) "%s"
--DATE_RFC3339 Constant--
string(25) "2008-08-08T08:08:08+00:00"
string(%d) "%s"
--DATE_RSS Constant--
string(31) "Fri, 08 Aug 2008 08:08:08 +0000"
string(%d) "%s"
--DATE_W3C Constant--
string(25) "2008-08-08T08:08:08+00:00"
string(%d) "%s"
===DONE===
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.