text
stringlengths 2
100k
| meta
dict |
---|---|
# Copyright © 2016 Advanced Micro Devices, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
CFLAGS ?= -g -O2 -march=native -pipe
CFLAGS += -std=gnu99 -fopenmp
LDLIBS = -lepoxy -lgbm
amdgcn_glslc:
clean:
rm -f amdgcn_glslc
| {
"pile_set_name": "Github"
} |
config BR2_PACKAGE_QT5SCRIPT
bool "qt5script"
select BR2_PACKAGE_QT5BASE
depends on BR2_PACKAGE_QT5_JSCORE_AVAILABLE
help
Qt is a cross-platform application and UI framework for
developers using C++.
This package corresponds to the qt5script module.
http://qt-project.org
| {
"pile_set_name": "Github"
} |
import { shallow } from 'avoriaz'
import withBreakpoint from '@/components/withBreakpoint'
describe('<with-breakpoint />', () => {
it('should contain an empty currentBreakpoint', () => {
const breakpoint = shallow(withBreakpoint)
expect(breakpoint.vm.$data.currentBreakpoint).to.equal('small')
})
it('should contain an internal breakpoints', () => {
const breakpoint = shallow(withBreakpoint)
expect(breakpoint.vm._breakpoints.small).to.equal(744)
})
it('should accept breakpoint props', () => {
const breakpoint = shallow(withBreakpoint, {
propsData: {
breakpoints: {
small: 100,
medium: 101,
large: 102
}
}
})
expect(breakpoint.vm.$props.breakpoints.small).to.equal(100)
expect(breakpoint.vm.$props.breakpoints.medium).to.equal(101)
expect(breakpoint.vm.$props.breakpoints.large).to.equal(102)
})
it('should overwrite the default breakpoints with breakpoints prop', () => {
const breakpoint = shallow(withBreakpoint, {
propsData: {
breakpoints: {
small: 100,
medium: 101,
large: 102
}
}
})
breakpoint.update()
expect(breakpoint.vm._breakpoints.small).to.equal(100)
expect(breakpoint.vm._breakpoints.medium).to.equal(101)
expect(breakpoint.vm._breakpoints.large).to.equal(102)
})
it('should merge the default breakpoints with breakpoints prop', () => {
const breakpoint = shallow(withBreakpoint, {
propsData: {
breakpoints: {
large: 105
}
}
})
breakpoint.update()
expect(breakpoint.vm.$props.breakpoints.large).to.equal(105)
expect(breakpoint.vm._breakpoints.large).to.equal(105)
})
it('should remove resize listener after destroy', () => {
const breakpoint = shallow(withBreakpoint)
breakpoint.destroy()
expect(breakpoint.vm.currentBreakpoint).to.equal('')
})
})
| {
"pile_set_name": "Github"
} |
// Copyright 2008 Google Inc.
// All Rights Reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * 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.
//
// Author: [email protected] (Vlad Losev)
// This sample shows how to test common properties of multiple
// implementations of an interface (aka interface tests) using
// value-parameterized tests. Each test in the test case has
// a parameter that is an interface pointer to an implementation
// tested.
// The interface and its implementations are in this header.
#include "prime_tables.h"
#include "gtest/gtest.h"
#if GTEST_HAS_PARAM_TEST
using ::testing::TestWithParam;
using ::testing::Values;
// As a general rule, to prevent a test from affecting the tests that come
// after it, you should create and destroy the tested objects for each test
// instead of reusing them. In this sample we will define a simple factory
// function for PrimeTable objects. We will instantiate objects in test's
// SetUp() method and delete them in TearDown() method.
typedef PrimeTable* CreatePrimeTableFunc();
PrimeTable* CreateOnTheFlyPrimeTable() {
return new OnTheFlyPrimeTable();
}
template <size_t max_precalculated>
PrimeTable* CreatePreCalculatedPrimeTable() {
return new PreCalculatedPrimeTable(max_precalculated);
}
// Inside the test body, fixture constructor, SetUp(), and TearDown() you
// can refer to the test parameter by GetParam(). In this case, the test
// parameter is a factory function which we call in fixture's SetUp() to
// create and store an instance of PrimeTable.
class PrimeTableTest : public TestWithParam<CreatePrimeTableFunc*> {
public:
virtual ~PrimeTableTest() { delete table_; }
virtual void SetUp() { table_ = (*GetParam())(); }
virtual void TearDown() {
delete table_;
table_ = NULL;
}
protected:
PrimeTable* table_;
};
TEST_P(PrimeTableTest, ReturnsFalseForNonPrimes) {
EXPECT_FALSE(table_->IsPrime(-5));
EXPECT_FALSE(table_->IsPrime(0));
EXPECT_FALSE(table_->IsPrime(1));
EXPECT_FALSE(table_->IsPrime(4));
EXPECT_FALSE(table_->IsPrime(6));
EXPECT_FALSE(table_->IsPrime(100));
}
TEST_P(PrimeTableTest, ReturnsTrueForPrimes) {
EXPECT_TRUE(table_->IsPrime(2));
EXPECT_TRUE(table_->IsPrime(3));
EXPECT_TRUE(table_->IsPrime(5));
EXPECT_TRUE(table_->IsPrime(7));
EXPECT_TRUE(table_->IsPrime(11));
EXPECT_TRUE(table_->IsPrime(131));
}
TEST_P(PrimeTableTest, CanGetNextPrime) {
EXPECT_EQ(2, table_->GetNextPrime(0));
EXPECT_EQ(3, table_->GetNextPrime(2));
EXPECT_EQ(5, table_->GetNextPrime(3));
EXPECT_EQ(7, table_->GetNextPrime(5));
EXPECT_EQ(11, table_->GetNextPrime(7));
EXPECT_EQ(131, table_->GetNextPrime(128));
}
// In order to run value-parameterized tests, you need to instantiate them,
// or bind them to a list of values which will be used as test parameters.
// You can instantiate them in a different translation module, or even
// instantiate them several times.
//
// Here, we instantiate our tests with a list of two PrimeTable object
// factory functions:
INSTANTIATE_TEST_CASE_P(
OnTheFlyAndPreCalculated,
PrimeTableTest,
Values(&CreateOnTheFlyPrimeTable, &CreatePreCalculatedPrimeTable<1000>));
#else
// Google Test may not support value-parameterized tests with some
// compilers. If we use conditional compilation to compile out all
// code referring to the gtest_main library, MSVC linker will not link
// that library at all and consequently complain about missing entry
// point defined in that library (fatal error LNK1561: entry point
// must be defined). This dummy test keeps gtest_main linked in.
TEST(DummyTest, ValueParameterizedTestsAreNotSupportedOnThisPlatform) {}
#endif // GTEST_HAS_PARAM_TEST
| {
"pile_set_name": "Github"
} |
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dan Larkin-York
////////////////////////////////////////////////////////////////////////////////
#ifndef ARANGOD_AQL_INDEX_HINT_H
#define ARANGOD_AQL_INDEX_HINT_H 1
#include <iosfwd>
#include <string>
#include <vector>
namespace arangodb {
namespace velocypack {
class Builder;
class Slice;
}
namespace aql {
struct AstNode;
/// @brief container for index hint information
class IndexHint {
public:
enum HintType : uint8_t { Illegal, None, Simple };
public:
explicit IndexHint();
explicit IndexHint(AstNode const* node);
explicit IndexHint(arangodb::velocypack::Slice const& slice);
public:
HintType type() const;
bool isForced() const;
std::vector<std::string> const& hint() const;
void toVelocyPack(arangodb::velocypack::Builder& builder) const;
std::string typeName() const;
std::string toString() const;
private:
HintType _type;
bool _forced;
// actual hint is a recursive structure, with the data type determined by the
// _type above; in the case of a nested IndexHint, the value of isForced() is
// inherited
struct HintData {
std::vector<std::string> simple;
} _hint;
};
std::ostream& operator<<(std::ostream& stream, arangodb::aql::IndexHint const& hint);
} // namespace aql
} // namespace arangodb
#endif
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="./dist/pageA.bundle.js"></script>
</body>
</html> | {
"pile_set_name": "Github"
} |
[1, 2, 3]
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{321B8E5A-77FE-4895-AAC8-5118BB1B7DB6}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>FaceDemo</RootNamespace>
<AssemblyName>FaceDemo</AssemblyName>
<TargetFrameworkVersion>v4.7</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
<Optimize>false</Optimize>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="Emgu.CV.UI, Version=3.2.0.2721, Culture=neutral, PublicKeyToken=7281126722ab4438, processorArchitecture=MSIL">
<HintPath>..\packages\Emgu.CV.3.2.0.2721\lib\net35\Emgu.CV.UI.dll</HintPath>
</Reference>
<Reference Include="Emgu.CV.World, Version=3.2.0.2721, Culture=neutral, PublicKeyToken=7281126722ab4438, processorArchitecture=MSIL">
<HintPath>..\packages\Emgu.CV.3.2.0.2721\lib\net35\Emgu.CV.World.dll</HintPath>
</Reference>
<Reference Include="NReco.VideoConverter, Version=1.1.2.0, Culture=neutral, PublicKeyToken=395ccb334978a0cd, processorArchitecture=MSIL">
<HintPath>..\packages\NReco.VideoConverter.1.1.2\lib\net20\NReco.VideoConverter.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="ZedGraph, Version=5.1.5.28844, Culture=neutral, PublicKeyToken=02a83cbd123fcd60, processorArchitecture=MSIL">
<HintPath>..\packages\ZedGraph.5.1.5\lib\ZedGraph.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="EmguDemo.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="EmguDemo.Designer.cs">
<DependentUpon>EmguDemo.cs</DependentUpon>
</Compile>
<Compile Include="Main.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Main.Designer.cs">
<DependentUpon>Main.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Main.resx">
<DependentUpon>Main.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Stepon.FaceRecognization\Stepon.FaceRecognization.csproj">
<Project>{ff2b6abe-1309-443a-a2b9-478ee9d7700a}</Project>
<Name>Stepon.FaceRecognization</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\packages\Emgu.CV.3.2.0.2721\build\Emgu.CV.targets" Condition="Exists('..\packages\Emgu.CV.3.2.0.2721\build\Emgu.CV.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\Emgu.CV.3.2.0.2721\build\Emgu.CV.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Emgu.CV.3.2.0.2721\build\Emgu.CV.targets'))" />
</Target>
</Project> | {
"pile_set_name": "Github"
} |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <ConfigAccess.hxx>
#include <unotools/configitem.hxx>
#include <o3tl/any.hxx>
#include <rtl/instance.hxx>
#include <com/sun/star/uno/Sequence.hxx>
namespace chart
{
using namespace ::com::sun::star;
namespace
{
class ChartConfigItem : public ::utl::ConfigItem
{
private:
virtual void ImplCommit() override;
public:
ChartConfigItem();
bool getUseErrorRectangle();
virtual void Notify(const uno::Sequence<OUString>& aPropertyNames) override;
};
}
ChartConfigItem::ChartConfigItem()
: ConfigItem("Office.Chart/ErrorProperties")
{
}
void ChartConfigItem::ImplCommit() {}
void ChartConfigItem::Notify(const uno::Sequence<OUString>&) {}
bool ChartConfigItem::getUseErrorRectangle()
{
uno::Sequence<OUString> aNames(1);
aNames[0] = "ErrorRectangle";
auto b = o3tl::tryAccess<bool>(GetProperties(aNames)[0]);
return b && *b;
}
namespace
{
//a ChartConfigItem Singleton
struct theChartConfigItem : public rtl::Static<ChartConfigItem, theChartConfigItem>
{
};
}
namespace ConfigAccess
{
bool getUseErrorRectangle()
{
bool bResult(theChartConfigItem::get().getUseErrorRectangle());
return bResult;
}
} //namespace ConfigAccess
} //namespace chart
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
| {
"pile_set_name": "Github"
} |
import Scheduler from "./scheduler.js";
export interface SpeedActor {
getSpeed: () => number;
}
/**
* @class Speed-based scheduler
*/
export default class Speed<T extends SpeedActor = SpeedActor> extends Scheduler<T> {
/**
* @param {object} item anything with "getSpeed" method
* @param {bool} repeat
* @param {number} [time=1/item.getSpeed()]
* @see ROT.Scheduler#add
*/
add(item: T, repeat: boolean, time?: number): this;
/**
* @see ROT.Scheduler#next
*/
next(): any;
}
| {
"pile_set_name": "Github"
} |
## A Class Decorator that Adds a copy() Method
Originally published: 2013-02-14 20:43:19
Last updated: 2013-02-14 20:43:20
Author: Eric Snow
Here's a class decorator that adds a rudimentary copy() method onto the decorated class. Use it like this:
@copiable
class SomethingDifferent:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
or like this:
@copiable("a b c")
class SomethingDifferent:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
s = SomethingDifferent(1,2,3)
sc = s.copy()
assert vars(s) == vars(sc)
(Python 3.3) | {
"pile_set_name": "Github"
} |
(ns clojure-hadoop.config
(:require [clojure-hadoop.imports :as imp]
[clojure-hadoop.load :as load])
(:import (org.apache.hadoop.io.compress
DefaultCodec GzipCodec LzoCodec)))
;; This file defines configuration options for clojure-hadoop.
;;
;; The SAME options may be given either on the command line (to
;; clojure_hadoop.job) or in a call to defjob.
;;
;; In defjob, option names are keywords. Values are symbols or
;; keywords. Symbols are resolved as functions or classes. Keywords
;; are converted to Strings.
;;
;; On the command line, option names are preceeded by "-".
;;
;; Options are defined as methods of the conf multimethod.
;; Documentation for individual options appears with each method,
;; below.
(imp/import-io)
(imp/import-fs)
(imp/import-mapred)
(imp/import-mapred-lib)
(defn- #^String as-str [s]
(cond (keyword? s) (name s)
(class? s) (.getName #^Class s)
(fn? s) (throw (Exception. "Cannot use function as value; use a symbol."))
:else (str s)))
(defmulti conf (fn [jobconf key value] key))
(defmethod conf :job [jobconf key value]
(let [f (load/load-name value)]
(doseq [[k v] (f)]
(conf jobconf k v))))
;; Job input paths, separated by commas, as a String.
(defmethod conf :input [#^JobConf jobconf key value]
(FileInputFormat/setInputPaths jobconf (as-str value)))
;; Job output path, as a String.
(defmethod conf :output [#^JobConf jobconf key value]
(FileOutputFormat/setOutputPath jobconf (Path. (as-str value))))
;; When true or "true", deletes output path before starting.
(defmethod conf :replace [#^JobConf jobconf key value]
(when (= (as-str value) "true")
(.set jobconf "clojure-hadoop.job.replace" "true")))
;; The mapper function. May be a class name or a Clojure function as
;; namespace/symbol. May also be "identity" for IdentityMapper.
(defmethod conf :map [#^JobConf jobconf key value]
(let [value (as-str value)]
(cond
(= "identity" value)
(.setMapperClass jobconf IdentityMapper)
(.contains value "/")
(.set jobconf "clojure-hadoop.job.map" value)
:else
(.setMapperClass jobconf (Class/forName value)))))
;; The reducer function. May be a class name or a Clojure function as
;; namespace/symbol. May also be "identity" for IdentityReducer or
;; "none" for no reduce stage.
(defmethod conf :reduce [#^JobConf jobconf key value]
(let [value (as-str value)]
(cond
(= "identity" value)
(.setReducerClass jobconf IdentityReducer)
(= "none" value)
(.setNumReduceTasks jobconf 0)
(.contains value "/")
(.set jobconf "clojure-hadoop.job.reduce" value)
:else
(.setReducerClass jobconf (Class/forName value)))))
;; The mapper reader function, converts Hadoop Writable types to
;; native Clojure types.
(defmethod conf :map-reader [#^JobConf jobconf key value]
(.set jobconf "clojure-hadoop.job.map.reader" (as-str value)))
;; The mapper writer function; converts native Clojure types to Hadoop
;; Writable types.
(defmethod conf :map-writer [#^JobConf jobconf key value]
(.set jobconf "clojure-hadoop.job.map.writer" (as-str value)))
;; The mapper output key class; used when the mapper writer outputs
;; types different from the job output.
(defmethod conf :map-output-key [#^JobConf jobconf key value]
(.setMapOutputKeyClass jobconf (Class/forName value)))
;; The mapper output value class; used when the mapper writer outputs
;; types different from the job output.
(defmethod conf :map-output-value [#^JobConf jobconf key value]
(.setMapOutputValueClass jobconf (Class/forName value)))
;; The job output key class.
(defmethod conf :output-key [#^JobConf jobconf key value]
(.setOutputKeyClass jobconf (Class/forName value)))
;; The job output value class.
(defmethod conf :output-value [#^JobConf jobconf key value]
(.setOutputValueClass jobconf (Class/forName value)))
;; The reducer reader function, converts Hadoop Writable types to
;; native Clojure types.
(defmethod conf :reduce-reader [#^JobConf jobconf key value]
(.set jobconf "clojure-hadoop.job.reduce.reader" (as-str value)))
;; The reducer writer function; converts native Clojure types to
;; Hadoop Writable types.
(defmethod conf :reduce-writer [#^JobConf jobconf key value]
(.set jobconf "clojure-hadoop.job.reduce.writer" (as-str value)))
;; The input file format. May be a class name or "text" for
;; TextInputFormat, "kvtext" fro KeyValueTextInputFormat, "seq" for
;; SequenceFileInputFormat.
(defmethod conf :input-format [#^JobConf jobconf key value]
(let [value (as-str value)]
(cond
(= "text" value)
(.setInputFormat jobconf TextInputFormat)
(= "kvtext" value)
(.setInputFormat jobconf KeyValueTextInputFormat)
(= "seq" value)
(.setInputFormat jobconf SequenceFileInputFormat)
:else
(.setInputFormat jobconf (Class/forName value)))))
;; The output file format. May be a class name or "text" for
;; TextOutputFormat, "seq" for SequenceFileOutputFormat.
(defmethod conf :output-format [#^JobConf jobconf key value]
(let [value (as-str value)]
(cond
(= "text" value)
(.setOutputFormat jobconf TextOutputFormat)
(= "seq" value)
(.setOutputFormat jobconf SequenceFileOutputFormat)
:else
(.setOutputFormat jobconf (Class/forName value)))))
;; If true, compress job output files.
(defmethod conf :compress-output [#^JobConf jobconf key value]
(cond
(= "true" (as-str value))
(FileOutputFormat/setCompressOutput jobconf true)
(= "false" (as-str value))
(FileOutputFormat/setCompressOutput jobconf false)
:else
(throw (Exception. "compress-output value must be true or false"))))
;; Codec to use for compressing job output files.
(defmethod conf :output-compressor [#^JobConf jobconf key value]
(cond
(= "default" (as-str value))
(FileOutputFormat/setOutputCompressorClass
jobconf DefaultCodec)
(= "gzip" (as-str value))
(FileOutputFormat/setOutputCompressorClass
jobconf GzipCodec)
(= "lzo" (as-str value))
(FileOutputFormat/setOutputCompressorClass
jobconf LzoCodec)
:else
(FileOutputFormat/setOutputCompressorClass
jobconf (Class/forName value))))
;; Type of compression to use for sequence files.
(defmethod conf :compression-type [#^JobConf jobconf key value]
(cond
(= "block" (as-str value))
(SequenceFileOutputFormat/setOutputCompressionType
jobconf SequenceFile$CompressionType/BLOCK)
(= "none" (as-str value))
(SequenceFileOutputFormat/setOutputCompressionType
jobconf SequenceFile$CompressionType/NONE)
(= "record" (as-str value))
(SequenceFileOutputFormat/setOutputCompressionType
jobconf SequenceFile$CompressionType/RECORD)))
(defn parse-command-line-args [#^JobConf jobconf args]
(when (empty? args)
(throw (Exception. "Missing required options.")))
(when-not (even? (count args))
(throw (Exception. "Number of options must be even.")))
(doseq [[k v] (partition 2 args)]
(conf jobconf (keyword (subs k 1)) v)))
(defn print-usage []
(println "Usage: java -cp [jars...] clojure_hadoop.job [options...]
Required options are:
-input comma-separated input paths
-output output path
-map mapper function, as namespace/name or class name
-reduce reducer function, as namespace/name or class name
OR
-job job definition function, as namespace/name
Mapper or reducer function may also be \"identity\".
Reducer function may also be \"none\".
Other available options are:
-input-format Class name or \"text\" or \"seq\" (SeqFile)
-output-format Class name or \"text\" or \"seq\" (SeqFile)
-output-key Class for job output key
-output-value Class for job output value
-map-output-key Class for intermediate Mapper output key
-map-output-value Class for intermediate Mapper output value
-map-reader Mapper reader function, as namespace/name
-map-writer Mapper writer function, as namespace/name
-reduce-reader Reducer reader function, as namespace/name
-reduce-writer Reducer writer function, as namespace/name
-name Job name
-replace If \"true\", deletes output dir before start
-compress-output If \"true\", compress job output files
-output-compressor Compression class or \"gzip\",\"lzo\",\"default\"
-compression-type For seqfiles, compress \"block\",\"record\",\"none\"
"))
| {
"pile_set_name": "Github"
} |
package xmlutil
import (
"encoding/base64"
"encoding/xml"
"fmt"
"io"
"reflect"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/private/protocol"
)
// UnmarshalXML deserializes an xml.Decoder into the container v. V
// needs to match the shape of the XML expected to be decoded.
// If the shape doesn't match unmarshaling will fail.
func UnmarshalXML(v interface{}, d *xml.Decoder, wrapper string) error {
n, err := XMLToStruct(d, nil)
if err != nil {
return err
}
if n.Children != nil {
for _, root := range n.Children {
for _, c := range root {
if wrappedChild, ok := c.Children[wrapper]; ok {
c = wrappedChild[0] // pull out wrapped element
}
err = parse(reflect.ValueOf(v), c, "")
if err != nil {
if err == io.EOF {
return nil
}
return err
}
}
}
return nil
}
return nil
}
// parse deserializes any value from the XMLNode. The type tag is used to infer the type, or reflect
// will be used to determine the type from r.
func parse(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
rtype := r.Type()
if rtype.Kind() == reflect.Ptr {
rtype = rtype.Elem() // check kind of actual element type
}
t := tag.Get("type")
if t == "" {
switch rtype.Kind() {
case reflect.Struct:
// also it can't be a time object
if _, ok := r.Interface().(*time.Time); !ok {
t = "structure"
}
case reflect.Slice:
// also it can't be a byte slice
if _, ok := r.Interface().([]byte); !ok {
t = "list"
}
case reflect.Map:
t = "map"
}
}
switch t {
case "structure":
if field, ok := rtype.FieldByName("_"); ok {
tag = field.Tag
}
return parseStruct(r, node, tag)
case "list":
return parseList(r, node, tag)
case "map":
return parseMap(r, node, tag)
default:
return parseScalar(r, node, tag)
}
}
// parseStruct deserializes a structure and its fields from an XMLNode. Any nested
// types in the structure will also be deserialized.
func parseStruct(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
t := r.Type()
if r.Kind() == reflect.Ptr {
if r.IsNil() { // create the structure if it's nil
s := reflect.New(r.Type().Elem())
r.Set(s)
r = s
}
r = r.Elem()
t = t.Elem()
}
// unwrap any payloads
if payload := tag.Get("payload"); payload != "" {
field, _ := t.FieldByName(payload)
return parseStruct(r.FieldByName(payload), node, field.Tag)
}
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if c := field.Name[0:1]; strings.ToLower(c) == c {
continue // ignore unexported fields
}
// figure out what this field is called
name := field.Name
if field.Tag.Get("flattened") != "" && field.Tag.Get("locationNameList") != "" {
name = field.Tag.Get("locationNameList")
} else if locName := field.Tag.Get("locationName"); locName != "" {
name = locName
}
// try to find the field by name in elements
elems := node.Children[name]
if elems == nil { // try to find the field in attributes
if val, ok := node.findElem(name); ok {
elems = []*XMLNode{{Text: val}}
}
}
member := r.FieldByName(field.Name)
for _, elem := range elems {
err := parse(member, elem, field.Tag)
if err != nil {
return err
}
}
}
return nil
}
// parseList deserializes a list of values from an XML node. Each list entry
// will also be deserialized.
func parseList(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
t := r.Type()
if tag.Get("flattened") == "" { // look at all item entries
mname := "member"
if name := tag.Get("locationNameList"); name != "" {
mname = name
}
if Children, ok := node.Children[mname]; ok {
if r.IsNil() {
r.Set(reflect.MakeSlice(t, len(Children), len(Children)))
}
for i, c := range Children {
err := parse(r.Index(i), c, "")
if err != nil {
return err
}
}
}
} else { // flattened list means this is a single element
if r.IsNil() {
r.Set(reflect.MakeSlice(t, 0, 0))
}
childR := reflect.Zero(t.Elem())
r.Set(reflect.Append(r, childR))
err := parse(r.Index(r.Len()-1), node, "")
if err != nil {
return err
}
}
return nil
}
// parseMap deserializes a map from an XMLNode. The direct children of the XMLNode
// will also be deserialized as map entries.
func parseMap(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
if r.IsNil() {
r.Set(reflect.MakeMap(r.Type()))
}
if tag.Get("flattened") == "" { // look at all child entries
for _, entry := range node.Children["entry"] {
parseMapEntry(r, entry, tag)
}
} else { // this element is itself an entry
parseMapEntry(r, node, tag)
}
return nil
}
// parseMapEntry deserializes a map entry from a XML node.
func parseMapEntry(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
kname, vname := "key", "value"
if n := tag.Get("locationNameKey"); n != "" {
kname = n
}
if n := tag.Get("locationNameValue"); n != "" {
vname = n
}
keys, ok := node.Children[kname]
values := node.Children[vname]
if ok {
for i, key := range keys {
keyR := reflect.ValueOf(key.Text)
value := values[i]
valueR := reflect.New(r.Type().Elem()).Elem()
parse(valueR, value, "")
r.SetMapIndex(keyR, valueR)
}
}
return nil
}
// parseScaller deserializes an XMLNode value into a concrete type based on the
// interface type of r.
//
// Error is returned if the deserialization fails due to invalid type conversion,
// or unsupported interface type.
func parseScalar(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
switch r.Interface().(type) {
case *string:
r.Set(reflect.ValueOf(&node.Text))
return nil
case []byte:
b, err := base64.StdEncoding.DecodeString(node.Text)
if err != nil {
return err
}
r.Set(reflect.ValueOf(b))
case *bool:
v, err := strconv.ParseBool(node.Text)
if err != nil {
return err
}
r.Set(reflect.ValueOf(&v))
case *int64:
v, err := strconv.ParseInt(node.Text, 10, 64)
if err != nil {
return err
}
r.Set(reflect.ValueOf(&v))
case *float64:
v, err := strconv.ParseFloat(node.Text, 64)
if err != nil {
return err
}
r.Set(reflect.ValueOf(&v))
case *time.Time:
format := tag.Get("timestampFormat")
if len(format) == 0 {
format = protocol.ISO8601TimeFormatName
}
t, err := protocol.ParseTime(format, node.Text)
if err != nil {
return err
}
r.Set(reflect.ValueOf(&t))
default:
return fmt.Errorf("unsupported value: %v (%s)", r.Interface(), r.Type())
}
return nil
}
| {
"pile_set_name": "Github"
} |
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* 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.
*/
var a = new Float32Array([-1.5, 0, 1.5]);
var b = a.reverse()
assert(a === b);
assert(a[0] === 1.5);
assert(a[1] === 0);
assert(a[2] === -1.5);
| {
"pile_set_name": "Github"
} |
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("IconSourceDemo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IconSourceDemo")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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("1c306d4f-98dc-4c10-b5fa-97200840c114")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"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.
package cryptobyte
import (
"errors"
"fmt"
)
// A Builder builds byte strings from fixed-length and length-prefixed values.
// Builders either allocate space as needed, or are ‘fixed’, which means that
// they write into a given buffer and produce an error if it's exhausted.
//
// The zero value is a usable Builder that allocates space as needed.
//
// Simple values are marshaled and appended to a Builder using methods on the
// Builder. Length-prefixed values are marshaled by providing a
// BuilderContinuation, which is a function that writes the inner contents of
// the value to a given Builder. See the documentation for BuilderContinuation
// for details.
type Builder struct {
err error
result []byte
fixedSize bool
child *Builder
offset int
pendingLenLen int
pendingIsASN1 bool
inContinuation *bool
}
// NewBuilder creates a Builder that appends its output to the given buffer.
// Like append(), the slice will be reallocated if its capacity is exceeded.
// Use Bytes to get the final buffer.
func NewBuilder(buffer []byte) *Builder {
return &Builder{
result: buffer,
}
}
// NewFixedBuilder creates a Builder that appends its output into the given
// buffer. This builder does not reallocate the output buffer. Writes that
// would exceed the buffer's capacity are treated as an error.
func NewFixedBuilder(buffer []byte) *Builder {
return &Builder{
result: buffer,
fixedSize: true,
}
}
// Bytes returns the bytes written by the builder or an error if one has
// occurred during during building.
func (b *Builder) Bytes() ([]byte, error) {
if b.err != nil {
return nil, b.err
}
return b.result[b.offset:], nil
}
// BytesOrPanic returns the bytes written by the builder or panics if an error
// has occurred during building.
func (b *Builder) BytesOrPanic() []byte {
if b.err != nil {
panic(b.err)
}
return b.result[b.offset:]
}
// AddUint8 appends an 8-bit value to the byte string.
func (b *Builder) AddUint8(v uint8) {
b.add(byte(v))
}
// AddUint16 appends a big-endian, 16-bit value to the byte string.
func (b *Builder) AddUint16(v uint16) {
b.add(byte(v>>8), byte(v))
}
// AddUint24 appends a big-endian, 24-bit value to the byte string. The highest
// byte of the 32-bit input value is silently truncated.
func (b *Builder) AddUint24(v uint32) {
b.add(byte(v>>16), byte(v>>8), byte(v))
}
// AddUint32 appends a big-endian, 32-bit value to the byte string.
func (b *Builder) AddUint32(v uint32) {
b.add(byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
}
// AddBytes appends a sequence of bytes to the byte string.
func (b *Builder) AddBytes(v []byte) {
b.add(v...)
}
// BuilderContinuation is continuation-passing interface for building
// length-prefixed byte sequences. Builder methods for length-prefixed
// sequences (AddUint8LengthPrefixed etc) will invoke the BuilderContinuation
// supplied to them. The child builder passed to the continuation can be used
// to build the content of the length-prefixed sequence. For example:
//
// parent := cryptobyte.NewBuilder()
// parent.AddUint8LengthPrefixed(func (child *Builder) {
// child.AddUint8(42)
// child.AddUint8LengthPrefixed(func (grandchild *Builder) {
// grandchild.AddUint8(5)
// })
// })
//
// It is an error to write more bytes to the child than allowed by the reserved
// length prefix. After the continuation returns, the child must be considered
// invalid, i.e. users must not store any copies or references of the child
// that outlive the continuation.
//
// If the continuation panics with a value of type BuildError then the inner
// error will be returned as the error from Bytes. If the child panics
// otherwise then Bytes will repanic with the same value.
type BuilderContinuation func(child *Builder)
// BuildError wraps an error. If a BuilderContinuation panics with this value,
// the panic will be recovered and the inner error will be returned from
// Builder.Bytes.
type BuildError struct {
Err error
}
// AddUint8LengthPrefixed adds a 8-bit length-prefixed byte sequence.
func (b *Builder) AddUint8LengthPrefixed(f BuilderContinuation) {
b.addLengthPrefixed(1, false, f)
}
// AddUint16LengthPrefixed adds a big-endian, 16-bit length-prefixed byte sequence.
func (b *Builder) AddUint16LengthPrefixed(f BuilderContinuation) {
b.addLengthPrefixed(2, false, f)
}
// AddUint24LengthPrefixed adds a big-endian, 24-bit length-prefixed byte sequence.
func (b *Builder) AddUint24LengthPrefixed(f BuilderContinuation) {
b.addLengthPrefixed(3, false, f)
}
// AddUint32LengthPrefixed adds a big-endian, 32-bit length-prefixed byte sequence.
func (b *Builder) AddUint32LengthPrefixed(f BuilderContinuation) {
b.addLengthPrefixed(4, false, f)
}
func (b *Builder) callContinuation(f BuilderContinuation, arg *Builder) {
if !*b.inContinuation {
*b.inContinuation = true
defer func() {
*b.inContinuation = false
r := recover()
if r == nil {
return
}
if buildError, ok := r.(BuildError); ok {
b.err = buildError.Err
} else {
panic(r)
}
}()
}
f(arg)
}
func (b *Builder) addLengthPrefixed(lenLen int, isASN1 bool, f BuilderContinuation) {
// Subsequent writes can be ignored if the builder has encountered an error.
if b.err != nil {
return
}
offset := len(b.result)
b.add(make([]byte, lenLen)...)
if b.inContinuation == nil {
b.inContinuation = new(bool)
}
b.child = &Builder{
result: b.result,
fixedSize: b.fixedSize,
offset: offset,
pendingLenLen: lenLen,
pendingIsASN1: isASN1,
inContinuation: b.inContinuation,
}
b.callContinuation(f, b.child)
b.flushChild()
if b.child != nil {
panic("cryptobyte: internal error")
}
}
func (b *Builder) flushChild() {
if b.child == nil {
return
}
b.child.flushChild()
child := b.child
b.child = nil
if child.err != nil {
b.err = child.err
return
}
length := len(child.result) - child.pendingLenLen - child.offset
if length < 0 {
panic("cryptobyte: internal error") // result unexpectedly shrunk
}
if child.pendingIsASN1 {
// For ASN.1, we reserved a single byte for the length. If that turned out
// to be incorrect, we have to move the contents along in order to make
// space.
if child.pendingLenLen != 1 {
panic("cryptobyte: internal error")
}
var lenLen, lenByte uint8
if int64(length) > 0xfffffffe {
b.err = errors.New("pending ASN.1 child too long")
return
} else if length > 0xffffff {
lenLen = 5
lenByte = 0x80 | 4
} else if length > 0xffff {
lenLen = 4
lenByte = 0x80 | 3
} else if length > 0xff {
lenLen = 3
lenByte = 0x80 | 2
} else if length > 0x7f {
lenLen = 2
lenByte = 0x80 | 1
} else {
lenLen = 1
lenByte = uint8(length)
length = 0
}
// Insert the initial length byte, make space for successive length bytes,
// and adjust the offset.
child.result[child.offset] = lenByte
extraBytes := int(lenLen - 1)
if extraBytes != 0 {
child.add(make([]byte, extraBytes)...)
childStart := child.offset + child.pendingLenLen
copy(child.result[childStart+extraBytes:], child.result[childStart:])
}
child.offset++
child.pendingLenLen = extraBytes
}
l := length
for i := child.pendingLenLen - 1; i >= 0; i-- {
child.result[child.offset+i] = uint8(l)
l >>= 8
}
if l != 0 {
b.err = fmt.Errorf("cryptobyte: pending child length %d exceeds %d-byte length prefix", length, child.pendingLenLen)
return
}
if !b.fixedSize {
b.result = child.result // In case child reallocated result.
}
}
func (b *Builder) add(bytes ...byte) {
if b.err != nil {
return
}
if b.child != nil {
panic("attempted write while child is pending")
}
if len(b.result)+len(bytes) < len(bytes) {
b.err = errors.New("cryptobyte: length overflow")
}
if b.fixedSize && len(b.result)+len(bytes) > cap(b.result) {
b.err = errors.New("cryptobyte: Builder is exceeding its fixed-size buffer")
return
}
b.result = append(b.result, bytes...)
}
// A MarshalingValue marshals itself into a Builder.
type MarshalingValue interface {
// Marshal is called by Builder.AddValue. It receives a pointer to a builder
// to marshal itself into. It may return an error that occurred during
// marshaling, such as unset or invalid values.
Marshal(b *Builder) error
}
// AddValue calls Marshal on v, passing a pointer to the builder to append to.
// If Marshal returns an error, it is set on the Builder so that subsequent
// appends don't have an effect.
func (b *Builder) AddValue(v MarshalingValue) {
err := v.Marshal(b)
if err != nil {
b.err = err
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2019 Confluent Inc.
*
* Licensed under the Confluent Community License (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.confluent.io/confluent-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package io.confluent.ksql.parser;
import java.util.function.Function;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.atn.PredictionMode;
import org.antlr.v4.runtime.misc.ParseCancellationException;
final class GrammarParseUtil {
private static final BaseErrorListener ERROR_LISTENER = new BaseErrorListener() {
@Override
public void syntaxError(
final Recognizer<?, ?> recognizer,
final Object offendingSymbol,
final int line,
final int charPositionInLine,
final String message,
final RecognitionException e
) {
throw new ParsingException(message, e, line, charPositionInLine);
}
};
private GrammarParseUtil() {
}
static <T extends ParserRuleContext> T getParseTree(
final String text,
final Function<SqlBaseParser, T> parseFunction) {
final SqlBaseLexer sqlBaseLexer = new SqlBaseLexer(
new CaseInsensitiveStream(CharStreams.fromString(text)));
final CommonTokenStream tokenStream = new CommonTokenStream(sqlBaseLexer);
final SqlBaseParser sqlBaseParser = new SqlBaseParser(tokenStream);
sqlBaseLexer.removeErrorListeners();
sqlBaseLexer.addErrorListener(ERROR_LISTENER);
sqlBaseParser.removeErrorListeners();
sqlBaseParser.addErrorListener(ERROR_LISTENER);
try {
// first, try parsing w/ potentially faster SLL mode
sqlBaseParser.getInterpreter().setPredictionMode(PredictionMode.SLL);
return castContext(parseFunction.apply(sqlBaseParser));
} catch (final ParseCancellationException ex) {
// if we fail, parse with LL mode
tokenStream.seek(0); // rewind input stream
sqlBaseParser.reset();
sqlBaseParser.getInterpreter().setPredictionMode(PredictionMode.LL);
return castContext(parseFunction.apply(sqlBaseParser));
}
}
@SuppressWarnings("unchecked")
private static <T extends ParserRuleContext> T castContext(final ParserRuleContext ctx) {
return (T) ctx;
}
}
| {
"pile_set_name": "Github"
} |
---
govuk::apps::manuals_publisher::mongodb_name: 'govuk_content_production'
govuk::apps::manuals_publisher::mongodb_nodes:
- 'shared-documentdb'
govuk::apps::manuals_publisher::mongodb_username: "%{hiera('shared_documentdb_user')}"
govuk::apps::manuals_publisher::mongodb_password: "%{hiera('shared_documentdb_password')}"
govuk::apps::maslow::mongodb_name: 'maslow_production'
govuk::apps::maslow::mongodb_nodes:
- 'shared-documentdb'
govuk::apps::maslow::mongodb_username: "%{hiera('shared_documentdb_user')}"
govuk::apps::maslow::mongodb_password: "%{hiera('shared_documentdb_password')}"
govuk::apps::publisher::mongodb_name: 'govuk_content_production'
govuk::apps::publisher::mongodb_nodes:
- 'shared-documentdb'
govuk::apps::publisher::mongodb_username: "%{hiera('shared_documentdb_user')}"
govuk::apps::publisher::mongodb_password: "%{hiera('shared_documentdb_password')}"
govuk::apps::short_url_manager::mongodb_name: 'short_url_manager_production'
govuk::apps::short_url_manager::mongodb_nodes:
- 'shared-documentdb'
govuk::apps::short_url_manager::mongodb_username: "%{hiera('shared_documentdb_user')}"
govuk::apps::short_url_manager::mongodb_password: "%{hiera('shared_documentdb_password')}"
govuk::apps::specialist_publisher::mongodb_name: 'govuk_content_production'
govuk::apps::specialist_publisher::mongodb_nodes:
- 'shared-documentdb'
govuk::apps::specialist_publisher::mongodb_username: "%{hiera('shared_documentdb_user')}"
govuk::apps::specialist_publisher::mongodb_password: "%{hiera('shared_documentdb_password')}"
govuk::apps::travel_advice_publisher::mongodb_name: 'travel_advice_publisher_production'
govuk::apps::travel_advice_publisher::mongodb_nodes:
- 'shared-documentdb'
govuk::apps::travel_advice_publisher::mongodb_username: "%{hiera('shared_documentdb_user')}"
govuk::apps::travel_advice_publisher::mongodb_password: "%{hiera('shared_documentdb_password')}"
| {
"pile_set_name": "Github"
} |
/*
Copyright 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.
*/
// Code generated by lister-gen. DO NOT EDIT.
package v1alpha1
import (
v1alpha1 "k8s.io/api/rbac/v1alpha1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// ClusterRoleLister helps list ClusterRoles.
type ClusterRoleLister interface {
// List lists all ClusterRoles in the indexer.
List(selector labels.Selector) (ret []*v1alpha1.ClusterRole, err error)
// Get retrieves the ClusterRole from the index for a given name.
Get(name string) (*v1alpha1.ClusterRole, error)
ClusterRoleListerExpansion
}
// clusterRoleLister implements the ClusterRoleLister interface.
type clusterRoleLister struct {
indexer cache.Indexer
}
// NewClusterRoleLister returns a new ClusterRoleLister.
func NewClusterRoleLister(indexer cache.Indexer) ClusterRoleLister {
return &clusterRoleLister{indexer: indexer}
}
// List lists all ClusterRoles in the indexer.
func (s *clusterRoleLister) List(selector labels.Selector) (ret []*v1alpha1.ClusterRole, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1alpha1.ClusterRole))
})
return ret, err
}
// Get retrieves the ClusterRole from the index for a given name.
func (s *clusterRoleLister) Get(name string) (*v1alpha1.ClusterRole, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1alpha1.Resource("clusterrole"), name)
}
return obj.(*v1alpha1.ClusterRole), nil
}
| {
"pile_set_name": "Github"
} |
local mType = Game.createMonsterType("Crypt Shambler")
local monster = {}
monster.description = "a crypt shambler"
monster.experience = 195
monster.outfit = {
lookType = 100,
lookHead = 0,
lookBody = 0,
lookLegs = 0,
lookFeet = 0,
lookAddons = 0,
lookMount = 0
}
monster.health = 330
monster.maxHealth = 330
monster.race = "undead"
monster.corpse = 6029
monster.speed = 140
monster.summonCost = 580
monster.maxSummons = 0
monster.changeTarget = {
interval = 4000,
chance = 10
}
monster.strategiesTarget = {
nearest = 70,
damage = 30,
}
monster.flags = {
summonable = true,
attackable = true,
hostile = true,
convinceable = true,
pushable = false,
rewardBoss = false,
illusionable = true,
canPushItems = true,
canPushCreatures = true,
staticAttackChance = 90,
targetDistance = 1,
runHealth = 0,
healthHidden = false,
canWalkOnEnergy = false,
canWalkOnFire = false,
canWalkOnPoison = false
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
{text = "Aaaaahhhh!", yell = false},
{text = "Hoooohhh!", yell = false},
{text = "Uhhhhhhh!", yell = false},
{text = "Chhhhhhh!", yell = false}
}
monster.loot = {
{id = "small diamond", chance = 510},
{id = "gold coin", chance = 57000, maxCount = 55},
{id = "rotten meat", chance = 1850},
{id = 2230, chance = 5000},
{id = "throwing star", chance = 910, maxCount = 3},
{id = "bone sword", chance = 1000},
{id = "iron helmet", chance = 2130},
{id = "iron helmet", chance = 2000},
{id = "bone shield", chance = 1000},
{id = "worm", chance = 9000, maxCount = 10},
{id = "half-digested piece of meat", chance = 5000}
}
monster.attacks = {
{name ="combat", type = COMBAT_PHYSICALDAMAGE, interval = 2000, chance = 100, minDamage = 0, maxDamage = -140, effect = CONST_ME_DRAWBLOOD},
{name ="combat", interval = 2000, chance = 15, minDamage = -28, maxDamage = -55, type = COMBAT_LIFEDRAIN, range = 1, target = true}
}
monster.defenses = {
defense = 25,
armor = 25
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = 0},
{type = COMBAT_ENERGYDAMAGE, percent = 0},
{type = COMBAT_EARTHDAMAGE, percent = 100},
{type = COMBAT_FIREDAMAGE, percent = 0},
{type = COMBAT_LIFEDRAIN, percent = 100},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 100},
{type = COMBAT_ICEDAMAGE, percent = 0},
{type = COMBAT_HOLYDAMAGE , percent = -25},
{type = COMBAT_DEATHDAMAGE , percent = 100}
}
monster.immunities = {
{type = "paralyze", condition = true},
{type = "outfit", condition = false},
{type = "invisible", condition = false},
{type = "bleed", condition = false}
}
mType:register(monster)
| {
"pile_set_name": "Github"
} |
// Package systemd/journal implements a client for the journal system. package journal
package journal
import (
"encoding/binary"
"errors"
"fmt"
"net"
"runtime"
"strings"
"sync"
)
// The path to the journald socket.
const systemdSocket = "/run/systemd/journal/socket"
var errMissingEquals = errors.New("journal: missing '=' in message")
func grow(s []byte) []byte {
buf := make([]byte, len(s), 8+len(s)+len(s)/4)
copy(buf, s)
return buf
}
type Handle struct {
path string
conn *net.UnixConn
lock sync.Mutex
}
var defaultHandle = &Handle{path: systemdSocket}
func Printf(format string, args ...interface{}) error { return defaultHandle.Printf(format, args...) }
// Send logs a sequence of strings in the form "key=value".
func Send(args ...string) error { return defaultHandle.Send(args...) }
// See standard field names in systemd.journal-fields(7).
func (h *Handle) Printf(format string, args ...interface{}) error {
pc, file, line, _ := runtime.Caller(1)
funcname := runtime.FuncForPC(pc).Name()
return h.Send("CODE_FILE="+file,
fmt.Sprintf("CODE_LINE=%d", line),
"CODE_FUNC="+funcname,
fmt.Sprintf("MESSAGE="+format, args...),
)
}
func (h *Handle) Send(args ...string) error {
const maxbufsize = 32 << 10
// Todo. Implement a zero copy version.
size := int64(0)
for _, s := range args {
size += int64(len(s) + 1)
}
if size > maxbufsize {
return h.sendLarge(args...)
}
// Build a buffer whose lines are the input strings.
buf := make([]byte, 0, size)
for _, s := range args {
// Validate.
i := strings.IndexRune(s, '=')
j := strings.IndexRune(s, '\n')
if i < 0 {
return errMissingEquals
}
if 0 <= j && j < i {
return errMissingEquals
}
if j >= 0 {
// Multiline message: key + '\n' + 64-bit LE length + msg + '\n'
buf = append(buf, s[:i]...)
buf = append(buf, '\n')
msg := s[i+1:]
if cap(buf) < len(buf)+8 {
buf = grow(buf)
}
binary.LittleEndian.PutUint64(buf[len(buf):len(buf)+8], uint64(len(msg)))
buf = append(buf[:len(buf)+8], msg...)
buf = append(buf, '\n')
fmt.Printf("%q\n", buf)
} else {
// Simple message.
buf = append(buf, s...)
buf = append(buf, '\n')
}
}
return h.send(buf)
}
func (h *Handle) send(buf []byte) error {
var err error
h.lock.Lock()
defer h.lock.Unlock()
jaddr := &net.UnixAddr{Net: "unixgram", Name: h.path}
if h.conn == nil {
h.conn, err = net.DialUnix("unixgram", nil, jaddr)
if err != nil {
return err
}
}
n, _, err := h.conn.WriteMsgUnix(buf, nil, jaddr)
if n == 0 {
return h.sendLargeBuf(buf)
}
return err
}
func (h *Handle) sendLargeBuf(msg []byte) error { panic("not implemented") }
func (h *Handle) sendLarge(args ...string) error { panic("not implemented") }
| {
"pile_set_name": "Github"
} |
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh
proxy:x:13:13:proxy:/bin:/bin/sh
www-data:x:33:33:www-data:/var/www:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
list:x:38:38:Mailing List Manager:/var/list:/bin/sh
irc:x:39:39:ircd:/var/run/ircd:/bin/sh
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
Debian-exim:x:102:102::/var/spool/exim4:/bin/false
myuser1:x:424242:424242::/home:/bin/bash
myuser2:x:424243:424242::/home:/bin/bash
myuser3:x:424244:424242::/home:/bin/bash
myuser4:x:424245:424242::/home:/bin/bash
myuser5:x:424246:424242::/home:/bin/bash
myuser6:x:424247:424242::/home:/bin/bash
myuser7:x:424248:424242::/home:/bin/bash
| {
"pile_set_name": "Github"
} |
TAP_DANCE_ENABLE = yes
| {
"pile_set_name": "Github"
} |
<table class="dijit dijitReset dijitInline dijitLeft"
cellspacing='0' cellpadding='0' role="presentation"
><tbody role="presentation"><tr role="presentation"
><td class="dijitReset dijitStretch dijitButtonNode" data-dojo-attach-point="buttonNode" data-dojo-attach-event="ondijitclick:__onClick,onkeydown:_onButtonKeyDown"
><div id="${id}_button" class="dijitReset dijitButtonContents"
data-dojo-attach-point="titleNode"
role="button" aria-labelledby="${id}_label"
><div class="dijitReset dijitInline dijitIcon" data-dojo-attach-point="iconNode" role="presentation"></div
><div class="dijitReset dijitInline dijitButtonText" id="${id}_label" data-dojo-attach-point="containerNode" role="presentation"></div
></div
></td
><td id="${id}_arrow" class='dijitReset dijitRight dijitButtonNode dijitArrowButton'
data-dojo-attach-point="_popupStateNode,focusNode,_buttonNode"
data-dojo-attach-event="onkeydown:_onArrowKeyDown"
title="${optionsTitle}"
role="button" aria-haspopup="true"
><div class="dijitReset dijitArrowButtonInner" role="presentation"></div
><div class="dijitReset dijitArrowButtonChar" role="presentation">▼</div
></td
><td style="display:none !important;"
><input ${!nameAttrSetting} type="${type}" value="${value}" data-dojo-attach-point="valueNode"
role="presentation" aria-hidden="true"
data-dojo-attach-event="onclick:_onClick"
/></td></tr></tbody
></table>
| {
"pile_set_name": "Github"
} |
import { Rule } from '@angular-devkit/schematics';
import { componentBuilder } from "@syncfusion/ej2-angular-base/schematics";
import { Schema } from './schema';
import * as sampleDetails from './sample-details';
export default function (options: Schema): Rule {
return componentBuilder(options, sampleDetails);
}
| {
"pile_set_name": "Github"
} |
// Acorn is a tiny, fast JavaScript parser written in JavaScript.
//
// Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and
// various contributors and released under an MIT license.
//
// Git repositories for Acorn are available at
//
// http://marijnhaverbeke.nl/git/acorn
// https://github.com/marijnh/acorn.git
//
// Please use the [github bug tracker][ghbt] to report issues.
//
// [ghbt]: https://github.com/marijnh/acorn/issues
//
// This file defines the main parser interface. The library also comes
// with a [error-tolerant parser][dammit] and an
// [abstract syntax tree walker][walk], defined in other files.
//
// [dammit]: acorn_loose.js
// [walk]: util/walk.js
import {Parser} from "./state"
import {getOptions} from "./options"
import "./parseutil"
import "./statement"
import "./lval"
import "./expression"
export {Parser, plugins} from "./state"
export {defaultOptions} from "./options"
export {SourceLocation} from "./location"
export {getLineInfo} from "./location"
export {Node} from "./node"
export {TokenType, types as tokTypes} from "./tokentype"
export {TokContext, types as tokContexts} from "./tokencontext"
export {isIdentifierChar, isIdentifierStart} from "./identifier"
export {Token} from "./tokenize"
export {isNewLine, lineBreak, lineBreakG} from "./whitespace"
export const version = "1.2.2"
// The main exported interface (under `self.acorn` when in the
// browser) is a `parse` function that takes a code string and
// returns an abstract syntax tree as specified by [Mozilla parser
// API][api].
//
// [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
export function parse(input, options) {
let p = parser(options, input)
let startPos = p.pos, startLoc = p.options.locations && p.curPosition()
p.nextToken()
return p.parseTopLevel(p.options.program || p.startNodeAt(startPos, startLoc))
}
// This function tries to parse a single expression at a given
// offset in a string. Useful for parsing mixed-language formats
// that embed JavaScript expressions.
export function parseExpressionAt(input, pos, options) {
let p = parser(options, input, pos)
p.nextToken()
return p.parseExpression()
}
// Acorn is organized as a tokenizer and a recursive-descent parser.
// The `tokenize` export provides an interface to the tokenizer.
export function tokenizer(input, options) {
return parser(options, input)
}
function parser(options, input) {
return new Parser(getOptions(options), String(input))
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2013-2020 Automatak, LLC
*
* Licensed to Green Energy Corp (www.greenenergycorp.com) and Automatak
* LLC (www.automatak.com) under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. Green Energy Corp and Automatak LLC license
* 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.
*/
#include "opendnp3/app/ControlRelayOutputBlock.h"
namespace opendnp3
{
ControlRelayOutputBlock::ControlRelayOutputBlock(OperationType opType_,
TripCloseCode tcc_,
bool clear_,
uint8_t count_,
uint32_t onTime_,
uint32_t offTime_,
CommandStatus status_)
: opType(opType_),
tcc(tcc_),
clear(clear_),
count(count_),
onTimeMS(onTime_),
offTimeMS(offTime_),
status(status_),
rawCode(((TripCloseCodeSpec::to_type(tcc) << 6) & 0xC0) | ((static_cast<uint8_t>(clear) << 5) & 0x20)
| (OperationTypeSpec::to_type(opType) & 0x0F))
{
}
ControlRelayOutputBlock::ControlRelayOutputBlock(
uint8_t rawCode_, uint8_t count_, uint32_t onTime_, uint32_t offTime_, CommandStatus status_)
: opType(OperationTypeSpec::from_type(rawCode_ & 0x0F)),
tcc(TripCloseCodeSpec::from_type((rawCode_ >> 6) & 0x3)),
clear(rawCode_ & 0x20),
count(count_),
onTimeMS(onTime_),
offTimeMS(offTime_),
status(status_),
rawCode(rawCode_)
{
}
} // namespace opendnp3
| {
"pile_set_name": "Github"
} |
{
"annotations": {
"list": [
{
"builtIn": 1,
"datasource": "-- Grafana --",
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations \u0026 Alerts",
"type": "dashboard"
}
]
},
"editable": true,
"gnetId": null,
"graphTooltip": 0,
"id": 73,
"iteration": 1547454421924,
"links": [],
"panels": [
{
"columns": [],
"datasource": "psql",
"description": "Shows company PRs in the given repository groups",
"fontSize": "80%",
"gridPos": {
"h": 22,
"w": 24,
"x": 0,
"y": 0
},
"hideTimeOverride": true,
"id": 1,
"links": [],
"pageSize": 200,
"scroll": true,
"showHeader": true,
"sort": {
"col": 4,
"desc": true
},
"styles": [
{
"alias": "Time",
"dateFormat": "YYYY-MM-DD HH:mm:ss",
"decimals": null,
"pattern": "Time",
"type": "hidden"
},
{
"alias": "",
"colorMode": null,
"colors": [
"rgba(245, 54, 54, 0.9)",
"rgba(237, 129, 40, 0.89)",
"rgba(50, 172, 45, 0.97)"
],
"dateFormat": "YYYY-MM-DD HH:mm:ss",
"decimals": 0,
"mappingType": 1,
"pattern": "Opened PRs",
"thresholds": [],
"type": "number",
"unit": "none"
},
{
"alias": "",
"colorMode": null,
"colors": [
"rgba(245, 54, 54, 0.9)",
"rgba(237, 129, 40, 0.89)",
"rgba(50, 172, 45, 0.97)"
],
"decimals": 2,
"pattern": "/.*/",
"thresholds": [],
"type": "number",
"unit": "none"
}
],
"targets": [
{
"alias": "",
"dsType": "influxdb",
"format": "table",
"groupBy": [
{
"params": [
"$__interval"
],
"type": "time"
},
{
"params": [
"null"
],
"type": "fill"
}
],
"orderByTime": "ASC",
"policy": "default",
"query": "SELECT \"name\", \"value\" FROM \"top_commenters_[[repogroup]]_[[period]]\" WHERE $timeFilter",
"rawQuery": true,
"rawSql": "select\n split_part(name, '$$$', 2) as \"Company\",\n split_part(name, '$$$', 1) as \"Repository group\",\n split_part(name, '$$$', 3) as \"GitHub ID\",\n split_part(name, '$$$', 4) as \"User names\",\n value as \"Opened PRs\"\nfrom\n scompany_prs\nwhere\n period = '[[period]]'\n and ('[[repogroups:csv]]' = 'null' or split_part(name, '$$$', 1) in ([[repogroups]]))\n and ('[[companies:csv]]' = 'null' or split_part(name, '$$$', 2) in ([[companies]]))",
"refId": "A",
"resultFormat": "table",
"select": [
[
{
"params": [
"value"
],
"type": "field"
},
{
"params": [],
"type": "mean"
}
]
],
"tags": []
}
],
"title": "[[full_name]] company PRs (Range: [[period_name]])",
"transform": "table",
"transparent": false,
"type": "table"
},
{
"content": "${docs:raw}",
"gridPos": {
"h": 9,
"w": 24,
"x": 0,
"y": 22
},
"id": 11,
"links": [],
"mode": "html",
"title": "Dashboard documentation",
"type": "text"
}
],
"refresh": false,
"schemaVersion": 16,
"style": "dark",
"tags": [
"dashboard",
"zephyr",
"table",
"companies"
],
"templating": {
"list": [
{
"allValue": null,
"current": {
"text": "Last decade",
"value": "Last decade"
},
"datasource": "psql",
"hide": 0,
"includeAll": false,
"label": "Range",
"multi": false,
"name": "period_name",
"options": [],
"query": "select quick_ranges_name from tquick_ranges order by time",
"refresh": 1,
"regex": "",
"skipUrlSync": false,
"sort": 0,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": false
},
{
"allValue": null,
"current": {
"text": "y10",
"value": "y10"
},
"datasource": "psql",
"hide": 2,
"includeAll": false,
"label": null,
"multi": false,
"name": "period",
"options": [],
"query": "select quick_ranges_suffix from tquick_ranges where quick_ranges_name = '[[period_name]]'",
"refresh": 1,
"regex": "",
"skipUrlSync": true,
"sort": 0,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": false
},
{
"allValue": "null",
"current": {
"tags": [],
"text": "All",
"value": [
"$__all"
]
},
"datasource": "psql",
"hide": 0,
"includeAll": true,
"label": "Repository groups",
"multi": true,
"name": "repogroups",
"options": [],
"query": "select repo_group_name from trepo_groups order by 1",
"refresh": 1,
"regex": "",
"skipUrlSync": false,
"sort": 0,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": false
},
{
"allValue": null,
"current": {
"text": "CNCF",
"value": "CNCF"
},
"datasource": "psql",
"hide": 2,
"includeAll": false,
"label": null,
"multi": false,
"name": "full_name",
"options": [],
"query": "select value_s from gha_vars where name = 'full_name'",
"refresh": 1,
"regex": "",
"skipUrlSync": true,
"sort": 0,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": false
},
{
"allValue": null,
"current": {
"isNone": true,
"text": "None",
"value": ""
},
"datasource": "psql",
"hide": 2,
"includeAll": false,
"label": null,
"multi": false,
"name": "docs",
"options": [],
"query": "select value_s from gha_vars where name = 'company_prs_docs_html'",
"refresh": 1,
"regex": "",
"skipUrlSync": true,
"sort": 0,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": false
},
{
"allValue": "null",
"current": {
"tags": [],
"text": "All",
"value": [
"$__all"
]
},
"datasource": "psql",
"hide": 0,
"includeAll": true,
"label": "Companies",
"multi": true,
"name": "companies",
"options": [],
"query": "select companies_name from tcompanies order by time asc",
"refresh": 1,
"regex": "",
"skipUrlSync": false,
"sort": 0,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": false
}
]
},
"time": {
"from": "now-5y",
"to": "now"
},
"timepicker": {
"hidden": true,
"refresh_intervals": [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
],
"time_options": [
"5m",
"15m",
"1h",
"6h",
"12h",
"24h",
"2d",
"7d",
"30d"
]
},
"timezone": "",
"title": "Company PRs in Repository Groups Table",
"uid": "55",
"version": 7
} | {
"pile_set_name": "Github"
} |
/*
* Minimal debug/trace/assert driver definitions for
* Broadcom 802.11 Networking Adapter.
*
* $Copyright Open Broadcom Corporation$
*
* $Id: wl_dbg.h 472390 2014-04-23 23:32:01Z $
*/
#ifndef _wl_dbg_h_
#define _wl_dbg_h_
/* wl_msg_level is a bit vector with defs in wlioctl.h */
extern uint32 wl_msg_level;
extern uint32 wl_msg_level2;
#define WL_TIMESTAMP()
#if 0 && (VERSION_MAJOR > 9)
extern int osl_printf(const char *fmt, ...);
#include <IOKit/apple80211/IO8Log.h>
#define WL_PRINT(args) do { osl_printf args; } while (0)
#define RELEASE_PRINT(args) do { WL_PRINT(args); IO8Log args; } while (0)
#else
#define WL_PRINT(args) do { WL_TIMESTAMP(); printf args; } while (0)
#endif
#if defined(EVENT_LOG_COMPILE) && defined(WLMSG_SRSCAN)
#define _WL_SRSCAN(fmt, ...) EVENT_LOG(EVENT_LOG_TAG_SRSCAN, fmt, ##__VA_ARGS__)
#define WL_SRSCAN(args) _WL_SRSCAN args
#else
#define WL_SRSCAN(args)
#endif
#if defined(BCMCONDITIONAL_LOGGING)
/* Ideally this should be some include file that vendors can include to conditionalize logging */
/* DBGONLY() macro to reduce ifdefs in code for statements that are only needed when
* BCMDBG is defined.
*/
#define DBGONLY(x)
/* To disable a message completely ... until you need it again */
#define WL_NONE(args)
#define WL_ERROR(args) do {if (wl_msg_level & WL_ERROR_VAL) WL_PRINT(args);} while (0)
#define WL_TRACE(args)
#define WL_PRHDRS_MSG(args)
#define WL_PRHDRS(i, p, f, t, r, l)
#define WL_PRPKT(m, b, n)
#define WL_INFORM(args)
#define WL_TMP(args)
#define WL_OID(args)
#define WL_RATE(args) do {if (wl_msg_level & WL_RATE_VAL) WL_PRINT(args);} while (0)
#define WL_ASSOC(args) do {if (wl_msg_level & WL_ASSOC_VAL) WL_PRINT(args);} while (0)
#define WL_PRUSR(m, b, n)
#define WL_PS(args) do {if (wl_msg_level & WL_PS_VAL) WL_PRINT(args);} while (0)
#define WL_PORT(args)
#define WL_DUAL(args)
#define WL_REGULATORY(args) do {if (wl_msg_level & WL_REGULATORY_VAL) WL_PRINT(args);} while (0)
#define WL_MPC(args)
#define WL_APSTA(args)
#define WL_APSTA_BCN(args)
#define WL_APSTA_TX(args)
#define WL_APSTA_TSF(args)
#define WL_APSTA_BSSID(args)
#define WL_BA(args)
#define WL_MBSS(args)
#define WL_PROTO(args)
#define WL_CAC(args) do {if (wl_msg_level & WL_CAC_VAL) WL_PRINT(args);} while (0)
#define WL_AMSDU(args)
#define WL_AMPDU(args)
#define WL_FFPLD(args)
#define WL_MCHAN(args)
#define WL_DFS(args)
#define WL_WOWL(args)
#define WL_DPT(args)
#define WL_ASSOC_OR_DPT(args)
#define WL_SCAN(args) do {if (wl_msg_level2 & WL_SCAN_VAL) WL_PRINT(args);} while (0)
#define WL_COEX(args)
#define WL_RTDC(w, s, i, j)
#define WL_RTDC2(w, s, i, j)
#define WL_CHANINT(args)
#define WL_BTA(args)
#define WL_P2P(args)
#define WL_ITFR(args)
#define WL_TDLS(args)
#define WL_MCNX(args)
#define WL_PROT(args)
#define WL_PSTA(args)
#define WL_TRF_MGMT(args)
#define WL_L2FILTER(args)
#define WL_MQ(args)
#define WL_TXBF(args)
#define WL_P2PO(args)
#define WL_NET_DETECT(args)
#define WL_ROAM(args)
#define WL_WNM(args)
#define WL_AMPDU_UPDN(args)
#define WL_AMPDU_RX(args)
#define WL_AMPDU_ERR(args)
#define WL_AMPDU_TX(args)
#define WL_AMPDU_CTL(args)
#define WL_AMPDU_HW(args)
#define WL_AMPDU_HWTXS(args)
#define WL_AMPDU_HWDBG(args)
#define WL_AMPDU_STAT(args)
#define WL_AMPDU_ERR_ON() 0
#define WL_AMPDU_HW_ON() 0
#define WL_AMPDU_HWTXS_ON() 0
#define WL_APSTA_UPDN(args)
#define WL_APSTA_RX(args)
#define WL_WSEC(args)
#define WL_WSEC_DUMP(args)
#define WL_PCIE(args)
#define WL_CHANLOG(w, s, i, j)
#define WL_ERROR_ON() (wl_msg_level & WL_ERROR_VAL)
#define WL_TRACE_ON() 0
#define WL_PRHDRS_ON() 0
#define WL_PRPKT_ON() 0
#define WL_INFORM_ON() 0
#define WL_TMP_ON() 0
#define WL_OID_ON() 0
#define WL_RATE_ON() (wl_msg_level & WL_RATE_VAL)
#define WL_ASSOC_ON() (wl_msg_level & WL_ASSOC_VAL)
#define WL_PRUSR_ON() 0
#define WL_PS_ON() (wl_msg_level & WL_PS_VAL)
#define WL_PORT_ON() 0
#define WL_WSEC_ON() 0
#define WL_WSEC_DUMP_ON() 0
#define WL_MPC_ON() 0
#define WL_REGULATORY_ON() (wl_msg_level & WL_REGULATORY_VAL)
#define WL_APSTA_ON() 0
#define WL_DFS_ON() 0
#define WL_MBSS_ON() 0
#define WL_CAC_ON() (wl_msg_level & WL_CAC_VAL)
#define WL_AMPDU_ON() 0
#define WL_DPT_ON() 0
#define WL_WOWL_ON() 0
#define WL_SCAN_ON() (wl_msg_level2 & WL_SCAN_VAL)
#define WL_BTA_ON() 0
#define WL_P2P_ON() 0
#define WL_ITFR_ON() 0
#define WL_MCHAN_ON() 0
#define WL_TDLS_ON() 0
#define WL_MCNX_ON() 0
#define WL_PROT_ON() 0
#define WL_PSTA_ON() 0
#define WL_TRF_MGMT_ON() 0
#define WL_LPC_ON() 0
#define WL_L2FILTER_ON() 0
#define WL_TXBF_ON() 0
#define WL_P2PO_ON() 0
#define WL_CHANLOG_ON() 0
#define WL_NET_DETECT_ON() 0
#define WL_WNM_ON() 0
#define WL_PCIE_ON() 0
#else /* !BCMDBG */
/* DBGONLY() macro to reduce ifdefs in code for statements that are only needed when
* BCMDBG is defined.
*/
#define DBGONLY(x)
/* To disable a message completely ... until you need it again */
#define WL_NONE(args)
#define WL_ERROR(args)
#define WL_TRACE(args)
#ifndef LINUX_POSTMOGRIFY_REMOVAL
#ifdef WLMSG_PRHDRS
#define WL_PRHDRS_MSG(args) WL_PRINT(args)
#define WL_PRHDRS(i, p, f, t, r, l) wlc_print_hdrs(i, p, f, t, r, l)
#else
#define WL_PRHDRS_MSG(args)
#define WL_PRHDRS(i, p, f, t, r, l)
#endif
#ifdef WLMSG_PRPKT
#define WL_PRPKT(m, b, n) prhex(m, b, n)
#else
#define WL_PRPKT(m, b, n)
#endif
#ifdef WLMSG_INFORM
#define WL_INFORM(args) WL_PRINT(args)
#else
#define WL_INFORM(args)
#endif
#define WL_TMP(args)
#ifdef WLMSG_OID
#define WL_OID(args) WL_PRINT(args)
#else
#define WL_OID(args)
#endif
#define WL_RATE(args)
#ifdef WLMSG_ASSOC
#define WL_ASSOC(args) WL_PRINT(args)
#else
#define WL_ASSOC(args)
#endif
#define WL_PRUSR(m, b, n)
#ifdef WLMSG_PS
#define WL_PS(args) WL_PRINT(args)
#else
#define WL_PS(args)
#endif
#ifdef WLMSG_ROAM
#define WL_ROAM(args) WL_PRINT(args)
#else
#define WL_ROAM(args)
#endif
#define WL_PORT(args)
#define WL_DUAL(args)
#define WL_REGULATORY(args)
#ifdef WLMSG_MPC
#define WL_MPC(args) WL_PRINT(args)
#else
#define WL_MPC(args)
#endif
#define WL_APSTA(args)
#define WL_APSTA_BCN(args)
#define WL_APSTA_TX(args)
#define WL_APSTA_TSF(args)
#define WL_APSTA_BSSID(args)
#define WL_BA(args)
#define WL_MBSS(args)
#define WL_MODE_SWITCH(args)
#define WL_PROTO(args)
#define WL_CAC(args)
#define WL_AMSDU(args)
#define WL_AMPDU(args)
#define WL_FFPLD(args)
#define WL_MCHAN(args)
/* Define WLMSG_DFS automatically for WLTEST builds */
#ifdef WLMSG_DFS
#define WL_DFS(args) do {if (wl_msg_level & WL_DFS_VAL) WL_PRINT(args);} while (0)
#else /* WLMSG_DFS */
#define WL_DFS(args)
#endif /* WLMSG_DFS */
#define WL_WOWL(args)
#ifdef WLMSG_SCAN
#define WL_SCAN(args) WL_PRINT(args)
#else
#define WL_SCAN(args)
#endif
#define WL_COEX(args)
#define WL_RTDC(w, s, i, j)
#define WL_RTDC2(w, s, i, j)
#define WL_CHANINT(args)
#ifdef WLMSG_BTA
#define WL_BTA(args) WL_PRINT(args)
#else
#define WL_BTA(args)
#endif
#define WL_WMF(args)
#define WL_P2P(args)
#define WL_ITFR(args)
#define WL_TDLS(args)
#define WL_MCNX(args)
#define WL_PROT(args)
#define WL_PSTA(args)
#define WL_TBTT(args)
#define WL_TRF_MGMT(args)
#define WL_L2FILTER(args)
#define WL_MQ(args)
#define WL_P2PO(args)
#define WL_WNM(args)
#define WL_TXBF(args)
#define WL_CHANLOG(w, s, i, j)
#define WL_NET_DETECT(args)
#define WL_ERROR_ON() 0
#define WL_TRACE_ON() 0
#ifdef WLMSG_PRHDRS
#define WL_PRHDRS_ON() 1
#else
#define WL_PRHDRS_ON() 0
#endif
#ifdef WLMSG_PRPKT
#define WL_PRPKT_ON() 1
#else
#define WL_PRPKT_ON() 0
#endif
#ifdef WLMSG_INFORM
#define WL_INFORM_ON() 1
#else
#define WL_INFORM_ON() 0
#endif
#ifdef WLMSG_OID
#define WL_OID_ON() 1
#else
#define WL_OID_ON() 0
#endif
#define WL_TMP_ON() 0
#define WL_RATE_ON() 0
#ifdef WLMSG_ASSOC
#define WL_ASSOC_ON() 1
#else
#define WL_ASSOC_ON() 0
#endif
#define WL_PORT_ON() 0
#ifdef WLMSG_WSEC
#define WL_WSEC_ON() 1
#define WL_WSEC_DUMP_ON() 1
#else
#define WL_WSEC_ON() 0
#define WL_WSEC_DUMP_ON() 0
#endif
#ifdef WLMSG_MPC
#define WL_MPC_ON() 1
#else
#define WL_MPC_ON() 0
#endif
#define WL_REGULATORY_ON() 0
#define WL_APSTA_ON() 0
#define WL_BA_ON() 0
#define WL_MBSS_ON() 0
#define WL_MODE_SWITCH_ON() 0
#ifdef WLMSG_DFS
#define WL_DFS_ON() 1
#else /* WLMSG_DFS */
#define WL_DFS_ON() 0
#endif /* WLMSG_DFS */
#ifdef WLMSG_SCAN
#define WL_SCAN_ON() 1
#else
#define WL_SCAN_ON() 0
#endif
#ifdef WLMSG_BTA
#define WL_BTA_ON() 1
#else
#define WL_BTA_ON() 0
#endif
#define WL_WMF_ON() 0
#define WL_P2P_ON() 0
#define WL_MCHAN_ON() 0
#define WL_TDLS_ON() 0
#define WL_MCNX_ON() 0
#define WL_PROT_ON() 0
#define WL_TBTT_ON() 0
#define WL_PWRSEL_ON() 0
#define WL_L2FILTER_ON() 0
#define WL_MQ_ON() 0
#define WL_P2PO_ON() 0
#define WL_TXBF_ON() 0
#define WL_CHANLOG_ON() 0
#define WL_AMPDU_UPDN(args)
#define WL_AMPDU_RX(args)
#define WL_AMPDU_ERR(args)
#define WL_AMPDU_TX(args)
#define WL_AMPDU_CTL(args)
#define WL_AMPDU_HW(args)
#define WL_AMPDU_HWTXS(args)
#define WL_AMPDU_HWDBG(args)
#define WL_AMPDU_STAT(args)
#define WL_AMPDU_ERR_ON() 0
#define WL_AMPDU_HW_ON() 0
#define WL_AMPDU_HWTXS_ON() 0
#define WL_WNM_ON() 0
#endif /* LINUX_POSTMOGRIFY_REMOVAL */
#define WL_APSTA_UPDN(args)
#define WL_APSTA_RX(args)
#ifdef WLMSG_WSEC
#define WL_WSEC(args) WL_PRINT(args)
#define WL_WSEC_DUMP(args) WL_PRINT(args)
#else
#define WL_WSEC(args)
#define WL_WSEC_DUMP(args)
#endif
#define WL_PCIE(args) do {if (wl_msg_level2 & WL_PCIE_VAL) WL_PRINT(args);} while (0)
#define WL_PCIE_ON() (wl_msg_level2 & WL_PCIE_VAL)
#endif
extern uint32 wl_msg_level;
extern uint32 wl_msg_level2;
#endif /* _wl_dbg_h_ */
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<title>ZINSZ-Funktion</title>
<meta charset="utf-8" />
<meta name="description" content="" />
<link type="text/css" rel="stylesheet" href="../editor.css" />
<script type="text/javascript" src="../callback.js"></script>
<script type="text/javascript" src="../search/js/page-search.js"></script>
</head>
<body>
<div class="mainpart">
<div class="search-field">
<input id="search" class="searchBar" placeholder="Suche" type="text" onkeypress="doSearch(event)">
</div>
<h1>ZINSZ-Funktion</h1>
<p>Die Funktion <b>ZINSZ</b> gehört zur Gruppe der Finanzmathematischen Funktionen. Sie gibt die Zinszahlung einer Investition für die angegebene Periode zurück, ausgehend von regelmäßigen, konstanten Zahlungen und einem konstanten Zinssatz.</p>
<p>Die Formelsyntax der Funktion <b>ZINSZ</b> ist:</p>
<p style="text-indent: 150px;"><b><em>ZINSZ(Zins;Zr;Zzr;Bw;[Zw];[F])</em></b></p>
<p><em>Dabei gilt:</em></p>
<p style="text-indent: 50px;"><b><em>Zins</em></b> ist die Effektivverzinsung für die Investition.</p>
<p style="text-indent: 50px;"><b><em>Zr</em></b> der Zeitraum, für den Sie die Zinsen berechnen möchten. Der Wert muss zwischen <b><em>1</em></b> und <b><em>Zzr</em></b> liegen.</p>
<p style="text-indent: 50px;"><b><em>Zzr</em></b> ist die Gesamtanzahl der Zahlungszeiträume.</p>
<p style="text-indent: 50px;"><b><em>Bw</em></b> ist der Barwert oder der heutige Gesamtwert einer Reihe zukünftiger Zahlungen.</p>
<p style="text-indent: 50px;"><b><em>Zw</em></b> ist ein zukünftiger Wert (d. h. ein Restguthaben, das übrigbleibt, nachdem die letzte Zahlung getätigt wurde). Dieses Argument ist optional. Fehlt das Argument <b><em>Zw</em></b>, wird es als 0 (Null) angenommen.</p>
<p style="text-indent: 50px;"><b><em>F</em></b> gibt an, wann die Zahlungen fällig sind. Dieses Argument ist optional. Fehlt das Argument oder ist auf 0 festgelegt, nimmt die Funktion an, dass die Zahlungen am Ende der Periode fällig sind. Ist <b><em>F</em></b> mit 1 angegeben, sind die Zahlungen zum Anfang der Periode fällig.</p>
<p class="note"><b>Hinweis:</b> für alle Argumente werden die Beträge, die Sie zahlen, beispielsweise Einlagen für Sparguthaben oder andere Abhebungen, durch negative Zahlen dargestellt. Beträge, die Sie erhalten, beispielsweise Dividendenzahlungen und andere Einlagen, werden durch positive Zahlen dargestellt. Sie sollten unbedingt darauf achten, dass Sie für <em>Zins</em> und <em>Zzr</em> zueinander passende Zeiteinheiten verwenden. Verwenden Sie beispielsweise bei monatliche Zahlungen N%/12 für <em>Zins</em> und N*12 für <em>Zzrn,</em> für vierteljährliche Zahlungen N%/4 für <em>Zins</em> and N*4 für <em>Zzr</em> und für jährliche Zahlungen N% für <em>Zins</em> und N für <em>Zzr</em>.</p>
<p>Die Argumente werden manuell eingegeben oder sind in die Zelle eingeschlossen, auf die Sie Bezug nehmen.</p>
<p>Anwendung der Funktion <b>ZINSZ</b>.</p>
<ol>
<li>Wählen Sie die gewünschte Zelle für die Ergebnisanzeige aus.</li>
<li>Klicken Sie auf das Symbol <b>Funktion einfügen</b> <img alt="Funktion einfügen" src="../images/insertfunction.png" /> auf der oberen Symbolleiste <br />oder klicken Sie mit der rechten Maustaste in die gewünschte Zelle und wählen Sie die Option <b>Funktion einfügen</b> aus dem Kontextenü aus <br />oder klicken Sie auf das Symbol <img alt="Funktion" src="../images/function.png" /> auf der Formelleiste.</li>
<li>Wählen Sie die Gruppe <b>Finanzmathematische</b> Funktionen aus der Liste aus.</li>
<li>Klicken Sie auf die Funktion <b>ZINSZ</b>.</li>
<li>Geben Sie die erforderlichen Argumente ein und trennen Sie diese durch Kommas.</li>
<li>Drücken Sie die <b>Eingabetaste</b>.</li>
</ol>
<p>Das Ergebnis wird in der gewählten Zelle angezeigt.</p>
<p style="text-indent: 150px;"><img alt="ZINSZ-Funktion" src="../images/ipmt.png" /></p>
</div>
</body>
</html> | {
"pile_set_name": "Github"
} |
<?php
/**
* @file
* Search query extender and helper functions.
*/
/**
* Do a query on the full-text search index for a word or words.
*
* This function is normally only called by each module that supports the
* indexed search (and thus, implements hook_update_index()).
*
* Results are retrieved in two logical passes. However, the two passes are
* joined together into a single query. And in the case of most simple
* queries the second pass is not even used.
*
* The first pass selects a set of all possible matches, which has the benefit
* of also providing the exact result set for simple "AND" or "OR" searches.
*
* The second portion of the query further refines this set by verifying
* advanced text conditions (such as negative or phrase matches).
*
* The used query object has the tag 'search_$module' and can be further
* extended with hook_query_alter().
*/
class SearchQuery extends SelectQueryExtender {
/**
* The search query that is used for searching.
*
* @var string
*/
protected $searchExpression;
/**
* Type of search (search module).
*
* This maps to the value of the type column in search_index, and is equal
* to the machine-readable name of the module that implements
* hook_search_info().
*
* @var string
*/
protected $type;
/**
* Positive and negative search keys.
*
* @var array
*/
protected $keys = array('positive' => array(), 'negative' => array());
/**
* Indicates whether the first pass query requires complex conditions (LIKE).
*
* @var boolean.
*/
protected $simple = TRUE;
/**
* Conditions that are used for exact searches.
*
* This is always used for the second pass query but not for the first pass,
* unless $this->simple is FALSE.
*
* @var DatabaseCondition
*/
protected $conditions;
/**
* Indicates how many matches for a search query are necessary.
*
* @var int
*/
protected $matches = 0;
/**
* Array of search words.
*
* These words have to match against {search_index}.word.
*
* @var array
*/
protected $words = array();
/**
* Multiplier for the normalized search score.
*
* This value is calculated by the first pass query and multiplied with the
* actual score of a specific word to make sure that the resulting calculated
* score is between 0 and 1.
*
* @var float
*/
protected $normalize;
/**
* Indicates whether the first pass query has been executed.
*
* @var boolean
*/
protected $executedFirstPass = FALSE;
/**
* Stores score expressions.
*
* @var array
*
* @see addScore()
*/
protected $scores = array();
/**
* Stores arguments for score expressions.
*
* @var array
*/
protected $scoresArguments = array();
/**
* Stores multipliers for score expressions.
*
* @var array
*/
protected $multiply = array();
/**
* Whether or not search expressions were ignored.
*
* The maximum number of AND/OR combinations exceeded can be configured to
* avoid Denial-of-Service attacks. Expressions beyond the limit are ignored.
*
* @var boolean
*/
protected $expressionsIgnored = FALSE;
/**
* Sets up the search query expression.
*
* @param $query
* A search query string, which can contain options.
* @param $module
* The search module. This maps to {search_index}.type in the database.
*
* @return
* The SearchQuery object.
*/
public function searchExpression($expression, $module) {
$this->searchExpression = $expression;
$this->type = $module;
// Add a search_* tag. This needs to be added before any preExecute methods
// for decorated queries are called, as $this->prepared will be set to TRUE
// and tags added in the execute method will never get used. For example,
// if $query is extended by 'SearchQuery' then 'PagerDefault', the
// search-specific tag will be added too late (when preExecute() has
// already been called from the PagerDefault extender), and as a
// consequence will not be available to hook_query_alter() implementations,
// nor will the correct hook_query_TAG_alter() implementations get invoked.
// See node_search_execute().
$this->addTag('search_' . $module);
return $this;
}
/**
* Applies a search option and removes it from the search query string.
*
* These options are in the form option:value,value2,value3.
*
* @param $option
* Name of the option.
* @param $column
* Name of the database column to which the value should be applied.
*
* @return
* TRUE if a value for that option was found, FALSE if not.
*/
public function setOption($option, $column) {
if ($values = search_expression_extract($this->searchExpression, $option)) {
$or = db_or();
foreach (explode(',', $values) as $value) {
$or->condition($column, $value);
}
$this->condition($or);
$this->searchExpression = search_expression_insert($this->searchExpression, $option);
return TRUE;
}
return FALSE;
}
/**
* Parses the search query into SQL conditions.
*
* We build two queries that match the dataset bodies.
*/
protected function parseSearchExpression() {
// Matchs words optionally prefixed by a dash. A word in this case is
// something between two spaces, optionally quoted.
preg_match_all('/ (-?)("[^"]+"|[^" ]+)/i', ' ' . $this->searchExpression , $keywords, PREG_SET_ORDER);
if (count($keywords) == 0) {
return;
}
// Classify tokens.
$or = FALSE;
$warning = '';
$limit_combinations = variable_get('search_and_or_limit', 7);
// The first search expression does not count as AND.
$and_count = -1;
$or_count = 0;
foreach ($keywords as $match) {
if ($or_count && $and_count + $or_count >= $limit_combinations) {
// Ignore all further search expressions to prevent Denial-of-Service
// attacks using a high number of AND/OR combinations.
$this->expressionsIgnored = TRUE;
break;
}
$phrase = FALSE;
// Strip off phrase quotes.
if ($match[2]{0} == '"') {
$match[2] = substr($match[2], 1, -1);
$phrase = TRUE;
$this->simple = FALSE;
}
// Simplify keyword according to indexing rules and external
// preprocessors. Use same process as during search indexing, so it
// will match search index.
$words = search_simplify($match[2]);
// Re-explode in case simplification added more words, except when
// matching a phrase.
$words = $phrase ? array($words) : preg_split('/ /', $words, -1, PREG_SPLIT_NO_EMPTY);
// Negative matches.
if ($match[1] == '-') {
$this->keys['negative'] = array_merge($this->keys['negative'], $words);
}
// OR operator: instead of a single keyword, we store an array of all
// OR'd keywords.
elseif ($match[2] == 'OR' && count($this->keys['positive'])) {
$last = array_pop($this->keys['positive']);
// Starting a new OR?
if (!is_array($last)) {
$last = array($last);
}
$this->keys['positive'][] = $last;
$or = TRUE;
$or_count++;
continue;
}
// AND operator: implied, so just ignore it.
elseif ($match[2] == 'AND' || $match[2] == 'and') {
$warning = $match[2];
continue;
}
// Plain keyword.
else {
if ($match[2] == 'or') {
$warning = $match[2];
}
if ($or) {
// Add to last element (which is an array).
$this->keys['positive'][count($this->keys['positive']) - 1] = array_merge($this->keys['positive'][count($this->keys['positive']) - 1], $words);
}
else {
$this->keys['positive'] = array_merge($this->keys['positive'], $words);
$and_count++;
}
}
$or = FALSE;
}
// Convert keywords into SQL statements.
$this->conditions = db_and();
$simple_and = FALSE;
$simple_or = FALSE;
// Positive matches.
foreach ($this->keys['positive'] as $key) {
// Group of ORed terms.
if (is_array($key) && count($key)) {
$simple_or = TRUE;
$any = FALSE;
$queryor = db_or();
foreach ($key as $or) {
list($num_new_scores) = $this->parseWord($or);
$any |= $num_new_scores;
$queryor->condition('d.data', "% $or %", 'LIKE');
}
if (count($queryor)) {
$this->conditions->condition($queryor);
// A group of OR keywords only needs to match once.
$this->matches += ($any > 0);
}
}
// Single ANDed term.
else {
$simple_and = TRUE;
list($num_new_scores, $num_valid_words) = $this->parseWord($key);
$this->conditions->condition('d.data', "% $key %", 'LIKE');
if (!$num_valid_words) {
$this->simple = FALSE;
}
// Each AND keyword needs to match at least once.
$this->matches += $num_new_scores;
}
}
if ($simple_and && $simple_or) {
$this->simple = FALSE;
}
// Negative matches.
foreach ($this->keys['negative'] as $key) {
$this->conditions->condition('d.data', "% $key %", 'NOT LIKE');
$this->simple = FALSE;
}
if ($warning == 'or') {
drupal_set_message(t('Search for either of the two terms with uppercase <strong>OR</strong>. For example, <strong>cats OR dogs</strong>.'));
}
}
/**
* Helper function for parseQuery().
*/
protected function parseWord($word) {
$num_new_scores = 0;
$num_valid_words = 0;
// Determine the scorewords of this word/phrase.
$split = explode(' ', $word);
foreach ($split as $s) {
$num = is_numeric($s);
if ($num || drupal_strlen($s) >= variable_get('minimum_word_size', 3)) {
if (!isset($this->words[$s])) {
$this->words[$s] = $s;
$num_new_scores++;
}
$num_valid_words++;
}
}
// Return matching snippet and number of added words.
return array($num_new_scores, $num_valid_words);
}
/**
* Executes the first pass query.
*
* This can either be done explicitly, so that additional scores and
* conditions can be applied to the second pass query, or implicitly by
* addScore() or execute().
*
* @return
* TRUE if search items exist, FALSE if not.
*/
public function executeFirstPass() {
$this->parseSearchExpression();
if (count($this->words) == 0) {
form_set_error('keys', format_plural(variable_get('minimum_word_size', 3), 'You must include at least one positive keyword with 1 character or more.', 'You must include at least one positive keyword with @count characters or more.'));
return FALSE;
}
if ($this->expressionsIgnored) {
drupal_set_message(t('Your search used too many AND/OR expressions. Only the first @count terms were included in this search.', array('@count' => variable_get('search_and_or_limit', 7))), 'warning');
}
$this->executedFirstPass = TRUE;
if (!empty($this->words)) {
$or = db_or();
foreach ($this->words as $word) {
$or->condition('i.word', $word);
}
$this->condition($or);
}
// Build query for keyword normalization.
$this->join('search_total', 't', 'i.word = t.word');
$this
->condition('i.type', $this->type)
->groupBy('i.type')
->groupBy('i.sid')
->having('COUNT(*) >= :matches', array(':matches' => $this->matches));
// Clone the query object to do the firstPass query;
$first = clone $this->query;
// For complex search queries, add the LIKE conditions to the first pass query.
if (!$this->simple) {
$first->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type');
$first->condition($this->conditions);
}
// Calculate maximum keyword relevance, to normalize it.
$first->addExpression('SUM(i.score * t.count)', 'calculated_score');
$this->normalize = $first
->range(0, 1)
->orderBy('calculated_score', 'DESC')
->execute()
->fetchField();
if ($this->normalize) {
return TRUE;
}
return FALSE;
}
/**
* Adds a custom score expression to the search query.
*
* Score expressions are used to order search results. If no calls to
* addScore() have taken place, a default keyword relevance score will be
* used. However, if at least one call to addScore() has taken place, the
* keyword relevance score is not automatically added.
*
* Note that you must use this method to add ordering to your searches, and
* not call orderBy() directly, when using the SearchQuery extender. This is
* because of the two-pass system the SearchQuery class uses to normalize
* scores.
*
* @param $score
* The score expression, which should evaluate to a number between 0 and 1.
* The string 'i.relevance' in a score expression will be replaced by a
* measure of keyword relevance between 0 and 1.
* @param $arguments
* Query arguments needed to provide values to the score expression.
* @param $multiply
* If set, the score is multiplied with this value. However, all scores
* with multipliers are then divided by the total of all multipliers, so
* that overall, the normalization is maintained.
*
* @return object
* The updated query object.
*/
public function addScore($score, $arguments = array(), $multiply = FALSE) {
if ($multiply) {
$i = count($this->multiply);
// Modify the score expression so it is multiplied by the multiplier,
// with a divisor to renormalize.
$score = "CAST(:multiply_$i AS DECIMAL) * COALESCE(( " . $score . "), 0) / CAST(:total_$i AS DECIMAL)";
// Add an argument for the multiplier. The :total_$i argument is taken
// care of in the execute() method, which is when the total divisor is
// calculated.
$arguments[':multiply_' . $i] = $multiply;
$this->multiply[] = $multiply;
}
$this->scores[] = $score;
$this->scoresArguments += $arguments;
return $this;
}
/**
* Executes the search.
*
* If not already done, this executes the first pass query. Then the complex
* conditions are applied to the query including score expressions and
* ordering.
*
* @return
* FALSE if the first pass query returned no results, and a database result
* set if there were results.
*/
public function execute()
{
if (!$this->executedFirstPass) {
$this->executeFirstPass();
}
if (!$this->normalize) {
return new DatabaseStatementEmpty();
}
// Add conditions to query.
$this->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type');
$this->condition($this->conditions);
if (empty($this->scores)) {
// Add default score.
$this->addScore('i.relevance');
}
if (count($this->multiply)) {
// Re-normalize scores with multipliers by dividing by the total of all
// multipliers. The expressions were altered in addScore(), so here just
// add the arguments for the total.
$i = 0;
$sum = array_sum($this->multiply);
foreach ($this->multiply as $total) {
$this->scoresArguments[':total_' . $i] = $sum;
$i++;
}
}
// Replace the pseudo-expression 'i.relevance' with a measure of keyword
// relevance in all score expressions, using string replacement. Careful
// though! If you just print out a float, some locales use ',' as the
// decimal separator in PHP, while SQL always uses '.'. So, make sure to
// set the number format correctly.
$relevance = number_format((1.0 / $this->normalize), 10, '.', '');
$this->scores = str_replace('i.relevance', '(' . $relevance . ' * i.score * t.count)', $this->scores);
// Add all scores together to form a query field.
$this->addExpression('SUM(' . implode(' + ', $this->scores) . ')', 'calculated_score', $this->scoresArguments);
// If an order has not yet been set for this query, add a default order
// that sorts by the calculated sum of scores.
if (count($this->getOrderBy()) == 0) {
$this->orderBy('calculated_score', 'DESC');
}
// Add useful metadata.
$this
->addMetaData('normalize', $this->normalize)
->fields('i', array('type', 'sid'));
return $this->query->execute();
}
/**
* Builds the default count query for SearchQuery.
*
* Since SearchQuery always uses GROUP BY, we can default to a subquery. We
* also add the same conditions as execute() because countQuery() is called
* first.
*/
public function countQuery() {
// Clone the inner query.
$inner = clone $this->query;
// Add conditions to query.
$inner->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type');
$inner->condition($this->conditions);
// Remove existing fields and expressions, they are not needed for a count
// query.
$fields =& $inner->getFields();
$fields = array();
$expressions =& $inner->getExpressions();
$expressions = array();
// Add the sid as the only field and count them as a subquery.
$count = db_select($inner->fields('i', array('sid')), NULL, array('target' => 'slave'));
// Add the COUNT() expression.
$count->addExpression('COUNT(*)');
return $count;
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 1990 The Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* @(#)stdio.h 5.3 (Berkeley) 3/15/86
*/
/*
* NB: to fit things in six character monocase externals, the
* stdio code uses the prefix `__s' for stdio objects, typically
* followed by a three-character attempt at a mnemonic.
*/
#ifndef _STDIO_H_
#define _STDIO_H_
#include "_ansi.h"
#define _FSTDIO /* ``function stdio'' */
#define __need_size_t
#include <stddef.h>
#define __need___va_list
#include <stdarg.h>
/*
* <sys/reent.h> defines __FILE, _fpos_t.
* They must be defined there because struct _reent needs them (and we don't
* want reent.h to include this file.
*/
#include <sys/reent.h>
#include <sys/types.h>
_BEGIN_STD_C
typedef __FILE FILE;
#ifdef __CYGWIN__
typedef _fpos64_t fpos_t;
#else
typedef _fpos_t fpos_t;
#ifdef __LARGE64_FILES
typedef _fpos64_t fpos64_t;
#endif
#endif /* !__CYGWIN__ */
#include <sys/stdio.h>
#define __SLBF 0x0001 /* line buffered */
#define __SNBF 0x0002 /* unbuffered */
#define __SRD 0x0004 /* OK to read */
#define __SWR 0x0008 /* OK to write */
/* RD and WR are never simultaneously asserted */
#define __SRW 0x0010 /* open for reading & writing */
#define __SEOF 0x0020 /* found EOF */
#define __SERR 0x0040 /* found error */
#define __SMBF 0x0080 /* _buf is from malloc */
#define __SAPP 0x0100 /* fdopen()ed in append mode - so must write to end */
#define __SSTR 0x0200 /* this is an sprintf/snprintf string */
#define __SOPT 0x0400 /* do fseek() optimisation */
#define __SNPT 0x0800 /* do not do fseek() optimisation */
#define __SOFF 0x1000 /* set iff _offset is in fact correct */
#define __SORD 0x2000 /* true => stream orientation (byte/wide) decided */
#if defined(__CYGWIN__)
# define __SCLE 0x4000 /* convert line endings CR/LF <-> NL */
#endif
#define __SL64 0x8000 /* is 64-bit offset large file */
/* _flags2 flags */
#define __SWID 0x2000 /* true => stream orientation wide, false => byte, only valid if __SORD in _flags is true */
/*
* The following three definitions are for ANSI C, which took them
* from System V, which stupidly took internal interface macros and
* made them official arguments to setvbuf(), without renaming them.
* Hence, these ugly _IOxxx names are *supposed* to appear in user code.
*
* Although these happen to match their counterparts above, the
* implementation does not rely on that (so these could be renumbered).
*/
#define _IOFBF 0 /* setvbuf should set fully buffered */
#define _IOLBF 1 /* setvbuf should set line buffered */
#define _IONBF 2 /* setvbuf should set unbuffered */
#ifndef NULL
#define NULL 0
#endif
#define EOF (-1)
#ifdef __BUFSIZ__
#define BUFSIZ __BUFSIZ__
#else
#define BUFSIZ 1024
#endif
#ifdef __FOPEN_MAX__
#define FOPEN_MAX __FOPEN_MAX__
#else
#define FOPEN_MAX 20
#endif
#ifdef __FILENAME_MAX__
#define FILENAME_MAX __FILENAME_MAX__
#else
#define FILENAME_MAX 1024
#endif
#ifdef __L_tmpnam__
#define L_tmpnam __L_tmpnam__
#else
#define L_tmpnam FILENAME_MAX
#endif
#ifndef __STRICT_ANSI__
#define P_tmpdir "/tmp"
#endif
#ifndef SEEK_SET
#define SEEK_SET 0 /* set file offset to offset */
#endif
#ifndef SEEK_CUR
#define SEEK_CUR 1 /* set file offset to current plus offset */
#endif
#ifndef SEEK_END
#define SEEK_END 2 /* set file offset to EOF plus offset */
#endif
#define TMP_MAX 26
#ifndef _REENT_ONLY
#define stdin (_REENT->_stdin)
#define stdout (_REENT->_stdout)
#define stderr (_REENT->_stderr)
#else /* _REENT_ONLY */
#define stdin (_impure_ptr->_stdin)
#define stdout (_impure_ptr->_stdout)
#define stderr (_impure_ptr->_stderr)
#endif /* _REENT_ONLY */
#define _stdin_r(x) ((x)->_stdin)
#define _stdout_r(x) ((x)->_stdout)
#define _stderr_r(x) ((x)->_stderr)
/*
* Functions defined in ANSI C standard.
*/
#ifndef __VALIST
#ifdef __GNUC__
#define __VALIST __gnuc_va_list
#else
#define __VALIST char*
#endif
#endif
FILE * _EXFUN(tmpfile, (void));
char * _EXFUN(tmpnam, (char *));
int _EXFUN(fclose, (FILE *));
int _EXFUN(fflush, (FILE *));
FILE * _EXFUN(freopen, (const char *, const char *, FILE *));
void _EXFUN(setbuf, (FILE *, char *));
int _EXFUN(setvbuf, (FILE *, char *, int, size_t));
int _EXFUN(fprintf, (FILE *, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 2, 3))));
int _EXFUN(fscanf, (FILE *, const char *, ...)
_ATTRIBUTE ((__format__ (__scanf__, 2, 3))));
int _EXFUN(printf, (const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 1, 2))));
int _EXFUN(scanf, (const char *, ...)
_ATTRIBUTE ((__format__ (__scanf__, 1, 2))));
int _EXFUN(sscanf, (const char *, const char *, ...)
_ATTRIBUTE ((__format__ (__scanf__, 2, 3))));
int _EXFUN(vfprintf, (FILE *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 2, 0))));
int _EXFUN(vprintf, (const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 1, 0))));
int _EXFUN(vsprintf, (char *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 2, 0))));
int _EXFUN(fgetc, (FILE *));
char * _EXFUN(fgets, (char *, int, FILE *));
int _EXFUN(fputc, (int, FILE *));
int _EXFUN(fputs, (const char *, FILE *));
int _EXFUN(getc, (FILE *));
int _EXFUN(getchar, (void));
char * _EXFUN(gets, (char *));
int _EXFUN(putc, (int, FILE *));
int _EXFUN(putchar, (int));
int _EXFUN(puts, (const char *));
int _EXFUN(ungetc, (int, FILE *));
size_t _EXFUN(fread, (_PTR, size_t _size, size_t _n, FILE *));
size_t _EXFUN(fwrite, (const _PTR , size_t _size, size_t _n, FILE *));
#ifdef _COMPILING_NEWLIB
int _EXFUN(fgetpos, (FILE *, _fpos_t *));
#else
int _EXFUN(fgetpos, (FILE *, fpos_t *));
#endif
int _EXFUN(fseek, (FILE *, long, int));
#ifdef _COMPILING_NEWLIB
int _EXFUN(fsetpos, (FILE *, const _fpos_t *));
#else
int _EXFUN(fsetpos, (FILE *, const fpos_t *));
#endif
long _EXFUN(ftell, ( FILE *));
void _EXFUN(rewind, (FILE *));
void _EXFUN(clearerr, (FILE *));
int _EXFUN(feof, (FILE *));
int _EXFUN(ferror, (FILE *));
void _EXFUN(perror, (const char *));
#ifndef _REENT_ONLY
FILE * _EXFUN(fopen, (const char *_name, const char *_type));
int _EXFUN(sprintf, (char *, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 2, 3))));
int _EXFUN(remove, (const char *));
int _EXFUN(rename, (const char *, const char *));
#endif
#if !defined(__STRICT_ANSI__) || defined(__USE_XOPEN2K)
#ifdef _COMPILING_NEWLIB
int _EXFUN(fseeko, (FILE *, _off_t, int));
_off_t _EXFUN(ftello, ( FILE *));
#else
int _EXFUN(fseeko, (FILE *, off_t, int));
off_t _EXFUN(ftello, ( FILE *));
#endif
#endif
#if !defined(__STRICT_ANSI__) || (__STDC_VERSION__ >= 199901L)
#ifndef _REENT_ONLY
int _EXFUN(asiprintf, (char **, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 2, 3))));
char * _EXFUN(asniprintf, (char *, size_t *, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 3, 4))));
char * _EXFUN(asnprintf, (char *, size_t *, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 3, 4))));
int _EXFUN(asprintf, (char **, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 2, 3))));
#ifndef diprintf
int _EXFUN(diprintf, (int, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 2, 3))));
#endif
int _EXFUN(fcloseall, (_VOID));
int _EXFUN(fiprintf, (FILE *, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 2, 3))));
int _EXFUN(fiscanf, (FILE *, const char *, ...)
_ATTRIBUTE ((__format__ (__scanf__, 2, 3))));
int _EXFUN(iprintf, (const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 1, 2))));
int _EXFUN(iscanf, (const char *, ...)
_ATTRIBUTE ((__format__ (__scanf__, 1, 2))));
int _EXFUN(siprintf, (char *, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 2, 3))));
int _EXFUN(siscanf, (const char *, const char *, ...)
_ATTRIBUTE ((__format__ (__scanf__, 2, 3))));
int _EXFUN(snprintf, (char *, size_t, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 3, 4))));
int _EXFUN(sniprintf, (char *, size_t, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 3, 4))));
char * _EXFUN(tempnam, (const char *, const char *));
int _EXFUN(vasiprintf, (char **, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 2, 0))));
char * _EXFUN(vasniprintf, (char *, size_t *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 3, 0))));
char * _EXFUN(vasnprintf, (char *, size_t *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 3, 0))));
int _EXFUN(vasprintf, (char **, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 2, 0))));
int _EXFUN(vdiprintf, (int, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 2, 0))));
int _EXFUN(vfiprintf, (FILE *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 2, 0))));
int _EXFUN(vfiscanf, (FILE *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__scanf__, 2, 0))));
int _EXFUN(vfscanf, (FILE *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__scanf__, 2, 0))));
int _EXFUN(viprintf, (const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 1, 0))));
int _EXFUN(viscanf, (const char *, __VALIST)
_ATTRIBUTE ((__format__ (__scanf__, 1, 0))));
int _EXFUN(vscanf, (const char *, __VALIST)
_ATTRIBUTE ((__format__ (__scanf__, 1, 0))));
int _EXFUN(vsiprintf, (char *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 2, 0))));
int _EXFUN(vsiscanf, (const char *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__scanf__, 2, 0))));
int _EXFUN(vsniprintf, (char *, size_t, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 3, 0))));
int _EXFUN(vsnprintf, (char *, size_t, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 3, 0))));
int _EXFUN(vsscanf, (const char *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__scanf__, 2, 0))));
#endif /* !_REENT_ONLY */
#endif /* !__STRICT_ANSI__ */
/*
* Routines in POSIX 1003.1:2001.
*/
#ifndef __STRICT_ANSI__
#ifndef _REENT_ONLY
FILE * _EXFUN(fdopen, (int, const char *));
#endif
int _EXFUN(fileno, (FILE *));
int _EXFUN(getw, (FILE *));
int _EXFUN(pclose, (FILE *));
FILE * _EXFUN(popen, (const char *, const char *));
int _EXFUN(putw, (int, FILE *));
void _EXFUN(setbuffer, (FILE *, char *, int));
int _EXFUN(setlinebuf, (FILE *));
int _EXFUN(getc_unlocked, (FILE *));
int _EXFUN(getchar_unlocked, (void));
void _EXFUN(flockfile, (FILE *));
int _EXFUN(ftrylockfile, (FILE *));
void _EXFUN(funlockfile, (FILE *));
int _EXFUN(putc_unlocked, (int, FILE *));
int _EXFUN(putchar_unlocked, (int));
#endif /* ! __STRICT_ANSI__ */
/*
* Routines in POSIX 1003.1:200x.
*/
#ifndef __STRICT_ANSI__
# ifndef _REENT_ONLY
# ifndef dprintf
int _EXFUN(dprintf, (int, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 2, 3))));
# endif
FILE * _EXFUN(fmemopen, (void *, size_t, const char *));
/* getdelim - see __getdelim for now */
/* getline - see __getline for now */
FILE * _EXFUN(open_memstream, (char **, size_t *));
#if defined (__CYGWIN__)
int _EXFUN(renameat, (int, const char *, int, const char *));
#endif
int _EXFUN(vdprintf, (int, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 2, 0))));
# endif
#endif
/*
* Recursive versions of the above.
*/
int _EXFUN(_asiprintf_r, (struct _reent *, char **, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 3, 4))));
char * _EXFUN(_asniprintf_r, (struct _reent *, char *, size_t *, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 4, 5))));
char * _EXFUN(_asnprintf_r, (struct _reent *, char *, size_t *, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 4, 5))));
int _EXFUN(_asprintf_r, (struct _reent *, char **, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 3, 4))));
int _EXFUN(_diprintf_r, (struct _reent *, int, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 3, 4))));
int _EXFUN(_dprintf_r, (struct _reent *, int, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 3, 4))));
int _EXFUN(_fclose_r, (struct _reent *, FILE *));
int _EXFUN(_fcloseall_r, (struct _reent *));
FILE * _EXFUN(_fdopen_r, (struct _reent *, int, const char *));
int _EXFUN(_fflush_r, (struct _reent *, FILE *));
int _EXFUN(_fgetc_r, (struct _reent *, FILE *));
char * _EXFUN(_fgets_r, (struct _reent *, char *, int, FILE *));
#ifdef _COMPILING_NEWLIB
int _EXFUN(_fgetpos_r, (struct _reent *, FILE *, _fpos_t *));
int _EXFUN(_fsetpos_r, (struct _reent *, FILE *, const _fpos_t *));
#else
int _EXFUN(_fgetpos_r, (struct _reent *, FILE *, fpos_t *));
int _EXFUN(_fsetpos_r, (struct _reent *, FILE *, const fpos_t *));
#endif
int _EXFUN(_fiprintf_r, (struct _reent *, FILE *, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 3, 4))));
int _EXFUN(_fiscanf_r, (struct _reent *, FILE *, const char *, ...)
_ATTRIBUTE ((__format__ (__scanf__, 3, 4))));
FILE * _EXFUN(_fmemopen_r, (struct _reent *, void *, size_t, const char *));
FILE * _EXFUN(_fopen_r, (struct _reent *, const char *, const char *));
FILE * _EXFUN(_freopen_r, (struct _reent *, const char *, const char *, FILE *));
int _EXFUN(_fprintf_r, (struct _reent *, FILE *, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 3, 4))));
int _EXFUN(_fpurge_r, (struct _reent *, FILE *));
int _EXFUN(_fputc_r, (struct _reent *, int, FILE *));
int _EXFUN(_fputs_r, (struct _reent *, const char *, FILE *));
size_t _EXFUN(_fread_r, (struct _reent *, _PTR, size_t _size, size_t _n, FILE *));
int _EXFUN(_fscanf_r, (struct _reent *, FILE *, const char *, ...)
_ATTRIBUTE ((__format__ (__scanf__, 3, 4))));
int _EXFUN(_fseek_r, (struct _reent *, FILE *, long, int));
int _EXFUN(_fseeko_r,(struct _reent *, FILE *, _off_t, int));
long _EXFUN(_ftell_r, (struct _reent *, FILE *));
_off_t _EXFUN(_ftello_r,(struct _reent *, FILE *));
void _EXFUN(_rewind_r, (struct _reent *, FILE *));
size_t _EXFUN(_fwrite_r, (struct _reent *, const _PTR , size_t _size, size_t _n, FILE *));
int _EXFUN(_getc_r, (struct _reent *, FILE *));
int _EXFUN(_getc_unlocked_r, (struct _reent *, FILE *));
int _EXFUN(_getchar_r, (struct _reent *));
int _EXFUN(_getchar_unlocked_r, (struct _reent *));
char * _EXFUN(_gets_r, (struct _reent *, char *));
int _EXFUN(_iprintf_r, (struct _reent *, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 2, 3))));
int _EXFUN(_iscanf_r, (struct _reent *, const char *, ...)
_ATTRIBUTE ((__format__ (__scanf__, 2, 3))));
FILE * _EXFUN(_open_memstream_r, (struct _reent *, char **, size_t *));
void _EXFUN(_perror_r, (struct _reent *, const char *));
int _EXFUN(_printf_r, (struct _reent *, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 2, 3))));
int _EXFUN(_putc_r, (struct _reent *, int, FILE *));
int _EXFUN(_putc_unlocked_r, (struct _reent *, int, FILE *));
int _EXFUN(_putchar_unlocked_r, (struct _reent *, int));
int _EXFUN(_putchar_r, (struct _reent *, int));
int _EXFUN(_puts_r, (struct _reent *, const char *));
int _EXFUN(_remove_r, (struct _reent *, const char *));
int _EXFUN(_rename_r, (struct _reent *,
const char *_old, const char *_new));
int _EXFUN(_scanf_r, (struct _reent *, const char *, ...)
_ATTRIBUTE ((__format__ (__scanf__, 2, 3))));
int _EXFUN(_siprintf_r, (struct _reent *, char *, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 3, 4))));
int _EXFUN(_siscanf_r, (struct _reent *, const char *, const char *, ...)
_ATTRIBUTE ((__format__ (__scanf__, 3, 4))));
int _EXFUN(_sniprintf_r, (struct _reent *, char *, size_t, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 4, 5))));
int _EXFUN(_snprintf_r, (struct _reent *, char *, size_t, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 4, 5))));
int _EXFUN(_sprintf_r, (struct _reent *, char *, const char *, ...)
_ATTRIBUTE ((__format__ (__printf__, 3, 4))));
int _EXFUN(_sscanf_r, (struct _reent *, const char *, const char *, ...)
_ATTRIBUTE ((__format__ (__scanf__, 3, 4))));
char * _EXFUN(_tempnam_r, (struct _reent *, const char *, const char *));
FILE * _EXFUN(_tmpfile_r, (struct _reent *));
char * _EXFUN(_tmpnam_r, (struct _reent *, char *));
int _EXFUN(_ungetc_r, (struct _reent *, int, FILE *));
int _EXFUN(_vasiprintf_r, (struct _reent *, char **, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 3, 0))));
char * _EXFUN(_vasniprintf_r, (struct _reent*, char *, size_t *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 4, 0))));
char * _EXFUN(_vasnprintf_r, (struct _reent*, char *, size_t *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 4, 0))));
int _EXFUN(_vasprintf_r, (struct _reent *, char **, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 3, 0))));
int _EXFUN(_vdiprintf_r, (struct _reent *, int, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 3, 0))));
int _EXFUN(_vdprintf_r, (struct _reent *, int, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 3, 0))));
int _EXFUN(_vfiprintf_r, (struct _reent *, FILE *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 3, 0))));
int _EXFUN(_vfiscanf_r, (struct _reent *, FILE *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__scanf__, 3, 0))));
int _EXFUN(_vfprintf_r, (struct _reent *, FILE *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 3, 0))));
int _EXFUN(_vfscanf_r, (struct _reent *, FILE *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__scanf__, 3, 0))));
int _EXFUN(_viprintf_r, (struct _reent *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 2, 0))));
int _EXFUN(_viscanf_r, (struct _reent *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__scanf__, 2, 0))));
int _EXFUN(_vprintf_r, (struct _reent *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 2, 0))));
int _EXFUN(_vscanf_r, (struct _reent *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__scanf__, 2, 0))));
int _EXFUN(_vsiprintf_r, (struct _reent *, char *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 3, 0))));
int _EXFUN(_vsiscanf_r, (struct _reent *, const char *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__scanf__, 3, 0))));
int _EXFUN(_vsniprintf_r, (struct _reent *, char *, size_t, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 4, 0))));
int _EXFUN(_vsnprintf_r, (struct _reent *, char *, size_t, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 4, 0))));
int _EXFUN(_vsprintf_r, (struct _reent *, char *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__printf__, 3, 0))));
int _EXFUN(_vsscanf_r, (struct _reent *, const char *, const char *, __VALIST)
_ATTRIBUTE ((__format__ (__scanf__, 3, 0))));
/* Other extensions. */
int _EXFUN(fpurge, (FILE *));
ssize_t _EXFUN(__getdelim, (char **, size_t *, int, FILE *));
ssize_t _EXFUN(__getline, (char **, size_t *, FILE *));
#ifdef __LARGE64_FILES
#if !defined(__CYGWIN__) || defined(_COMPILING_NEWLIB)
FILE * _EXFUN(fdopen64, (int, const char *));
FILE * _EXFUN(fopen64, (const char *, const char *));
FILE * _EXFUN(freopen64, (_CONST char *, _CONST char *, FILE *));
_off64_t _EXFUN(ftello64, (FILE *));
_off64_t _EXFUN(fseeko64, (FILE *, _off64_t, int));
int _EXFUN(fgetpos64, (FILE *, _fpos64_t *));
int _EXFUN(fsetpos64, (FILE *, const _fpos64_t *));
FILE * _EXFUN(tmpfile64, (void));
FILE * _EXFUN(_fdopen64_r, (struct _reent *, int, const char *));
FILE * _EXFUN(_fopen64_r, (struct _reent *,const char *, const char *));
FILE * _EXFUN(_freopen64_r, (struct _reent *, _CONST char *, _CONST char *, FILE *));
_off64_t _EXFUN(_ftello64_r, (struct _reent *, FILE *));
_off64_t _EXFUN(_fseeko64_r, (struct _reent *, FILE *, _off64_t, int));
int _EXFUN(_fgetpos64_r, (struct _reent *, FILE *, _fpos64_t *));
int _EXFUN(_fsetpos64_r, (struct _reent *, FILE *, const _fpos64_t *));
FILE * _EXFUN(_tmpfile64_r, (struct _reent *));
#endif /* !__CYGWIN__ */
#endif /* __LARGE64_FILES */
/*
* Routines internal to the implementation.
*/
int _EXFUN(__srget_r, (struct _reent *, FILE *));
int _EXFUN(__swbuf_r, (struct _reent *, int, FILE *));
/*
* Stdio function-access interface.
*/
#ifndef __STRICT_ANSI__
# ifdef __LARGE64_FILES
FILE *_EXFUN(funopen,(const _PTR __cookie,
int (*__readfn)(_PTR __c, char *__buf, int __n),
int (*__writefn)(_PTR __c, const char *__buf, int __n),
_fpos64_t (*__seekfn)(_PTR __c, _fpos64_t __off, int __whence),
int (*__closefn)(_PTR __c)));
FILE *_EXFUN(_funopen_r,(struct _reent *, const _PTR __cookie,
int (*__readfn)(_PTR __c, char *__buf, int __n),
int (*__writefn)(_PTR __c, const char *__buf, int __n),
_fpos64_t (*__seekfn)(_PTR __c, _fpos64_t __off, int __whence),
int (*__closefn)(_PTR __c)));
# else
FILE *_EXFUN(funopen,(const _PTR __cookie,
int (*__readfn)(_PTR __cookie, char *__buf, int __n),
int (*__writefn)(_PTR __cookie, const char *__buf, int __n),
fpos_t (*__seekfn)(_PTR __cookie, fpos_t __off, int __whence),
int (*__closefn)(_PTR __cookie)));
FILE *_EXFUN(_funopen_r,(struct _reent *, const _PTR __cookie,
int (*__readfn)(_PTR __cookie, char *__buf, int __n),
int (*__writefn)(_PTR __cookie, const char *__buf, int __n),
fpos_t (*__seekfn)(_PTR __cookie, fpos_t __off, int __whence),
int (*__closefn)(_PTR __cookie)));
# endif /* !__LARGE64_FILES */
# define fropen(__cookie, __fn) funopen(__cookie, __fn, (int (*)())0, \
(fpos_t (*)())0, (int (*)())0)
# define fwopen(__cookie, __fn) funopen(__cookie, (int (*)())0, __fn, \
(fpos_t (*)())0, (int (*)())0)
typedef ssize_t cookie_read_function_t(void *__cookie, char *__buf, size_t __n);
typedef ssize_t cookie_write_function_t(void *__cookie, const char *__buf,
size_t __n);
# ifdef __LARGE64_FILES
typedef int cookie_seek_function_t(void *__cookie, _off64_t *__off,
int __whence);
# else
typedef int cookie_seek_function_t(void *__cookie, off_t *__off, int __whence);
# endif /* !__LARGE64_FILES */
typedef int cookie_close_function_t(void *__cookie);
typedef struct
{
/* These four struct member names are dictated by Linux; hopefully,
they don't conflict with any macros. */
cookie_read_function_t *read;
cookie_write_function_t *write;
cookie_seek_function_t *seek;
cookie_close_function_t *close;
} cookie_io_functions_t;
FILE *_EXFUN(fopencookie,(void *__cookie,
const char *__mode, cookie_io_functions_t __functions));
FILE *_EXFUN(_fopencookie_r,(struct _reent *, void *__cookie,
const char *__mode, cookie_io_functions_t __functions));
#endif /* ! __STRICT_ANSI__ */
#ifndef __CUSTOM_FILE_IO__
/*
* The __sfoo macros are here so that we can
* define function versions in the C library.
*/
#define __sgetc_raw_r(__ptr, __f) (--(__f)->_r < 0 ? __srget_r(__ptr, __f) : (int)(*(__f)->_p++))
#ifdef __SCLE
/* For a platform with CR/LF, additional logic is required by
__sgetc_r which would otherwise simply be a macro; therefore we
use an inlined function. The function is only meant to be inlined
in place as used and the function body should never be emitted.
There are two possible means to this end when compiling with GCC,
one when compiling with a standard C99 compiler, and for other
compilers we're just stuck. At the moment, this issue only
affects the Cygwin target, so we'll most likely be using GCC. */
_ELIDABLE_INLINE int __sgetc_r(struct _reent *__ptr, FILE *__p);
_ELIDABLE_INLINE int __sgetc_r(struct _reent *__ptr, FILE *__p)
{
int __c = __sgetc_raw_r(__ptr, __p);
if ((__p->_flags & __SCLE) && (__c == '\r'))
{
int __c2 = __sgetc_raw_r(__ptr, __p);
if (__c2 == '\n')
__c = __c2;
else
ungetc(__c2, __p);
}
return __c;
}
#else
#define __sgetc_r(__ptr, __p) __sgetc_raw_r(__ptr, __p)
#endif
#ifdef _never /* __GNUC__ */
/* If this inline is actually used, then systems using coff debugging
info get hopelessly confused. 21sept93 [email protected]. */
_ELIDABLE_INLINE int __sputc_r(struct _reent *_ptr, int _c, FILE *_p) {
if (--_p->_w >= 0 || (_p->_w >= _p->_lbfsize && (char)_c != '\n'))
return (*_p->_p++ = _c);
else
return (__swbuf_r(_ptr, _c, _p));
}
#else
/*
* This has been tuned to generate reasonable code on the vax using pcc
*/
#define __sputc_raw_r(__ptr, __c, __p) \
(--(__p)->_w < 0 ? \
(__p)->_w >= (__p)->_lbfsize ? \
(*(__p)->_p = (__c)), *(__p)->_p != '\n' ? \
(int)*(__p)->_p++ : \
__swbuf_r(__ptr, '\n', __p) : \
__swbuf_r(__ptr, (int)(__c), __p) : \
(*(__p)->_p = (__c), (int)*(__p)->_p++))
#ifdef __SCLE
#define __sputc_r(__ptr, __c, __p) \
((((__p)->_flags & __SCLE) && ((__c) == '\n')) \
? __sputc_raw_r(__ptr, '\r', (__p)) : 0 , \
__sputc_raw_r((__ptr), (__c), (__p)))
#else
#define __sputc_r(__ptr, __c, __p) __sputc_raw_r(__ptr, __c, __p)
#endif
#endif
#define __sfeof(p) (((p)->_flags & __SEOF) != 0)
#define __sferror(p) (((p)->_flags & __SERR) != 0)
#define __sclearerr(p) ((void)((p)->_flags &= ~(__SERR|__SEOF)))
#define __sfileno(p) ((p)->_file)
#ifndef _REENT_SMALL
#define feof(p) __sfeof(p)
#define ferror(p) __sferror(p)
#define clearerr(p) __sclearerr(p)
#endif
#if 0 /*ndef __STRICT_ANSI__ - FIXME: must initialize stdio first, use fn */
#define fileno(p) __sfileno(p)
#endif
#ifndef __CYGWIN__
#ifndef lint
#define getc(fp) __sgetc_r(_REENT, fp)
#define putc(x, fp) __sputc_r(_REENT, x, fp)
#endif /* lint */
#endif /* __CYGWIN__ */
#ifndef __STRICT_ANSI__
/* fast always-buffered version, true iff error */
#define fast_putc(x,p) (--(p)->_w < 0 ? \
__swbuf_r(_REENT, (int)(x), p) == EOF : (*(p)->_p = (x), (p)->_p++, 0))
#define L_cuserid 9 /* posix says it goes in stdio.h :( */
#ifdef __CYGWIN__
#define L_ctermid 16
#endif
#endif
#endif /* !__CUSTOM_FILE_IO__ */
#define getchar() getc(stdin)
#define putchar(x) putc(x, stdout)
_END_STD_C
#endif /* _STDIO_H_ */
| {
"pile_set_name": "Github"
} |
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a{struct d<A{struct B{func a<g{func b<T where g.e:P{
| {
"pile_set_name": "Github"
} |
//! moment.js locale configuration
//! locale : kazakh (kk)
//! authors : Nurlan Rakhimzhanov : https://github.com/nurlan
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['moment'], factory) :
factory(global.moment)
}(this, function (moment) { 'use strict';
var suffixes = {
0: '-ші',
1: '-ші',
2: '-ші',
3: '-ші',
4: '-ші',
5: '-ші',
6: '-шы',
7: '-ші',
8: '-ші',
9: '-шы',
10: '-шы',
20: '-шы',
30: '-шы',
40: '-шы',
50: '-ші',
60: '-шы',
70: '-ші',
80: '-ші',
90: '-шы',
100: '-ші'
};
var kk = moment.defineLocale('kk', {
months : 'қаңтар_ақпан_наурыз_сәуір_мамыр_маусым_шілде_тамыз_қыркүйек_қазан_қараша_желтоқсан'.split('_'),
monthsShort : 'қаң_ақп_нау_сәу_мам_мау_шіл_там_қыр_қаз_қар_жел'.split('_'),
weekdays : 'жексенбі_дүйсенбі_сейсенбі_сәрсенбі_бейсенбі_жұма_сенбі'.split('_'),
weekdaysShort : 'жек_дүй_сей_сәр_бей_жұм_сен'.split('_'),
weekdaysMin : 'жк_дй_сй_ср_бй_жм_сн'.split('_'),
longDateFormat : {
LT : 'HH:mm',
LTS : 'HH:mm:ss',
L : 'DD.MM.YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY HH:mm',
LLLL : 'dddd, D MMMM YYYY HH:mm'
},
calendar : {
sameDay : '[Бүгін сағат] LT',
nextDay : '[Ертең сағат] LT',
nextWeek : 'dddd [сағат] LT',
lastDay : '[Кеше сағат] LT',
lastWeek : '[Өткен аптаның] dddd [сағат] LT',
sameElse : 'L'
},
relativeTime : {
future : '%s ішінде',
past : '%s бұрын',
s : 'бірнеше секунд',
m : 'бір минут',
mm : '%d минут',
h : 'бір сағат',
hh : '%d сағат',
d : 'бір күн',
dd : '%d күн',
M : 'бір ай',
MM : '%d ай',
y : 'бір жыл',
yy : '%d жыл'
},
ordinalParse: /\d{1,2}-(ші|шы)/,
ordinal : function (number) {
var a = number % 10,
b = number >= 100 ? 100 : null;
return number + (suffixes[number] || suffixes[a] || suffixes[b]);
},
week : {
dow : 1, // Monday is the first day of the week.
doy : 7 // The week that contains Jan 1st is the first week of the year.
}
});
return kk;
})); | {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@class NSData, NSDictionary, NSError, NSString, NSXMLParser;
@protocol NSXMLParserDelegate <NSObject>
@optional
- (void)parser:(NSXMLParser *)arg1 validationErrorOccurred:(NSError *)arg2;
- (void)parser:(NSXMLParser *)arg1 parseErrorOccurred:(NSError *)arg2;
- (NSData *)parser:(NSXMLParser *)arg1 resolveExternalEntityName:(NSString *)arg2 systemID:(NSString *)arg3;
- (void)parser:(NSXMLParser *)arg1 foundCDATA:(NSData *)arg2;
- (void)parser:(NSXMLParser *)arg1 foundComment:(NSString *)arg2;
- (void)parser:(NSXMLParser *)arg1 foundProcessingInstructionWithTarget:(NSString *)arg2 data:(NSString *)arg3;
- (void)parser:(NSXMLParser *)arg1 foundIgnorableWhitespace:(NSString *)arg2;
- (void)parser:(NSXMLParser *)arg1 foundCharacters:(NSString *)arg2;
- (void)parser:(NSXMLParser *)arg1 didEndMappingPrefix:(NSString *)arg2;
- (void)parser:(NSXMLParser *)arg1 didStartMappingPrefix:(NSString *)arg2 toURI:(NSString *)arg3;
- (void)parser:(NSXMLParser *)arg1 didEndElement:(NSString *)arg2 namespaceURI:(NSString *)arg3 qualifiedName:(NSString *)arg4;
- (void)parser:(NSXMLParser *)arg1 didStartElement:(NSString *)arg2 namespaceURI:(NSString *)arg3 qualifiedName:(NSString *)arg4 attributes:(NSDictionary *)arg5;
- (void)parser:(NSXMLParser *)arg1 foundExternalEntityDeclarationWithName:(NSString *)arg2 publicID:(NSString *)arg3 systemID:(NSString *)arg4;
- (void)parser:(NSXMLParser *)arg1 foundInternalEntityDeclarationWithName:(NSString *)arg2 value:(NSString *)arg3;
- (void)parser:(NSXMLParser *)arg1 foundElementDeclarationWithName:(NSString *)arg2 model:(NSString *)arg3;
- (void)parser:(NSXMLParser *)arg1 foundAttributeDeclarationWithName:(NSString *)arg2 forElement:(NSString *)arg3 type:(NSString *)arg4 defaultValue:(NSString *)arg5;
- (void)parser:(NSXMLParser *)arg1 foundUnparsedEntityDeclarationWithName:(NSString *)arg2 publicID:(NSString *)arg3 systemID:(NSString *)arg4 notationName:(NSString *)arg5;
- (void)parser:(NSXMLParser *)arg1 foundNotationDeclarationWithName:(NSString *)arg2 publicID:(NSString *)arg3 systemID:(NSString *)arg4;
- (void)parserDidEndDocument:(NSXMLParser *)arg1;
- (void)parserDidStartDocument:(NSXMLParser *)arg1;
@end
| {
"pile_set_name": "Github"
} |
FILE(GLOB Eigen_UmfPackSupport_SRCS "*.h")
INSTALL(FILES
${Eigen_UmfPackSupport_SRCS}
DESTINATION ${INCLUDE_INSTALL_DIR}/Eigen/src/UmfPackSupport COMPONENT Devel
)
| {
"pile_set_name": "Github"
} |
before1, before2 {
declaration: value;
&:nested1, & :nested2 {
declaration: value;
}
& :nested3, &:nested4 {
declaration: value;
}
}
before1, before2 {
declaration: value;
:nested1, &:nested2 {
declaration: value;
}
nested3, & nested4 {
declaration: value;
}
}
before1, before2 {
declaration: value;
&:nested1, :nested2 {
declaration: value;
}
& nested3, nested4 {
declaration: value;
}
}
.abc > .def {
&.selector {
property: value;
}
}
.abc > .def {
& .selector {
property: value;
}
}
.abc {
&+.selector {
property: value;
}
} | {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Jul 6 2018 12:02:43).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <SketchModel/MSBitmapLayer.h>
@interface MSBitmapLayer (DataApplicable)
- (void)applyData:(id)arg1 fromDataSupplier:(id)arg2 identifier:(id)arg3;
- (BOOL)canChangeBooleanOperation;
@end
| {
"pile_set_name": "Github"
} |
<Window x:Class="ExampleBrowser.Examples.TriangularizationDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:HelixToolkit="clr-namespace:HelixToolkit.Wpf;assembly=HelixToolkit.Wpf"
xmlns:triangularizationDemo="clr-namespace:ExampleBrowser.Examples.TriangularizationDemo"
Title="SimpleDemo" Height="480" Width="640">
<Window.DataContext>
<triangularizationDemo:MainViewModel/>
</Window.DataContext>
<Grid>
<!-- The HelixViewport3D supports camera manipulation, and can be used just like the Viewport3D -->
<HelixToolkit:HelixViewport3D ZoomExtentsWhenLoaded="True">
<!-- Remember to add light to the scene -->
<HelixToolkit:SunLight/>
<!-- The content of this visual is defined in MainViewModel.cs -->
<ModelVisual3D Content="{Binding Model}"/>
<!-- You can also add elements here in the xaml -->
<HelixToolkit:GridLinesVisual3D Width="8" Length="8" MinorDistance="1" MajorDistance="1" Thickness="0.01"/>
</HelixToolkit:HelixViewport3D>
</Grid>
</Window>
| {
"pile_set_name": "Github"
} |
/**
* Prim's algorithm is a greedy algorithm that finds a minimum
* spanning tree for a connected weighted undirected graph.
*
* @example
*
* var Prim = require('path-to-algorithms/src/graphs/spanning-trees/prim');
* var Graph = Prim.Graph;
* var Edge = Prim.Edge;
* var Vertex = Prim.Vertex;
*
* var graph, edges = [];
* edges.push(new Edge(new Vertex(0), new Vertex(1), 4));
* edges.push(new Edge(new Vertex(0), new Vertex(7), 8));
* edges.push(new Edge(new Vertex(1), new Vertex(7), 11));
* edges.push(new Edge(new Vertex(1), new Vertex(2), 8));
* edges.push(new Edge(new Vertex(2), new Vertex(8), 2));
* edges.push(new Edge(new Vertex(2), new Vertex(3), 7));
* edges.push(new Edge(new Vertex(2), new Vertex(5), 4));
* edges.push(new Edge(new Vertex(2), new Vertex(3), 7));
* edges.push(new Edge(new Vertex(3), new Vertex(4), 9));
* edges.push(new Edge(new Vertex(3), new Vertex(5), 14));
* edges.push(new Edge(new Vertex(4), new Vertex(5), 10));
* edges.push(new Edge(new Vertex(5), new Vertex(6), 2));
* edges.push(new Edge(new Vertex(6), new Vertex(8), 6));
* edges.push(new Edge(new Vertex(8), new Vertex(7), 7));
* graph = new Graph(edges, edges.length);
*
* // { edges:
* // [ { e: '1', v: 0, distance: 4 },
* // { e: '2', v: 8, distance: 2 },
* // { e: '3', v: 2, distance: 7 },
* // { e: '4', v: 3, distance: 9 },
* // { e: '5', v: 2, distance: 4 },
* // { e: '6', v: 5, distance: 2 },
* // { e: '7', v: 0, distance: 8 },
* // { e: '8', v: 7, distance: 7 } ],
* // nodesCount: 0 }
* var spanningTree = graph.prim();
*
* @module graphs/spanning-trees/prim
*/
(function (exports) {
'use strict';
var Heap = require('../../data-structures/heap').Heap;
exports.Vertex = require('../../data-structures/vertex').Vertex;
exports.Edge = require('../../data-structures/edge').Edge;
/**
* Graph.
*
* @constructor
* @public
* @param {Array} edges Array with graph edges.
* @param {Number} nodesCount Number of nodes in graph.
*/
exports.Graph = function (edges, nodesCount) {
this.edges = edges || [];
this.nodesCount = nodesCount || 0;
};
/**
* Executes Prim's algorithm and returns minimum spanning tree.
*
* @public
* @method
* @return {Graph} Graph which is the minimum spanning tree.
*/
exports.Graph.prototype.prim = (function () {
var queue;
/**
* Used for comparitions in the heap
*
* @private
* @param {Vertex} a First operand of the comparition.
* @param {Vertex} b Second operand of the comparition.
* @return {number} Number which which is equal, greater or
* less then zero and indicates whether the first vertex is
* "greater" than the second.
*/
function compareEdges(a, b) {
return b.distance - a.distance;
}
/**
* Initialize the algorithm.
*
* @private
*/
function init() {
queue = new Heap(compareEdges);
}
return function () {
init.call(this);
var inTheTree = {};
var startVertex = this.edges[0].e.id;
var spannigTree = [];
var parents = {};
var distances = {};
var current;
inTheTree[startVertex] = true;
queue.add({
node: startVertex,
distance: 0
});
const process = function (e) {
if (inTheTree[e.v.id] && inTheTree[e.e.id]) {
return;
}
var collection = queue.getCollection();
var node;
if (e.e.id === current) {
node = e.v.id;
} else if (e.v.id === current) {
node = e.e.id;
} else {
return;
}
for (var i = 0; i < collection.length; i += 1) {
if (collection[i].node === node) {
if (collection[i].distance > e.distance) {
queue.changeKey(i, {
node: node,
distance: e.distance
});
parents[node] = current;
distances[node] = e.distance;
}
return;
}
}
queue.add({
node: node,
distance: e.distance
});
parents[node] = current;
distances[node] = e.distance;
};
for (var i = 0; i < this.nodesCount - 1; i += 1) {
current = queue.extract().node;
inTheTree[current] = true;
this.edges.forEach(process);
}
for (var node in parents) {
spannigTree.push(
new exports.Edge(node, parents[node], distances[node]));
}
return new exports.Graph(spannigTree);
};
}());
})(typeof window === 'undefined' ? module.exports : window);
| {
"pile_set_name": "Github"
} |
module.exports = require('./dist/config')
| {
"pile_set_name": "Github"
} |
Generator of Nit extern classes to wrap Objective-C services.
# Description
_objcwrapper_ is a tool to help access Objective-C classes and methods from Nit.
It generates Nit code composed of extern classes and extern methods from the Objective-C FFI.
The code should be valid Nit, but it may need some tweaking by hand before use.
_objcwrapper_ takes as input preprocessed Objective-C header files.
This preprocessing is usually done by combinig (or piping) calls to:
`gcc -E`, `header_keeper` and `header_static`.
See the check rules in the Makefile for example preprocessing.
# Usage
1. Compile _objcwrapper_ with: `make`
2. Compile the wrapper `NSArray.nit` from the preprocessed header `NSArray.h` with:
~~~
bin/objcwrapper -o NSArray.h NSArray.h
~~~
3. Import the generated module as usual from any Nit program.
It is not recommended to modify the generated file directly,
but you can redef the generated classes from other modules.
# See also
_jwrapper_ is the inspiration for this tool.
It generate wrappers to access Java services from Nit.
| {
"pile_set_name": "Github"
} |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Peter Van der Beken <[email protected]>
* Allan Beaufour <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef nsIAttribute_h___
#define nsIAttribute_h___
#include "nsINode.h"
class nsDOMAttributeMap;
class nsIContent;
#define NS_IATTRIBUTE_IID \
{ 0x68b13198, 0x6d81, 0x4ab6, \
{ 0xb9, 0x98, 0xd0, 0xa4, 0x55, 0x82, 0x5f, 0xb1 } }
class nsIAttribute : public nsINode
{
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IATTRIBUTE_IID)
virtual void SetMap(nsDOMAttributeMap *aMap) = 0;
nsDOMAttributeMap *GetMap()
{
return mAttrMap;
}
nsINodeInfo *NodeInfo()
{
return mNodeInfo;
}
virtual nsIContent* GetContent() const = 0;
/**
* Called when our ownerElement is moved into a new document.
* Updates the nodeinfo of this node.
*/
virtual nsresult SetOwnerDocument(nsIDocument* aDocument) = 0;
protected:
#ifdef MOZILLA_INTERNAL_API
nsIAttribute(nsDOMAttributeMap *aAttrMap, nsINodeInfo *aNodeInfo)
: nsINode(aNodeInfo), mAttrMap(aAttrMap)
{
}
#endif //MOZILLA_INTERNAL_API
nsDOMAttributeMap *mAttrMap; // WEAK
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIAttribute, NS_IATTRIBUTE_IID)
#endif /* nsIAttribute_h___ */
| {
"pile_set_name": "Github"
} |
using System;
using System.Transactions;
using Abp.Data;
using Abp.Dependency;
using Abp.Domain.Uow;
using Abp.EntityFrameworkCore;
using Abp.Extensions;
using Abp.MultiTenancy;
using Microsoft.EntityFrameworkCore;
namespace Abp.Zero.EntityFrameworkCore
{
public abstract class AbpZeroDbMigrator<TDbContext> : IAbpZeroDbMigrator, ITransientDependency
where TDbContext : DbContext
{
private readonly IUnitOfWorkManager _unitOfWorkManager;
private readonly IDbPerTenantConnectionStringResolver _connectionStringResolver;
private readonly IDbContextResolver _dbContextResolver;
protected AbpZeroDbMigrator(
IUnitOfWorkManager unitOfWorkManager,
IDbPerTenantConnectionStringResolver connectionStringResolver,
IDbContextResolver dbContextResolver)
{
_unitOfWorkManager = unitOfWorkManager;
_connectionStringResolver = connectionStringResolver;
_dbContextResolver = dbContextResolver;
}
public virtual void CreateOrMigrateForHost()
{
CreateOrMigrateForHost(null);
}
public virtual void CreateOrMigrateForHost(Action<TDbContext> seedAction)
{
CreateOrMigrate(null, seedAction);
}
public virtual void CreateOrMigrateForTenant(AbpTenantBase tenant)
{
CreateOrMigrateForTenant(tenant, null);
}
public virtual void CreateOrMigrateForTenant(AbpTenantBase tenant, Action<TDbContext> seedAction)
{
if (tenant.ConnectionString.IsNullOrEmpty())
{
return;
}
CreateOrMigrate(tenant, seedAction);
}
protected virtual void CreateOrMigrate(AbpTenantBase tenant, Action<TDbContext> seedAction)
{
var args = new DbPerTenantConnectionStringResolveArgs(
tenant == null ? (int?) null : (int?) tenant.Id,
tenant == null ? MultiTenancySides.Host : MultiTenancySides.Tenant
);
args["DbContextType"] = typeof(TDbContext);
args["DbContextConcreteType"] = typeof(TDbContext);
var nameOrConnectionString = ConnectionStringHelper.GetConnectionString(
_connectionStringResolver.GetNameOrConnectionString(args)
);
using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.Suppress))
{
using (var dbContext = _dbContextResolver.Resolve<TDbContext>(nameOrConnectionString, null))
{
dbContext.Database.Migrate();
seedAction?.Invoke(dbContext);
_unitOfWorkManager.Current.SaveChanges();
uow.Complete();
}
}
}
}
}
| {
"pile_set_name": "Github"
} |
/*---------------------------------------------------------------------------*\
OneFLOW - LargeScale Multiphysics Scientific Simulation Environment
Copyright (C) 2017-2020 He Xin and the OneFLOW contributors.
-------------------------------------------------------------------------------
License
This file is part of OneFLOW.
OneFLOW is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OneFLOW 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 OneFLOW. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#pragma once
#include "HXDefine.h"
#include "Task.h"
BeginNameSpace( ONEFLOW )
class CReadFile : public Task
{
public:
CReadFile();
~CReadFile();
public:
void Run();
VoidFunc mainAction;
public:
void ServerRead();
void ServerRead( VoidFunc mainAction );
};
EndNameSpace | {
"pile_set_name": "Github"
} |
/**
* Select2 Portuguese (Portugal) translation
*/
(function ($) {
"use strict";
$.extend($.fn.select2.defaults, {
formatNoMatches: function () { return "Nenhum resultado encontrado"; },
formatInputTooShort: function (input, min) { var n = min - input.length; return "Introduza " + n + " caracter" + (n == 1 ? "" : "es"); },
formatInputTooLong: function (input, max) { var n = input.length - max; return "Apague " + n + " caracter" + (n == 1 ? "" : "es"); },
formatSelectionTooBig: function (limit) { return "Só é possível selecionar " + limit + " elemento" + (limit == 1 ? "" : "s"); },
formatLoadMore: function (pageNumber) { return "A carregar mais resultados..."; },
formatSearching: function () { return "A pesquisar..."; }
});
})(jQuery);
| {
"pile_set_name": "Github"
} |
//@flow
import React from 'react';
import { pick } from '../../libs/utils'
import { PropTypes } from '../../libs';
import BasePicker from './BasePicker'
import DateRangePanel from './panel/DateRangePanel'
import type { DateRangePickerProps } from './Types';
export default class DateRangePicker extends BasePicker {
static get propTypes() {
return Object.assign(
{},
{rangeSeparator: PropTypes.string},
BasePicker.propTypes,
// default value is been defined in ./constants file
pick(DateRangePanel.propTypes,
['value', 'isShowTime', 'shortcuts', 'firstDayOfWeek']))
}
static get defaultProps() {
let result: any = Object.assign({}, BasePicker.defaultProps)
return result;
}
constructor(props: DateRangePickerProps) {
super(props, 'daterange', {})
}
getFormatSeparator(){
return this.props.rangeSeparator
}
pickerPanel(state: any, props: DateRangePickerProps) {
let value = state.value
if (value instanceof Date) {
value = [value, null]
}
return (
<DateRangePanel
{...props}
value={value}
onPick={this.onPicked.bind(this)}
/>
)
}
}
| {
"pile_set_name": "Github"
} |
#import <Foundation/Foundation.h>
@interface PodsDummy_ZMJGanttChart_iOS9_3 : NSObject
@end
@implementation PodsDummy_ZMJGanttChart_iOS9_3
@end
| {
"pile_set_name": "Github"
} |
# This file is just a pointer to the file
#
# "Library/./maCalcDB/setAlgebra13Inequalities/ur_ab_7_1.pg"
#
# You may want to change your problem set to use that problem
# directly, especially if you want to make a copy of the problem
# for modification.
DOCUMENT();
includePGproblem("Library/./maCalcDB/setAlgebra13Inequalities/ur_ab_7_1.pg");
ENDDOCUMENT();
## These tags keep this problem from being added to the NPL database
##
## DBsubject('ZZZ-Inserted Text')
## DBchapter('ZZZ-Inserted Text')
## DBsection('ZZZ-Inserted Text')
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2019-2020 Unbounded Systems, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import should from "should";
import { k8sutils } from "@adpt/testutils";
import ld from "lodash";
import {
Kubeconfig
} from "../../src/k8s";
import { getKubectl, kubectlGet, kubectlOpManifest } from "../../src/k8s/kubectl";
import { labelKey, Manifest } from "../../src/k8s/manifest_support";
import { mkInstance } from "../run_minikube";
import { makeDeployId } from "../testlib";
const { deleteAll, getAll } = k8sutils;
describe("kubectl utility function tests", function () {
this.timeout(10 * 1000);
let kubeconfig: Kubeconfig;
let client: k8sutils.KubeClient;
const deployID = makeDeployId("kubectl");
before(async function () {
this.timeout(mkInstance.setupTimeoutMs);
this.slow(20 * 1000);
kubeconfig = await mkInstance.kubeconfig as Kubeconfig;
client = await mkInstance.client;
});
before(async function () {
this.timeout("10s");
await getKubectl();
});
afterEach(async function () {
this.timeout(20 * 1000);
if (client) {
await deleteAll("pods", { client, deployID });
await deleteAll("services", { client, deployID });
}
});
const origManifest: Manifest = {
apiVersion: "v1",
kind: "Pod",
metadata: {
name: "foo",
annotations: {
[labelKey("deployID")]: deployID
}
},
spec: {
containers: [{
name: "main",
image: "busybox",
command: ["sh", "-c", "Hello Kubectl Tests! && sleep 3600"]
}],
terminationGracePeriodSeconds: 0
}
};
async function createOrigResource() {
const result = await kubectlOpManifest("create", {
kubeconfig,
manifest: origManifest
});
should(result.stderr).empty();
should(result.stdout).match(/created/);
should(result.exitCode).equal(0);
const pods = await getAll("pods", { client, deployID });
should(pods).be.ok();
should(pods).length(1);
should(pods[0]).be.ok();
should(pods[0].metadata.name).equal(origManifest.metadata.name);
}
it("should create object by manifest and get by name", async () => {
await createOrigResource();
const result = await kubectlGet({
kubeconfig,
name: origManifest.metadata.name,
kind: origManifest.kind,
});
should(result).be.ok();
should(result.metadata).be.ok();
should(result.kind).equal(origManifest.kind);
should(result.metadata.name).equal(origManifest.metadata.name);
should(result.status).be.ok();
});
it("Should delete object by manifest", async () => {
await createOrigResource();
const result = await kubectlOpManifest("delete", {
kubeconfig,
manifest: origManifest
});
should(result.stderr).empty();
should(result.stdout).match(/deleted/);
should(result.exitCode).equal(0);
});
it("Should update object by manifest", async () => {
const origResult = await kubectlOpManifest("apply", {
kubeconfig,
manifest: origManifest
});
should(origResult.stderr).empty();
should(origResult.stdout).match(/created/);
should(origResult.exitCode).equal(0);
const origPods = await getAll("pods", { client, deployID });
should(origPods).be.ok();
should(origPods).length(1);
should(origPods[0]).be.ok();
should(origPods[0].metadata.name).equal(origManifest.metadata.name);
const newManifest = ld.cloneDeep(origManifest);
(newManifest.spec as any).containers[0].image = "alpine";
const result = await kubectlOpManifest("apply", {
kubeconfig,
manifest: newManifest
});
should(result.stderr).empty();
should(result.stdout).match(/configured/);
should(result.exitCode).equal(0);
const pods = await getAll("pods", { client, deployID });
should(pods).be.ok();
should(pods).length(1);
should(pods[0]).be.ok();
should(pods[0].metadata.name).equal(origManifest.metadata.name);
should(pods[0].spec).be.ok();
should(pods[0].spec.containers).length(1);
should(pods[0].spec.containers[0]).be.ok();
should(pods[0].spec.containers[0].image).equal((newManifest.spec as any).containers[0].image);
});
});
| {
"pile_set_name": "Github"
} |
=pod
=head1 NAME
openssl-rsautl,
rsautl - RSA utility
=head1 SYNOPSIS
B<openssl> B<rsautl>
[B<-help>]
[B<-in file>]
[B<-out file>]
[B<-inkey file>]
[B<-keyform PEM|DER|ENGINE>]
[B<-pubin>]
[B<-certin>]
[B<-sign>]
[B<-verify>]
[B<-encrypt>]
[B<-decrypt>]
[B<-rand file...>]
[B<-writerand file>]
[B<-pkcs>]
[B<-ssl>]
[B<-raw>]
[B<-hexdump>]
[B<-asn1parse>]
=head1 DESCRIPTION
The B<rsautl> command can be used to sign, verify, encrypt and decrypt
data using the RSA algorithm.
=head1 OPTIONS
=over 4
=item B<-help>
Print out a usage message.
=item B<-in filename>
This specifies the input filename to read data from or standard input
if this option is not specified.
=item B<-out filename>
Specifies the output filename to write to or standard output by
default.
=item B<-inkey file>
The input key file, by default it should be an RSA private key.
=item B<-keyform PEM|DER|ENGINE>
The key format PEM, DER or ENGINE.
=item B<-pubin>
The input file is an RSA public key.
=item B<-certin>
The input is a certificate containing an RSA public key.
=item B<-sign>
Sign the input data and output the signed result. This requires
an RSA private key.
=item B<-verify>
Verify the input data and output the recovered data.
=item B<-encrypt>
Encrypt the input data using an RSA public key.
=item B<-decrypt>
Decrypt the input data using an RSA private key.
=item B<-rand file...>
A file or files containing random data used to seed the random number
generator.
Multiple files can be specified separated by an OS-dependent character.
The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for
all others.
=item [B<-writerand file>]
Writes random data to the specified I<file> upon exit.
This can be used with a subsequent B<-rand> flag.
=item B<-pkcs, -oaep, -ssl, -raw>
The padding to use: PKCS#1 v1.5 (the default), PKCS#1 OAEP,
special padding used in SSL v2 backwards compatible handshakes,
or no padding, respectively.
For signatures, only B<-pkcs> and B<-raw> can be used.
=item B<-hexdump>
Hex dump the output data.
=item B<-asn1parse>
Parse the ASN.1 output data, this is useful when combined with the
B<-verify> option.
=back
=head1 NOTES
B<rsautl> because it uses the RSA algorithm directly can only be
used to sign or verify small pieces of data.
=head1 EXAMPLES
Sign some data using a private key:
openssl rsautl -sign -in file -inkey key.pem -out sig
Recover the signed data
openssl rsautl -verify -in sig -inkey key.pem
Examine the raw signed data:
openssl rsautl -verify -in sig -inkey key.pem -raw -hexdump
0000 - 00 01 ff ff ff ff ff ff-ff ff ff ff ff ff ff ff ................
0010 - ff ff ff ff ff ff ff ff-ff ff ff ff ff ff ff ff ................
0020 - ff ff ff ff ff ff ff ff-ff ff ff ff ff ff ff ff ................
0030 - ff ff ff ff ff ff ff ff-ff ff ff ff ff ff ff ff ................
0040 - ff ff ff ff ff ff ff ff-ff ff ff ff ff ff ff ff ................
0050 - ff ff ff ff ff ff ff ff-ff ff ff ff ff ff ff ff ................
0060 - ff ff ff ff ff ff ff ff-ff ff ff ff ff ff ff ff ................
0070 - ff ff ff ff 00 68 65 6c-6c 6f 20 77 6f 72 6c 64 .....hello world
The PKCS#1 block formatting is evident from this. If this was done using
encrypt and decrypt the block would have been of type 2 (the second byte)
and random padding data visible instead of the 0xff bytes.
It is possible to analyse the signature of certificates using this
utility in conjunction with B<asn1parse>. Consider the self signed
example in certs/pca-cert.pem . Running B<asn1parse> as follows yields:
openssl asn1parse -in pca-cert.pem
0:d=0 hl=4 l= 742 cons: SEQUENCE
4:d=1 hl=4 l= 591 cons: SEQUENCE
8:d=2 hl=2 l= 3 cons: cont [ 0 ]
10:d=3 hl=2 l= 1 prim: INTEGER :02
13:d=2 hl=2 l= 1 prim: INTEGER :00
16:d=2 hl=2 l= 13 cons: SEQUENCE
18:d=3 hl=2 l= 9 prim: OBJECT :md5WithRSAEncryption
29:d=3 hl=2 l= 0 prim: NULL
31:d=2 hl=2 l= 92 cons: SEQUENCE
33:d=3 hl=2 l= 11 cons: SET
35:d=4 hl=2 l= 9 cons: SEQUENCE
37:d=5 hl=2 l= 3 prim: OBJECT :countryName
42:d=5 hl=2 l= 2 prim: PRINTABLESTRING :AU
....
599:d=1 hl=2 l= 13 cons: SEQUENCE
601:d=2 hl=2 l= 9 prim: OBJECT :md5WithRSAEncryption
612:d=2 hl=2 l= 0 prim: NULL
614:d=1 hl=3 l= 129 prim: BIT STRING
The final BIT STRING contains the actual signature. It can be extracted with:
openssl asn1parse -in pca-cert.pem -out sig -noout -strparse 614
The certificate public key can be extracted with:
openssl x509 -in test/testx509.pem -pubkey -noout >pubkey.pem
The signature can be analysed with:
openssl rsautl -in sig -verify -asn1parse -inkey pubkey.pem -pubin
0:d=0 hl=2 l= 32 cons: SEQUENCE
2:d=1 hl=2 l= 12 cons: SEQUENCE
4:d=2 hl=2 l= 8 prim: OBJECT :md5
14:d=2 hl=2 l= 0 prim: NULL
16:d=1 hl=2 l= 16 prim: OCTET STRING
0000 - f3 46 9e aa 1a 4a 73 c9-37 ea 93 00 48 25 08 b5 .F...Js.7...H%..
This is the parsed version of an ASN1 DigestInfo structure. It can be seen that
the digest used was md5. The actual part of the certificate that was signed can
be extracted with:
openssl asn1parse -in pca-cert.pem -out tbs -noout -strparse 4
and its digest computed with:
openssl md5 -c tbs
MD5(tbs)= f3:46:9e:aa:1a:4a:73:c9:37:ea:93:00:48:25:08:b5
which it can be seen agrees with the recovered value above.
=head1 SEE ALSO
L<dgst(1)>, L<rsa(1)>, L<genrsa(1)>
=head1 COPYRIGHT
Copyright 2000-2017 The OpenSSL Project Authors. All Rights Reserved.
Licensed under the OpenSSL license (the "License"). You may not use
this file except in compliance with the License. You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.
=cut
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2008-2013 Various Authors
* Copyright 2004 Timo Hirvonen
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CMUS_PATH_H
#define CMUS_PATH_H
const char *get_extension(const char *filename);
const char *path_basename(const char *path);
void path_strip(char *str);
char *path_absolute_cwd(const char *src, const char *cwd);
char *path_absolute(const char *src);
#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.
*/
package org.apache.druid.server.initialization;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
*/
public class CuratorDiscoveryConfig
{
@JsonProperty
private String path = "/druid/discovery";
public String getPath()
{
return path;
}
public boolean useDiscovery()
{
return path != 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.
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix mf: <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#> .
@prefix mfx: <http://jena.hpl.hp.com/2005/05/test-manifest-extra#> .
@prefix qt: <http://www.w3.org/2001/sw/DataAccess/tests/test-query#> .
<> rdf:type mf:Manifest ;
rdfs:label "Sub Query" ;
mf:entries
(
[ mf:name "Sub SELECT 1" ;
rdf:type mfx:TestQuery ;
mf:action
[ qt:query <sub-select-01.rq> ;
qt:data <data.ttl> ] ;
mf:result <sub-select-01.srx>
]
[ mf:name "Sub SELECT 2" ;
rdf:type mfx:TestQuery ;
mf:action
[ qt:query <sub-select-02.rq> ;
qt:data <data.ttl> ] ;
mf:result <sub-select-02.srx>
]
[ mf:name "Sub SELECT 3" ;
rdf:type mfx:TestQuery ;
mf:action
[ qt:query <sub-select-03.rq> ;
qt:data <data.ttl> ] ;
mf:result <sub-select-03.srx>
]
[ mf:name "Sub SELECT 4" ;
rdf:type mfx:TestQuery ;
mf:action
[ qt:query <sub-select-04.rq> ;
qt:data <data.ttl> ] ;
mf:result <sub-select-04.srx>
]
## Scoping related tests.
[ mf:name "graph-subquery-1.rq" ;
mf:action
[ qt:query <graph-subquery-1.rq> ;
qt:graphData <data-sq.ttl> ;
] ;
mf:result <graph-subquery-1.srj>
]
).
| {
"pile_set_name": "Github"
} |
#
# Copyright (C) 2010-2017 Samuel Abels
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from Exscript.stdlib import connection
from Exscript.stdlib import crypt
from Exscript.stdlib import file
from Exscript.stdlib import ipv4
from Exscript.stdlib import list
from Exscript.stdlib import string
from Exscript.stdlib import mysys
functions = {
'connection.authenticate': connection.authenticate,
'connection.authorize': connection.authorize,
'connection.auto_authorize': connection.auto_authorize,
'connection.autoinit': connection.autoinit,
'connection.close': connection.close,
'connection.exec': connection.exec_,
'connection.execline': connection.execline,
'connection.guess_os': connection.guess_os,
'connection.send': connection.send,
'connection.sendline': connection.sendline,
'connection.set_error': connection.set_error,
'connection.set_prompt': connection.set_prompt,
'connection.set_timeout': connection.set_timeout,
'connection.wait_for': connection.wait_for,
'crypt.otp': crypt.otp,
'file.chmod': file.chmod,
'file.clear': file.clear,
'file.exists': file.exists,
'file.mkdir': file.mkdir,
'file.read': file.read,
'file.rm': file.rm,
'file.write': file.write,
'ipv4.in_network': ipv4.in_network,
'ipv4.mask': ipv4.mask,
'ipv4.mask2pfxlen': ipv4.mask2pfxlen,
'ipv4.pfxlen2mask': ipv4.pfxlen2mask,
'ipv4.pfxmask': ipv4.pfxmask,
'ipv4.network': ipv4.network,
'ipv4.broadcast': ipv4.broadcast,
'ipv4.remote_ip': ipv4.remote_ip,
'list.new': list.new,
'list.get': list.get,
'list.length': list.length,
'list.unique': list.unique,
'string.replace': string.replace,
'string.split': string.split,
'string.tolower': string.tolower,
'string.toupper': string.toupper,
'sys.env': mysys.env,
'sys.exec': mysys.execute,
'sys.message': mysys.message,
'sys.wait': mysys.wait,
}
| {
"pile_set_name": "Github"
} |
/* Interface to GNU libc specific functions for version information.
Copyright (C) 1998, 1999, 2001 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#ifndef _GNU_LIBC_VERSION_H
#define _GNU_LIBC_VERSION_H 1
#include <features.h>
__BEGIN_DECLS
/* Return string describing release status of currently running GNU libc. */
extern const char *gnu_get_libc_release (void) __THROW;
/* Return string describing version of currently running GNU libc. */
extern const char *gnu_get_libc_version (void) __THROW;
__END_DECLS
#endif /* gnu/libc-version.h */
| {
"pile_set_name": "Github"
} |
/* Area: ffi_call, closure_call
Purpose: Check structure alignment of sint16.
Limitations: none.
PR: none.
Originator: <[email protected]> 20031203 */
/* { dg-do run } */
#include "ffitest.h"
typedef struct cls_struct_align {
unsigned char a;
signed short b;
unsigned char c;
} cls_struct_align;
cls_struct_align cls_struct_align_fn(struct cls_struct_align a1,
struct cls_struct_align a2)
{
struct cls_struct_align result;
result.a = a1.a + a2.a;
result.b = a1.b + a2.b;
result.c = a1.c + a2.c;
printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c);
return result;
}
static void
cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
void* userdata __UNUSED__)
{
struct cls_struct_align a1, a2;
a1 = *(struct cls_struct_align*)(args[0]);
a2 = *(struct cls_struct_align*)(args[1]);
*(cls_struct_align*)resp = cls_struct_align_fn(a1, a2);
}
int main (void)
{
ffi_cif cif;
void *code;
ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
void* args_dbl[5];
ffi_type* cls_struct_fields[4];
ffi_type cls_struct_type;
ffi_type* dbl_arg_types[5];
struct cls_struct_align g_dbl = { 12, 4951, 127 };
struct cls_struct_align f_dbl = { 1, 9320, 13 };
struct cls_struct_align res_dbl;
cls_struct_type.size = 0;
cls_struct_type.alignment = 0;
cls_struct_type.type = FFI_TYPE_STRUCT;
cls_struct_type.elements = cls_struct_fields;
cls_struct_fields[0] = &ffi_type_uchar;
cls_struct_fields[1] = &ffi_type_sshort;
cls_struct_fields[2] = &ffi_type_uchar;
cls_struct_fields[3] = NULL;
dbl_arg_types[0] = &cls_struct_type;
dbl_arg_types[1] = &cls_struct_type;
dbl_arg_types[2] = NULL;
CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type,
dbl_arg_types) == FFI_OK);
args_dbl[0] = &g_dbl;
args_dbl[1] = &f_dbl;
args_dbl[2] = NULL;
ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl);
/* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */
printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
/* { dg-output "\nres: 13 14271 140" } */
CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK);
res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl);
/* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */
printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c);
/* { dg-output "\nres: 13 14271 140" } */
exit(0);
}
| {
"pile_set_name": "Github"
} |
/*!
* jQuery UI Effects Blind 1.10.3
* http://jqueryui.com
*
* Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/blind-effect/
*
* Depends:
* jquery.ui.effect.js
*/
(function( $, undefined ) {
var rvertical = /up|down|vertical/,
rpositivemotion = /up|left|vertical|horizontal/;
$.effects.effect.blind = function( o, done ) {
// Create element
var el = $( this ),
props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
mode = $.effects.setMode( el, o.mode || "hide" ),
direction = o.direction || "up",
vertical = rvertical.test( direction ),
ref = vertical ? "height" : "width",
ref2 = vertical ? "top" : "left",
motion = rpositivemotion.test( direction ),
animation = {},
show = mode === "show",
wrapper, distance, margin;
// if already wrapped, the wrapper's properties are my property. #6245
if ( el.parent().is( ".ui-effects-wrapper" ) ) {
$.effects.save( el.parent(), props );
} else {
$.effects.save( el, props );
}
el.show();
wrapper = $.effects.createWrapper( el ).css({
overflow: "hidden"
});
distance = wrapper[ ref ]();
margin = parseFloat( wrapper.css( ref2 ) ) || 0;
animation[ ref ] = show ? distance : 0;
if ( !motion ) {
el
.css( vertical ? "bottom" : "right", 0 )
.css( vertical ? "top" : "left", "auto" )
.css({ position: "absolute" });
animation[ ref2 ] = show ? margin : distance + margin;
}
// start at 0 if we are showing
if ( show ) {
wrapper.css( ref, 0 );
if ( ! motion ) {
wrapper.css( ref2, margin + distance );
}
}
// Animate
wrapper.animate( animation, {
duration: o.duration,
easing: o.easing,
queue: false,
complete: function() {
if ( mode === "hide" ) {
el.hide();
}
$.effects.restore( el, props );
$.effects.removeWrapper( el );
done();
}
});
};
})(jQuery);
| {
"pile_set_name": "Github"
} |
#
# Text, formatting for JXDatePicker
#
JXDatePicker.linkFormat=Today is {0,date}
# Issue #945-swingx: force a default fallback here not the right thing to
# for locales which do not have a properties file. In that case the
# language defaults provide a better fit
#JXDatePicker.longFormat=EEE MM/dd/yyyy
#JXDatePicker.mediumFormat=MM/dd/yy
#JXDatePicker.shortFormat=MM/dd
JXDatePicker.numColumns=10
| {
"pile_set_name": "Github"
} |
# frozen_string_literal: true
require 'open-uri'
class PgpAnnotationjob
include Sidekiq::Worker
sidekiq_options queue: :pgp, retry: 5, unique: true
def perform()
puts "Running PgpAnnotationJob\n"
known_snps = {}
Snp.find_each do |s| known_snps[s.name] = true end
pgp_file = open('http://evidence.personalgenomes.org/download/latest/flat/latest-flat.tsv') {|f| f.readlines }
puts "got pgp file"
pgp_file.each do |pgp_entry|
puts pgp_entry
pgp_entry_array = pgp_entry.strip().split("\t")
snp_id = pgp_entry_array[7]
if snp_id == nil
snp_id = "NA"
puts "snp not found"
end
if known_snps.has_key?(snp_id.downcase)
puts "yes"
gene = pgp_entry_array[0]
qualified_impact = pgp_entry_array[4]
inheritance = pgp_entry_array[5]
summary = pgp_entry_array[-1]
trait = pgp_entry_array[37]
snp = Snp.find_by_name(snp_id)
annotation = PgpAnnotation.find_by_snp_id(snp.id)
if annotation == nil
annotation = PgpAnnotation.new()
annotation.snp_id = snp.id
end
# enter all the information here and update if needed, just to keep everything fresh
annotation.gene = gene
annotation.qualified_impact = qualified_impact
annotation.inheritance = inheritance
annotation.summary = summary
annotation.trait = trait
snp.ranking = snp.mendeley_paper.count + 2*snp.plos_paper.count + 5*snp.snpedia_paper.count + 2*snp.genome_gov_paper.count + 2*snp.pgp_annotations.count
if qualified_impact != "Insufficiently evaluated not reviewed" and qualified_impact != "Insufficiently evaluated pharmacogenetic"
annotation.save
snp.save()
end
end
end
end
end
| {
"pile_set_name": "Github"
} |
// Copyright (C) 2014 Internet Systems Consortium, Inc. ("ISC")
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
#include <config.h>
#include <dhcp_ddns/watch_socket.h>
#include <test_utils.h>
#include <gtest/gtest.h>
#include <sys/select.h>
#include <sys/ioctl.h>
#ifdef HAVE_SYS_FILIO_H
// FIONREAD is here on Solaris
#include <sys/filio.h>
#endif
using namespace std;
using namespace bundy;
using namespace bundy::dhcp_ddns;
namespace {
/// @brief Tests the basic functionality of WatchSocket.
TEST(WatchSocketTest, basics) {
WatchSocketPtr watch;
/// Verify that we can construct a WatchSocket.
ASSERT_NO_THROW(watch.reset(new WatchSocket()));
ASSERT_TRUE(watch);
/// Verify that post-construction the state the select-fd is valid.
int select_fd = watch->getSelectFd();
EXPECT_NE(select_fd, WatchSocket::INVALID_SOCKET);
/// Verify that isReady() is false and that a call to select agrees.
EXPECT_FALSE(watch->isReady());
EXPECT_EQ(0, selectCheck(select_fd));
/// Verify that the socket can be marked ready.
ASSERT_NO_THROW(watch->markReady());
/// Verify that we have exactly one marker waiting to be read.
int count = 0;
EXPECT_FALSE(ioctl(select_fd, FIONREAD, &count));
EXPECT_EQ(sizeof(WatchSocket::MARKER), count);
/// Verify that we can call markReady again without error.
ASSERT_NO_THROW(watch->markReady());
/// Verify that we STILL have exactly one marker waiting to be read.
EXPECT_FALSE(ioctl(select_fd, FIONREAD, &count));
EXPECT_EQ(sizeof(WatchSocket::MARKER), count);
/// Verify that isReady() is true and that a call to select agrees.
EXPECT_TRUE(watch->isReady());
EXPECT_EQ(1, selectCheck(select_fd));
/// Verify that the socket can be cleared.
ASSERT_NO_THROW(watch->clearReady());
/// Verify that isReady() is false and that a call to select agrees.
EXPECT_FALSE(watch->isReady());
EXPECT_EQ(0, selectCheck(select_fd));
}
/// @brief Checks behavior when select_fd is closed externally while in the
/// "cleared" state.
TEST(WatchSocketTest, closedWhileClear) {
WatchSocketPtr watch;
/// Verify that we can construct a WatchSocket.
ASSERT_NO_THROW(watch.reset(new WatchSocket()));
ASSERT_TRUE(watch);
/// Verify that post-construction the state the select-fd is valid.
int select_fd = watch->getSelectFd();
ASSERT_NE(select_fd, WatchSocket::INVALID_SOCKET);
// Verify that socket does not appear ready.
ASSERT_EQ(0, watch->isReady());
// Interfere by closing the fd.
ASSERT_EQ(0, close(select_fd));
// Verify that socket does not appear ready.
ASSERT_EQ(0, watch->isReady());
// Verify that clear does NOT throw.
ASSERT_NO_THROW(watch->clearReady());
// Verify that trying to mark it fails.
ASSERT_THROW(watch->markReady(), WatchSocketError);
// Verify that clear does NOT throw.
ASSERT_NO_THROW(watch->clearReady());
// Verify that getSelectFd() returns invalid socket.
ASSERT_EQ(WatchSocket::INVALID_SOCKET, watch->getSelectFd());
}
/// @brief Checks behavior when select_fd has closed while in the "ready"
/// state.
TEST(WatchSocketTest, closedWhileReady) {
WatchSocketPtr watch;
/// Verify that we can construct a WatchSocket.
ASSERT_NO_THROW(watch.reset(new WatchSocket()));
ASSERT_TRUE(watch);
/// Verify that post-construction the state the select-fd is valid.
int select_fd = watch->getSelectFd();
ASSERT_NE(select_fd, WatchSocket::INVALID_SOCKET);
/// Verify that the socket can be marked ready.
ASSERT_NO_THROW(watch->markReady());
EXPECT_EQ(1, selectCheck(select_fd));
// Interfere by closing the fd.
ASSERT_EQ(0, close(select_fd));
// Verify that trying to clear it does not throw.
ASSERT_NO_THROW(watch->clearReady());
// Verify the select_fd fails as socket is invalid/closed.
EXPECT_EQ(-1, selectCheck(select_fd));
// Verify that subsequent attempts to mark it will fail.
ASSERT_THROW(watch->markReady(), WatchSocketError);
}
/// @brief Checks behavior when select_fd has been marked ready but then
/// emptied by an external read.
TEST(WatchSocketTest, emptyReadySelectFd) {
WatchSocketPtr watch;
/// Verify that we can construct a WatchSocket.
ASSERT_NO_THROW(watch.reset(new WatchSocket()));
ASSERT_TRUE(watch);
/// Verify that post-construction the state the select-fd is valid.
int select_fd = watch->getSelectFd();
ASSERT_NE(select_fd, WatchSocket::INVALID_SOCKET);
/// Verify that the socket can be marked ready.
ASSERT_NO_THROW(watch->markReady());
EXPECT_EQ(1, selectCheck(select_fd));
// Interfere by reading the fd. This should empty the read pipe.
uint32_t buf = 0;
ASSERT_EQ((read (select_fd, &buf, sizeof(buf))), sizeof(buf));
ASSERT_EQ(WatchSocket::MARKER, buf);
// Really nothing that can be done to protect against this, but let's
// make sure we aren't in a weird state.
ASSERT_NO_THROW(watch->clearReady());
// Verify the select_fd fails as socket is invalid/closed.
EXPECT_EQ(0, selectCheck(select_fd));
// Verify that getSelectFd() returns is still good.
ASSERT_EQ(select_fd, watch->getSelectFd());
}
/// @brief Checks behavior when select_fd has been marked ready but then
/// contents have been "corrupted" by a partial read.
TEST(WatchSocketTest, badReadOnClear) {
WatchSocketPtr watch;
/// Verify that we can construct a WatchSocket.
ASSERT_NO_THROW(watch.reset(new WatchSocket()));
ASSERT_TRUE(watch);
/// Verify that post-construction the state the select-fd is valid.
int select_fd = watch->getSelectFd();
ASSERT_NE(select_fd, WatchSocket::INVALID_SOCKET);
/// Verify that the socket can be marked ready.
ASSERT_NO_THROW(watch->markReady());
EXPECT_EQ(1, selectCheck(select_fd));
// Interfere by reading the fd. This should empty the read pipe.
uint32_t buf = 0;
ASSERT_EQ((read (select_fd, &buf, 1)), 1);
ASSERT_NE(WatchSocket::MARKER, buf);
// Really nothing that can be done to protect against this, but let's
// make sure we aren't in a weird state.
/// @todo maybe clear should never throw, log only
ASSERT_THROW(watch->clearReady(), WatchSocketError);
// Verify the select_fd does not evalute to ready.
EXPECT_NE(1, selectCheck(select_fd));
// Verify that getSelectFd() returns INVALID.
ASSERT_EQ(WatchSocket::INVALID_SOCKET, watch->getSelectFd());
// Verify that subsequent attempt to mark it fails.
ASSERT_THROW(watch->markReady(), WatchSocketError);
}
} // end of anonymous namespace
| {
"pile_set_name": "Github"
} |
<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Migrations\Migration;
class CreateModulesConfigMovimentoGeralTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::unprepared(
'
SET default_with_oids = false;
CREATE SEQUENCE modules.config_movimento_geral_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
CREATE TABLE modules.config_movimento_geral (
id integer NOT NULL,
ref_cod_serie integer NOT NULL,
coluna integer NOT NULL
);
ALTER SEQUENCE modules.config_movimento_geral_id_seq OWNED BY modules.config_movimento_geral.id;
ALTER TABLE ONLY modules.config_movimento_geral
ADD CONSTRAINT cod_config_movimento_geral_pkey PRIMARY KEY (id);
ALTER TABLE ONLY modules.config_movimento_geral ALTER COLUMN id SET DEFAULT nextval(\'modules.config_movimento_geral_id_seq\'::regclass);
SELECT pg_catalog.setval(\'modules.config_movimento_geral_id_seq\', 1, false);
'
);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('modules.config_movimento_geral');
}
}
| {
"pile_set_name": "Github"
} |
Stormhammers - Archon's Shield Light 'Mechs - ED:Dark Age
@Light IndustrialMechs - ED-DA, 3
Wight WGT-1LAW/SC, 3
Locust LCT-5W2, 4
Nyx NX-80, 5
Firestarter FS9-M2, 6
Wolfhound WLF-5, 5
Spider SDR-7K, 4
Uller (Kit Fox) Prime, 3
Crimson Hawk (Standard), 2
Blade BLD-7R, 1
| {
"pile_set_name": "Github"
} |
ceaaf3204fdf3167f56829156d5f6397b7ad79ce32320bbbc4e405973fa8d0c11c722ab89913ae870aeff06054efe37aa38047a3c6060ce45124e94c51fcd3fa
| {
"pile_set_name": "Github"
} |
void simple () {
var texture = Twitter.no_avatar;
var cache = new Cb.AvatarCache ();
assert (cache.get_n_entries () == 0);
cache.add (1337, texture, "some_url");
assert (cache.get_n_entries () == 1);
cache.increase_refcount_for_texture (texture);
assert (cache.get_n_entries () == 1);
cache.decrease_refcount_for_texture (texture);
assert (cache.get_n_entries () == 0);
}
void deferred_texture () {
var texture = Twitter.no_avatar;
var cache = new Cb.AvatarCache ();
cache.add (1337, null, "some_url");
assert (cache.get_n_entries () == 1);
bool found;
var cached_texture = cache.get_texture_for_id (1337, out found);
assert (cached_texture == null);
assert (found);
cache.set_avatar (1337, texture, "some_url");
assert (cache.get_n_entries () == 1);
cache.increase_refcount_for_texture (texture);
cached_texture = cache.get_texture_for_id (1337, out found);
assert (cached_texture == texture);
assert (found);
cache.decrease_refcount_for_texture (texture);
assert (cache.get_n_entries () == 0);
cached_texture = cache.get_texture_for_id (1337, out found);
assert (cached_texture == null);
assert (!found);
}
int main (string[] args) {
GLib.Test.init (ref args);
Twitter.get ().init ();
GLib.Test.add_func ("/avatarcache/simple", simple);
GLib.Test.add_func ("/avatarcache/deferred_texture", deferred_texture);
return GLib.Test.run ();
}
| {
"pile_set_name": "Github"
} |
/*
* This set (target) cpu specific macros:
* - Possible values:
* NPY_CPU_X86
* NPY_CPU_AMD64
* NPY_CPU_PPC
* NPY_CPU_PPC64
* NPY_CPU_PPC64LE
* NPY_CPU_SPARC
* NPY_CPU_S390
* NPY_CPU_IA64
* NPY_CPU_HPPA
* NPY_CPU_ALPHA
* NPY_CPU_ARMEL
* NPY_CPU_ARMEB
* NPY_CPU_SH_LE
* NPY_CPU_SH_BE
*/
#ifndef _NPY_CPUARCH_H_
#define _NPY_CPUARCH_H_
#include "numpyconfig.h"
#include <string.h> /* for memcpy */
#if defined( __i386__ ) || defined(i386) || defined(_M_IX86)
/*
* __i386__ is defined by gcc and Intel compiler on Linux,
* _M_IX86 by VS compiler,
* i386 by Sun compilers on opensolaris at least
*/
#define NPY_CPU_X86
#elif defined(__x86_64__) || defined(__amd64__) || defined(__x86_64) || defined(_M_AMD64)
/*
* both __x86_64__ and __amd64__ are defined by gcc
* __x86_64 defined by sun compiler on opensolaris at least
* _M_AMD64 defined by MS compiler
*/
#define NPY_CPU_AMD64
#elif defined(__ppc__) || defined(__powerpc__) || defined(_ARCH_PPC)
/*
* __ppc__ is defined by gcc, I remember having seen __powerpc__ once,
* but can't find it ATM
* _ARCH_PPC is used by at least gcc on AIX
*/
#define NPY_CPU_PPC
#elif defined(__ppc64le__)
#define NPY_CPU_PPC64LE
#elif defined(__ppc64__)
#define NPY_CPU_PPC64
#elif defined(__sparc__) || defined(__sparc)
/* __sparc__ is defined by gcc and Forte (e.g. Sun) compilers */
#define NPY_CPU_SPARC
#elif defined(__s390__)
#define NPY_CPU_S390
#elif defined(__ia64)
#define NPY_CPU_IA64
#elif defined(__hppa)
#define NPY_CPU_HPPA
#elif defined(__alpha__)
#define NPY_CPU_ALPHA
#elif defined(__arm__) && defined(__ARMEL__)
#define NPY_CPU_ARMEL
#elif defined(__arm__) && defined(__ARMEB__)
#define NPY_CPU_ARMEB
#elif defined(__sh__) && defined(__LITTLE_ENDIAN__)
#define NPY_CPU_SH_LE
#elif defined(__sh__) && defined(__BIG_ENDIAN__)
#define NPY_CPU_SH_BE
#elif defined(__MIPSEL__)
#define NPY_CPU_MIPSEL
#elif defined(__MIPSEB__)
#define NPY_CPU_MIPSEB
#elif defined(__or1k__)
#define NPY_CPU_OR1K
#elif defined(__aarch64__)
#define NPY_CPU_AARCH64
#elif defined(__mc68000__)
#define NPY_CPU_M68K
#else
#error Unknown CPU, please report this to numpy maintainers with \
information about your platform (OS, CPU and compiler)
#endif
#define NPY_COPY_PYOBJECT_PTR(dst, src) memcpy(dst, src, sizeof(PyObject *))
#if (defined(NPY_CPU_X86) || defined(NPY_CPU_AMD64))
#define NPY_CPU_HAVE_UNALIGNED_ACCESS 1
#else
#define NPY_CPU_HAVE_UNALIGNED_ACCESS 0
#endif
#endif
| {
"pile_set_name": "Github"
} |
'use strict';
export default function DSElementHandler(commandStack, eventBus, modeling) {
commandStack.registerHandler('element.colorChange', element_colorChange);
commandStack.registerHandler('shape.removeGroupWithChildren', removeGroupWithChildren);
function element_colorChange() {
this.preExecute = function(context) {
context.oldColor= context.businessObject.pickedColor;
};
this.execute = function(context) {
let semantic = context.businessObject;
let element = context.element;
semantic.pickedColor = context.newColor;
eventBus.fire('element.changed', { element });
};
this.revert = function(context) {
let semantic = context.businessObject;
let element = context.element;
semantic.pickedColor = context.oldColor;
eventBus.fire('element.changed', { element });
};
}
function removeGroupWithChildren() {
this.preExecute = function(ctx) {
ctx.parent = ctx.element.parent;
};
this.execute = function(ctx) {
let element = ctx.element;
eventBus.fire('element.changed', { element });
};
this.revert = function(ctx) {
let element = ctx.element;
eventBus.fire('element.changed', { element });
};
}
} | {
"pile_set_name": "Github"
} |
# Design
**Home → Design**
This page allows you to configure the display of all your home automation in a very fine way.
It takes time but its only limit is your imagination.
> **Tip**
>
> It is possible to go directly to a design thanks to the submenu.
> **IMPORTANT**
>
> All actions are done by right clicking on this page, be careful to do it well in the design. When creating, you must do it in the middle of the page (to be sure of being on the design).
In the menu (right click), we find the following actions :
- **Designs** : Displays the list of your designs and allows you to access them.
- **Editing** : Switch to edit mode.
- **Full screen** : Allows you to use the entire web page, which will remove the Jeedom menu from the top.
- **Add graphic** : Add a graphic.
- **Add text / html** : Allows you to add text or html / JavaScript code.
- **Add scenario** : Add a scenario.
- **Add link**
- **Towards a view** : Add a link to a view.
- **Towards a design** : Add a link to another design.
- **Add equipment** : Adds equipment.
- **Add command** : Add a command.
- **Add image / camera** : Allows you to add a picture or a stream from a camera.
- **Add area** : Allows to add a clickable transparent zone which will be able to execute a series of actions during a click (depending or not on the status of another command).
- **Add summary** : Adds information from an object or general summary.
- **Viewing**
- **Any** : Does not display any grid.
- **10x10** : Displays a 10 by 10 grid.
- **15x15** : Displays a grid of 15 by 15.
- **20x20** : Displays a 20 by 20 grid.
- **Magnetize the elements** : Adds magnetization between the elements to make it easier to stick them.
- **Magnet on the grid** : Add a magnetization of the elements to the grid (attention : depending on the zoom of the element this functionality can more or less work).
- **Hide item highlighting** : Hide highlighting around items.
- **Delete design** : Remove design.
- **Create a design** : Allows you to add a new design.
- **Duplicate design** : Duplicates current design.
- **Configure the design** : Access to the configuration of the design.
- **Save** : Save the design (note, there are also automatic backups during certain actions).
> **IMPORTANT**
>
> The configuration of the design elements is done by a click on them.
## Design configuration
Found here :
- **General**
- **Last name** : The name of your design.
- **Position** : The position of the design in the menu. Allows you to order the designs.
- **Transparent background** : Makes the background transparent. Attention if the box is checked, the background color is not used.
- **Background color** : Design background color.
- **Access code* : Access code to your design (if empty, no code is required).
- **Icon** : An icon for it (appears in the design choice menu).
- **Picture**
- **To send** : Allows you to add a background image to the design.
- **Delete image** : Delete image.
- **Sizes**
- **Size (WxH)** : Allows you to set the size in pixels of your design.
## General configuration of elements
> **NOTE**
>
> Depending on the type of item, options may change.
### Common display settings
- **Depth** : Allows you to choose the depth level
- **Position X (%)** : Horizontal coordinate of the element.
- **Position Y (%)** : Vertical coordinate of the element.
- **Width (px)** : Element width in pixels.
- **Height (px)** : Element height in pixels.
### Supprimer
Remove item
### Dupliquer
Allows you to duplicate the element
### Verrouiller
Allows you to lock the element so that it is no longer movable or resizable.
## Graphique
### Specific display settings
- **Period** : Allows you to choose the display period
- **Show caption** : Displays the legend.
- **Show browser** : Displays the browser (second lighter graph below the first).
- **Show period selector** : Displays the period selector at the top left.
- **Show scroll bar** : Displays the scroll bar.
- **Transparent background** : Makes the background transparent.
- **Border** : Allows you to add a border, be careful the syntax is HTML (be careful, you must use CSS syntax, for example : solid 1px black).
### Advanced configuration
Allows you to choose the commands to grapher.
## Text / html
### Specific display settings
- **Icon** : Icon displayed in front of the Design name.
- **Background color** : allows you to change the background color or make it transparent, do not forget to change "Default" to NO.
- **Text color** : allows you to change the color of icons and texts (be careful to set Default to No)..
- **Smooth it out** : allows to round the angles (do not forget to put%, ex 50%).
- **Border** : allows you to add a border, beware the syntax is HTML (you must use CSS syntax, for example : solid 1px black).
- **Font size** : allows you to change the font size (ex 50%, you must put the% sign).
- **Text alignment** : allows you to choose the alignment of the text (left / right / centered).
- **Fat** : bold text.
- **Text** : Text in HTML code that will be in the element.
> **IMPORTANT**
>
> If you put HTML code (in particular Javascript), be careful to check it before because you can if there is an error in it or if it overwrites a Jeedom component completely crash the design and it will only have to delete it directly into the database.
## Scenario
*No specific display settings*
## Lien
### Specific display settings
- **Last name** : Name of the link (displayed text).
- **Link** : Link to the design or view in question.
- **Background color** : Allows you to change the background color or make it transparent, do not forget to change "Default" to NO.
- **Text color** : Allows you to change the color of icons and texts (be careful to set Default to No).
- **Round off the angles (don't forget to put%, ex 50%)** : Allows to round the angles, do not forget to put the%.
- **Border (attention CSS syntax, ex : solid 1px black)** : Allows you to add a border, beware the syntax is HTML.
- **Font size (ex 50%, you must put the% sign)** : Allows you to change the font size.
- **Text alignment** : Allows you to choose the alignment of the text (left / right / centered).
- **Fat** : Bold text.
## Equipement
### Specific display settings
- **Display object name** : Check to display the name of the parent object of the device.
- **Hide name** : Check to hide the name of the equipment.
- **Background color** : Allows you to choose a custom background color, or to display the equipment with a transparent background, or to use the default color.
- **Text color** : Lets you choose a custom background color, or use the default color.
- **Rounded** : Value in pixels of the rounding of the angles of the equipment tile.
- **Border** : CSS definition of an equipment tile border. Ex : 1px solid black.
- **Opacity** : Opacity of the equipment tile, between 0 and 1. Warning : a background color must be defined.
- **Custom CSS** : CSS rules to apply on the equipment.
- **Apply custom css on** : CSS selector on which to apply custom CSS.
### Commandes
The list of commands present on the equipment allows you, for each command, to:
- Hide command name.
- Hide command.
- Display the order with a transparent background.
### Advanced configuration
Displays the advanced equipment configuration window (see documentation **Home automation summary**).
## Commande
*No specific display settings*
### Advanced configuration
Displays the advanced equipment configuration window (see documentation **Home automation summary**).
## Picture / Camera
### Specific display settings
- **Pin up** : Defines what you want to display, still image or stream from a camera.
- **Picture** : Send the image in question (if you have chosen an image).
- **Camera** : Camera to display (if you chose camera).
## Zone
### Specific display settings
- **Type of area** : This is where you choose the type of area : Simple macro, Binary macro or Widget on hover.
### Single macro
In this mode, a click on the zone performs one or more actions. Here you just need to indicate the list of actions to do when clicking on the area.
### Binary macro
In this mode, Jeedom will execute the On or Off action (s) depending on the status of the command you indicate. Ex : if the command is worth 0 then Jeedom will execute the On action (s) otherwise it will execute the Off action (s)
- **Binary information** : Command giving the status to check to decide what action to do (On or Off).
You just have to put the actions to do for the On and for the Off.
### Hover widget
In this mode, when hovering or clicking in the Jeedom area, you will display the widget in question.
- **Equipment** : Widget to display when hovering or clicking.
- **Show on flyover** : If checked, displays the widget on hover.
- **View on one click** : If checked, then the widget is displayed on click.
- **Position** : Allows you to choose where the widget will appear (by default bottom right).
## Summary
### Specific display settings
- **Link** : Allows you to indicate the summary to display (General for the global otherwise indicate the subject).
- **Background color** : Allows you to change the background color or make it transparent, do not forget to change "Default" to NO.
- **Text color** : Allows you to change the color of icons and texts (be careful to set Default to No).
- **Round off the angles (don't forget to put%, ex 50%)** : Allows to round the angles, do not forget to put the%.
- **Border (attention CSS syntax, ex : solid 1px black)** : Allows you to add a border, beware the syntax is HTML.
- **Font size (ex 50%, you must put the% sign)** : Allows you to change the font size.
- **Fat** : Bold text.
## FAQ
>**I can no longer edit my design**
>If you have put a widget or an image that takes almost the entire design, you must click outside the widget or image to access the menu by right-clicking.
>**Delete a design that no longer works**
>In the administration part then OS / DB, make "select * from planHeader", recover the id of the design in question and make a "delete from planHeader where id=#TODO#" and "delete from plan where planHeader_id=#todo#" replacing well #TODO# by the design id previously found.
| {
"pile_set_name": "Github"
} |
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using LanguageExt.Common;
using LanguageExt.Interfaces;
using static LanguageExt.Prelude;
namespace LanguageExt
{
/// <summary>
/// Atoms provide a way to manage shared, synchronous, independent state without
/// locks.
/// </summary>
/// <remarks>
/// The intended use of atom is to hold one an immutable data structure. You change
/// the value by applying a function to the old value. This is done in an atomic
/// manner by `Swap`.
///
/// Internally, `Swap` reads the current value, applies the function to it, and
/// attempts to `CompareExchange` it in. Since another thread may have changed the
/// value in the intervening time, it may have to retry, and does so in a spin loop.
///
/// The net effect is that the value will always be the result of the application
/// of the supplied function to a current value, atomically. However, because the
/// function might be called multiple times, it must be free of side effects.
///
/// Atoms are an efficient way to represent some state that will never need to be
/// coordinated with any other, and for which you wish to make synchronous changes.
/// </remarks>
public sealed class Atom<A>
{
const int maxRetries = 500;
volatile object value;
readonly Func<A, bool> validator;
public event AtomChangedEvent<A> Change;
/// <summary>
/// Constructor
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
Atom(A value, Func<A, bool> validator)
{
this.value = Box<A>.New(value);
this.validator = validator;
}
/// <summary>
/// Internal constructor function that runs the validator on the value
/// before returning the Atom so that the Atom can never be in an invalid
/// state. The validator is then used for all state transitions going
/// forward.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static Option<Atom<A>> New(A value, Func<A, bool> validator)
{
var atom = new Atom<A>(value, validator ?? throw new ArgumentNullException(nameof(validator)));
return validator(value)
? Some(atom)
: None;
}
/// <summary>
/// Internal constructor
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static Atom<A> New(A value) =>
new Atom<A>(value, True);
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="f">Function to update the atom</param>
/// <returns>Option in a Some state, with the result of the invocation of `f`, if the swap succeeded
/// and its validation passed. None otherwise</returns>
public Option<A> Swap(Func<A, A> f)
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newValueA = f(Box<A>.GetValue(value));
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return default;
}
if(Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return Optional(newValueA);
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
}
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="x">Additional value to pass to `f`</param>
/// <param name="f">Function to update the atom</param>
/// <returns>Eff in a Succ state, with the result of the invocation of `f`, if the swap succeeded and its
/// validation passed. Failure state otherwise</returns>
public Eff<A> SwapEff(Func<A, Eff<A>> f) =>
EffMaybe<A>(() =>
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newValueFinA = f(Box<A>.GetValue(value)).RunIO();
if (newValueFinA.IsFail)
{
return newValueFinA;
}
var newValueA = newValueFinA.Value;
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return FinFail<A>(Error.New("Validation failed for swap"));
}
if(Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return newValueFinA;
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
});
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="f">Function to update the atom</param>
/// <returns>Eff in a Succ state, with the result of the invocation of `f`, if the swap succeeded and its
/// validation passed. Failure state otherwise</returns>
public Eff<RT, A> SwapEff<RT>(Func<A, Eff<RT, A>> f) =>
EffMaybe<RT, A>(env =>
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newValueFinA = f(Box<A>.GetValue(value)).RunIO(env);
if (newValueFinA.IsFail)
{
return newValueFinA;
}
var newValueA = newValueFinA.Value;
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return FinFail<A>(Error.New("Validation failed for swap"));
}
if(Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return newValueFinA;
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
});
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="f">Function to update the atom</param>
/// <returns>Option in a Some state, with the result of the invocation of `f`, if the swap succeeded
/// and its validation passed. None otherwise</returns>
public async ValueTask<Option<A>> SwapAsync(Func<A, ValueTask<A>> f)
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newValueA = await f(Box<A>.GetValue(value)).ConfigureAwait(false);
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return default;
}
if (Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return Optional(newValueA);
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
}
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="f">Function to update the atom</param>
/// <returns>Aff in a Succ state, with the result of the invocation of `f`, if the swap succeeded and its
/// validation passed. Failure state otherwise</returns>
public Aff<A> SwapAff(Func<A, Aff<A>> f) =>
AffMaybe<A>(async () =>
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newValueFinA = await f(Box<A>.GetValue(value)).RunIO().ConfigureAwait(false);
if (newValueFinA.IsFail)
{
return newValueFinA;
}
var newValueA = newValueFinA.Value;
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return FinFail<A>(Error.New("Validation failed for swap"));
}
if (Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return newValueFinA;
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
});
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="f">Function to update the atom</param>
/// <returns>Aff in a Succ state, with the result of the invocation of `f`, if the swap succeeded and its
/// validation passed. Failure state otherwise</returns>
public Aff<A> SwapAff(Func<A, ValueTask<A>> f) =>
AffMaybe<A>(async () =>
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newValueA = await f(Box<A>.GetValue(value)).ConfigureAwait(false);
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return FinFail<A>(Error.New("Validation failed for swap"));
}
if (Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return FinSucc<A>(newValueA);
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
});
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="f">Function to update the atom</param>
/// <returns>Aff in a Succ state, with the result of the invocation of `f`, if the swap succeeded and its
/// validation passed. Failure state otherwise</returns>
public Aff<RT, A> SwapAff<RT>(Func<A, Aff<RT, A>> f) where RT : struct, HasCancel<RT> =>
AffMaybe<RT, A>(async env =>
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newFinValueA = await f(Box<A>.GetValue(value)).RunIO(env).ConfigureAwait(false);
if (newFinValueA.IsFail)
{
return newFinValueA;
}
var newValueA = newFinValueA.Value;
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return FinFail<A>(Error.New("Validation failed for swap"));
}
if (Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return newFinValueA;
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
});
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="x">Additional value to pass to `f`</param>
/// <param name="f">Function to update the atom</param>
/// <returns>Option in a Some state, with the result of the invocation of `f`, if the swap succeeded
/// and its validation passed. None otherwise</returns>
public Option<A> Swap<X>(X x, Func<X, A, A> f)
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newValueA = f(x, Box<A>.GetValue(value));
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return default;
}
if (Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return Optional(newValueA);
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
}
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="x">Additional value to pass to `f`</param>
/// <param name="f">Function to update the atom</param>
/// <returns>Eff in a Succ state, with the result of the invocation of `f`, if the swap succeeded and its
/// validation passed. Failure state otherwise</returns>
public Eff<A> SwapEff<X>(X x, Func<X, A, Eff<A>> f) =>
EffMaybe<A>(() =>
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newValueFinA = f(x, Box<A>.GetValue(value)).RunIO();
if (newValueFinA.IsFail)
{
return newValueFinA;
}
var newValueA = newValueFinA.Value;
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return FinFail<A>(Error.New("Validation failed for swap"));
}
if(Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return newValueFinA;
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
});
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="x">Additional value to pass to `f`</param>
/// <param name="f">Function to update the atom</param>
/// <returns>Eff in a Succ state, with the result of the invocation of `f`, if the swap succeeded and its
/// validation passed. Failure state otherwise</returns>
public Eff<RT, A> SwapEff<RT, X>(X x, Func<X, A, Eff<RT, A>> f) =>
EffMaybe<RT, A>(env =>
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newValueFinA = f(x, Box<A>.GetValue(value)).RunIO(env);
if (newValueFinA.IsFail)
{
return newValueFinA;
}
var newValueA = newValueFinA.Value;
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return FinFail<A>(Error.New("Validation failed for swap"));
}
if(Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return newValueFinA;
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
});
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="x">Additional value to pass to `f`</param>
/// <param name="f">Function to update the atom</param>
/// <returns>Option in a Some state, with the result of the invocation of `f`, if the swap succeeded
/// and its validation passed. None otherwise</returns>
public async ValueTask<Option<A>> SwapAsync<X>(X x, Func<X, A, ValueTask<A>> f)
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newValueA = await f(x, Box<A>.GetValue(value)).ConfigureAwait(false);
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return default;
}
if (Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return Optional(newValueA);
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
}
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="x">Additional value to pass to `f`</param>
/// <param name="f">Function to update the atom</param>
/// <returns>Aff in a Succ state, with the result of the invocation of `f`, if the swap succeeded and its
/// validation passed. Failure state otherwise</returns>
public Aff<A> SwapAff<X>(X x, Func<X, A, Aff<A>> f) =>
AffMaybe<A>(async () =>
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newValueFinA = await f(x, Box<A>.GetValue(value)).RunIO().ConfigureAwait(false);
if (newValueFinA.IsFail)
{
return newValueFinA;
}
var newValueA = newValueFinA.Value;
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return FinFail<A>(Error.New("Validation failed for swap"));
}
if (Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return newValueFinA;
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
});
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="x">Additional value to pass to `f`</param>
/// <param name="f">Function to update the atom</param>
/// <returns>Aff in a Succ state, with the result of the invocation of `f`, if the swap succeeded and its
/// validation passed. Failure state otherwise</returns>
public Aff<A> SwapAff<X>(X x, Func<X, A, ValueTask<A>> f) =>
AffMaybe<A>(async () =>
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newValueA = await f(x, Box<A>.GetValue(value)).ConfigureAwait(false);
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return FinFail<A>(Error.New("Validation failed for swap"));
}
if (Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return FinSucc<A>(newValueA);
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
});
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="x">Additional value to pass to `f`</param>
/// <param name="f">Function to update the atom</param>
/// <returns>Aff in a Succ state, with the result of the invocation of `f`, if the swap succeeded and its
/// validation passed. Failure state otherwise</returns>
public Aff<RT, A> SwapAff<RT, X>(X x, Func<X, A, Aff<RT, A>> f) where RT : struct, HasCancel<RT> =>
AffMaybe<RT, A>(async env =>
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newFinValueA = await f(x, Box<A>.GetValue(value)).RunIO(env).ConfigureAwait(false);
if (newFinValueA.IsFail)
{
return newFinValueA;
}
var newValueA = newFinValueA.Value;
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return FinFail<A>(Error.New("Validation failed for swap"));
}
if (Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return newFinValueA;
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
});
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="x">Additional value to pass to `f`</param>
/// <param name="y">Additional value to pass to `f`</param>
/// <param name="f">Function to update the atom</param>
/// <returns>Option in a Some state, with the result of the invocation of `f`, if the swap succeeded
/// and its validation passed. None otherwise</returns>
public Option<A> Swap<X, Y>(X x, Y y, Func<X, Y, A, A> f)
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newValueA = f(x, y, Box<A>.GetValue(value));
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return default;
}
if (Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return Optional(newValueA);
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
}
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="x">Additional value to pass to `f`</param>
/// <param name="y">Additional value to pass to `f`</param>
/// <param name="f">Function to update the atom</param>
/// <returns>Eff in a Succ state, with the result of the invocation of `f`, if the swap succeeded and its
/// validation passed. Failure state otherwise</returns>
public Eff<A> SwapEff<X, Y>(X x, Y y, Func<X, Y, A, Eff<A>> f) =>
EffMaybe<A>(() =>
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newValueFinA = f(x, y, Box<A>.GetValue(value)).RunIO();
if (newValueFinA.IsFail)
{
return newValueFinA;
}
var newValueA = newValueFinA.Value;
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return FinFail<A>(Error.New("Validation failed for swap"));
}
if(Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return newValueFinA;
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
});
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="x">Additional value to pass to `f`</param>
/// <param name="y">Additional value to pass to `f`</param>
/// <param name="f">Function to update the atom</param>
/// <returns>Eff in a Succ state, with the result of the invocation of `f`, if the swap succeeded and its
/// validation passed. Failure state otherwise</returns>
public Eff<RT, A> SwapEff<RT, X, Y>(X x, Y y, Func<X, Y, A, Eff<RT, A>> f) =>
EffMaybe<RT, A>(env =>
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newValueFinA = f(x, y, Box<A>.GetValue(value)).RunIO(env);
if (newValueFinA.IsFail)
{
return newValueFinA;
}
var newValueA = newValueFinA.Value;
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return FinFail<A>(Error.New("Validation failed for swap"));
}
if(Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return newValueFinA;
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
});
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="x">Additional value to pass to `f`</param>
/// <param name="y">Additional value to pass to `f`</param>
/// <param name="f">Function to update the atom</param>
/// <returns>Option in a Some state, with the result of the invocation of `f`, if the swap succeeded
/// and its validation passed. None otherwise</returns>
public async ValueTask<Option<A>> SwapAsync<X, Y>(X x, Y y, Func<X, Y, A, ValueTask<A>> f)
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newValueA = await f(x, y, Box<A>.GetValue(value)).ConfigureAwait(false);
var newValue = Box<A>.New(newValueA);
if (!validator(Box<A>.GetValue(newValue)))
{
return default;
}
if (Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return Optional(newValueA);
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
}
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="x">Additional value to pass to `f`</param>
/// <param name="y">Additional value to pass to `f`</param>
/// <param name="f">Function to update the atom</param>
/// <returns>Aff in a Succ state, with the result of the invocation of `f`, if the swap succeeded and its
/// validation passed. Failure state otherwise</returns>
public Aff<A> SwapAff<X, Y>(X x, Y y, Func<X, Y, A, Aff<A>> f) =>
AffMaybe<A>(async () =>
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newValueFinA = await f(x, y, Box<A>.GetValue(value)).RunIO().ConfigureAwait(false);
if (newValueFinA.IsFail)
{
return newValueFinA;
}
var newValueA = newValueFinA.Value;
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return FinFail<A>(Error.New("Validation failed for swap"));
}
if (Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return newValueFinA;
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
});
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="x">Additional value to pass to `f`</param>
/// <param name="y">Additional value to pass to `f`</param>
/// <param name="f">Function to update the atom</param>
/// <returns>Aff in a Succ state, with the result of the invocation of `f`, if the swap succeeded and its
/// validation passed. Failure state otherwise</returns>
public Aff<A> SwapAff<X, Y>(X x, Y y, Func<X, Y, A, ValueTask<A>> f) =>
AffMaybe<A>(async () =>
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newValueA = await f(x, y, Box<A>.GetValue(value)).ConfigureAwait(false);
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return FinFail<A>(Error.New("Validation failed for swap"));
}
if (Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return FinSucc<A>(newValueA);
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
});
/// <summary>
/// Atomically updates the value by passing the old value to `f` and updating
/// the atom with the result. Note: `f` may be called multiple times, so it
/// should be free of side-effects.
/// </summary>
/// <param name="x">Additional value to pass to `f`</param>
/// <param name="y">Additional value to pass to `f`</param>
/// <param name="f">Function to update the atom</param>
/// <returns>Aff in a Succ state, with the result of the invocation of `f`, if the swap succeeded and its
/// validation passed. Failure state otherwise</returns>
public Aff<RT, A> SwapAff<RT, X, Y>(X x, Y y, Func<X, Y, A, Aff<RT, A>> f) where RT : struct, HasCancel<RT> =>
AffMaybe<RT, A>(async env =>
{
f = f ?? throw new ArgumentNullException(nameof(f));
var retries = maxRetries;
while (retries > 0)
{
retries--;
var current = value;
var newFinValueA = await f(x, y, Box<A>.GetValue(value)).RunIO(env).ConfigureAwait(false);
if (newFinValueA.IsFail)
{
return newFinValueA;
}
var newValueA = newFinValueA.Value;
var newValue = Box<A>.New(newValueA);
if (!validator(newValueA))
{
return FinFail<A>(Error.New("Validation failed for swap"));
}
if (Interlocked.CompareExchange(ref value, newValue, current) == current)
{
Change?.Invoke(newValueA);
return newFinValueA;
}
SpinWait sw = default;
sw.SpinOnce();
}
throw new DeadlockException();
});
/// <summary>
/// Current state
/// </summary>
public A Value
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Box<A>.GetValue(value);
}
/// <summary>
/// Implicit conversion to `A`
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator A(Atom<A> atom) =>
atom.Value;
/// <summary>
/// Helper for validator
/// </summary>
/// <param name="_"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool True(A _) => true;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override string ToString() =>
Value.ToString();
}
}
| {
"pile_set_name": "Github"
} |
/**
* @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'codesnippet', 'bg', {
button: 'Въвеждане на блок с код',
codeContents: 'Съдържание на кода',
emptySnippetError: 'Блока с код не може да бъде празен.',
language: 'Език',
title: 'Блок с код',
pathName: 'блок с код'
} );
| {
"pile_set_name": "Github"
} |
/*
Copyright Charly Chevalier 2015
Copyright Joel Falcou 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_PREDEF_HARDWARE_SIMD_X86_AMD_H
#define BOOST_PREDEF_HARDWARE_SIMD_X86_AMD_H
#include <boost/predef/version_number.h>
#include <boost/predef/hardware/simd/x86_amd/versions.h>
/*`
[heading `BOOST_HW_SIMD_X86_AMD`]
The SIMD extension for x86 (AMD) (*if detected*).
Version number depends on the most recent detected extension.
[table
[[__predef_symbol__] [__predef_version__]]
[[`__SSE4A__`] [__predef_detection__]]
[[`__FMA4__`] [__predef_detection__]]
[[`__XOP__`] [__predef_detection__]]
[[`BOOST_HW_SIMD_X86`] [__predef_detection__]]
]
[table
[[__predef_symbol__] [__predef_version__]]
[[`__SSE4A__`] [BOOST_HW_SIMD_X86_SSE4A_VERSION]]
[[`__FMA4__`] [BOOST_HW_SIMD_X86_FMA4_VERSION]]
[[`__XOP__`] [BOOST_HW_SIMD_X86_XOP_VERSION]]
[[`BOOST_HW_SIMD_X86`] [BOOST_HW_SIMD_X86]]
]
[note This predef includes every other x86 SIMD extensions and also has other
more specific extensions (FMA4, XOP, SSE4a). You should use this predef
instead of `BOOST_HW_SIMD_X86` to test if those specific extensions have
been detected.]
*/
#define BOOST_HW_SIMD_X86_AMD BOOST_VERSION_NUMBER_NOT_AVAILABLE
// AMD CPUs also use x86 architecture. We first try to detect if any AMD
// specific extension are detected, if yes, then try to detect more recent x86
// common extensions.
#undef BOOST_HW_SIMD_X86_AMD
#if !defined(BOOST_HW_SIMD_X86_AMD) && defined(__XOP__)
# define BOOST_HW_SIMD_X86_AMD BOOST_HW_SIMD_X86_AMD_XOP_VERSION
#endif
#if !defined(BOOST_HW_SIMD_X86_AMD) && defined(__FMA4__)
# define BOOST_HW_SIMD_X86_AMD BOOST_HW_SIMD_X86_AMD_FMA4_VERSION
#endif
#if !defined(BOOST_HW_SIMD_X86_AMD) && defined(__SSE4A__)
# define BOOST_HW_SIMD_X86_AMD BOOST_HW_SIMD_X86_AMD_SSE4A_VERSION
#endif
#if !defined(BOOST_HW_SIMD_X86_AMD)
# define BOOST_HW_SIMD_X86_AMD BOOST_VERSION_NUMBER_NOT_AVAILABLE
#else
// At this point, we know that we have an AMD CPU, we do need to check for
// other x86 extensions to determine the final version number.
# include <boost/predef/hardware/simd/x86.h>
# if BOOST_HW_SIMD_X86 > BOOST_HW_SIMD_X86_AMD
# undef BOOST_HW_SIMD_X86_AMD
# define BOOST_HW_SIMD_X86_AMD BOOST_HW_SIMD_X86
# endif
# define BOOST_HW_SIMD_X86_AMD_AVAILABLE
#endif
#define BOOST_HW_SIMD_X86_AMD_NAME "x86 (AMD) SIMD"
#endif
#include <boost/predef/detail/test.h>
BOOST_PREDEF_DECLARE_TEST(BOOST_HW_SIMD_X86_AMD, BOOST_HW_SIMD_X86_AMD_NAME)
| {
"pile_set_name": "Github"
} |
@mixin badge-color($color) {
border-color: $color;
color: $color;
}
| {
"pile_set_name": "Github"
} |
SELECT 1 as a \gset
\echo :a \\ SELECT :a; \unset a
SELECT 'test' \g testfile.txt
\! cat testfile.txt
SELECT current_timestamp;
\watch 3
| {
"pile_set_name": "Github"
} |
package dev.olog.media.widget
import android.content.Context
import android.util.AttributeSet
import android.widget.SeekBar
import androidx.appcompat.widget.AppCompatSeekBar
import dev.olog.media.R
import dev.olog.media.model.PlayerPlaybackState
import kotlinx.coroutines.flow.Flow
class CustomSeekBar(
context: Context,
attrs: AttributeSet
) : AppCompatSeekBar(context, attrs),
IProgressDeletegate {
private var isTouched = false
private var listener: OnSeekBarChangeListener? = null
private val delegate: IProgressDeletegate by lazy { ProgressDeletegate(this) }
init {
if (!isInEditMode){
max = Int.MAX_VALUE
}
}
fun setListener(
onProgressChanged: (Int) -> Unit,
onStartTouch: (Int) -> Unit,
onStopTouch: (Int) -> Unit
) {
listener = object : OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
onProgressChanged(progress)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
isTouched = true
onStartTouch(progress)
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
isTouched = false
onStopTouch(progress)
}
}
setOnSeekBarChangeListener(null) // clear old listener
if (isAttachedToWindow) {
setOnSeekBarChangeListener(listener)
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
setOnSeekBarChangeListener(listener)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
setOnSeekBarChangeListener(null)
stopAutoIncrement(0)
}
override fun setProgress(progress: Int) {
if (!isTouched) {
super.setProgress(progress)
}
}
override fun setProgress(progress: Int, animate: Boolean) {
if (!isTouched) {
super.setProgress(progress, animate)
}
}
override fun startAutoIncrement(startMillis: Int, speed: Float) {
delegate.startAutoIncrement(startMillis, speed)
}
override fun stopAutoIncrement(startMillis: Int) {
delegate.stopAutoIncrement(startMillis)
}
override fun onStateChanged(state: PlayerPlaybackState) {
delegate.onStateChanged(state)
}
override fun observeProgress(): Flow<Long> {
return delegate.observeProgress()
}
} | {
"pile_set_name": "Github"
} |
{
"images" : [
{
"idiom" : "universal",
"filename" : "bus.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "[email protected]",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
} | {
"pile_set_name": "Github"
} |
#!/bin/sh
# Modify this script to pass the necessary parameters to
# the configure of the captive package you're configuring
prefix="@prefix@"
exec_prefix="@exec_prefix@"
HOST_OS=@HOST_OS@
if [ "@VS_CROSS_COMPILE@" = "1" ]; then
CROSS="--host ${HOST_OS}"
# needed for mingw32 cross-compile to work
case $HOST_OS in
*mingw*|*cygwin*)
export as_cv_unaligned_access=yes
;;
esac
else
CROSS=
fi
CC="@CC@" \
CFLAGS="-I@includedir@ -O0 @CFLAGS@" \
LD="@LD@" \
LDFLAGS="-L@libdir@ @LDFLAGS@" \
CPP="@CPP@" \
CPPFLAGS="@CPPFLAGS@" \
CXX="@CXX@" \
CXXFLAGS="@CXXFLAGS@" \
NM="@NM@" \
AS="@AS@" \
ASFLAGS="@ASFLAGS@" \
STRIP="@STRIP@" \
RANLIB="@RANLIB@" \
AR="@AR@" \
DLLTOOL="@DLLTOOL@" \
PATH="$PATH:@abs_top_builddir@@bindir@@" sh @abs_srcdir@/csrc/configure \
${CROSS} \
--disable-dependency-tracking \
--disable-glib \
--with-pic \
--disable-shared \
--prefix="${prefix}" || \
(echo "Could not configure library: \"@abs_srcdir@\"; you may want to try disabling it or installing your own version" && exit 1)
| {
"pile_set_name": "Github"
} |
package com.leanote.android.networking;
import com.android.volley.RequestQueue;
import com.wordpress.rest.RestClient;
public class RestClientFactory {
private static RestClientFactoryAbstract sFactory;
public static RestClient instantiate(RequestQueue queue) {
return instantiate(queue, RestClient.REST_CLIENT_VERSIONS.V1);
}
public static RestClient instantiate(RequestQueue queue, RestClient.REST_CLIENT_VERSIONS version) {
if (sFactory == null) {
sFactory = new RestClientFactoryDefault();
}
return sFactory.make(queue, version);
}
}
| {
"pile_set_name": "Github"
} |
#include "dxvk_device.h"
namespace dxvk {
DxvkUnboundResources::DxvkUnboundResources(DxvkDevice* dev)
: m_sampler (createSampler(dev)),
m_buffer (createBuffer(dev)),
m_bufferView (createBufferView(dev, m_buffer)),
m_image1D (createImage(dev, VK_IMAGE_TYPE_1D, 1)),
m_image2D (createImage(dev, VK_IMAGE_TYPE_2D, 6)),
m_image3D (createImage(dev, VK_IMAGE_TYPE_3D, 1)),
m_viewsSampled (createImageViews(dev, VK_FORMAT_R32_SFLOAT)),
m_viewsStorage (createImageViews(dev, VK_FORMAT_R32_UINT)) {
}
DxvkUnboundResources::~DxvkUnboundResources() {
}
void DxvkUnboundResources::clearResources(DxvkDevice* dev) {
const Rc<DxvkContext> ctx = dev->createContext();
ctx->beginRecording(dev->createCommandList());
this->clearBuffer(ctx, m_buffer);
this->clearImage(ctx, m_image1D);
this->clearImage(ctx, m_image2D);
this->clearImage(ctx, m_image3D);
dev->submitCommandList(
ctx->endRecording(),
VK_NULL_HANDLE,
VK_NULL_HANDLE);
}
Rc<DxvkSampler> DxvkUnboundResources::createSampler(DxvkDevice* dev) {
DxvkSamplerCreateInfo info;
info.minFilter = VK_FILTER_LINEAR;
info.magFilter = VK_FILTER_LINEAR;
info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
info.mipmapLodBias = 0.0f;
info.mipmapLodMin = -256.0f;
info.mipmapLodMax = 256.0f;
info.useAnisotropy = VK_FALSE;
info.maxAnisotropy = 1.0f;
info.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
info.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
info.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
info.compareToDepth = VK_FALSE;
info.compareOp = VK_COMPARE_OP_NEVER;
info.borderColor = VkClearColorValue();
info.usePixelCoord = VK_FALSE;
return dev->createSampler(info);
}
Rc<DxvkBuffer> DxvkUnboundResources::createBuffer(DxvkDevice* dev) {
DxvkBufferCreateInfo info;
info.size = MaxUniformBufferSize;
info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT
| VK_BUFFER_USAGE_VERTEX_BUFFER_BIT
| VK_BUFFER_USAGE_INDEX_BUFFER_BIT
| VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT
| VK_BUFFER_USAGE_STORAGE_BUFFER_BIT
| VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT
| VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT;
info.stages = VK_PIPELINE_STAGE_TRANSFER_BIT
| dev->getShaderPipelineStages();
info.access = VK_ACCESS_UNIFORM_READ_BIT
| VK_ACCESS_SHADER_READ_BIT
| VK_ACCESS_SHADER_WRITE_BIT;
return dev->createBuffer(info,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
}
Rc<DxvkBufferView> DxvkUnboundResources::createBufferView(
DxvkDevice* dev,
const Rc<DxvkBuffer>& buffer) {
DxvkBufferViewCreateInfo info;
info.format = VK_FORMAT_R32_UINT;
info.rangeOffset = 0;
info.rangeLength = buffer->info().size;
return dev->createBufferView(buffer, info);
}
Rc<DxvkImage> DxvkUnboundResources::createImage(
DxvkDevice* dev,
VkImageType type,
uint32_t layers) {
DxvkImageCreateInfo info;
info.type = type;
info.format = VK_FORMAT_R32_UINT;
info.flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
info.sampleCount = VK_SAMPLE_COUNT_1_BIT;
info.extent = { 1, 1, 1 };
info.numLayers = layers;
info.mipLevels = 1;
info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT
| VK_IMAGE_USAGE_SAMPLED_BIT
| VK_IMAGE_USAGE_STORAGE_BIT;
info.stages = VK_PIPELINE_STAGE_TRANSFER_BIT
| dev->getShaderPipelineStages();
info.access = VK_ACCESS_SHADER_READ_BIT;
info.layout = VK_IMAGE_LAYOUT_GENERAL;
info.tiling = VK_IMAGE_TILING_OPTIMAL;
if (type == VK_IMAGE_TYPE_2D)
info.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
return dev->createImage(info,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
}
Rc<DxvkImageView> DxvkUnboundResources::createImageView(
DxvkDevice* dev,
const Rc<DxvkImage>& image,
VkFormat format,
VkImageViewType type,
uint32_t layers) {
DxvkImageViewCreateInfo info;
info.type = type;
info.format = format;
info.usage = VK_IMAGE_USAGE_SAMPLED_BIT
| VK_IMAGE_USAGE_STORAGE_BIT;
info.aspect = VK_IMAGE_ASPECT_COLOR_BIT;
info.minLevel = 0;
info.numLevels = 1;
info.minLayer = 0;
info.numLayers = layers;
info.swizzle = VkComponentMapping {
VK_COMPONENT_SWIZZLE_ZERO, VK_COMPONENT_SWIZZLE_ZERO,
VK_COMPONENT_SWIZZLE_ZERO, VK_COMPONENT_SWIZZLE_ZERO };
return dev->createImageView(image, info);
}
DxvkUnboundResources::UnboundViews DxvkUnboundResources::createImageViews(DxvkDevice* dev, VkFormat format) {
UnboundViews result;
result.view1D = createImageView(dev, m_image1D, format, VK_IMAGE_VIEW_TYPE_1D, 1);
result.view1DArr = createImageView(dev, m_image1D, format, VK_IMAGE_VIEW_TYPE_1D_ARRAY, 1);
result.view2D = createImageView(dev, m_image2D, format, VK_IMAGE_VIEW_TYPE_2D, 1);
result.view2DArr = createImageView(dev, m_image2D, format, VK_IMAGE_VIEW_TYPE_2D_ARRAY, 1);
result.viewCube = createImageView(dev, m_image2D, format, VK_IMAGE_VIEW_TYPE_CUBE, 6);
result.viewCubeArr = createImageView(dev, m_image2D, format, VK_IMAGE_VIEW_TYPE_CUBE_ARRAY, 6);
result.view3D = createImageView(dev, m_image3D, format, VK_IMAGE_VIEW_TYPE_3D, 1);
return result;
}
const DxvkImageView* DxvkUnboundResources::getImageView(VkImageViewType type, bool sampled) const {
auto views = sampled ? &m_viewsSampled : &m_viewsStorage;
switch (type) {
case VK_IMAGE_VIEW_TYPE_1D: return views->view1D.ptr();
case VK_IMAGE_VIEW_TYPE_1D_ARRAY: return views->view1DArr.ptr();
// When implicit samplers are unbound -- we assume 2D in the shader.
case VK_IMAGE_VIEW_TYPE_MAX_ENUM:
case VK_IMAGE_VIEW_TYPE_2D: return views->view2D.ptr();
case VK_IMAGE_VIEW_TYPE_2D_ARRAY: return views->view2DArr.ptr();
case VK_IMAGE_VIEW_TYPE_CUBE: return views->viewCube.ptr();
case VK_IMAGE_VIEW_TYPE_CUBE_ARRAY: return views->viewCubeArr.ptr();
case VK_IMAGE_VIEW_TYPE_3D: return views->view3D.ptr();
default: return nullptr;
}
}
void DxvkUnboundResources::clearBuffer(
const Rc<DxvkContext>& ctx,
const Rc<DxvkBuffer>& buffer) {
ctx->clearBuffer(buffer, 0, buffer->info().size, 0);
}
void DxvkUnboundResources::clearImage(
const Rc<DxvkContext>& ctx,
const Rc<DxvkImage>& image) {
ctx->clearColorImage(image,
VkClearColorValue { },
VkImageSubresourceRange {
VK_IMAGE_ASPECT_COLOR_BIT,
0, image->info().mipLevels,
0, image->info().numLayers });
}
} | {
"pile_set_name": "Github"
} |
//
// Created by getroot on 20. 1. 16.
//
#pragma once
#include "base/info/host.h"
#include "base/info/info.h"
#include "host_metrics.h"
#include <shared_mutex>
#define MonitorInstance mon::Monitoring::GetInstance()
#define HostMetrics(info) mon::Monitoring::GetInstance()->GetHostMetrics(info);
#define ApplicationMetrics(info) mon::Monitoring::GetInstance()->GetApplicationMetrics(info);
#define StreamMetrics(info) mon::Monitoring::GetInstance()->GetStreamMetrics(info);
namespace mon
{
class Monitoring
{
public:
static Monitoring *GetInstance()
{
static Monitoring monitor;
return &monitor;
}
void Release();
void ShowInfo();
bool OnHostCreated(const info::Host &host_info);
bool OnHostDeleted(const info::Host &host_info);
bool OnApplicationCreated(const info::Application &app_info);
bool OnApplicationDeleted(const info::Application &app_info);
bool OnStreamCreated(const info::Stream &stream_info);
bool OnStreamDeleted(const info::Stream &stream_info);
std::shared_ptr<HostMetrics> GetHostMetrics(const info::Host &host_info);
std::shared_ptr<ApplicationMetrics> GetApplicationMetrics(const info::Application &app_info);
std::shared_ptr<StreamMetrics> GetStreamMetrics(const info::Stream &stream_info);
private:
std::shared_mutex _map_guard;
std::map<uint32_t, std::shared_ptr<HostMetrics>> _hosts;
};
} // namespace mon | {
"pile_set_name": "Github"
} |
/**
* The MIT License (MIT)
* Copyright (c) 2018 Rudi Theunissen
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
* THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdio.h>
#include <php.h>
#include <ext/standard/php_math.h>
#include <ext/standard/php_string.h>
#include <ext/standard/php_var.h>
#include <Zend/zend_interfaces.h>
#include <zend_smart_str.h>
#include <mpdecimal.h>
#include "arginfo.h"
#include "bool.h"
#include "common.h"
#include "compare.h"
#include "context.h"
#include "convert.h"
#include "decimal.h"
#include "errors.h"
#include "limits.h"
#include "math.h"
#include "number.h"
#include "params.h"
#include "parse.h"
#include "rational.h"
#include "round.h"
/**
* Class entry.
*/
zend_class_entry *php_decimal_rational_ce;
/**
* Object handlers.
*/
static zend_object_handlers php_decimal_rational_handlers;
/******************************************************************************/
/* ALLOC, INIT, FREE, CLONE */
/******************************************************************************/
/**
* Allocates a new php_decimal_t that has not been initialized. We don't want to
* initialize a decimal until its constructor is called, so that we can check in
* the constructor whether the object has already been initialized.
*/
static php_rational_t *php_decimal_rational_alloc()
{
php_rational_t *obj = ecalloc(1, sizeof(php_rational_t));
if (EXPECTED(obj)) {
obj->std.handlers = &php_decimal_rational_handlers;
zend_object_std_init((zend_object *) obj, php_decimal_rational_ce);
} else {
php_decimal_memory_error();
}
return obj;
}
/**
* Creates a new decimal object, initialized to the default precision.
*/
php_rational_t *php_rational()
{
php_rational_t *obj = php_decimal_rational_alloc();
php_decimal_init_mpd(PHP_RATIONAL_NUM(obj));
php_decimal_init_mpd(PHP_RATIONAL_DEN(obj));
return obj;
}
/**
* Creates a custom zend_object that is also an uninitialized decimal object.
*/
static zend_object *php_decimal_rational_create_object(zend_class_entry *ce)
{
return (zend_object *) php_decimal_rational_alloc();
}
/**
* Creates a copy of the given decimal object.
*/
static php_rational_t *php_decimal_rational_create_copy(php_rational_t *src)
{
uint32_t status = 0;
php_rational_t *dst = php_rational();
mpd_qcopy(PHP_RATIONAL_NUM(dst), PHP_RATIONAL_NUM(src), &status);
mpd_qcopy(PHP_RATIONAL_DEN(dst), PHP_RATIONAL_DEN(src), &status);
return dst;
}
/**
* Clones the given zval, which must be a decimal object.
*/
static zend_object *php_decimal_rational_clone_obj(zval *obj)
{
return (zend_object *) php_decimal_rational_create_copy(Z_RATIONAL_P(obj));
}
/**
* Free handler, should only free internal memory, not the object itself.
*/
static void php_decimal_rational_free_object(zend_object *obj)
{
php_decimal_release_mpd(PHP_RATIONAL_NUM((php_rational_t*) obj));
php_decimal_release_mpd(PHP_RATIONAL_DEN((php_rational_t*) obj));
zend_object_std_dtor(obj);
}
/**
*
*/
static inline zend_bool php_decimal_rational_is_integer(const php_rational_t *obj)
{
return !mpd_isspecial(PHP_RATIONAL_NUM(obj)) && php_decimal_mpd_is_one(PHP_RATIONAL_DEN(obj));
}
/******************************************************************************/
/* OBJECT HANDLERS */
/******************************************************************************/
/**
* Compares two zval's, one of which must be a decimal. This is the function
* used by the compare handler, as well as compareTo.
*/
static php_decimal_success_t php_decimal_rational_compare_handler(zval *res, zval *op1, zval *op2)
{
int result;
int invert;
if (Z_IS_RATIONAL_P(op1)) {
result = php_decimal_rational_compare(Z_RATIONAL_P(op1), op2);
invert = 0;
} else {
result = php_decimal_rational_compare(Z_RATIONAL_P(op2), op1);
invert = 1;
}
/* */
if (UNEXPECTED(result == PHP_DECIMAL_COMPARISON_UNDEFINED)) {
ZVAL_LONG(res, 1);
} else {
ZVAL_LONG(res, invert ? -result : result);
}
return SUCCESS;
}
/**
* var_dump, print_r etc.
*/
static HashTable *php_decimal_rational_get_debug_info(zval *obj, int *is_temp)
{
zval num;
zval den;
HashTable *debug_info;
ALLOC_HASHTABLE(debug_info);
zend_hash_init(debug_info, 2, NULL, ZVAL_PTR_DTOR, 0);
ZVAL_STR(&num, php_decimal_mpd_to_string(PHP_RATIONAL_NUM(Z_RATIONAL_P(obj))));
zend_hash_str_update(debug_info, "num", sizeof("num") - 1, &num);
ZVAL_STR(&den, php_decimal_mpd_to_string(PHP_RATIONAL_DEN(Z_RATIONAL_P(obj))));
zend_hash_str_update(debug_info, "den", sizeof("den") - 1, &den);
*is_temp = 1;
return debug_info;
}
/**
* Cast to string, int, float or bool.
*/
static php_decimal_success_t php_decimal_rational_cast_object(zval *obj, zval *result, int type)
{
switch (type) {
case IS_STRING:
ZVAL_STR(result, php_decimal_rational_to_string(Z_RATIONAL_P(obj)));
return SUCCESS;
case IS_LONG:
ZVAL_LONG(result, php_decimal_rational_to_long(Z_RATIONAL_P(obj)));
return SUCCESS;
case IS_DOUBLE:
ZVAL_DOUBLE(result, php_decimal_rational_to_double(Z_RATIONAL_P(obj)));
return SUCCESS;
case _IS_BOOL:
ZVAL_BOOL(result, 1); /* Objects are always true */
return SUCCESS;
default:
return FAILURE;
}
}
/**
* Converts a zend opcode to a binary arithmetic function pointer.
*
* Returns NULL if a function is not mapped.
*/
static php_decimal_binary_rop_t php_decimal_get_binary_rop(zend_uchar opcode)
{
switch (opcode) {
case ZEND_ADD: return php_decimal_radd;
case ZEND_SUB: return php_decimal_rsub;
case ZEND_MUL: return php_decimal_rmul;
case ZEND_DIV: return php_decimal_rdiv;
case ZEND_MOD: return php_decimal_rmod;
case ZEND_POW: return php_decimal_rpow;
case ZEND_SL: return php_decimal_rshiftl;
case ZEND_SR: return php_decimal_rshiftr;
default:
return NULL;
}
}
/**
* Attempts a binary operation on two zval's, writing the result to res.
*
* We don't know which of the operands is a decimal, if not both.
*/
static void php_decimal_do_binary_rop(php_decimal_binary_rop_t rop, php_rational_t *res, zval *op1, zval *op2)
{
mpd_t *num1;
mpd_t *den1;
mpd_t *num2;
mpd_t *den2;
mpd_t *rnum = PHP_RATIONAL_NUM(res);
mpd_t *rden = PHP_RATIONAL_DEN(res);
PHP_DECIMAL_TEMP_MPD(a);
PHP_DECIMAL_TEMP_MPD(b);
if (Z_IS_RATIONAL_P(op1)) {
if (Z_IS_RATIONAL_P(op2)) {
num1 = PHP_RATIONAL_NUM(Z_RATIONAL_P(op1));
den1 = PHP_RATIONAL_DEN(Z_RATIONAL_P(op1));
num2 = PHP_RATIONAL_NUM(Z_RATIONAL_P(op2));
den2 = PHP_RATIONAL_DEN(Z_RATIONAL_P(op2));
} else {
num1 = PHP_RATIONAL_NUM(Z_RATIONAL_P(op1));
den1 = PHP_RATIONAL_DEN(Z_RATIONAL_P(op1));
num2 = &a;
den2 = &b;
if (php_decimal_parse_num_den(num2, den2, op2) == FAILURE) {
goto failure;
}
}
} else {
num1 = &a;
den1 = &b;
num2 = PHP_RATIONAL_NUM(Z_RATIONAL_P(op2));
den2 = PHP_RATIONAL_DEN(Z_RATIONAL_P(op2));
if (php_decimal_parse_num_den(num1, den1, op1) == FAILURE) {
goto failure;
}
}
/* Parsed successfully, so we can attempt the rational op. */
rop(rnum, rden, num1, den1, num2, den2);
mpd_del(&a);
mpd_del(&b);
return;
failure:
php_decimal_mpd_set_nan(rnum);
php_decimal_mpd_set_one(rden);
mpd_del(&a);
mpd_del(&b);
}
/**
* Operator overloading.
*
* We don't know which of op1 and op2 is a rational object (if not both).
*/
static php_decimal_success_t php_decimal_rational_do_operation(zend_uchar opcode, zval *result, zval *op1, zval *op2)
{
zval op1_copy;
php_rational_t *res;
php_decimal_binary_rop_t op = php_decimal_get_binary_rop(opcode);
/* Unsupported operator - return success to avoid casting. */
if (UNEXPECTED(op == NULL)) {
php_decimal_operator_not_supported();
return SUCCESS;
}
/**
* Check for assignment, eg. $a += 1
*
* If we know that we are writing to an object that is not referenced by
* anything else, we can mutate that object without the need for an
* intermediary. The goal is to avoid unnecessary allocations.
*
* If either the value we are writing to is unknown or it is referenced by
* something else, we have no choice but to allocate a new object.
*/
if (op1 == result) {
if (EXPECTED(Z_IS_RATIONAL_P(op1)) && Z_REFCOUNT_P(op1) == 1) {
res = Z_RATIONAL_P(op1);
} else {
ZVAL_COPY_VALUE(&op1_copy, op1);
op1 = &op1_copy;
res = php_rational();
}
} else {
res = php_rational();
}
/* Attempt operation. */
ZVAL_DECIMAL(result, res);
php_decimal_do_binary_rop(op, res, op1, op2);
/* Operation failed - return success to avoid casting. */
if (UNEXPECTED(EG(exception))) {
php_decimal_mpd_set_nan(PHP_RATIONAL_NUM(Z_RATIONAL_P(result)));
php_decimal_mpd_set_one(PHP_RATIONAL_DEN(Z_RATIONAL_P(result)));
return SUCCESS;
}
if (op1 == &op1_copy) {
zval_dtor(op1);
}
return SUCCESS;
}
/******************************************************************************/
/* SERIALIZATION */
/******************************************************************************/
/**
* Serialize
*/
static php_decimal_success_t php_decimal_rational_serialize(zval *object, unsigned char **buffer, size_t *length, zend_serialize_data *data)
{
zval tmp;
smart_str buf = {0};
php_rational_t *obj = Z_RATIONAL_P(object);
php_serialize_data_t serialize_data = (php_serialize_data_t) data;
PHP_VAR_SERIALIZE_INIT(serialize_data);
/* Serialize the numerator as a string. */
ZVAL_STR(&tmp, php_decimal_mpd_to_serialized(PHP_RATIONAL_NUM(obj)));
php_var_serialize(&buf, &tmp, &serialize_data);
zval_ptr_dtor(&tmp);
/* Serialize the denominator as a string. */
ZVAL_STR(&tmp, php_decimal_mpd_to_serialized(PHP_RATIONAL_DEN(obj)));
php_var_serialize(&buf, &tmp, &serialize_data);
zval_ptr_dtor(&tmp);
PHP_VAR_SERIALIZE_DESTROY(serialize_data);
*buffer = (unsigned char *) estrndup(ZSTR_VAL(buf.s), ZSTR_LEN(buf.s));
*length = ZSTR_LEN(buf.s);
smart_str_free(&buf);
return SUCCESS;
}
/**
* Unserialize
*/
static php_decimal_success_t php_decimal_rational_unserialize(zval *object, zend_class_entry *ce, const unsigned char *buffer, size_t length, zend_unserialize_data *data)
{
zval *num;
zval *den;
php_rational_t *res = php_rational();
ZVAL_RATIONAL(object, res);
php_unserialize_data_t unserialize_data = (php_unserialize_data_t) data;
const unsigned char *pos = buffer;
const unsigned char *end = buffer + length;
PHP_VAR_UNSERIALIZE_INIT(unserialize_data);
/* Unserialize the numerator. */
num = var_tmp_var(&unserialize_data);
if (!php_var_unserialize(num, &pos, end, &unserialize_data) || Z_TYPE_P(num) != IS_STRING) {
goto error;
}
/* Unserialize the denominator. */
den = var_tmp_var(&unserialize_data);
if (!php_var_unserialize(den, &pos, end, &unserialize_data) || Z_TYPE_P(den) != IS_STRING) {
goto error;
}
/* Check that we've parsed the entire serialized string. */
if (pos != end) {
goto error;
}
/* Attempt to parse the unserialized numerator, quietly, delegate to local error. */
if (php_decimal_mpd_set_string(PHP_RATIONAL_NUM(res), Z_STR_P(num)) == FAILURE) {
goto error;
}
/* Attempt to parse the unserialized denominator, quietly, delegate to local error. */
if (php_decimal_mpd_set_string(PHP_RATIONAL_DEN(res), Z_STR_P(den)) == FAILURE) {
goto error;
}
/* Success! Set as zval and return. */
PHP_VAR_UNSERIALIZE_DESTROY(unserialize_data);
return SUCCESS;
error:
zval_ptr_dtor(object);
php_decimal_unserialize_error();
return FAILURE;
}
/******************************************************************************/
/* PHP CLASS METHODS */
/******************************************************************************/
/**
* Determines the rational object to use for the result of an operation.
*/
static php_rational_t *php_decimal_get_result_store(zval *obj)
{
/* Create a new decimal if something else relies on this decimal? */
if (Z_REFCOUNT_P(obj) > 1) {
return php_rational();
}
/* No other reference to $this, so we can re-use it as the result? */
Z_ADDREF_P(obj);
return Z_RATIONAL_P(obj);
}
/**
* Parse a rational binary operation (op1 OP op2).
*/
#define PHP_DECIMAL_PARSE_BINARY_ROP(rop) do { \
zval *op2 = NULL; \
\
PHP_DECIMAL_PARSE_PARAMS(1, 1) \
Z_PARAM_ZVAL(op2) \
PHP_DECIMAL_PARSE_PARAMS_END() \
{ \
php_rational_t *op1 = THIS_RATIONAL(); \
php_rational_t *res = php_decimal_get_result_store(getThis()); \
\
PHP_DECIMAL_TEMP_MPD(a); \
PHP_DECIMAL_TEMP_MPD(b); \
\
mpd_t *rnum = PHP_RATIONAL_NUM(res); \
mpd_t *rden = PHP_RATIONAL_DEN(res); \
mpd_t *num1 = PHP_RATIONAL_NUM(op1); \
mpd_t *den1 = PHP_RATIONAL_DEN(op1); \
mpd_t *num2 = &a; \
mpd_t *den2 = &b; \
\
ZVAL_RATIONAL(return_value, res); \
\
if (EXPECTED(php_decimal_parse_num_den(num2, den2, op2) == SUCCESS)) { \
rop(rnum, rden, num1, den1, num2, den2); \
} else { \
php_decimal_mpd_set_nan(rnum); \
php_decimal_mpd_set_one(rden); \
} \
mpd_del(&a); \
mpd_del(&b); \
} \
} while (0)
/**
* Parse a rational unary operation (OP op1).
*/
#define PHP_DECIMAL_PARSE_UNARY_ROP(op) do { \
php_rational_t *obj = THIS_RATIONAL(); \
php_rational_t *res = php_decimal_get_result_store(getThis()); \
\
mpd_t *rnum = PHP_RATIONAL_NUM(res); \
mpd_t *rden = PHP_RATIONAL_DEN(res); \
mpd_t *num = PHP_RATIONAL_NUM(obj); \
mpd_t *den = PHP_RATIONAL_DEN(obj); \
\
PHP_DECIMAL_PARSE_PARAMS_NONE(); \
op(rnum, rden, num, den); \
RETURN_RATIONAL(res); \
} while (0)
/**
* Rational::valueOf
*/
PHP_DECIMAL_ARGINFO_RETURN_NUMBER(Rational, valueOf, 1)
PHP_DECIMAL_ARGINFO_ZVAL(value)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, valueOf)
{
zval *val = NULL;
PHP_DECIMAL_PARSE_PARAMS(1, 1)
Z_PARAM_ZVAL(val)
PHP_DECIMAL_PARSE_PARAMS_END()
php_decimal_parse_rational(return_value, val);
}
/**
* Rational::__construct
*/
PHP_DECIMAL_ARGINFO(Rational, __construct, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, __construct)
{
/* Does nothing, is private. */
}
/**
* Rational::add
*/
PHP_DECIMAL_ARGINFO_RETURN_NUMBER(Rational, add, 1)
PHP_DECIMAL_ARGINFO_ZVAL(value)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, add)
{
PHP_DECIMAL_PARSE_BINARY_ROP(php_decimal_radd);
}
/**
* Rational::sub
*/
PHP_DECIMAL_ARGINFO_RETURN_NUMBER(Rational, sub, 1)
PHP_DECIMAL_ARGINFO_ZVAL(value)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, sub)
{
PHP_DECIMAL_PARSE_BINARY_ROP(php_decimal_rsub);
}
/**
* Rational::mul
*/
PHP_DECIMAL_ARGINFO_RETURN_NUMBER(Rational, mul, 1)
PHP_DECIMAL_ARGINFO_ZVAL(value)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, mul)
{
PHP_DECIMAL_PARSE_BINARY_ROP(php_decimal_rmul);
}
/**
* Rational::div
*/
PHP_DECIMAL_ARGINFO_RETURN_NUMBER(Rational, div, 1)
PHP_DECIMAL_ARGINFO_ZVAL(value)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, div)
{
PHP_DECIMAL_PARSE_BINARY_ROP(php_decimal_rdiv);
}
/**
* Rational::mod
*/
PHP_DECIMAL_ARGINFO_RETURN_NUMBER(Rational, mod, 1)
PHP_DECIMAL_ARGINFO_ZVAL(value)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, mod)
{
PHP_DECIMAL_PARSE_BINARY_ROP(php_decimal_rmod);
}
/**
* Rational::rem
*/
PHP_DECIMAL_ARGINFO_RETURN_NUMBER(Rational, rem, 1)
PHP_DECIMAL_ARGINFO_ZVAL(value)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, rem)
{
PHP_DECIMAL_PARSE_BINARY_ROP(php_decimal_rrem);
}
/**
* Rational::pow
*/
PHP_DECIMAL_ARGINFO_RETURN_NUMBER(Rational, pow, 1)
PHP_DECIMAL_ARGINFO_ZVAL(exponent)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, pow)
{
PHP_DECIMAL_PARSE_BINARY_ROP(php_decimal_rpow);
}
/**
* Rational::floor
*/
PHP_DECIMAL_ARGINFO_RETURN_NUMBER(Rational, floor, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, floor)
{
PHP_DECIMAL_PARSE_UNARY_ROP(php_decimal_rfloor);
}
/**
* Rational::ceil
*/
PHP_DECIMAL_ARGINFO_RETURN_NUMBER(Rational, ceil, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, ceil)
{
PHP_DECIMAL_PARSE_UNARY_ROP(php_decimal_rceil);
}
/**
* Rational::trunc
*/
PHP_DECIMAL_ARGINFO_RETURN_NUMBER(Rational, trunc, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, trunc)
{
PHP_DECIMAL_PARSE_UNARY_ROP(php_decimal_rtrunc);
}
/**
* Rational::round
*/
PHP_DECIMAL_ARGINFO_RETURN_NUMBER(Rational, round, 0)
PHP_DECIMAL_ARGINFO_OPTIONAL_LONG(places)
PHP_DECIMAL_ARGINFO_OPTIONAL_LONG(rounding)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, round)
{
zend_long places = 0;
zend_long mode = PHP_DECIMAL_DEFAULT_ROUNDING;
PHP_DECIMAL_PARSE_PARAMS(0, 2)
Z_PARAM_OPTIONAL
Z_PARAM_STRICT_LONG(places)
Z_PARAM_STRICT_LONG(mode)
PHP_DECIMAL_PARSE_PARAMS_END()
{
php_rational_t *res = php_rational();
php_rational_t *obj = THIS_RATIONAL();
mpd_t *num = PHP_RATIONAL_NUM(res);
mpd_t *den = PHP_RATIONAL_DEN(res);
mpd_t *tmp = num;
// TODO We should be able to round the fraction inplace, no
// need to evaluate then normalize again and then simply as well.
// It should be a lot easier.
php_decimal_rational_round(tmp, obj, places, mode);
php_decimal_rational_from_mpd(num, den, tmp);
php_decimal_rational_simplify(num, den);
RETURN_RATIONAL(res);
}
}
/**
* Rational::shiftl
*/
PHP_DECIMAL_ARGINFO_RETURN_NUMBER(Rational, shiftl, 1)
PHP_DECIMAL_ARGINFO_ZVAL(places)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, shiftl)
{
PHP_DECIMAL_PARSE_BINARY_ROP(php_decimal_rshiftl);
}
/**
* Rational::shiftr
*/
PHP_DECIMAL_ARGINFO_RETURN_NUMBER(Rational, shiftr, 1)
PHP_DECIMAL_ARGINFO_ZVAL(places)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, shiftr)
{
PHP_DECIMAL_PARSE_BINARY_ROP(php_decimal_rshiftr);
}
/**
* Rational::abs
*/
PHP_DECIMAL_ARGINFO_RETURN_NUMBER(Rational, abs, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, abs)
{
PHP_DECIMAL_PARSE_UNARY_ROP(php_decimal_rabs);
}
/**
* Rational::negate
*/
PHP_DECIMAL_ARGINFO_RETURN_NUMBER(Rational, negate, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, negate)
{
PHP_DECIMAL_PARSE_UNARY_ROP(php_decimal_rneg);
}
/**
* Rational::isEven
*/
PHP_DECIMAL_ARGINFO_RETURN_TYPE(Rational, isEven, _IS_BOOL, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, isEven)
{
php_rational_t *obj = THIS_RATIONAL();
PHP_DECIMAL_PARSE_PARAMS_NONE();
RETURN_BOOL(php_decimal_rational_is_integer(obj) && !php_decimal_rational_parity(obj));
}
/**
* Rational::isOdd
*/
PHP_DECIMAL_ARGINFO_RETURN_TYPE(Rational, isOdd, _IS_BOOL, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, isOdd)
{
php_rational_t *obj = THIS_RATIONAL();
PHP_DECIMAL_PARSE_PARAMS_NONE();
RETURN_BOOL(php_decimal_rational_is_integer(obj) && php_decimal_rational_parity(obj));
}
/**
* Rational::isPositive
*/
PHP_DECIMAL_ARGINFO_RETURN_TYPE(Rational, isPositive, _IS_BOOL, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, isPositive)
{
PHP_DECIMAL_PARSE_PARAMS_NONE();
RETURN_BOOL(mpd_ispositive(PHP_RATIONAL_NUM(THIS_RATIONAL())));
}
/**
* Rational::isNegative
*/
PHP_DECIMAL_ARGINFO_RETURN_TYPE(Rational, isNegative, _IS_BOOL, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, isNegative)
{
PHP_DECIMAL_PARSE_PARAMS_NONE();
RETURN_BOOL(mpd_isnegative(PHP_RATIONAL_NUM(THIS_RATIONAL())));
}
/**
* Rational::isNaN
*/
PHP_DECIMAL_ARGINFO_RETURN_TYPE(Rational, isNaN, _IS_BOOL, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, isNaN)
{
PHP_DECIMAL_PARSE_PARAMS_NONE();
RETURN_BOOL(mpd_isnan(PHP_RATIONAL_NUM(THIS_RATIONAL())));
}
/**
* Rational::isInf
*/
PHP_DECIMAL_ARGINFO_RETURN_TYPE(Rational, isInf, _IS_BOOL, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, isInf)
{
PHP_DECIMAL_PARSE_PARAMS_NONE();
RETURN_BOOL(mpd_isinfinite(PHP_RATIONAL_NUM(THIS_RATIONAL())));
}
/**
* Rational::isInteger
*/
PHP_DECIMAL_ARGINFO_RETURN_TYPE(Rational, isInteger, _IS_BOOL, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, isInteger)
{
PHP_DECIMAL_PARSE_PARAMS_NONE();
RETURN_BOOL(php_decimal_rational_is_integer(THIS_RATIONAL()));
}
/**
* Rational::isZero
*/
PHP_DECIMAL_ARGINFO_RETURN_TYPE(Rational, isZero, _IS_BOOL, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, isZero)
{
PHP_DECIMAL_PARSE_PARAMS_NONE();
RETURN_BOOL(mpd_iszero(PHP_RATIONAL_NUM(THIS_RATIONAL())));
}
/**
* Rational::toFixed
*/
PHP_DECIMAL_ARGINFO_RETURN_TYPE(Rational, toFixed, IS_STRING, 0)
PHP_DECIMAL_ARGINFO_OPTIONAL_LONG(places)
PHP_DECIMAL_ARGINFO_OPTIONAL_BOOL(commas)
PHP_DECIMAL_ARGINFO_OPTIONAL_LONG(mode)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, toFixed)
{
zend_long places = 0;
zend_bool commas = false;
zend_long mode = PHP_DECIMAL_DEFAULT_ROUNDING;
PHP_DECIMAL_PARSE_PARAMS(0, 3)
Z_PARAM_OPTIONAL
Z_PARAM_STRICT_LONG(places)
Z_PARAM_BOOL(commas)
Z_PARAM_STRICT_LONG(mode)
PHP_DECIMAL_PARSE_PARAMS_END()
RETURN_STR(php_decimal_rational_to_fixed(THIS_RATIONAL(), places, commas, mode));
}
/**
* Rational::toSci
*/
PHP_DECIMAL_ARGINFO_RETURN_TYPE(Rational, toSci, IS_STRING, 0)
PHP_DECIMAL_ARGINFO_OPTIONAL_LONG(precision)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, toSci)
{
zend_long prec = PHP_DECIMAL_DEFAULT_PREC;
PHP_DECIMAL_PARSE_PARAMS(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_STRICT_LONG(prec)
PHP_DECIMAL_PARSE_PARAMS_END()
RETURN_STR(php_decimal_rational_to_sci(THIS_RATIONAL(), prec));
}
/**
* Rational::__toString
* Rational::toString
* Rational::jsonSerialize
*/
PHP_DECIMAL_ARGINFO_RETURN_TYPE(Rational, toString, IS_STRING, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, toString)
{
PHP_DECIMAL_PARSE_PARAMS_NONE();
RETURN_STR(php_decimal_rational_to_string(THIS_RATIONAL()));
}
/**
* Rational::toInt
*/
PHP_DECIMAL_ARGINFO_RETURN_TYPE(Rational, toInt, IS_LONG, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, toInt)
{
PHP_DECIMAL_PARSE_PARAMS_NONE();
RETURN_LONG(php_decimal_rational_to_long(THIS_RATIONAL()));
}
/**
* Rational::toFloat
*/
PHP_DECIMAL_ARGINFO_RETURN_TYPE(Rational, toFloat, IS_DOUBLE, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, toFloat)
{
PHP_DECIMAL_PARSE_PARAMS_NONE();
RETURN_DOUBLE(php_decimal_rational_to_double(THIS_RATIONAL()));
}
/**
* Rational::toDecimal
*/
PHP_DECIMAL_ARGINFO_RETURN_DECIMAL(Rational, toDecimal, 1)
PHP_DECIMAL_ARGINFO_LONG(precision)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, toDecimal)
{
zend_long prec;
PHP_DECIMAL_PARSE_PARAMS(1, 1)
Z_PARAM_STRICT_LONG(prec)
PHP_DECIMAL_PARSE_PARAMS_END()
if (php_decimal_validate_prec(prec)) {
php_rational_t *obj = THIS_RATIONAL();
php_decimal_t *res = php_decimal_with_prec(prec);
php_decimal_rational_evaluate(PHP_DECIMAL_MPD(res), obj, prec);
RETURN_DECIMAL(res);
}
}
/**
* Rational::toRational
*/
PHP_DECIMAL_ARGINFO_RETURN_RATIONAL(Rational, toRational, 0)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, toRational)
{
PHP_DECIMAL_PARSE_PARAMS_NONE();
ZVAL_COPY(return_value, getThis());
}
/**
* Rational::compareTo
*/
PHP_DECIMAL_ARGINFO_RETURN_TYPE(Rational, compareTo, IS_LONG, 1)
PHP_DECIMAL_ARGINFO_ZVAL(other)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, compareTo)
{
zval *op2 = NULL;
PHP_DECIMAL_PARSE_PARAMS(1, 1)
Z_PARAM_ZVAL(op2)
PHP_DECIMAL_PARSE_PARAMS_END()
php_decimal_rational_compare_handler(return_value, getThis(), op2);
}
/**
* Rational::between
*/
PHP_DECIMAL_ARGINFO_RETURN_TYPE(Rational, between, _IS_BOOL, 2)
PHP_DECIMAL_ARGINFO_ZVAL(a)
PHP_DECIMAL_ARGINFO_ZVAL(b)
PHP_DECIMAL_ARGINFO_OPTIONAL_BOOL(inclusive)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, between)
{
zval *a, *b;
zend_bool inclusive = PHP_DECIMAL_COMPARE_BETWEEN_INCLUSIVE_DEFAULT;
PHP_DECIMAL_PARSE_PARAMS(2, 3)
Z_PARAM_ZVAL(a)
Z_PARAM_ZVAL(b)
Z_PARAM_OPTIONAL
Z_PARAM_BOOL(inclusive)
PHP_DECIMAL_PARSE_PARAMS_END()
ZVAL_BOOL(return_value, php_decimal_rational_between(THIS_RATIONAL(), a, b, inclusive));
zval_ptr_dtor(a);
zval_ptr_dtor(b);
}
/**
* Rational::equals
*/
PHP_DECIMAL_ARGINFO_RETURN_TYPE(Rational, equals, _IS_BOOL, 1)
PHP_DECIMAL_ARGINFO_ZVAL(other)
PHP_DECIMAL_ARGINFO_END()
PHP_DECIMAL_METHOD(Rational, equals)
{
zval *other;
PHP_DECIMAL_PARSE_PARAMS(1, 1)
Z_PARAM_ZVAL(other)
PHP_DECIMAL_PARSE_PARAMS_END()
ZVAL_BOOL(return_value, php_decimal_rational_compare(THIS_RATIONAL(), other) == 0);
zval_ptr_dtor(other);
}
/******************************************************************************/
/* CLASS ENTRY */
/******************************************************************************/
static zend_function_entry rational_methods[] = {
/* */
PHP_DECIMAL_ME_STATIC(Rational, valueOf)
/* */
PHP_DECIMAL_ME_EX(Rational, __construct, ZEND_ACC_PRIVATE)
PHP_DECIMAL_ME(Rational, add)
PHP_DECIMAL_ME(Rational, sub)
PHP_DECIMAL_ME(Rational, mul)
PHP_DECIMAL_ME(Rational, div)
PHP_DECIMAL_ME(Rational, pow)
PHP_DECIMAL_ME(Rational, rem)
PHP_DECIMAL_ME(Rational, mod)
PHP_DECIMAL_ME(Rational, shiftl)
PHP_DECIMAL_ME(Rational, shiftr)
PHP_DECIMAL_ME(Rational, floor)
PHP_DECIMAL_ME(Rational, ceil)
PHP_DECIMAL_ME(Rational, trunc)
PHP_DECIMAL_ME(Rational, round)
PHP_DECIMAL_ME(Rational, abs)
PHP_DECIMAL_ME(Rational, negate)
PHP_DECIMAL_ME(Rational, isEven)
PHP_DECIMAL_ME(Rational, isOdd)
PHP_DECIMAL_ME(Rational, isPositive)
PHP_DECIMAL_ME(Rational, isNegative)
PHP_DECIMAL_ME(Rational, isNaN)
PHP_DECIMAL_ME(Rational, isInf)
PHP_DECIMAL_ME(Rational, isInteger)
PHP_DECIMAL_ME(Rational, isZero)
PHP_DECIMAL_ME(Rational, toFixed)
PHP_DECIMAL_ME(Rational, toSci)
PHP_DECIMAL_ME(Rational, toString)
PHP_DECIMAL_ME(Rational, toInt)
PHP_DECIMAL_ME(Rational, toFloat)
PHP_DECIMAL_ME(Rational, toDecimal)
PHP_DECIMAL_ME(Rational, toRational)
PHP_DECIMAL_ME(Rational, compareTo)
PHP_DECIMAL_ME(Rational, between)
PHP_DECIMAL_ME(Rational, equals)
PHP_FE_END
};
/**
* Registers the class entry and constants.
*/
void php_decimal_register_rational_class()
{
zend_class_entry ce;
INIT_CLASS_ENTRY(ce, PHP_DECIMAL_RATIONAL_FQCN, rational_methods);
php_decimal_rational_ce = zend_register_internal_class_ex(&ce, php_decimal_number_ce);
/**
*
*/
php_decimal_rational_ce->ce_flags |= ZEND_ACC_FINAL;
/**
*
*/
php_decimal_rational_ce->create_object = php_decimal_rational_create_object;
php_decimal_rational_ce->serialize = php_decimal_rational_serialize;
php_decimal_rational_ce->unserialize = php_decimal_rational_unserialize;
/**
*
*/
memcpy(&php_decimal_rational_handlers, &std_object_handlers, sizeof(zend_object_handlers));
/**
* No need for an offset because we're casting back and forth between
* zend_object and php_decimal. Malloc should know the size of the block so
* when the engine frees the zend_object, it will free the php_decimal. We
* also don't have any class properties and the class is final.
*/
php_decimal_rational_handlers.offset = 0;
php_decimal_rational_handlers.free_obj = php_decimal_rational_free_object;
php_decimal_rational_handlers.clone_obj = php_decimal_rational_clone_obj;
php_decimal_rational_handlers.cast_object = php_decimal_rational_cast_object;
php_decimal_rational_handlers.compare = php_decimal_rational_compare_handler;
php_decimal_rational_handlers.do_operation = php_decimal_rational_do_operation;
php_decimal_rational_handlers.get_debug_info = php_decimal_rational_get_debug_info;
php_decimal_rational_handlers.read_property = php_decimal_blocked_read_property;
php_decimal_rational_handlers.write_property = php_decimal_blocked_write_property;
php_decimal_rational_handlers.has_property = php_decimal_blocked_has_property;
php_decimal_rational_handlers.unset_property = php_decimal_blocked_unset_property;
}
| {
"pile_set_name": "Github"
} |
/**
* SDRangel
* This is the web REST/JSON API of SDRangel SDR software. SDRangel is an Open Source Qt5/OpenGL 3.0+ (4.3+ in Windows) GUI and server Software Defined Radio and signal analyzer in software. It supports Airspy, BladeRF, HackRF, LimeSDR, PlutoSDR, RTL-SDR, SDRplay RSP1 and FunCube --- Limitations and specifcities: * In SDRangel GUI the first Rx device set cannot be deleted. Conversely the server starts with no device sets and its number of device sets can be reduced to zero by as many calls as necessary to /sdrangel/deviceset with DELETE method. * Preset import and export from/to file is a server only feature. * Device set focus is a GUI only feature. * The following channels are not implemented (status 501 is returned): ATV and DATV demodulators, Channel Analyzer NG, LoRa demodulator * The device settings and report structures contains only the sub-structure corresponding to the device type. The DeviceSettings and DeviceReport structures documented here shows all of them but only one will be or should be present at a time * The channel settings and report structures contains only the sub-structure corresponding to the channel type. The ChannelSettings and ChannelReport structures documented here shows all of them but only one will be or should be present at a time ---
*
* OpenAPI spec version: 4.15.0
* Contact: [email protected]
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/*
* SWGAMDemodSettings.h
*
* AMDemod
*/
#ifndef SWGAMDemodSettings_H_
#define SWGAMDemodSettings_H_
#include <QJsonObject>
#include <QString>
#include "SWGObject.h"
#include "export.h"
namespace SWGSDRangel {
class SWG_API SWGAMDemodSettings: public SWGObject {
public:
SWGAMDemodSettings();
SWGAMDemodSettings(QString* json);
virtual ~SWGAMDemodSettings();
void init();
void cleanup();
virtual QString asJson () override;
virtual QJsonObject* asJsonObject() override;
virtual void fromJsonObject(QJsonObject &json) override;
virtual SWGAMDemodSettings* fromJson(QString &jsonString) override;
qint64 getInputFrequencyOffset();
void setInputFrequencyOffset(qint64 input_frequency_offset);
float getRfBandwidth();
void setRfBandwidth(float rf_bandwidth);
float getSquelch();
void setSquelch(float squelch);
float getVolume();
void setVolume(float volume);
qint32 getAudioMute();
void setAudioMute(qint32 audio_mute);
qint32 getBandpassEnable();
void setBandpassEnable(qint32 bandpass_enable);
qint32 getRgbColor();
void setRgbColor(qint32 rgb_color);
QString* getTitle();
void setTitle(QString* title);
QString* getAudioDeviceName();
void setAudioDeviceName(QString* audio_device_name);
qint32 getPll();
void setPll(qint32 pll);
qint32 getSyncAmOperation();
void setSyncAmOperation(qint32 sync_am_operation);
qint32 getStreamIndex();
void setStreamIndex(qint32 stream_index);
qint32 getUseReverseApi();
void setUseReverseApi(qint32 use_reverse_api);
QString* getReverseApiAddress();
void setReverseApiAddress(QString* reverse_api_address);
qint32 getReverseApiPort();
void setReverseApiPort(qint32 reverse_api_port);
qint32 getReverseApiDeviceIndex();
void setReverseApiDeviceIndex(qint32 reverse_api_device_index);
qint32 getReverseApiChannelIndex();
void setReverseApiChannelIndex(qint32 reverse_api_channel_index);
virtual bool isSet() override;
private:
qint64 input_frequency_offset;
bool m_input_frequency_offset_isSet;
float rf_bandwidth;
bool m_rf_bandwidth_isSet;
float squelch;
bool m_squelch_isSet;
float volume;
bool m_volume_isSet;
qint32 audio_mute;
bool m_audio_mute_isSet;
qint32 bandpass_enable;
bool m_bandpass_enable_isSet;
qint32 rgb_color;
bool m_rgb_color_isSet;
QString* title;
bool m_title_isSet;
QString* audio_device_name;
bool m_audio_device_name_isSet;
qint32 pll;
bool m_pll_isSet;
qint32 sync_am_operation;
bool m_sync_am_operation_isSet;
qint32 stream_index;
bool m_stream_index_isSet;
qint32 use_reverse_api;
bool m_use_reverse_api_isSet;
QString* reverse_api_address;
bool m_reverse_api_address_isSet;
qint32 reverse_api_port;
bool m_reverse_api_port_isSet;
qint32 reverse_api_device_index;
bool m_reverse_api_device_index_isSet;
qint32 reverse_api_channel_index;
bool m_reverse_api_channel_index_isSet;
};
}
#endif /* SWGAMDemodSettings_H_ */
| {
"pile_set_name": "Github"
} |
sha256:281f1790d69d56469bf102ed5a3943515acd00de3953aeb2e9d90c87c1dd11fe
| {
"pile_set_name": "Github"
} |
// bdlmt_fixedthreadpool.h -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#ifndef INCLUDED_BDLMT_FIXEDTHREADPOOL
#define INCLUDED_BDLMT_FIXEDTHREADPOOL
#include <bsls_ident.h>
BSLS_IDENT("$Id: $")
//@PURPOSE: Provide portable implementation for a fixed-size pool of threads.
//
//@CLASSES:
// bdlmt::FixedThreadPool: portable fixed-size thread pool
//
//@SEE_ALSO: bdlmt_threadpool
//
//@DESCRIPTION: This component defines a portable and efficient implementation
// of a thread pool, 'bdlmt::FixedThreadPool', that can be used to distribute
// various user-defined functions ("jobs") to a separate threads to execute
// the jobs concurrently. Each thread pool object manages a fixed number of
// processing threads and can hold up to a fixed maximum number of pending
// jobs.
//
// 'bdlmt::FixedThreadPool' implements a queuing mechanism that distributes
// work among the threads. Jobs are queued for execution as they arrive, and
// each queued job is processed by the next available thread. If each of the
// concurrent threads is busy processing a job, new jobs will remain enqueued
// until a thread becomes available. If the queue capacity is reached,
// enqueuing jobs will block until threads consume more jobs from the queue,
// causing its length to drop below its capacity. Both the queue's capacity
// and number of threads are specified at construction and cannot be changed.
//
// The thread pool provides two interfaces for specifying jobs: the commonly
// used "void function/void pointer" interface and the more versatile functor
// based interface. The void function/void pointer interface allows callers to
// use a C-style function to be executed as a job. The application need only
// specify the address of the function, and a single void pointer argument, to
// be passed to the function. The specified function will be invoked with the
// specified argument by the processing thread. The functor based interface
// allows for more flexible job execution such as the invocation of member
// functions or the passing of multiple user-defined arguments. See the 'bdef'
// package-level documentation for more on functors and their usage.
//
// Unlike a 'bdlmt::ThreadPool', an application can not tune a
// 'bdlmt::FixedThreadPool' once it is created with a specified number of
// threads and queue capacity, hence the name "fixed" thread pool. An
// application can, however, specify the attributes of the threads in the pool
// (e.g., thread priority or stack size), by providing a
// 'bslmt::ThreadAttributes' object with the desired values set. See
// 'bslmt_threadutil' package documentation for a description of
// 'bslmt::ThreadAttributes'.
//
// Thread pools are ideal for developing multi-threaded server applications. A
// server need only package client requests to execute as jobs, and
// 'bdlmt::FixedThreadPool' will handle the queue management, thread
// management, and request dispatching. Thread pools are also well suited for
// parallelizing certain types of application logic. Without any complex or
// redundant thread management code, an application can easily create a thread
// pool, enqueue a series of jobs to be executed, and wait until all the jobs
// have executed.
//
///Thread Safety
///-------------
// The 'bdlmt::FixedThreadPool' class is both *fully thread-safe* (i.e., all
// non-creator methods can correctly execute concurrently), and is
// *thread-enabled* (i.e., the classes does not function correctly in a
// non-multi-threading environment). See 'bsldoc_glossary' for complete
// definitions of *fully thread-safe* and *thread-enabled*.
//
///Synchronous Signals on Unix
///---------------------------
// A thread pool ensures that, on unix platforms, all the threads in the pool
// block all asynchronous signals. Specifically all the signals, except the
// following synchronous signals are blocked:
//..
// SIGBUS
// SIGFPE
// SIGILL
// SIGSEGV
// SIGSYS
// SIGABRT
// SIGTRAP
// SIGIOT
//..
//
///Usage
///-----
// This example demonstrates the use of a 'bdlmt::FixedThreadPool' to
// parallelize a segment of program logic. The example implements a
// multi-threaded file search utility. The utility searches multiple files for
// a string, similar to the Unix command 'fgrep'; the use of a
// 'bdlmt::FixedThreadPool' allows the utility to search multiple files
// concurrently.
//
// The example program will take as input a string and a list of files to
// search. The program creates a 'bdlmt::FixedThreadPool', and then enqueues a
// single "job" for each file to be searched. Each thread in the pool will
// take a job from the queue, open the file, and search for the string. If a
// match is found, the job adds the filename to an array of matching filenames.
// Because this array of filenames is shared across multiple jobs and across
// multiple threads, access to the array is controlled via a 'bslmt::Mutex'.
//
///Setting FixedThreadPool Attributes
/// - - - - - - - - - - - - - - - - -
// To get started, we declare thread attributes, to be used in constructing the
// thread pool. In this example, our choices for number of threads and queue
// capacity are arbitrary.
//..
// #define SEARCH_THREADS 10
// #define SEARCH_QUEUE_CAPACITY 50
//..
// Below is the structure that will be used to pass arguments to the file
// search function. Since each job will be searching a separate file, a
// distinct instance of the structure will be used for each job.
//..
// struct my_FastSearchJobInfo {
// const bsl::string *d_word; // word to search for
// const bsl::string *d_path; // path of the file to search
// bslmt::Mutex *d_mutex; // mutex to control access to the
// // result file list
// bsl::vector<bsl::string> *d_outList; // list of matching files
// };
//..
//
///The "void function/void pointer" Interface
/// - - - - - - - - - - - - - - - - - - - - -
// 'myFastSearchJob' is the search function to be executed as a job by threads
// in the thread pool, matching the "void function/void pointer" interface.
// The single 'void *' argument is received and cast to point to a 'struct
// my_FastSearchJobInfo', which then points to the search string and a single
// file to be searched. Note that different 'my_FastSearchInfo' structures for
// the same search request will differ only in the attribute 'd_path', which
// points to a specific filename among the set of files to be searched; other
// fields will be identical across all structures for a given Fast Search.
//
// See the following section for an illustration of the functor interface.
//..
// static void myFastSearchJob(void *arg)
// {
// myFastSearchJobInfo *job = (myFastSearchJobInfo*)arg;
// FILE *file;
//
// file = fopen(job->d_path->c_str(), "r");
//
// if (file) {
// char buffer[1024];
// size_t nread;
// int wordLen = job->d_word->length();
// const char *word = job->d_word->c_str();
//
// nread = fread(buffer, 1, sizeof(buffer) - 1, file);
// while(nread >= wordLen) {
// buffer[nread] = 0;
// if (strstr(buffer, word)) {
//..
// If we find a match, we add the file to the result list and return. Since
// the result list is shared among multiple processing threads, we use a mutex
// lock to regulate access to the list. We use a 'bslmt::LockGuard' to manage
// access to the mutex lock. This template object acquires a mutex lock on
// 'job->d_mutex' at construction, releases that lock on destruction. Thus,
// the mutex will be locked within the scope of the 'if' block, and released
// when the program exits that scope.
//
// See 'bslmt_threadutil' for information about the 'bslmt::Mutex' class, and
// component 'bslmt_lockguard' for information about the 'bslmt::LockGuard'
// template class.
//..
// bslmt::LockGuard<bslmt::Mutex> lock(job->d_mutex);
// job->d_outList->push_back(*job->d_path);
// break; // bslmt::LockGuard destructor unlocks mutex.
// }
// memcpy(buffer, &buffer[nread - wordLen - 1], wordLen - 1);
// nread = fread(buffer + wordLen - 1, 1, sizeof(buffer) - wordLen,
// file);
// }
// fclose(file);
// }
// }
//..
// Routine 'myFastSearch' is the main driving routine, taking three arguments:
// a single string to search for ('word'), a list of files to search, and an
// output list of files. When the function completes, the file list will
// contain the names of files where a match was found.
//..
// void myFastSearch(const bsl::string& word,
// const bsl::vector<bsl::string>& fileList,
// bsl::vector<bsl::string>& outFileList)
// {
// bslmt::Mutex mutex;
// bslmt::ThreadAttributes defaultAttributes;
//..
// We initialize the thread pool using default thread attributes. We then
// start the pool so that the threads can begin while we prepare the jobs.
//..
// bdlmt::FixedThreadPool pool(defaultAttributes,
// SEARCH_THREADS,
// SEARCH_QUEUE_CAPACITY);
//
// if (0 != pool.start()) {
// bsl::cerr << "Thread start() failed. Thread quota exceeded?"
// << bsl::endl;
// exit(1);
// }
//..
// For each file to be searched, we create the job info structure that will be
// passed to the search function and add the job to the pool.
//
// As noted above, all jobs will share a single mutex to guard the output file
// list. Function 'myFastSearchJob' uses a 'bslmt::LockGuard' on this mutex to
// serialize access to the list.
//..
// int count = fileList.size();
// my_FastSearchJobInfo *jobInfoArray = new my_FastSearchJobInfo[count];
//
// for (int i = 0; i < count; ++i) {
// my_FastSearchJobInfo &job = jobInfoArray[i];
// job.d_word = &word;
// job.d_path = &fileList[i];
// job.d_mutex = &mutex;
// job.d_outList = &outFileList;
// pool.enqueueJob(myFastSearchJob, &job);
// }
//..
// Now we simply wait for all the jobs in the queue to complete. Any matched
// files should have been added to the output file list.
//..
// pool.drain();
// delete[] jobInfoArray;
// }
//..
//
///The Functor Interface
///- - - - - - - - - - -
// The "void function/void pointer" convention is idiomatic for C programs.
// The 'void' pointer argument provides a generic way of passing in user data,
// without regard to the data type. Clients who prefer better or more explicit
// type safety may wish to use the Functor Interface instead. This interface
// uses 'bsl::function' to provide type-safe wrappers that can match argument
// number and type for a C++ free function or member function.
//
// To illustrate the Functor Interface, we will make two small changes to the
// usage example above. First, we change the signature of the function that
// executes a single job, so that it uses a 'myFastSearchJobInfo' pointer
// rather than a 'void' pointer. With this change, we can remove the first
// executable statement, which casts the 'void *' pointer to
// 'myFastSearchJobInfo *'.
//..
// static void myFastFunctorSearchJob(myFastSearchJobInfo *job)
// {
// FILE *file;
//
// file = fopen(job->d_path->c_str(), "r");
// // the rest of the function is unchanged.
//..
// Next, we make a change to the loop that enqueues the jobs in 'myFastSearch'.
// We create a functor - a C++ object that acts as a function. The thread pool
// will "execute" this functor (by calling its 'operator()' member function) on
// a thread when one becomes available.
//..
// for (int i = 0; i < count; ++i) {
// my_FastSearchJobInfo &job = jobInfoArray[i];
// job.d_word = &word;
// job.d_path = &fileList[i];
// job.d_mutex = &mutex;
// job.d_outList = &outFileList;
//
// bsl::function<void()> jobHandle =
// bdlf::BindUtil::bind(&myFastFunctorSearchJob, &job);
// pool.enqueueJob(jobHandle);
// }
//..
// Use of 'bsl::function' and 'bdlf::BindUtil' is described in the 'bdef'
// package documentation. For this example, it is important to note that
// 'jobHandle' is a functor object, and that 'bdlf::BindUtil::bind' populates
// that functor object with a function pointer (to the 'void' function
// 'myFastFunctorSearchJob') and user data ('&job'). When the functor is
// executed via 'operator()', it will in turn execute the
// 'myFastFunctorSearchJob' function with the supplied data as its argument.
//
// Note also that the functor is created locally and handed to the thread pool.
// The thread pool copies the functor onto its internal queue, and takes
// responsibility for the copied functor until execution is complete.
//
// The function is completed exactly as it was in the previous example.
//..
// pool.drain();
// delete[] jobInfoArray;
// }
//..
#include <bdlscm_version.h>
#include <bdlcc_fixedqueue.h>
#include <bslmf_movableref.h>
#include <bslmt_mutex.h>
#include <bslmt_semaphore.h>
#include <bslmt_threadattributes.h>
#include <bslmt_threadutil.h>
#include <bslmt_condition.h>
#include <bslmt_threadgroup.h>
#include <bsls_atomic.h>
#include <bsls_platform.h>
#include <bdlf_bind.h>
#include <bslma_allocator.h>
#include <bsl_cstdlib.h>
#include <bsl_functional.h>
namespace BloombergLP {
#ifndef BDE_OMIT_INTERNAL_DEPRECATED
extern "C" typedef void (*bcep_FixedThreadPoolJobFunc)(void *);
// This type declares the prototype for functions that are suitable to
// be specified 'bdlmt::FixedThreadPool::enqueueJob'.
#endif // BDE_OMIT_INTERNAL_DEPRECATED
namespace bdlmt {
extern "C" typedef void (*FixedThreadPoolJobFunc)(void *);
// This type declares the prototype for functions that are suitable to be
// specified 'bdlmt::FixedThreadPool::enqueueJob'.
// =====================
// class FixedThreadPool
// =====================
class FixedThreadPool {
// This class implements a thread pool used for concurrently executing
// multiple user-defined functions ("jobs").
public:
// TYPES
typedef bsl::function<void()> Job;
typedef bdlcc::FixedQueue<Job> Queue;
enum {
e_STOP
, e_RUN
, e_SUSPEND
, e_DRAIN
#ifndef BDE_OMIT_INTERNAL_DEPRECATED
, BCEP_STOP = e_STOP
, BCEP_RUN = e_RUN
, BCEP_SUSPEND = e_SUSPEND
, BCEP_DRAIN = e_DRAIN
, TP_STOP = e_STOP
, TP_RUN = e_RUN
, TP_SUSPEND = e_SUSPEND
, TP_DRAIN = e_DRAIN
#endif // BDE_OMIT_INTERNAL_DEPRECATED
};
private:
// DATA
Queue d_queue; // underlying queue
bslmt::Semaphore d_queueSemaphore; // used to implemented
// blocking popping on the
// queue
bsls::AtomicInt d_numThreadsWaiting; // number of idle thread in
// the pool
bslmt::Mutex d_metaMutex; // mutex to ensure that there
// is only one controlling
// thread at any time
bsls::AtomicInt d_control; // controls which action is
// to be performed by the
// worker threads (i.e.,
// e_RUN, e_DRAIN, or e_STOP)
int d_gateCount; // count incremented every
// time worker threads are
// allowed to proceed through
// the gate
int d_numThreadsReady; // number of worker threads
// ready to go through the
// gate
bslmt::Mutex d_gateMutex; // mutex used to protect the
// gate count
bslmt::Condition d_threadsReadyCond; // condition signaled when a
// worker thread is ready at
// the gate
bslmt::Condition d_gateCond; // condition signaled when
// the gate count is
// incremented
bslmt::ThreadGroup d_threadGroup; // threads used by this pool
bslmt::ThreadAttributes d_threadAttributes; // thread attributes to be
// used when constructing
// processing threads
const int d_numThreads; // number of configured
// processing threads.
#if defined(BSLS_PLATFORM_OS_UNIX)
sigset_t d_blockSet; // set of signals to be
// blocked in managed threads
#endif
// PRIVATE MANIPULATORS
void processJobs();
// Repeatedly retrieves the next job off of the queue and processes it
// or blocks until one is available. This function terminates when it
// detects a change in the control state.
void drainQueue();
// Repeatedly retrieves the next job off of the queue and processes it
// until the queue is empty.
void workerThread();
// The main function executed by each worker thread.
int startNewThread();
// Internal method to spawn a new processing thread and increment the
// current count. Note that this method must be called with
// 'd_metaMutex' locked.
void waitWorkerThreads();
// Waits for worker threads to be ready at the gate.
void releaseWorkerThreads();
// Allows worker threads to proceed through the gate.
void interruptWorkerThreads();
// Awaken any waiting worker threads by signaling the queue semaphore.
// NOT IMPLEMENTED
FixedThreadPool(const FixedThreadPool&);
FixedThreadPool& operator=(const FixedThreadPool&);
public:
// CREATORS
FixedThreadPool(int numThreads,
int maxNumPendingJobs,
bslma::Allocator *basicAllocator = 0);
// Construct a thread pool with the specified 'numThreads' number of
// threads and a job queue of capacity sufficient to enqueue the
// specified 'maxNumPendingJobs' without blocking. Optionally specify
// a 'basicAllocator' used to supply memory. If 'basicAllocator' is 0,
// the currently installed default allocator is used. The behavior is
// undefined unless '1 <= numThreads' and
// '1 <= maxPendingJobs <= 0x01FFFFFF'.
FixedThreadPool(const bslmt::ThreadAttributes& threadAttributes,
int numThreads,
int maxNumPendingJobs,
bslma::Allocator *basicAllocator = 0);
// Construct a thread pool with the specified 'threadAttributes',
// 'numThreads' number of threads, and a job queue with capacity
// sufficient to enqueue the specified 'maxNumPendingJobs' without
// blocking. Optionally specify a 'basicAllocator' used to supply
// memory. If 'basicAllocator' is 0, the currently installed default
// allocator is used. The behavior is undefined unless
// '1 <= numThreads' and '1 <= maxPendingJobs <= 0x01FFFFFF'.
~FixedThreadPool();
// Remove all pending jobs from the queue without executing them, block
// until all currently running jobs complete, and then destroy this
// thread pool.
// MANIPULATORS
void disable();
// Disable queuing into this pool. Subsequent calls to enqueueJob() or
// tryEnqueueJob() will immediately fail. Note that this method has no
// effect on jobs currently in the pool.
void enable();
// Enable queuing into this pool.
int enqueueJob(const Job& functor);
int enqueueJob(bslmf::MovableRef<Job> functor);
// Enqueue the specified 'functor' to be executed by the next available
// thread. Return 0 if enqueued successfully, and a non-zero value if
// queuing is currently disabled. Note that this function can block if
// the underlying fixed queue has reached full capacity; use
// 'tryEnqueueJob' instead for non-blocking. The behavior is undefined
// unless 'functor' is not "unset". See 'bsl::function' for more
// information on functors.
int enqueueJob(FixedThreadPoolJobFunc function, void *userData);
// Enqueue the specified 'function' to be executed by the next
// available thread. The specified 'userData' pointer will be passed
// to the function by the processing thread. Return 0 if enqueued
// successfully, and a non-zero value if queuing is currently disabled.
int tryEnqueueJob(const Job& functor);
int tryEnqueueJob(bslmf::MovableRef<Job> functor);
// Attempt to enqueue the specified 'functor' to be executed by the
// next available thread. Return 0 if enqueued successfully, and a
// nonzero value if queuing is currently disabled or the queue is full.
// The behavior is undefined unless 'functor' is not "unset".
int tryEnqueueJob(FixedThreadPoolJobFunc function, void *userData);
// Attempt to enqueue the specified 'function' to be executed by the
// next available thread. The specified 'userData' pointer will be
// passed to the function by the processing thread. Return 0 if
// enqueued successfully, and a nonzero value if queuing is currently
// disabled or the queue is full.
void drain();
// Wait until all pending jobs complete. Note that if any jobs are
// submitted concurrently with this method, this method may or may not
// wait until they have also completed.
void shutdown();
// Disable queuing on this thread pool, cancel all queued jobs, and
// after all actives jobs have completed, join all processing threads.
int start();
// Spawn 'numThreads()' processing threads. On success, enable
// enqueuing and return 0. Return a nonzero value otherwise. If
// 'numThreads()' threads were not successfully started, all threads
// are stopped.
void stop();
// Disable queuing on this thread pool and wait until all pending jobs
// complete, then shut down all processing threads.
// ACCESSORS
bool isEnabled() const;
// Return 'true' if queuing is enabled on this thread pool, and 'false'
// otherwise.
bool isStarted() const;
// Return 'true' if 'numThreads()' are started on this threadpool() and
// 'false' otherwise (indicating that 0 threads are started on this
// thread pool.)
int numActiveThreads() const;
// Return a snapshot of the number of threads that are currently
// processing a job for this threadpool.
int numPendingJobs() const;
// Return a snapshot of the number of jobs currently enqueued to be
// processed by thread pool.
int numThreads() const;
// Return the number of threads passed to this thread pool at
// construction.
int numThreadsStarted() const;
// Return a snapshot of the number of threads currently started by this
// thread pool.
int queueCapacity() const;
// Return the capacity of the queue used to enqueue jobs by this thread
// pool.
};
// ============================================================================
// INLINE DEFINITIONS
// ============================================================================
// ---------------------
// class FixedThreadPool
// ---------------------
// MANIPULATORS
inline
void FixedThreadPool::disable()
{
d_queue.disable();
}
inline
void FixedThreadPool::enable()
{
d_queue.enable();
}
inline
int FixedThreadPool::enqueueJob(FixedThreadPoolJobFunc function,
void *userData)
{
return enqueueJob(bdlf::BindUtil::bindR<void>(function, userData));
}
inline
int FixedThreadPool::tryEnqueueJob(FixedThreadPoolJobFunc function,
void *userData)
{
return tryEnqueueJob(bdlf::BindUtil::bindR<void>(function, userData));
}
// ACCESSORS
inline
bool FixedThreadPool::isEnabled() const
{
return d_queue.isEnabled();
}
inline
bool FixedThreadPool::isStarted() const
{
return d_numThreads == d_threadGroup.numThreads();
}
inline
int FixedThreadPool::numActiveThreads() const
{
int numStarted = d_threadGroup.numThreads();
return d_numThreads == numStarted
? numStarted - d_numThreadsWaiting.loadRelaxed()
: 0;
}
inline
int FixedThreadPool::numPendingJobs() const
{
return d_queue.length();
}
inline
int FixedThreadPool::numThreads() const
{
return d_numThreads;
}
inline
int FixedThreadPool::numThreadsStarted() const
{
return d_threadGroup.numThreads();
}
inline
int FixedThreadPool::queueCapacity() const
{
return d_queue.size();
}
} // close package namespace
} // close enterprise namespace
#endif
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| {
"pile_set_name": "Github"
} |
#
# Makefile for the PowerPC 85xx linux kernel.
#
obj-$(CONFIG_SMP) += smp.o
obj-y += common.o
obj-$(CONFIG_MPC8540_ADS) += mpc85xx_ads.o
obj-$(CONFIG_MPC8560_ADS) += mpc85xx_ads.o
obj-$(CONFIG_MPC85xx_CDS) += mpc85xx_cds.o
obj-$(CONFIG_MPC8536_DS) += mpc8536_ds.o
obj-$(CONFIG_MPC85xx_DS) += mpc85xx_ds.o
obj-$(CONFIG_MPC85xx_MDS) += mpc85xx_mds.o
obj-$(CONFIG_MPC85xx_RDB) += mpc85xx_rdb.o
obj-$(CONFIG_P1010_RDB) += p1010rdb.o
obj-$(CONFIG_P1022_DS) += p1022_ds.o
obj-$(CONFIG_P1023_RDS) += p1023_rds.o
obj-$(CONFIG_P2041_RDB) += p2041_rdb.o corenet_ds.o
obj-$(CONFIG_P3041_DS) += p3041_ds.o corenet_ds.o
obj-$(CONFIG_P3060_QDS) += p3060_qds.o corenet_ds.o
obj-$(CONFIG_P4080_DS) += p4080_ds.o corenet_ds.o
obj-$(CONFIG_P5020_DS) += p5020_ds.o corenet_ds.o
obj-$(CONFIG_STX_GP3) += stx_gp3.o
obj-$(CONFIG_TQM85xx) += tqm85xx.o
obj-$(CONFIG_SBC8560) += sbc8560.o
obj-$(CONFIG_SBC8548) += sbc8548.o
obj-$(CONFIG_SOCRATES) += socrates.o socrates_fpga_pic.o
obj-$(CONFIG_KSI8560) += ksi8560.o
obj-$(CONFIG_XES_MPC85xx) += xes_mpc85xx.o
obj-$(CONFIG_GE_IMP3A) += ge_imp3a.o
| {
"pile_set_name": "Github"
} |
import React from 'react';
import renderer from 'react-test-renderer';
import View from '../../src/components/View';
it('renders correctly', () => {
const tree = renderer.create(<View />).toJSON();
expect(tree).toMatchSnapshot();
});
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<refentry xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svg="http://www.w3.org/2000/svg" xmlns:ns4="http://www.w3.org/1999/xhtml" xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:db="http://docbook.org/ns/docbook" xmlns:scilab="http://www.scilab.org" xml:id="interp" xml:lang="pt">
<refnamediv>
<refname>interp</refname>
<refpurpose>função de avaliação de spline cúbico</refpurpose>
</refnamediv>
<refsynopsisdiv>
<title>Seqüência de Chamamento</title>
<synopsis>[yp [,yp1 [,yp2 [,yp3]]]]=interp(xp, x, y, d [, out_mode])</synopsis>
</refsynopsisdiv>
<refsection>
<title>Parâmetros</title>
<variablelist>
<varlistentry>
<term>xp</term>
<listitem>
<para>vetor ou matriz de reais</para>
</listitem>
</varlistentry>
<varlistentry>
<term>x,y,d</term>
<listitem>
<para>vetores de reais de mesmo tamanho definindo uma função de
spline cúbico ou sub-spline (chamado <literal>s</literal> a partir
daqui)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>out_mode</term>
<listitem>
<para>
(opcional) string definido a avaliação de <literal>s</literal>
fora do intervalo [x1,xn]
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>yp</term>
<listitem>
<para>
vetor ou matriz de mesmo tamanho que <literal>xp</literal>,
avaliação elemento a elemento de <literal>s</literal> em
<literal>xp</literal> (yp(i)=s(xp(i) ou yp(i,j)=s(xp(i,j))
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>yp1, yp2, yp3</term>
<listitem>
<para>vetores (ou matrizes) de mesmo tamanho que
<literal>xp</literal>, avaliação elemento a elemento das derivadas
sucessivas de <literal>s</literal> em <literal>xp</literal>
</para>
</listitem>
</varlistentry>
</variablelist>
</refsection>
<refsection>
<title>Descrição</title>
<para>
Dados três vetores <literal>(x,y,d)</literal> ddefinindo uma função
de spline cúbico ou sup-spline (ver <link linkend="splin">splin</link>)
com <literal>yi=s(xi), di = s'(xi)</literal> esta função avalia
<literal>s</literal> (e <literal>s', s'', s'''</literal> se necessário) em
<literal>xp(i)</literal> :
</para>
<programlisting role=""><![CDATA[
yp(i) = s(xp(i)) ou yp(i,j) = s(xp(i,j))
yp1(i) = s'(xp(i)) ou yp1(i,j) = s'(xp(i,j))
yp2(i) = s''(xp(i)) ou yp2(i,j) = s''(xp(i,j))
yp3(i) = s'''(xp(i)) ou yp3(i,j) = s'''(xp(i,j))
]]></programlisting>
<para>
O parâmetro <literal>out_mode</literal> ajusta a regra de avaliação
para extrapolação, i.e., para <literal>xp(i)</literal> fora de [x1,xn] :
</para>
<variablelist>
<varlistentry>
<term>"by_zero"</term>
<listitem>
<para>uma extrapolação por zero é feita </para>
</listitem>
</varlistentry>
<varlistentry>
<term>"by_nan"</term>
<listitem>
<para>extrapolação por NaN </para>
</listitem>
</varlistentry>
<varlistentry>
<term>"C0"</term>
<listitem>
<para>a extrapolação é definida como segue :</para>
<programlisting role=""><![CDATA[
s(x) = y1 para x < x1
s(x) = yn para x > xn
]]></programlisting>
</listitem>
</varlistentry>
<varlistentry>
<term>"natural"</term>
<listitem>
<para>a extrapolação é definida como segue (p_i sendo o polinômio
que define <literal>s</literal> em [x_i,x_{i+1}]) :
</para>
<programlisting role=""><![CDATA[
s(x) = p_1(x) para x < x1
s(x) = p_{n-1}(x) para x > xn
]]></programlisting>
</listitem>
</varlistentry>
<varlistentry>
<term>"linear"</term>
<listitem>
<para>a extrapolação é definida como segue :</para>
<programlisting role=""><![CDATA[
s(x) = y1 + s'(x1)(x-x1) para x < x1
s(x) = yn + s'(xn)(x-xn) para x > xn
]]></programlisting>
</listitem>
</varlistentry>
<varlistentry>
<term>"periodic"</term>
<listitem>
<para>
<literal>s</literal> é estendido por periodicidade.
</para>
</listitem>
</varlistentry>
</variablelist>
</refsection>
<refsection>
<title>Exemplos </title>
<programlisting role="example"><![CDATA[
// veja os exemplos de splin e lsq_splin
// um exemplo exibindo as continuidades C2 e C1 de um spline e um sub-spline
a = -8; b = 8;
x = linspace(a,b,20)';
y = sinc(x);
dk = splin(x,y); // not_a_knot
df = splin(x,y, "fast");
xx = linspace(a,b,800)';
[yyk, yy1k, yy2k] = interp(xx, x, y, dk);
[yyf, yy1f, yy2f] = interp(xx, x, y, df);
clf()
subplot(3,1,1)
plot2d(xx, [yyk yyf])
plot2d(x, y, style=-9)
legends(["spline não é um nó","sub-spline rápido","pontos de interpolação"],...
[1 2 -9], "ur",%f)
xtitle("interpolação por spline")
subplot(3,1,2)
plot2d(xx, [yy1k yy1f])
legends(["spline não é um nó","sub-spline rápido"], [1 2], "ur",%f)
xtitle("interpolação por spline (derivadas)")
subplot(3,1,3)
plot2d(xx, [yy2k yy2f])
legends(["spline não é um nó","sub-spline rápido"], [1 2], "lr",%f)
xtitle("interpolação por splines (segundas derivadas)")
// aqui está um exemplo mostrando as diferentes possibilidades de extrapolação
x = linspace(0,1,11)';
y = cosh(x-0.5);
d = splin(x,y);
xx = linspace(-0.5,1.5,401)';
yy0 = interp(xx,x,y,d,"C0");
yy1 = interp(xx,x,y,d,"linear");
yy2 = interp(xx,x,y,d,"natural");
yy3 = interp(xx,x,y,d,"periodic");
clf()
plot2d(xx,[yy0 yy1 yy2 yy3],style=2:5,frameflag=2,leg="C0@linear@natural@periodic")
xtitle(" Modos diferentes de avaliar um spline fora de seu domínio")
]]></programlisting>
</refsection>
<refsection role="see also">
<title>Ver Também</title>
<simplelist type="inline">
<member>
<link linkend="splin">splin</link>
</member>
<member>
<link linkend="lsq_splin">lsq_splin</link>
</member>
</simplelist>
</refsection>
</refentry>
| {
"pile_set_name": "Github"
} |
#include <core.p4>
#define V1MODEL_VERSION 20200408
#include <v1model.p4>
header ethernet_t {
bit<48> dstAddr;
bit<48> srcAddr;
bit<16> etherType;
}
struct metadata {
}
struct headers {
@name(".ethernet")
ethernet_t ethernet;
@name(".inner_ethernet")
ethernet_t inner_ethernet;
}
parser ParserImpl(packet_in packet, out headers hdr, inout metadata meta, inout standard_metadata_t standard_metadata) {
@name(".pvs0") value_set<bit<16>>(4) pvs0;
@name(".pvs1") value_set<bit<16>>(4) pvs1;
@name(".parse_ethernet") state parse_ethernet {
packet.extract(hdr.ethernet);
transition select(hdr.ethernet.etherType) {
pvs0: accept;
pvs1: parse_inner_ethernet;
default: accept;
}
}
@name(".parse_inner_ethernet") state parse_inner_ethernet {
packet.extract(hdr.inner_ethernet);
transition accept;
}
@name(".start") state start {
transition parse_ethernet;
}
}
control ingress(inout headers hdr, inout metadata meta, inout standard_metadata_t standard_metadata) {
@name(".noop") action noop() {
;
}
@name(".dummy") table dummy {
actions = {
noop;
}
key = {
hdr.ethernet.dstAddr: exact;
}
size = 512;
}
apply {
dummy.apply();
}
}
control egress(inout headers hdr, inout metadata meta, inout standard_metadata_t standard_metadata) {
apply {
}
}
control DeparserImpl(packet_out packet, in headers hdr) {
apply {
packet.emit(hdr.ethernet);
packet.emit(hdr.inner_ethernet);
}
}
control verifyChecksum(inout headers hdr, inout metadata meta) {
apply {
}
}
control computeChecksum(inout headers hdr, inout metadata meta) {
apply {
}
}
V1Switch(ParserImpl(), verifyChecksum(), ingress(), egress(), computeChecksum(), DeparserImpl()) main;
| {
"pile_set_name": "Github"
} |
user_data = {}
base_data = dict(image='http://u.fashiocdn.com/images/users/0/0/6/O/J/5.jpg',
image_thumb='http://u.fashiocdn.com/images/users/0/0/6/O/J/5.jpg')
user_data['no_email'] = {'first_name': 'Thierry', 'last_name': 'Schellenbach', 'verified': True, 'name': 'Thierry Schellenbach', 'gender': 'man', 'image': 'http://graph.facebook.com/me/picture?type=large', 'updated_time':
'2010-04-01T14:26:55+0000', 'birthday': '04/07', 'link': 'http://www.facebook.com/profile.php?id=1225707780', 'location': {'id': None, 'name': None}, 'timezone': -5, 'id': '1225707780', 'image_thumb': 'http://graph.facebook.com/me/picture'}
user_data[
'tschellenbach'] = {'email': '[email protected]', 'first_name': 'Thierry', 'last_name': 'Schellenbach', 'verified': True, 'name': 'Thierry Schellenbach', 'gender': 'man', 'image': 'http://graph.facebook.com/me/picture?type=large',
'updated_time': '2010-04-01T14:26:55+0000', 'birthday': '04/07', 'link': 'http://www.facebook.com/profile.php?id=1225707780', 'location': {'id': None, 'name': None}, 'timezone': -5, 'id': '1225707780', 'image_thumb': 'http://graph.facebook.com/me/picture'}
user_data[
'new_user'] = {'email': '[email protected]', 'first_name': 'Thierry', 'last_name': 'Schellenbach', 'verified': True, 'name': 'Thierry Schellenbach', 'gender': 'male', 'image': 'http://graph.facebook.com/me/picture?type=large',
'updated_time': '2010-04-01T14:26:55+0000', 'birthday': '04/07', 'link': 'http://www.facebook.com/profile.php?id=1225707780', 'location': {'id': None, 'name': None}, 'timezone': -5, 'id': '1225707781', 'image_thumb': 'http://graph.facebook.com/me/picture'}
user_data[
'no_birthday'] = {'website': 'www.pytell.com', 'first_name': 'Jonathan', 'last_name': 'Pytell', 'verified': True, 'name': 'Jonathan Pytell', 'image': 'http://graph.facebook.com/me/picture?type=large',
'updated_time': '2010-01-01T18:13:17+0000', 'link': 'http://www.facebook.com/jpytell', 'location': {'id': None, 'name': None}, 'timezone': -4, 'id': '776872663', 'image_thumb': 'http://graph.facebook.com/me/picture'}
user_data['partial_birthday'] = {'first_name': 'Thierry', 'last_name': 'Schellenbach', 'verified': True, 'name': 'Thierry Schellenbach', 'gender': 'man', 'image': 'http://graph.facebook.com/me/picture?type=large', 'updated_time':
'2010-04-01T14:26:55+0000', 'birthday': '04/07', 'link': 'http://www.facebook.com/profile.php?id=1225707780', 'location': {'id': None, 'name': None}, 'timezone': -5, 'id': '1225707780', 'image_thumb': 'http://graph.facebook.com/me/picture'}
user_data[
'short_username'] = {'email': '[email protected]', 'first_name': 'Thierry', 'last_name': 'Schellenbach', 'verified': True, 'name': 'Thierry Schellenbach', 'gender': 'man', 'image': 'http://graph.facebook.com/me/picture?type=large',
'updated_time': '2010-04-01T14:26:55+0000', 'birthday': '04/07', 'link': 'http://www.facebook.com/profile.php?id=1225707780', 'location': {'id': None, 'name': None}, 'timezone': -5, 'id': '1225707782', 'image_thumb': 'http://graph.facebook.com/me/picture'}
user_data[
'long_username'] = {'email': '[email protected]', 'first_name': 'Thierry123456789123456789123456789123456789123456789123456789123456789123456789123456789', 'last_name': 'Schellenbach123456789123456789123456789123456789123456789123456789', 'verified': True, 'name': 'Thierry Schellenbach',
'gender': 'man', 'image': 'http://graph.facebook.com/me/picture?type=large', 'updated_time': '2010-04-01T14:26:55+0000', 'birthday': '04/07', 'link': 'http://www.facebook.com/profile.php?id=1225707780', 'location': {'id': None, 'name': None}, 'timezone': -5, 'id': '1225707782', 'image_thumb': 'http://graph.facebook.com/me/picture'}
user_data['same_username'] = user_data['short_username'].copy()
user_data['same_username'].update(dict(id='1111111', email='[email protected]'))
user_data['paul'] = {"website": "http://usabilla.com", "last_name": "Veugen", "locale": "en_US", "image": "https://graph.facebook.com/me/picture?access_token=aa&type=large", "quotes": "\"Make no small plans for they have no power to stir the soul.\" - Machiavelli", "timezone": 1, "education": [{"school": {"id": "114174235260224", "name": "Tilburg University"}, "type": "College", "year": {"id": "136328419721520", "name": "2009"}}, {"school": {"id": "111600322189438", "name": "Tilburg University"}, "type": "Graduate School", "concentration": [{"id": "187998924566551", "name": "Business Communication and Digital Media"}, {"id": "105587479474873", "name": "Entrepreneurship"}], "degree": {"id": "110198449002528", "name": "BA"}}], "id": "555227728", "first_name": "Paul", "verified": True, "sports": [{"id": "114031331940797", "name": "Cycling"}, {"id": "107496599279538", "name": "Snowboarding"}, {"id": "109368782422374", "name": "Running"}], "languages": [{"id": "106059522759137", "name": "English"}, {"id": "107672419256005", "name": "Dutch"}], "location": {
"id": "111777152182368", "name": "Amsterdam, Netherlands"}, "image_thumb": "https://graph.facebook.com/me/picture?access_token=aa", "email": "[email protected]", "username": "pveugen", "bio": "Founder Usabilla. User Experience designer, entrepeneur and digital media addict. On a mission to make user experience research simple and fun with Usabilla.com.", "birthday": "07/11/1984", "link": "http://www.facebook.com/pveugen", "name": "Paul Veugen", "gender": "male", "work": [{"description": "http://usabilla.com", "employer": {"id": "235754672838", "name": "Usabilla"}, "location": {"id": "111777152182368", "name": "Amsterdam, Netherlands"}, "position": {"id": "130899310279007", "name": "Founder, CEO"}, "with": [{"id": "1349358449", "name": "Marc van Agteren"}], "start_date": "2009-01"}, {"position": {"id": "143357809027330", "name": "Communication Designer"}, "start_date": "2000-02", "location": {"id": "112258135452858", "name": "Venray"}, "end_date": "2010-01", "employer": {"id": "133305113393672", "name": "Flyers Internet Communicatie"}}], "updated_time": "2011-11-27T14:34:34+0000"}
user_data['paul2'] = user_data['paul']
user_data[
'unicode_string'] = {u'bio': u'ATELIER : TODOS LOS DIAS DE 14 A 22 HS C CITA PREVIA. MIX DE ESTETICAS - ECLECTICA - PRENDAS UNICAS-HAND MADE- SEASSON LESS RETROMODERNIDAD -CUSTOMIZADO !!!\r\n\r\nMe encanta todo el proceso que lleva lograr un objeto que sea unico....personalizarlo de acuerdo a cada uno...a cada persona....a su forma de ser.......elegir los materiales, los avios, las telas...siendo la premisa DIFERENCIARSE!!!!\r\n Atemporal..Retro modernidad...Eclecticismo!!!',
u'birthday': u'04/09/1973',
u'education': [{u'classes': [{u'description': u'direccion de arte',
u'id': u'188729917815843',
u'name': u'AAAP'},
{u'id': u'200142039998266',
u'name': u'Indumentaria',
u'with': [{u'id': u'546455670',
u'name': u'Gustavo Lento'}]},
{u'description': u'dise\xf1o ',
u'id': u'102056769875267',
u'name': u'figurin',
u'with': [{u'id': u'1285841477',
u'name': u'La Maison Madrid'}]},
{u'id': u'194463713907701',
u'name': u'indumentaria -figurin-seriado'},
{u'id': u'180792848632395',
u'name': u'indumentaria-figurin -seriado.etc',
u'with': [{u'id': u'704003068',
u'name': u'Mariano Toledo'}]}],
u'concentration': [{u'id': u'176664472378719',
u'name': u'indumentaria y dise\xf1o textil'}],
u'school': {u'id': u'115805661780893',
u'name': u'uba arquitectura dise\xf1o y urbanismo'},
u'type': u'College'},
{u'classes': [{u'id': u'116042535136769',
u'name': u'whadrove asesory'}],
u'concentration': [{u'id': u'146715355391868',
u'name': u'producer- stylist - asesora de imagen -personal-shooper -whadrove asesory'}],
u'school': {u'id': u'107827585907242',
u'name': u'Miami International University of Art & Design'},
u'type': u'Graduate School'},
{u'classes': [{u'id': u'199608053396849',
u'name': u'Reporter, Producer and Director'},
{u'id': u'209828275699578',
u'name': u'personal shooper'},
{u'id': u'208913322452336',
u'name': u'Designer-stylisti'}],
u'concentration': [{u'id': u'184808144897752',
u'name': u'whadrobing'}],
u'school': {u'id': u'105548239478812',
u'name': u'New York Institute of Technology'},
u'type': u'College'},
{u'school': {u'id': u'106431826058746',
u'name': u'Colegio Nuestra Se\xf1ora de la Misericordia'},
u'type': u'High School'},
{u'school': {u'id': u'106011862771707',
u'name': u'Mary E. Graham'},
u'type': u'High School'},
{u'school': {u'id': u'106011862771707',
u'name': u'Mary E. Graham'},
u'type': u'High School'}],
u'email': u'[email protected]',
u'first_name': u'Fernanda',
u'gender': u'female',
u'hometown': {u'id': u'109238842431095',
u'name': u'La Coru\xf1a, Galicia, Spain'},
u'id': u'1157872766',
u'image': u'https://graph.facebook.com/me/picture?type3Dlarge&access_token3D100314226679773|2.1ZkFz1Cusu5RlY1xGft_Pg__.86400.1303534800.4-1157872766|ZgsRrRYwp2pqHEHtncqS5-rBiSg',
u'image_thumb': u'https://graph.facebook.com/me/picture?access_token3D100314226679773|2.1ZkFz1Cusu5RlY1xGft_Pg__.86400.1303534800.4-1157872766|ZgsRrRYwp2pqHEHtncqS5-rBiSg',
u'languages': [{u'id': u'111021838921932', u'name': u'Espa\xf1ol'},
{u'id': u'110867825605119',
u'name': u'Ingles'},
{u'id': u'108083115891989',
u'name': u'Portugu\xe9s'},
{u'id': u'113051562042989', u'name': u'Italiano'}],
u'last_name': u'Ferrer Vazquez',
u'link': u'http://www.facebook.com/FernandaFerrerVazquez',
u'locale': u'es_LA',
u'location': {u'id': u'106423786059675', u'name': u'Buenos Aires, Argentina'},
u'name': u'Fernanda Ferrer Vazquez',
u'timezone': -3,
u'updated_time': u'2011-04-22T04:28:27+0000',
u'username': u'FernandaFerrerVazquez',
u'verified': True,
u'website': u'http://fernandaferrervazquez.blogspot.com/\r\nhttp://twitter.com/fferrervazquez\r\nhttp://comunidad.redfashion.es/profile/fernandaferrervazquez\r\nhttp://www.facebook.com/group.php?gid3D40257259997&ref3Dts\r\nhttp://fernandaferrervazquez.spaces.live.com/blog/cns!EDCBAC31EE9D9A0C!326.trak\r\nhttp://www.linkedin.com/myprofile?trk3Dhb_pro\r\nhttp://www.youtube.com/account#profile\r\nhttp://www.flickr.com/\r\n Mi galer\xeda\r\nhttp://www.flickr.com/photos/wwwfernandaferrervazquez-showroomrecoletacom/ \r\n\r\nhttp://www.facebook.com/pages/Buenos-Aires-Argentina/Fernanda-F-Showroom-Recoleta/200218353804?ref3Dts\r\nhttp://fernandaferrervazquez.wordpress.com/wp-admin/',
u'work': [{u'description': u'ATELIER : un mix de esteticas que la hacen eclectica, multicultural, excentrica, customizada, artesanal, unica , exclusiva, lujosa, eco-reciclada,con bordados a mano y texturas..especial atencion a los peque\xf1os detalles!!!! \nSeason less \nHand made ',
u'employer': {u'id': u'113960871952651',
u'name': u'fernanda ferrer vazquez'},
u'location': {u'id': u'106423786059675',
u'name': u'Buenos Aires, Argentina'},
u'position': {u'id': u'145270362165639',
u'name': u'Dise\xf1adora'},
u'projects': [{u'description': u'produccion-estilismo-fotografia-make up-pelo-asesoramiento de imagen-whadrobing-perso\xf1an shooper-rent an outfit!!',
u'id': u'200218353804',
u'name': u'Fernanda F -Showroom Recoleta'}],
u'start_date': u'2008-12'},
{u'employer': {u'id': u'198034683561689',
u'name': u'el atelier de la isla'}}]}
for k, v in user_data.items():
v.update(base_data)
| {
"pile_set_name": "Github"
} |
//
// AppDelegate.h
// FLWebView
//
// Created by Steve Richey on 11/21/14.
// Copyright (c) 2014 Float Mobile Learning. Shared under an MIT license. See license.md for details.
//
#import <UIKit/UIKit.h>
/*
* This class isn't really used in this project.
*/
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end | {
"pile_set_name": "Github"
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE127_Buffer_Underread__malloc_wchar_t_cpy_64b.c
Label Definition File: CWE127_Buffer_Underread__malloc.label.xml
Template File: sources-sink-64b.tmpl.c
*/
/*
* @description
* CWE: 127 Buffer Under-read
* BadSource: Set data pointer to before the allocated memory buffer
* GoodSource: Set data pointer to the allocated memory buffer
* Sinks: cpy
* BadSink : Copy data to string using wcscpy
* Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifndef OMITBAD
void CWE127_Buffer_Underread__malloc_wchar_t_cpy_64b_badSink(void * dataVoidPtr)
{
/* cast void pointer to a pointer of the appropriate type */
wchar_t * * dataPtr = (wchar_t * *)dataVoidPtr;
/* dereference dataPtr into data */
wchar_t * data = (*dataPtr);
{
wchar_t dest[100*2];
wmemset(dest, L'C', 100*2-1); /* fill with 'C's */
dest[100*2-1] = L'\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */
wcscpy(dest, data);
printWLine(dest);
/* INCIDENTAL CWE-401: Memory Leak - data may not point to location
* returned by malloc() so can't safely call free() on it */
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE127_Buffer_Underread__malloc_wchar_t_cpy_64b_goodG2BSink(void * dataVoidPtr)
{
/* cast void pointer to a pointer of the appropriate type */
wchar_t * * dataPtr = (wchar_t * *)dataVoidPtr;
/* dereference dataPtr into data */
wchar_t * data = (*dataPtr);
{
wchar_t dest[100*2];
wmemset(dest, L'C', 100*2-1); /* fill with 'C's */
dest[100*2-1] = L'\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */
wcscpy(dest, data);
printWLine(dest);
/* INCIDENTAL CWE-401: Memory Leak - data may not point to location
* returned by malloc() so can't safely call free() on it */
}
}
#endif /* OMITGOOD */
| {
"pile_set_name": "Github"
} |
import tensorflow as tf
from tensorflow.contrib import slim
from frontends import resnet_utils
resnet_arg_scope = resnet_utils.resnet_arg_scope
@slim.add_arg_scope
def bottleneck(inputs, depth, depth_bottleneck, stride, rate=1,
outputs_collections=None, scope=None):
"""Bottleneck residual unit variant with BN after convolutions.
This is the original residual unit proposed in [1]. See Fig. 1(a) of [2] for
its definition. Note that we use here the bottleneck variant which has an
extra bottleneck layer.
When putting together two consecutive ResNet blocks that use this unit, one
should use stride = 2 in the last unit of the first block.
Args:
inputs: A tensor of size [batch, height, width, channels].
depth: The depth of the ResNet unit output.
depth_bottleneck: The depth of the bottleneck layers.
stride: The ResNet unit's stride. Determines the amount of downsampling of
the units output compared to its input.
rate: An integer, rate for atrous convolution.
outputs_collections: Collection to add the ResNet unit output.
scope: Optional variable_scope.
Returns:
The ResNet unit's output.
"""
with tf.variable_scope(scope, 'bottleneck_v1', [inputs]) as sc:
depth_in = slim.utils.last_dimension(inputs.get_shape(), min_rank=4)
if depth == depth_in:
shortcut = resnet_utils.subsample(inputs, stride, 'shortcut')
else:
shortcut = slim.conv2d(inputs, depth, [1, 1], stride=stride,
activation_fn=None, scope='shortcut')
residual = slim.conv2d(inputs, depth_bottleneck, [1, 1], stride=1,
scope='conv1')
residual = resnet_utils.conv2d_same(residual, depth_bottleneck, 3, stride,
rate=rate, scope='conv2')
residual = slim.conv2d(residual, depth, [1, 1], stride=1,
activation_fn=None, scope='conv3')
output = tf.nn.relu(shortcut + residual)
return slim.utils.collect_named_outputs(outputs_collections,
sc.original_name_scope,
output)
def resnet_v1(inputs,
blocks,
num_classes=None,
is_training=True,
global_pool=True,
output_stride=None,
include_root_block=True,
spatial_squeeze=True,
reuse=None,
scope=None):
"""Generator for v1 ResNet models.
This function generates a family of ResNet v1 models. See the resnet_v1_*()
methods for specific model instantiations, obtained by selecting different
block instantiations that produce ResNets of various depths.
Training for image classification on Imagenet is usually done with [224, 224]
inputs, resulting in [7, 7] feature maps at the output of the last ResNet
block for the ResNets defined in [1] that have nominal stride equal to 32.
However, for dense prediction tasks we advise that one uses inputs with
spatial dimensions that are multiples of 32 plus 1, e.g., [321, 321]. In
this case the feature maps at the ResNet output will have spatial shape
[(height - 1) / output_stride + 1, (width - 1) / output_stride + 1]
and corners exactly aligned with the input image corners, which greatly
facilitates alignment of the features to the image. Using as input [225, 225]
images results in [8, 8] feature maps at the output of the last ResNet block.
For dense prediction tasks, the ResNet needs to run in fully-convolutional
(FCN) mode and global_pool needs to be set to False. The ResNets in [1, 2] all
have nominal stride equal to 32 and a good choice in FCN mode is to use
output_stride=16 in order to increase the density of the computed features at
small computational and memory overhead, cf. http://arxiv.org/abs/1606.00915.
Args:
inputs: A tensor of size [batch, height_in, width_in, channels].
blocks: A list of length equal to the number of ResNet blocks. Each element
is a resnet_utils.Block object describing the units in the block.
num_classes: Number of predicted classes for classification tasks. If None
we return the features before the logit layer.
is_training: whether is training or not.
global_pool: If True, we perform global average pooling before computing the
logits. Set to True for image classification, False for dense prediction.
output_stride: If None, then the output will be computed at the nominal
network stride. If output_stride is not None, it specifies the requested
ratio of input to output spatial resolution.
include_root_block: If True, include the initial convolution followed by
max-pooling, if False excludes it.
spatial_squeeze: if True, logits is of shape [B, C], if false logits is
of shape [B, 1, 1, C], where B is batch_size and C is number of classes.
reuse: whether or not the network and its variables should be reused. To be
able to reuse 'scope' must be given.
scope: Optional variable_scope.
Returns:
net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].
If global_pool is False, then height_out and width_out are reduced by a
factor of output_stride compared to the respective height_in and width_in,
else both height_out and width_out equal one. If num_classes is None, then
net is the output of the last ResNet block, potentially after global
average pooling. If num_classes is not None, net contains the pre-softmax
activations.
end_points: A dictionary from components of the network to the corresponding
activation.
Raises:
ValueError: If the target output_stride is not valid.
"""
with tf.variable_scope(scope, 'resnet_v1', [inputs], reuse=reuse) as sc:
end_points_collection = sc.name + '_end_points'
with slim.arg_scope([slim.conv2d, bottleneck,
resnet_utils.stack_blocks_dense],
outputs_collections=end_points_collection):
with slim.arg_scope([slim.batch_norm], is_training=is_training):
net = inputs
if include_root_block:
if output_stride is not None:
if output_stride % 4 != 0:
raise ValueError('The output_stride needs to be a multiple of 4.')
output_stride /= 4
net = resnet_utils.conv2d_same(net, 64, 7, stride=2, scope='conv1')
net = slim.max_pool2d(net, [3, 3], stride=2, scope='pool1')
net = slim.utils.collect_named_outputs(end_points_collection, 'pool2', net)
net = resnet_utils.stack_blocks_dense(net, blocks, output_stride)
end_points = slim.utils.convert_collection_to_dict(end_points_collection)
end_points['pool3'] = end_points[scope + '/block1']
end_points['pool4'] = end_points[scope + '/block2']
end_points['pool5'] = net
return net, end_points
resnet_v1.default_image_size = 224
def resnet_v1_50(inputs,
num_classes=None,
is_training=True,
global_pool=True,
output_stride=None,
spatial_squeeze=True,
reuse=None,
scope='resnet_v1_50'):
"""ResNet-50 model of [1]. See resnet_v1() for arg and return description."""
blocks = [
resnet_utils.Block(
'block1', bottleneck, [(256, 64, 1)] * 2 + [(256, 64, 2)]),
resnet_utils.Block(
'block2', bottleneck, [(512, 128, 1)] * 3 + [(512, 128, 2)]),
resnet_utils.Block(
'block3', bottleneck, [(1024, 256, 1)] * 5 + [(1024, 256, 2)]),
resnet_utils.Block(
'block4', bottleneck, [(2048, 512, 1)] * 3)
]
return resnet_v1(inputs, blocks, num_classes, is_training,
global_pool=global_pool, output_stride=output_stride,
include_root_block=True, spatial_squeeze=spatial_squeeze,
reuse=reuse, scope=scope)
resnet_v1_50.default_image_size = resnet_v1.default_image_size
def resnet_v1_101(inputs,
num_classes=None,
is_training=True,
global_pool=True,
output_stride=None,
spatial_squeeze=True,
reuse=None,
scope='resnet_v1_101'):
"""ResNet-101 model of [1]. See resnet_v1() for arg and return description."""
blocks = [
resnet_utils.Block(
'block1', bottleneck, [(256, 64, 1)] * 2 + [(256, 64, 2)]),
resnet_utils.Block(
'block2', bottleneck, [(512, 128, 1)] * 3 + [(512, 128, 2)]),
resnet_utils.Block(
'block3', bottleneck, [(1024, 256, 1)] * 22 + [(1024, 256, 2)]),
resnet_utils.Block(
'block4', bottleneck, [(2048, 512, 1)] * 3)
]
return resnet_v1(inputs, blocks, num_classes, is_training,
global_pool=global_pool, output_stride=output_stride,
include_root_block=True, spatial_squeeze=spatial_squeeze,
reuse=reuse, scope=scope)
resnet_v1_101.default_image_size = resnet_v1.default_image_size
def resnet_v1_152(inputs,
num_classes=None,
is_training=True,
global_pool=True,
output_stride=None,
spatial_squeeze=True,
reuse=None,
scope='resnet_v1_152'):
"""ResNet-152 model of [1]. See resnet_v1() for arg and return description."""
blocks = [
resnet_utils.Block(
'block1', bottleneck, [(256, 64, 1)] * 2 + [(256, 64, 2)]),
resnet_utils.Block(
'block2', bottleneck, [(512, 128, 1)] * 7 + [(512, 128, 2)]),
resnet_utils.Block(
'block3', bottleneck, [(1024, 256, 1)] * 35 + [(1024, 256, 2)]),
resnet_utils.Block(
'block4', bottleneck, [(2048, 512, 1)] * 3)]
return resnet_v1(inputs, blocks, num_classes, is_training,
global_pool=global_pool, output_stride=output_stride,
include_root_block=True, spatial_squeeze=spatial_squeeze,
reuse=reuse, scope=scope)
resnet_v1_152.default_image_size = resnet_v1.default_image_size
def resnet_v1_200(inputs,
num_classes=None,
is_training=True,
global_pool=True,
output_stride=None,
spatial_squeeze=True,
reuse=None,
scope='resnet_v1_200'):
"""ResNet-200 model of [2]. See resnet_v1() for arg and return description."""
blocks = [
resnet_utils.Block(
'block1', bottleneck, [(256, 64, 1)] * 2 + [(256, 64, 2)]),
resnet_utils.Block(
'block2', bottleneck, [(512, 128, 1)] * 23 + [(512, 128, 2)]),
resnet_utils.Block(
'block3', bottleneck, [(1024, 256, 1)] * 35 + [(1024, 256, 2)]),
resnet_utils.Block(
'block4', bottleneck, [(2048, 512, 1)] * 3)]
return resnet_v1(inputs, blocks, num_classes, is_training,
global_pool=global_pool, output_stride=output_stride,
include_root_block=True, spatial_squeeze=spatial_squeeze,
reuse=reuse, scope=scope)
resnet_v1_200.default_image_size = resnet_v1.default_image_size
if __name__ == '__main__':
input = tf.placeholder(tf.float32, shape=(None, 224, 224, 3), name='input')
with slim.arg_scope(resnet_arg_scope()) as sc:
logits = resnet_v1_50(input) | {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2014, Oculus VR, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/// \file Rackspace.h
/// \brief Helper to class to manage Rackspace servers
#include "NativeFeatureIncludes.h"
#if _RAKNET_SUPPORT_TCPInterface==1
#include "Export.h"
#include "RakNetTypes.h"
#include "DS_Queue.h"
#include "RakString.h"
#include "jansson.h"
#ifndef __RACKSPACE_2_H
#define __RACKSPACE_2_H
namespace RakNet
{
class TCPInterface;
class HTTPConnection2;
struct Packet;
enum Rackspace2ResponseCode
{
R2RC_AUTHENTICATED,
R2RC_GOT_DOMAINS,
R2RC_GOT_RECORDS,
R2RC_GOT_SERVERS,
R2RC_GOT_IMAGES,
R2RC_NO_CONTENT,
R2RC_BAD_JSON,
R2RC_UNAUTHORIZED,
R2RC_404_NOT_FOUND,
R2RC_UNKNOWN,
};
/// \brief Callback interface to receive the results of operations
class RAK_DLL_EXPORT Rackspace2EventCallback
{
public:
virtual void OnTCPFailure(void)=0;
virtual void OnTransmissionFailed(HTTPConnection2 *httpConnection2, RakString postStr, RakString authURLDomain)=0;
virtual void OnResponse(Rackspace2ResponseCode r2rc, RakString responseReceived, int contentOffset)=0;
virtual void OnEmptyResponse(RakString stringTransmitted)=0;
virtual void OnMessage(const char *message, RakString responseReceived, RakString stringTransmitted, int contentOffset)=0;
};
/// \brief Version 2 of the code that uses the TCPInterface class to communicate with the Rackspace API servers
/// Works with their "next-gen" API as of 2012
/// API operations are hidden at http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ch_api_operations.html
/// \pre Compile RakNet with OPEN_SSL_CLIENT_SUPPORT set to 1
/// Maintains its own TCPInterface class
class RAK_DLL_EXPORT Rackspace2
{
public:
Rackspace2();
~Rackspace2();
// Call periodically
void Update(void);
/// Sets the callback to be used when an operation completes
void SetEventCallback(Rackspace2EventCallback *callback);
int GetCloudAccountNumber(void) const;
const char *GetAuthToken(void) const;
/// \brief Authenticate with Rackspace servers, required before executing any commands.
/// \details All requests to authenticate and operate against Cloud Servers are performed using SSL over HTTP (HTTPS) on TCP port 443.
/// TODO - Will reauthenticate automatically as needed
/// \param[in] authenticationURL See http://docs.rackspace.com/cdns/api/v1.0/cdns-devguide/content/Authentication-d1e647.html
/// \param[in] rackspaceCloudUsername Username you registered with Rackspace on their website
/// \param[in] apiAccessKey Obtain your API access key from the Rackspace Cloud Control Panel in the Your Account API Access section.
void Authenticate(const char *authenticationURL, const char *rackspaceCloudUsername, const char *apiAccessKey);
enum OpType
{
OT_POST,
OT_PUT,
OT_GET,
OT_DELETE,
};
/// \param[in] URL Path to command, for example https://identity.api.rackspacecloud.com/v2.0/tokens
/// \param[in] opType Type of operation to perform
/// \param[in] data If the operation requires data, put it here
/// \param[in] setAuthToken true to automatically set the auth token for the operation. I believe this should be true for everything except authentication itself
void AddOperation(RakNet::RakString URL, OpType opType, json_t *data, bool setAuthToken);
struct Operation
{
RakNet::RakString URL;
bool isPost;
json_t *data;
};
protected:
void AuthenticateInt(const char *authenticationURL, const char *rackspaceCloudUsername, const char *apiAccessKey);
void Reauthenticate(void);
char X_Auth_Token[128];
Rackspace2EventCallback *eventCallback;
DataStructures::Queue<Operation> operations;
TCPInterface *tcp;
HTTPConnection2 *httpConnection2;
int cloudAccountNumber;
RakString lastAuthenticationURL;
RakString lastRackspaceCloudUsername;
RakString lastApiAccessKey;
bool reexecuteLastRequestOnAuth;
//SystemAddress serverAddress;
RakString __addOpLast_URL;
OpType __addOpLast_isPost;
RakString __addOpLast_dataAsStr;
};
} // namespace RakNet
#endif // __RACKSPACE_API_H
#endif // _RAKNET_SUPPORT_Rackspace
| {
"pile_set_name": "Github"
} |
// ***************************************************************************
// *
// * Copyright (C) 2010 International Business Machines
// * Corporation and others. All Rights Reserved.
// * Tool: com.ibm.icu.dev.tool.cldr.LDML2ICUConverter.java
// * Source File:<path>/common/main/bg_BG.xml
// *
// ***************************************************************************
bg_BG{
Version{"2.0.41.23"}
}
| {
"pile_set_name": "Github"
} |
/* Copyright (C) 2004 Garrett A. Kajmowicz
This file is part of the uClibc++ Library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <numeric>
namespace std{
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.java.j2seproject</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/j2se-project/3">
<name>StringBuilderExample</name>
<source-roots>
<root id="src.dir"/>
</source-roots>
<test-roots>
<root id="test.src.dir"/>
</test-roots>
</data>
</configuration>
</project>
| {
"pile_set_name": "Github"
} |
/* Script for --shared -z combreloc -z now -z relro: shared library, combine & sort relocs */
OUTPUT_FORMAT("elf32-tradbigmips", "elf32-tradbigmips",
"elf32-tradlittlemips")
OUTPUT_ARCH(mips)
ENTRY(__start)
SECTIONS
{
/* Read-only sections, merged into text segment: */
. = 0 + SIZEOF_HEADERS;
.reginfo : { *(.reginfo) }
.dynamic : { *(.dynamic) }
.hash : { *(.hash) }
.dynsym : { *(.dynsym) }
.dynstr : { *(.dynstr) }
.gnu.version : { *(.gnu.version) }
.gnu.version_d : { *(.gnu.version_d) }
.gnu.version_r : { *(.gnu.version_r) }
.rel.dyn :
{
*(.rel.init)
*(.rel.text .rel.text.* .rel.gnu.linkonce.t.*)
*(.rel.fini)
*(.rel.rodata .rel.rodata.* .rel.gnu.linkonce.r.*)
*(.rel.data.rel.ro* .rel.gnu.linkonce.d.rel.ro.*)
*(.rel.data .rel.data.* .rel.gnu.linkonce.d.*)
*(.rel.tdata .rel.tdata.* .rel.gnu.linkonce.td.*)
*(.rel.tbss .rel.tbss.* .rel.gnu.linkonce.tb.*)
*(.rel.ctors)
*(.rel.dtors)
*(.rel.got)
*(.rel.sdata .rel.sdata.* .rel.gnu.linkonce.s.*)
*(.rel.sbss .rel.sbss.* .rel.gnu.linkonce.sb.*)
*(.rel.sdata2 .rel.sdata2.* .rel.gnu.linkonce.s2.*)
*(.rel.sbss2 .rel.sbss2.* .rel.gnu.linkonce.sb2.*)
*(.rel.bss .rel.bss.* .rel.gnu.linkonce.b.*)
}
.rela.dyn :
{
*(.rela.init)
*(.rela.text .rela.text.* .rela.gnu.linkonce.t.*)
*(.rela.fini)
*(.rela.rodata .rela.rodata.* .rela.gnu.linkonce.r.*)
*(.rela.data .rela.data.* .rela.gnu.linkonce.d.*)
*(.rela.tdata .rela.tdata.* .rela.gnu.linkonce.td.*)
*(.rela.tbss .rela.tbss.* .rela.gnu.linkonce.tb.*)
*(.rela.ctors)
*(.rela.dtors)
*(.rela.got)
*(.rela.sdata .rela.sdata.* .rela.gnu.linkonce.s.*)
*(.rela.sbss .rela.sbss.* .rela.gnu.linkonce.sb.*)
*(.rela.sdata2 .rela.sdata2.* .rela.gnu.linkonce.s2.*)
*(.rela.sbss2 .rela.sbss2.* .rela.gnu.linkonce.sb2.*)
*(.rela.bss .rela.bss.* .rela.gnu.linkonce.b.*)
}
.rel.plt : { *(.rel.plt) }
.rela.plt : { *(.rela.plt) }
.init :
{
KEEP (*(.init))
} =0
.plt : { *(.plt) }
.text :
{
_ftext = . ;
*(.text .stub .text.* .gnu.linkonce.t.*)
KEEP (*(.text.*personality*))
/* .gnu.warning sections are handled specially by elf32.em. */
*(.gnu.warning)
*(.mips16.fn.*) *(.mips16.call.*)
} =0
.fini :
{
KEEP (*(.fini))
} =0
PROVIDE (__etext = .);
PROVIDE (_etext = .);
PROVIDE (etext = .);
.rodata : { *(.rodata .rodata.* .gnu.linkonce.r.*) }
.rodata1 : { *(.rodata1) }
.eh_frame_hdr : { *(.eh_frame_hdr) }
.eh_frame : ONLY_IF_RO { KEEP (*(.eh_frame)) }
.gcc_except_table : ONLY_IF_RO { *(.gcc_except_table .gcc_except_table.*) }
/* Adjust the address for the data segment. We want to adjust up to
the same address within the page on the next page up. */
. = ALIGN (0x40000) - ((0x40000 - .) & (0x40000 - 1)); . = DATA_SEGMENT_ALIGN (0x40000, 0x1000);
/* Exception handling */
.eh_frame : ONLY_IF_RW { KEEP (*(.eh_frame)) }
.gcc_except_table : ONLY_IF_RW { *(.gcc_except_table .gcc_except_table.*) }
/* Thread Local Storage sections */
.tdata : { *(.tdata .tdata.* .gnu.linkonce.td.*) }
.tbss : { *(.tbss .tbss.* .gnu.linkonce.tb.*) *(.tcommon) }
.preinit_array :
{
KEEP (*(.preinit_array))
}
.init_array :
{
KEEP (*(SORT(.init_array.*)))
KEEP (*(.init_array))
}
.fini_array :
{
KEEP (*(.fini_array))
KEEP (*(SORT(.fini_array.*)))
}
.ctors :
{
/* gcc uses crtbegin.o to find the start of
the constructors, so we make sure it is
first. Because this is a wildcard, it
doesn't matter if the user does not
actually link against crtbegin.o; the
linker won't look for a file to match a
wildcard. The wildcard also means that it
doesn't matter which directory crtbegin.o
is in. */
KEEP (*crtbegin*.o(.ctors))
/* We don't want to include the .ctor section from
the crtend.o file until after the sorted ctors.
The .ctor section from the crtend file contains the
end of ctors marker and it must be last */
KEEP (*(EXCLUDE_FILE (*crtend*.o ) .ctors))
KEEP (*(SORT(.ctors.*)))
KEEP (*(.ctors))
}
.dtors :
{
KEEP (*crtbegin*.o(.dtors))
KEEP (*(EXCLUDE_FILE (*crtend*.o ) .dtors))
KEEP (*(SORT(.dtors.*)))
KEEP (*(.dtors))
}
.jcr : { KEEP (*(.jcr)) }
.data.rel.ro : { *(.data.rel.ro.local* .gnu.linkonce.d.rel.ro.local.*) *(.data.rel.ro* .gnu.linkonce.d.rel.ro.*) }
. = DATA_SEGMENT_RELRO_END (0, .);
.data :
{
_fdata = . ;
*(.data .data.* .gnu.linkonce.d.*)
KEEP (*(.gnu.linkonce.d.*personality*))
SORT(CONSTRUCTORS)
}
.data1 : { *(.data1) }
. = .;
_gp = ALIGN(16) + 0x7ff0;
.got : { *(.got.plt) *(.got) }
/* We want the small data sections together, so single-instruction offsets
can access them all, and initialized data all before uninitialized, so
we can shorten the on-disk segment size. */
.sdata :
{
*(.sdata2 .sdata2.* .gnu.linkonce.s2.*)
*(.sdata .sdata.* .gnu.linkonce.s.*)
}
.lit8 : { *(.lit8) }
.lit4 : { *(.lit4) }
_edata = .; PROVIDE (edata = .);
__bss_start = .;
_fbss = .;
.sbss :
{
*(.sbss2 .sbss2.* .gnu.linkonce.sb2.*)
*(.dynsbss)
*(.sbss .sbss.* .gnu.linkonce.sb.*)
*(.scommon)
}
.bss :
{
*(.dynbss)
*(.bss .bss.* .gnu.linkonce.b.*)
*(COMMON)
/* Align here to ensure that the .bss section occupies space up to
_end. Align after .bss to ensure correct alignment even if the
.bss section disappears because there are no input sections.
FIXME: Why do we need it? When there is no .bss section, we don't
pad the .data section. */
. = ALIGN(. != 0 ? 32 / 8 : 1);
}
. = ALIGN(32 / 8);
. = ALIGN(32 / 8);
_end = .; PROVIDE (end = .);
. = DATA_SEGMENT_END (.);
/* Stabs debugging sections. */
.stab 0 : { *(.stab) }
.stabstr 0 : { *(.stabstr) }
.stab.excl 0 : { *(.stab.excl) }
.stab.exclstr 0 : { *(.stab.exclstr) }
.stab.index 0 : { *(.stab.index) }
.stab.indexstr 0 : { *(.stab.indexstr) }
.comment 0 : { *(.comment) }
/* DWARF debug sections.
Symbols in the DWARF debugging sections are relative to the beginning
of the section so we begin them at 0. */
/* DWARF 1 */
.debug 0 : { *(.debug) }
.line 0 : { *(.line) }
/* GNU DWARF 1 extensions */
.debug_srcinfo 0 : { *(.debug_srcinfo) }
.debug_sfnames 0 : { *(.debug_sfnames) }
/* DWARF 1.1 and DWARF 2 */
.debug_aranges 0 : { *(.debug_aranges) }
.debug_pubnames 0 : { *(.debug_pubnames) }
/* DWARF 2 */
.debug_info 0 : { *(.debug_info .gnu.linkonce.wi.*) }
.debug_abbrev 0 : { *(.debug_abbrev) }
.debug_line 0 : { *(.debug_line) }
.debug_frame 0 : { *(.debug_frame) }
.debug_str 0 : { *(.debug_str) }
.debug_loc 0 : { *(.debug_loc) }
.debug_macinfo 0 : { *(.debug_macinfo) }
/* SGI/MIPS DWARF 2 extensions */
.debug_weaknames 0 : { *(.debug_weaknames) }
.debug_funcnames 0 : { *(.debug_funcnames) }
.debug_typenames 0 : { *(.debug_typenames) }
.debug_varnames 0 : { *(.debug_varnames) }
.gptab.sdata : { *(.gptab.data) *(.gptab.sdata) }
.gptab.sbss : { *(.gptab.bss) *(.gptab.sbss) }
.mdebug.abi32 : { KEEP(*(.mdebug.abi32)) }
.mdebug.abiN32 : { KEEP(*(.mdebug.abiN32)) }
.mdebug.abi64 : { KEEP(*(.mdebug.abi64)) }
.mdebug.abiO64 : { KEEP(*(.mdebug.abiO64)) }
.mdebug.eabi32 : { KEEP(*(.mdebug.eabi32)) }
.mdebug.eabi64 : { KEEP(*(.mdebug.eabi64)) }
.gcc_compiled_long32 : { KEEP(*(.gcc_compiled_long32)) }
.gcc_compiled_long64 : { KEEP(*(.gcc_compiled_long64)) }
/DISCARD/ : { *(.note.GNU-stack) }
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2008 Intel Corporation
Use, modification and distribution are subject to the Boost Software License,
Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
*/
#ifndef BOOST_POLYGON_BOOLEAN_OP_HPP
#define BOOST_POLYGON_BOOLEAN_OP_HPP
namespace boost { namespace polygon{
namespace boolean_op {
//BooleanOp is the generic boolean operation scanline algorithm that provides
//all the simple boolean set operations on manhattan data. By templatizing
//the intersection count of the input and algorithm internals it is extensible
//to multi-layer scans, properties and other advanced scanline operations above
//and beyond simple booleans.
//T must cast to int
template <class T, typename Unit>
class BooleanOp {
public:
typedef std::map<Unit, T> ScanData;
typedef std::pair<Unit, T> ElementType;
protected:
ScanData scanData_;
typename ScanData::iterator nextItr_;
T nullT_;
public:
inline BooleanOp () : scanData_(), nextItr_(), nullT_() { nextItr_ = scanData_.end(); nullT_ = 0; }
inline BooleanOp (T nullT) : scanData_(), nextItr_(), nullT_(nullT) { nextItr_ = scanData_.end(); }
inline BooleanOp (const BooleanOp& that) : scanData_(that.scanData_), nextItr_(),
nullT_(that.nullT_) { nextItr_ = scanData_.begin(); }
inline BooleanOp& operator=(const BooleanOp& that);
//moves scanline forward
inline void advanceScan() { nextItr_ = scanData_.begin(); }
//proceses the given interval and T data
//appends output edges to cT
template <class cT>
inline void processInterval(cT& outputContainer, interval_data<Unit> ivl, T deltaCount);
private:
inline typename ScanData::iterator lookup_(Unit pos){
if(nextItr_ != scanData_.end() && nextItr_->first >= pos) {
return nextItr_;
}
return nextItr_ = scanData_.lower_bound(pos);
}
inline typename ScanData::iterator insert_(Unit pos, T count){
return nextItr_ = scanData_.insert(nextItr_, ElementType(pos, count));
}
template <class cT>
inline void evaluateInterval_(cT& outputContainer, interval_data<Unit> ivl, T beforeCount, T afterCount);
};
class BinaryAnd {
public:
inline BinaryAnd() {}
inline bool operator()(int a, int b) { return (a > 0) & (b > 0); }
};
class BinaryOr {
public:
inline BinaryOr() {}
inline bool operator()(int a, int b) { return (a > 0) | (b > 0); }
};
class BinaryNot {
public:
inline BinaryNot() {}
inline bool operator()(int a, int b) { return (a > 0) & !(b > 0); }
};
class BinaryXor {
public:
inline BinaryXor() {}
inline bool operator()(int a, int b) { return (a > 0) ^ (b > 0); }
};
//BinaryCount is an array of two deltaCounts coming from two different layers
//of scan event data. It is the merged count of the two suitable for consumption
//as the template argument of the BooleanOp algorithm because BinaryCount casts to int.
//T is a binary functor object that evaluates the array of counts and returns a logical
//result of some operation on those values.
//BinaryCount supports many of the operators that work with int, particularly the
//binary operators, but cannot support less than or increment.
template <class T>
class BinaryCount {
public:
inline BinaryCount()
#ifndef BOOST_POLYGON_MSVC
: counts_()
#endif
{ counts_[0] = counts_[1] = 0; }
// constructs from two integers
inline BinaryCount(int countL, int countR)
#ifndef BOOST_POLYGON_MSVC
: counts_()
#endif
{ counts_[0] = countL, counts_[1] = countR; }
inline BinaryCount& operator=(int count) { counts_[0] = count, counts_[1] = count; return *this; }
inline BinaryCount& operator=(const BinaryCount& that);
inline BinaryCount(const BinaryCount& that)
#ifndef BOOST_POLYGON_MSVC
: counts_()
#endif
{ *this = that; }
inline bool operator==(const BinaryCount& that) const;
inline bool operator!=(const BinaryCount& that) const { return !((*this) == that);}
inline BinaryCount& operator+=(const BinaryCount& that);
inline BinaryCount& operator-=(const BinaryCount& that);
inline BinaryCount operator+(const BinaryCount& that) const;
inline BinaryCount operator-(const BinaryCount& that) const;
inline BinaryCount operator-() const;
inline int& operator[](bool index) { return counts_[index]; }
//cast to int operator evaluates data using T binary functor
inline operator int() const { return T()(counts_[0], counts_[1]); }
private:
int counts_[2];
};
class UnaryCount {
public:
inline UnaryCount() : count_(0) {}
// constructs from two integers
inline explicit UnaryCount(int count) : count_(count) {}
inline UnaryCount& operator=(int count) { count_ = count; return *this; }
inline UnaryCount& operator=(const UnaryCount& that) { count_ = that.count_; return *this; }
inline UnaryCount(const UnaryCount& that) : count_(that.count_) {}
inline bool operator==(const UnaryCount& that) const { return count_ == that.count_; }
inline bool operator!=(const UnaryCount& that) const { return !((*this) == that);}
inline UnaryCount& operator+=(const UnaryCount& that) { count_ += that.count_; return *this; }
inline UnaryCount& operator-=(const UnaryCount& that) { count_ -= that.count_; return *this; }
inline UnaryCount operator+(const UnaryCount& that) const { UnaryCount tmp(*this); tmp += that; return tmp; }
inline UnaryCount operator-(const UnaryCount& that) const { UnaryCount tmp(*this); tmp -= that; return tmp; }
inline UnaryCount operator-() const { UnaryCount tmp; return tmp - *this; }
//cast to int operator evaluates data using T binary functor
inline operator int() const { return count_ % 2; }
private:
int count_;
};
template <class T, typename Unit>
inline BooleanOp<T, Unit>& BooleanOp<T, Unit>::operator=(const BooleanOp& that) {
scanData_ = that.scanData_;
nextItr_ = scanData_.begin();
nullT_ = that.nullT_;
return *this;
}
//appends output edges to cT
template <class T, typename Unit>
template <class cT>
inline void BooleanOp<T, Unit>::processInterval(cT& outputContainer, interval_data<Unit> ivl, T deltaCount) {
typename ScanData::iterator lowItr = lookup_(ivl.low());
typename ScanData::iterator highItr = lookup_(ivl.high());
//add interval to scan data if it is past the end
if(lowItr == scanData_.end()) {
lowItr = insert_(ivl.low(), deltaCount);
highItr = insert_(ivl.high(), nullT_);
evaluateInterval_(outputContainer, ivl, nullT_, deltaCount);
return;
}
//ensure that highItr points to the end of the ivl
if(highItr == scanData_.end() || (*highItr).first > ivl.high()) {
T value = nullT_;
if(highItr != scanData_.begin()) {
--highItr;
value = highItr->second;
}
nextItr_ = highItr;
highItr = insert_(ivl.high(), value);
}
//split the low interval if needed
if(lowItr->first > ivl.low()) {
if(lowItr != scanData_.begin()) {
--lowItr;
nextItr_ = lowItr;
lowItr = insert_(ivl.low(), lowItr->second);
} else {
nextItr_ = lowItr;
lowItr = insert_(ivl.low(), nullT_);
}
}
//process scan data intersecting interval
for(typename ScanData::iterator itr = lowItr; itr != highItr; ){
T beforeCount = itr->second;
T afterCount = itr->second += deltaCount;
Unit low = itr->first;
++itr;
Unit high = itr->first;
evaluateInterval_(outputContainer, interval_data<Unit>(low, high), beforeCount, afterCount);
}
//merge the bottom interval with the one below if they have the same count
if(lowItr != scanData_.begin()){
typename ScanData::iterator belowLowItr = lowItr;
--belowLowItr;
if(belowLowItr->second == lowItr->second) {
scanData_.erase(lowItr);
}
}
//merge the top interval with the one above if they have the same count
if(highItr != scanData_.begin()) {
typename ScanData::iterator beforeHighItr = highItr;
--beforeHighItr;
if(beforeHighItr->second == highItr->second) {
scanData_.erase(highItr);
highItr = beforeHighItr;
++highItr;
}
}
nextItr_ = highItr;
}
template <class T, typename Unit>
template <class cT>
inline void BooleanOp<T, Unit>::evaluateInterval_(cT& outputContainer, interval_data<Unit> ivl,
T beforeCount, T afterCount) {
bool before = (int)beforeCount > 0;
bool after = (int)afterCount > 0;
int value = (!before & after) - (before & !after);
if(value) {
outputContainer.insert(outputContainer.end(), std::pair<interval_data<Unit>, int>(ivl, value));
}
}
template <class T>
inline BinaryCount<T>& BinaryCount<T>::operator=(const BinaryCount<T>& that) {
counts_[0] = that.counts_[0];
counts_[1] = that.counts_[1];
return *this;
}
template <class T>
inline bool BinaryCount<T>::operator==(const BinaryCount<T>& that) const {
return counts_[0] == that.counts_[0] &&
counts_[1] == that.counts_[1];
}
template <class T>
inline BinaryCount<T>& BinaryCount<T>::operator+=(const BinaryCount<T>& that) {
counts_[0] += that.counts_[0];
counts_[1] += that.counts_[1];
return *this;
}
template <class T>
inline BinaryCount<T>& BinaryCount<T>::operator-=(const BinaryCount<T>& that) {
counts_[0] += that.counts_[0];
counts_[1] += that.counts_[1];
return *this;
}
template <class T>
inline BinaryCount<T> BinaryCount<T>::operator+(const BinaryCount<T>& that) const {
BinaryCount retVal(*this);
retVal += that;
return retVal;
}
template <class T>
inline BinaryCount<T> BinaryCount<T>::operator-(const BinaryCount<T>& that) const {
BinaryCount retVal(*this);
retVal -= that;
return retVal;
}
template <class T>
inline BinaryCount<T> BinaryCount<T>::operator-() const {
return BinaryCount<T>() - *this;
}
template <class T, typename Unit, typename iterator_type_1, typename iterator_type_2>
inline void applyBooleanBinaryOp(std::vector<std::pair<Unit, std::pair<Unit, int> > >& output,
//const std::vector<std::pair<Unit, std::pair<Unit, int> > >& input1,
//const std::vector<std::pair<Unit, std::pair<Unit, int> > >& input2,
iterator_type_1 itr1, iterator_type_1 itr1_end,
iterator_type_2 itr2, iterator_type_2 itr2_end,
T defaultCount) {
BooleanOp<T, Unit> boolean(defaultCount);
//typename std::vector<std::pair<Unit, std::pair<Unit, int> > >::const_iterator itr1 = input1.begin();
//typename std::vector<std::pair<Unit, std::pair<Unit, int> > >::const_iterator itr2 = input2.begin();
std::vector<std::pair<interval_data<Unit>, int> > container;
//output.reserve((std::max)(input1.size(), input2.size()));
//consider eliminating dependecy on limits with bool flag for initial state
Unit UnitMax = (std::numeric_limits<Unit>::max)();
Unit prevCoord = UnitMax;
Unit prevPosition = UnitMax;
T count(defaultCount);
//define the starting point
if(itr1 != itr1_end) {
prevCoord = (*itr1).first;
prevPosition = (*itr1).second.first;
count[0] += (*itr1).second.second;
}
if(itr2 != itr2_end) {
if((*itr2).first < prevCoord ||
((*itr2).first == prevCoord && (*itr2).second.first < prevPosition)) {
prevCoord = (*itr2).first;
prevPosition = (*itr2).second.first;
count = defaultCount;
count[1] += (*itr2).second.second;
++itr2;
} else if((*itr2).first == prevCoord && (*itr2).second.first == prevPosition) {
count[1] += (*itr2).second.second;
++itr2;
if(itr1 != itr1_end) ++itr1;
} else {
if(itr1 != itr1_end) ++itr1;
}
} else {
if(itr1 != itr1_end) ++itr1;
}
while(itr1 != itr1_end || itr2 != itr2_end) {
Unit curCoord = UnitMax;
Unit curPosition = UnitMax;
T curCount(defaultCount);
if(itr1 != itr1_end) {
curCoord = (*itr1).first;
curPosition = (*itr1).second.first;
curCount[0] += (*itr1).second.second;
}
if(itr2 != itr2_end) {
if((*itr2).first < curCoord ||
((*itr2).first == curCoord && (*itr2).second.first < curPosition)) {
curCoord = (*itr2).first;
curPosition = (*itr2).second.first;
curCount = defaultCount;
curCount[1] += (*itr2).second.second;
++itr2;
} else if((*itr2).first == curCoord && (*itr2).second.first == curPosition) {
curCount[1] += (*itr2).second.second;
++itr2;
if(itr1 != itr1_end) ++itr1;
} else {
if(itr1 != itr1_end) ++itr1;
}
} else {
++itr1;
}
if(prevCoord != curCoord) {
boolean.advanceScan();
prevCoord = curCoord;
prevPosition = curPosition;
count = curCount;
continue;
}
if(curPosition != prevPosition && count != defaultCount) {
interval_data<Unit> ivl(prevPosition, curPosition);
container.clear();
boolean.processInterval(container, ivl, count);
for(std::size_t i = 0; i < container.size(); ++i) {
std::pair<interval_data<Unit>, int>& element = container[i];
if(!output.empty() && output.back().first == prevCoord &&
output.back().second.first == element.first.low() &&
output.back().second.second == element.second * -1) {
output.pop_back();
} else {
output.push_back(std::pair<Unit, std::pair<Unit, int> >(prevCoord, std::pair<Unit, int>(element.first.low(),
element.second)));
}
output.push_back(std::pair<Unit, std::pair<Unit, int> >(prevCoord, std::pair<Unit, int>(element.first.high(),
element.second * -1)));
}
}
prevPosition = curPosition;
count += curCount;
}
}
template <class T, typename Unit>
inline void applyBooleanBinaryOp(std::vector<std::pair<Unit, std::pair<Unit, int> > >& inputOutput,
const std::vector<std::pair<Unit, std::pair<Unit, int> > >& input2,
T defaultCount) {
std::vector<std::pair<Unit, std::pair<Unit, int> > > output;
applyBooleanBinaryOp(output, inputOutput, input2, defaultCount);
if(output.size() < inputOutput.size() / 2) {
inputOutput = std::vector<std::pair<Unit, std::pair<Unit, int> > >();
} else {
inputOutput.clear();
}
inputOutput.insert(inputOutput.end(), output.begin(), output.end());
}
template <typename count_type = int>
struct default_arg_workaround {
template <typename Unit>
static inline void applyBooleanOr(std::vector<std::pair<Unit, std::pair<Unit, int> > >& input) {
BooleanOp<count_type, Unit> booleanOr;
std::vector<std::pair<interval_data<Unit>, int> > container;
std::vector<std::pair<Unit, std::pair<Unit, int> > > output;
output.reserve(input.size());
//consider eliminating dependecy on limits with bool flag for initial state
Unit UnitMax = (std::numeric_limits<Unit>::max)();
Unit prevPos = UnitMax;
Unit prevY = UnitMax;
int count = 0;
for(typename std::vector<std::pair<Unit, std::pair<Unit, int> > >::iterator itr = input.begin();
itr != input.end(); ++itr) {
Unit pos = (*itr).first;
Unit y = (*itr).second.first;
if(pos != prevPos) {
booleanOr.advanceScan();
prevPos = pos;
prevY = y;
count = (*itr).second.second;
continue;
}
if(y != prevY && count != 0) {
interval_data<Unit> ivl(prevY, y);
container.clear();
booleanOr.processInterval(container, ivl, count_type(count));
for(std::size_t i = 0; i < container.size(); ++i) {
std::pair<interval_data<Unit>, int>& element = container[i];
if(!output.empty() && output.back().first == prevPos &&
output.back().second.first == element.first.low() &&
output.back().second.second == element.second * -1) {
output.pop_back();
} else {
output.push_back(std::pair<Unit, std::pair<Unit, int> >(prevPos, std::pair<Unit, int>(element.first.low(),
element.second)));
}
output.push_back(std::pair<Unit, std::pair<Unit, int> >(prevPos, std::pair<Unit, int>(element.first.high(),
element.second * -1)));
}
}
prevY = y;
count += (*itr).second.second;
}
if(output.size() < input.size() / 2) {
input = std::vector<std::pair<Unit, std::pair<Unit, int> > >();
} else {
input.clear();
}
input.insert(input.end(), output.begin(), output.end());
}
};
}
}
}
#endif
| {
"pile_set_name": "Github"
} |
<?php
namespace App\ViewFunctions;
use App\Config;
use Tightenco\Collect\Support\Collection;
class Asset extends ViewFunction
{
/** @var string The function name */
protected $name = 'asset';
/** @var Config The application configuration */
protected $config;
/** Create a new Asset object. */
public function __construct(Config $container)
{
$this->config = $container;
}
/** Return the path to an asset. */
public function __invoke(string $path): string
{
$path = '/' . ltrim($path, '/');
if ($this->mixManifest()->has($path)) {
$path = $this->mixManifest()->get($path);
}
return 'app/assets/' . ltrim($path, '/');
}
/** Return the mix manifest collection. */
protected function mixManifest(): Collection
{
$mixManifest = $this->config->get('asset_path') . '/mix-manifest.json';
if (! is_file($mixManifest)) {
return new Collection;
}
return Collection::make(
json_decode(file_get_contents($mixManifest), true) ?? []
);
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* Copyright (c) 2014 Robin Appelman <[email protected]>
* This file is licensed under the Licensed under the MIT license:
* http://opensource.org/licenses/MIT
*/
namespace Icewind\Streams;
/**
* Wrapper that provides callbacks for write, read and close
*
* The following options should be passed in the context when opening the stream
* [
* 'callback' => [
* 'source' => resource
* 'read' => function($count){} (optional)
* 'write' => function($data){} (optional)
* 'close' => function(){} (optional)
* 'readdir' => function(){} (optional)
* ]
* ]
*
* All callbacks are called after the operation is executed on the source stream
*/
class CallbackWrapper extends Wrapper {
/**
* @var callable
*/
protected $readCallback;
/**
* @var callable
*/
protected $writeCallback;
/**
* @var callable
*/
protected $closeCallback;
/**
* @var callable
*/
protected $readDirCallBack;
/**
* @var callable
*/
protected $preCloseCallback;
/**
* Wraps a stream with the provided callbacks
*
* @param resource $source
* @param callable $read (optional)
* @param callable $write (optional)
* @param callable $close (optional)
* @param callable $readDir (optional)
* @return resource
*
* @throws \BadMethodCallException
*/
public static function wrap($source, $read = null, $write = null, $close = null, $readDir = null, $preClose = null) {
$context = stream_context_create(array(
'callback' => array(
'source' => $source,
'read' => $read,
'write' => $write,
'close' => $close,
'readDir' => $readDir,
'preClose' => $preClose,
)
));
return Wrapper::wrapSource($source, $context, 'callback', '\Icewind\Streams\CallbackWrapper');
}
protected function open() {
$context = $this->loadContext('callback');
$this->readCallback = $context['read'];
$this->writeCallback = $context['write'];
$this->closeCallback = $context['close'];
$this->readDirCallBack = $context['readDir'];
$this->preCloseCallback = $context['preClose'];
return true;
}
public function dir_opendir($path, $options) {
return $this->open();
}
public function stream_open($path, $mode, $options, &$opened_path) {
return $this->open();
}
public function stream_read($count) {
$result = parent::stream_read($count);
if (is_callable($this->readCallback)) {
call_user_func($this->readCallback, strlen($result));
}
return $result;
}
public function stream_write($data) {
$result = parent::stream_write($data);
if (is_callable($this->writeCallback)) {
call_user_func($this->writeCallback, $data);
}
return $result;
}
public function stream_close() {
if (is_callable($this->preCloseCallback)) {
call_user_func($this->preCloseCallback, $this->loadContext('callback')['source']);
// prevent further calls by potential PHP 7 GC ghosts
$this->preCloseCallback = null;
}
$result = parent::stream_close();
if (is_callable($this->closeCallback)) {
call_user_func($this->closeCallback);
// prevent further calls by potential PHP 7 GC ghosts
$this->closeCallback = null;
}
return $result;
}
public function dir_readdir() {
$result = parent::dir_readdir();
if (is_callable($this->readDirCallBack)) {
call_user_func($this->readDirCallBack);
}
return $result;
}
}
| {
"pile_set_name": "Github"
} |
{
"name": "container-training-pub-sub-server",
"version": "0.0.1",
"dependencies": {
"express": "^4.16.2",
"socket.io": "^2.0.4"
}
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.