text
stringlengths 2
100k
| meta
dict |
---|---|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "corefunctions.h"
#include "macros.h"
#include "YogaJniException.h"
namespace facebook {
namespace yoga {
namespace vanillajni {
namespace {
JavaVM* globalVm = NULL;
struct JavaVMInitializer {
JavaVMInitializer(JavaVM* vm) {
if (!vm) {
logErrorMessageAndDie(
"You cannot pass a NULL JavaVM to ensureInitialized");
}
globalVm = vm;
}
};
} // namespace
jint ensureInitialized(JNIEnv** env, JavaVM* vm) {
static JavaVMInitializer init(vm);
if (!env) {
logErrorMessageAndDie(
"Need to pass a valid JNIEnv pointer to vanillajni initialization "
"routine");
}
if (vm->GetEnv(reinterpret_cast<void**>(env), JNI_VERSION_1_6) != JNI_OK) {
logErrorMessageAndDie(
"Error retrieving JNIEnv during initialization of vanillajni");
}
return JNI_VERSION_1_6;
}
// TODO why we need JNIEXPORT for getCurrentEnv ?
JNIEXPORT JNIEnv* getCurrentEnv() {
JNIEnv* env;
jint ret = globalVm->GetEnv((void**) &env, JNI_VERSION_1_6);
if (ret != JNI_OK) {
logErrorMessageAndDie(
"There was an error retrieving the current JNIEnv. Make sure the "
"current thread is attached");
}
return env;
}
void logErrorMessageAndDie(const char* message) {
VANILLAJNI_LOG_ERROR(
"VanillaJni",
"Aborting due to error detected in native code: %s",
message);
VANILLAJNI_DIE();
}
void assertNoPendingJniException(JNIEnv* env) {
if (env->ExceptionCheck() == JNI_FALSE) {
return;
}
auto throwable = env->ExceptionOccurred();
if (!throwable) {
logErrorMessageAndDie("Unable to get pending JNI exception.");
}
env->ExceptionClear();
throw YogaJniException(throwable);
}
void assertNoPendingJniExceptionIf(JNIEnv* env, bool condition) {
if (!condition) {
return;
}
if (env->ExceptionCheck() == JNI_TRUE) {
assertNoPendingJniException(env);
return;
}
throw YogaJniException();
}
} // namespace vanillajni
} // namespace yoga
} // namespace facebook
| {
"pile_set_name": "Github"
} |
@org.osgi.annotation.versioning.Version("1.3.0")
package aQute.launchpad;
| {
"pile_set_name": "Github"
} |
export default class GraphAdaptor {
constructor(data) {
this._processData(data);
}
update(data) {
this._processData(data);
}
getTopology() {
const {nodes, links} = this;
return {
nodes,
links
};
}
getNode(id) {
return this.nodeMap[id];
}
// pass through as-is
_processData(data) {
this.nodes = [];
this.links = [];
this.nodeMap = {};
this.linkMap = {};
data.forEach(link => {
const {source, target} = link;
if (this.linkMap[`${source}-${target}`] || this.linkMap[`${target}-${source}`]) {
return;
}
this.links.push({
id: this.links.length,
source,
target
});
this.linkMap[`${source}-${target}`] = true;
let node = this.nodeMap[source];
if (!node) {
node = this.nodeMap[source] = {
id: source,
sourceCount: 0,
targetCount: 0,
size: 4
};
this.nodes.push(node);
}
node.sourceCount++;
node = this.nodeMap[target];
if (!node) {
node = this.nodeMap[target] = {
id: target,
sourceCount: 0,
targetCount: 0,
size: 4
};
this.nodes.push(node);
}
node.targetCount++;
});
}
}
| {
"pile_set_name": "Github"
} |
/* Copyright (C) 1992, 1996, 1997, 1998, 1999 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 _ALLOCA_H
#define _ALLOCA_H 1
#include <features.h>
#define __need_size_t
#include <stddef.h>
__BEGIN_DECLS
/* Remove any previous definitions. */
#undef alloca
/* Allocate a block that will be freed when the calling function exits. */
extern void *alloca (size_t __size) __THROW;
#ifdef __GNUC__
# define alloca(size) __builtin_alloca (size)
#endif /* GCC. */
#define __MAX_ALLOCA_CUTOFF 65536
__END_DECLS
#endif /* alloca.h */
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
*
* https://www.gz-yami.com/
*
* 未经允许,不可做商业用途!
*
* 版权所有,侵权必究!
*/
package com.yami.shop.quartz.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yami.shop.quartz.model.ScheduleJobLog;
public interface ScheduleJobLogMapper extends BaseMapper<ScheduleJobLog> {
} | {
"pile_set_name": "Github"
} |
import sys
class RangeLookup(object):
def __init__(self):
self.ranges = []
def register(self, start, end, name):
self.ranges.append((start, end, name))
def lookup(self, addr):
for start, end, name in self.ranges:
if start <= addr < end:
return "jit:" + name
return hex(addr)
if __name__ == "__main__":
raw_fn = sys.argv[1]
jit_fns = sys.argv[2:]
ranger = RangeLookup()
for fn in jit_fns:
for l in open(fn):
start, end, name = l.split(' ', 2)
name = name.strip()
ranger.register(int(start, 16), int(end, 16), name)
mode = 0
for l in open(raw_fn):
l = l.strip()
if mode == 0:
assert l == "--- symbol"
mode = 1
print l
elif mode == 1:
assert l == "binary=jit_pprof"
mode = 2
print l
elif mode == 3:
print l
elif mode == 2:
if l == "---":
mode = 3
print l
else:
addr, curname = l.split(' ', 1)
if addr != curname:
print l
else:
addr_int = int(addr, 16)
print addr, ranger.lookup(addr_int)
else:
assert 0, mode
| {
"pile_set_name": "Github"
} |
# 协议列表
| {
"pile_set_name": "Github"
} |
// Copyright 2018 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP__WAITABLE_HPP_
#define RCLCPP__WAITABLE_HPP_
#include <atomic>
#include "rclcpp/macros.hpp"
#include "rclcpp/visibility_control.hpp"
#include "rcl/wait.h"
namespace rclcpp
{
class Waitable
{
public:
RCLCPP_SMART_PTR_DEFINITIONS_NOT_COPYABLE(Waitable)
RCLCPP_PUBLIC
virtual ~Waitable() = default;
/// Get the number of ready subscriptions
/**
* Returns a value of 0 by default.
* This should be overridden if the Waitable contains one or more subscriptions.
* \return The number of subscriptions associated with the Waitable.
*/
RCLCPP_PUBLIC
virtual
size_t
get_number_of_ready_subscriptions();
/// Get the number of ready timers
/**
* Returns a value of 0 by default.
* This should be overridden if the Waitable contains one or more timers.
* \return The number of timers associated with the Waitable.
*/
RCLCPP_PUBLIC
virtual
size_t
get_number_of_ready_timers();
/// Get the number of ready clients
/**
* Returns a value of 0 by default.
* This should be overridden if the Waitable contains one or more clients.
* \return The number of clients associated with the Waitable.
*/
RCLCPP_PUBLIC
virtual
size_t
get_number_of_ready_clients();
/// Get the number of ready events
/**
* Returns a value of 0 by default.
* This should be overridden if the Waitable contains one or more events.
* \return The number of events associated with the Waitable.
*/
RCLCPP_PUBLIC
virtual
size_t
get_number_of_ready_events();
/// Get the number of ready services
/**
* Returns a value of 0 by default.
* This should be overridden if the Waitable contains one or more services.
* \return The number of services associated with the Waitable.
*/
RCLCPP_PUBLIC
virtual
size_t
get_number_of_ready_services();
/// Get the number of ready guard_conditions
/**
* Returns a value of 0 by default.
* This should be overridden if the Waitable contains one or more guard_conditions.
* \return The number of guard_conditions associated with the Waitable.
*/
RCLCPP_PUBLIC
virtual
size_t
get_number_of_ready_guard_conditions();
/// Add the Waitable to a wait set.
/**
* \param[in] wait_set A handle to the wait set to add the Waitable to.
* \return `true` if the Waitable is added successfully, `false` otherwise.
* \throws rclcpp::execptions::RCLError from rcl_wait_set_add_*()
*/
RCLCPP_PUBLIC
virtual
bool
add_to_wait_set(rcl_wait_set_t * wait_set) = 0;
/// Check if the Waitable is ready.
/**
* The input wait set should be the same that was used in a previously call to
* `add_to_wait_set()`.
* The wait set should also have been previously waited on with `rcl_wait()`.
*
* \param[in] wait_set A handle to the wait set the Waitable was previously added to
* and that has been waited on.
* \return `true` if the Waitable is ready, `false` otherwise.
*/
RCLCPP_PUBLIC
virtual
bool
is_ready(rcl_wait_set_t * wait_set) = 0;
/// Execute any entities of the Waitable that are ready.
/**
* Before calling this method, the Waitable should be added to a wait set,
* waited on, and then updated.
*
* Example usage:
*
* ```cpp
* // ... create a wait set and a Waitable
* // Add the Waitable to the wait set
* bool add_ret = waitable.add_to_wait_set(wait_set);
* // ... error handling
* // Wait
* rcl_ret_t wait_ret = rcl_wait(wait_set);
* // ... error handling
* // Update the Waitable
* waitable.update(wait_set);
* // Execute any entities of the Waitable that may be ready
* waitable.execute();
* ```
*/
RCLCPP_PUBLIC
virtual
void
execute() = 0;
/// Exchange the "in use by wait set" state for this timer.
/**
* This is used to ensure this timer is not used by multiple
* wait sets at the same time.
*
* \param[in] in_use_state the new state to exchange into the state, true
* indicates it is now in use by a wait set, and false is that it is no
* longer in use by a wait set.
* \returns the previous state.
*/
RCLCPP_PUBLIC
bool
exchange_in_use_by_wait_set_state(bool in_use_state);
private:
std::atomic<bool> in_use_by_wait_set_{false};
}; // class Waitable
} // namespace rclcpp
#endif // RCLCPP__WAITABLE_HPP_
| {
"pile_set_name": "Github"
} |
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// The ClearCanvas RIS/PACS open source project 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
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using ClearCanvas.Common;
namespace ClearCanvas.Server.ShredHost
{
internal class ShredControllerList : MarshallableList<ShredController>
{
public ShredControllerList()
{
}
public ReadOnlyCollection<ShredController> AllShredInfo
{
get { return this.ContainedObjects; }
}
public ShredController this[int index]
{
get
{
foreach (ShredController shredController in this.ContainedObjects)
{
if (shredController.Id == index)
{
return shredController;
}
}
string message = "Could not find ShredController object with Id = " + index.ToString();
throw new System.IndexOutOfRangeException(message);
}
}
public WcfDataShred[] WcfDataShredCollection
{
get
{
WcfDataShred[] shreds = new WcfDataShred[this.ContainedObjects.Count];
int i = 0;
foreach (ShredController shredController in this.ContainedObjects)
{
shreds[i++] = shredController.WcfDataShred;
}
return shreds;
}
}
}
}
| {
"pile_set_name": "Github"
} |
/* @flow */
import React from "react";
import { Text } from "react-native";
import { Trans } from "react-i18next";
const el = () => (
<Text
allowFontScaling={false}
style={{
padding: 60,
opacity: 0.5,
textAlign: "center",
}}
>
<Trans i18nKey="common:operationList.noMoreOperations" />
</Text>
);
export default el;
| {
"pile_set_name": "Github"
} |
-----BEGIN CERTIFICATE-----
MIIELDCCApSgAwIBAgIBATANBgkqhkiG9w0BAQsFADAgMR4wHAYDVQQDDBVzZWJh
c3RpYW4vREM9eW8vREM9bGswHhcNMTkxMTE1MTIzMzUwWhcNMjAxMTE0MTIzMzUw
WjAgMR4wHAYDVQQDDBVzZWJhc3RpYW4vREM9eW8vREM9bGswggGiMA0GCSqGSIb3
DQEBAQUAA4IBjwAwggGKAoIBgQC96oQ16N6R0H69fWFfsfHo2oIJHtLgETPK6ly+
tLeznJsZomCkZgFS0wNwnExr9qlH+AmygvNoaniVq/Pp2+2jwMuLgk5hkZMRM8Rf
i3wp5LCbW4BysT1rURQoqfo4iH8d60WgUl2Ggou70RMGlizvgvGOfszxfRTkuNXd
Eisbzs3UTKIWdx/umzHW4hbfbZcJ89cXoRLbxPjzozCfXPymmimlyva3Tu3QrxNH
/IBdzni9qj6gctmTYgWHMwzRJz+yJBY7V3G7jss/3vWaAoOhLns5bJUAXOvNsR4D
sWE5676q+Hi8Ti7B7AvWhqxB+9HSevjNrK+fNV7GFNRtbPW6o6vzYjPhtsdjluzP
94UA2AC6rjxtzNgzaXtQHZAnBjCf6ayoqbizh++SHU7J+tdoyxHjSfKPfdIW0P7Z
W5npDb+b2kGTa6cclciBpRqyZWVz0CIgi06k+GuxgroQVf7465CEjyh2krQqGXtt
A7d8gWiKsxpZgOjh5wFmFT97h8MCAwEAAaNxMG8wCQYDVR0TBAIwADALBgNVHQ8E
BAMCBLAwHQYDVR0OBBYEFOGxpUkCn17xMxFtmn/CFk5W57s6MBoGA1UdEQQTMBGB
D3NlYmFzdGlhbkB5by5sazAaBgNVHRIEEzARgQ9zZWJhc3RpYW5AeW8ubGswDQYJ
KoZIhvcNAQELBQADggGBAEDGrRAAvS7w793sYSoE8VAt45pw71zio2BgdcpYRoHB
rdaghjIVg77lybTmKdRGPM1T9m4zL01xddrqpgQFflVLmd/JVfEHwkLfJzZKvpy+
1vxgdIHhXkBB9G/X+LZC3PtMQx4f6BYIyf4kiVrTSWiKeeftFsH1tdvU5oYR7Gzy
dugPR09J0oVA/DiLlzfUy9o2meH8QyCGX8c0LHY8gx4C4orZz+FIFZczZB1FUOeu
LjR/yNUh7bYqwVHTQL5sajfQMFyt8HotazwdBvUETXGZW3VQZymR99gcMjr/H4xg
mPEildrYsY7glEKryCc2YDYC1ahqWshnpOLqAXatonsoDBXpVKl+HGsUnrnCiaxh
ctN4at+sy0CqPL+zXqp14b34rO0lP6hf0l+/LnuM96ImE+Rw+3gPX2iOtqivhrfM
rAFNAD1QEGN6elQdy1MRuXwjcUhM8P8ofLDEaE225TSZvAI+XoCxW2PSsQj5cGER
9vbf6JSKzQPa/HeBoU0s1Q==
-----END CERTIFICATE-----
| {
"pile_set_name": "Github"
} |
<?php
/**
* This file is part of the LuneticsLocaleBundle package.
*
* <https://github.com/lunetics/LocaleBundle/>
*
* For the full copyright and license information, please view the LICENSE
* file that is distributed with this source code.
*/
namespace Lunetics\LocaleBundle\Tests\DependencyInjection;
use Lunetics\LocaleBundle\Cookie\LocaleCookie;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Cookie;
class LocaleCookieTest extends TestCase
{
public function testCookieParamsAreSet()
{
$localeCookie = new LocaleCookie('lunetics_locale', 86400, '/', null, false, true, true);
$cookie = $localeCookie->getLocaleCookie('en');
$this->assertTrue($cookie instanceof Cookie);
$this->assertEquals('lunetics_locale', $cookie->getName());
$this->assertEquals('en', $cookie->getValue());
$this->assertEquals('/', $cookie->getPath());
$this->assertEquals(null, $cookie->getDomain());
$this->assertTrue($cookie->isHttpOnly());
$this->assertFalse($cookie->isSecure());
}
public function testCookieExpiresDateTime()
{
$localeCookie = new LocaleCookie('lunetics_locale', 86400, '/', null, false, true, true);
$cookie = $localeCookie->getLocaleCookie('en');
$this->assertTrue($cookie->getExpiresTime() > time());
$this->assertTrue($cookie->getExpiresTime() <= (time() + 86400));
}
}
| {
"pile_set_name": "Github"
} |
{
"metadata": {
"name": "",
"signature": "sha256:f27471ecbd79f2ade29af683349371a088591f10065165f2e861846e8806e995"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"import os\n",
"import sys\n",
"import glob\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import pandas as pd\n",
"%matplotlib inline\n",
"%precision 4"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 1,
"text": [
"u'%.4f'"
]
}
],
"prompt_number": 1
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**References**:\n",
"\n",
"[Functional Programming HOWTO](https://docs.python.org/2/howto/functional.html)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Functions are first class objects\n",
"----\n",
"\n",
"In Python, functions behave like any other object, such as an int or a list. That means that you can use functions as arguments to other functions, store functions as dictionary values, or return a function from another function. This leads to many powerful ways to use functions."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def square(x):\n",
" \"\"\"Square of x.\"\"\"\n",
" return x*x\n",
"\n",
"def cube(x):\n",
" \"\"\"Cube of x.\"\"\"\n",
" return x*x*x"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 2
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# create a dictionary of functions\n",
"\n",
"funcs = {\n",
" 'square': square,\n",
" 'cube': cube,\n",
"}"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 3
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"x = 2\n",
"\n",
"print square(x)\n",
"print cube(x)\n",
"\n",
"for func in sorted(funcs):\n",
" print func, funcs[func](x)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"4\n",
"8\n",
"cube 8\n",
"square 4\n"
]
}
],
"prompt_number": 4
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Function argumnents\n",
"----\n",
"\n",
"This is caution to be careful of how Python treats function arguments. \n",
"\n",
"### Call by \"object reference\"\n",
"\n",
"Some data types, such as strings and tuples, cannot be directly modified and are called immutable. Atomic variables such as integers or floats are always immutable. Other datatypes, such as lists and dictionaries, can be directly modified and are called mutable. Passing mutable variables as function arguments can have different outcomes, depedning on what is done to the variable inside the function. When we call\n",
"\n",
"```python\n",
"x = [1,2,3] # mutable\n",
"f(x)\n",
"```\n",
"\n",
"what is passsed to the function is a *copy* of the *name* `x` that refers to the content (a list) `[1, 2, 3]`. If we use this copy of the name to change the content directly (e.g. `x[0] = 999`) within the function, then `x` chanes *outside* the funciton as well. However, if we reassgne `x` within the function to a new object (e.g. another list), then the copy of the name `x` now points to the new object, but `x` outside the function is unhcanged."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def transmogrify(x):\n",
" x[0] = 999\n",
" return x\n",
"\n",
"x = [1,2,3]\n",
"print x\n",
"print transmogrify(x)\n",
"print x"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[1, 2, 3]\n",
"[999, 2, 3]\n",
"[999, 2, 3]\n"
]
}
],
"prompt_number": 5
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def no_mogrify(x):\n",
" x = [4,5,6]\n",
" return x\n",
"\n",
"x = [1,2,3]\n",
"print x\n",
"print no_mogrify(x)\n",
"print x"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[1, 2, 3]\n",
"[4, 5, 6]\n",
"[1, 2, 3]\n"
]
}
],
"prompt_number": 6
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Binding of default arguments occurs at function *definition*"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def f(x = []):\n",
" x.append(1)\n",
" return x\n",
"\n",
"print f()\n",
"print f()\n",
"print f()\n",
"print f(x = [9,9,9])\n",
"print f()\n",
"print f()"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[1]\n",
"[1, 1]\n",
"[1, 1, 1]\n",
"[9, 9, 9, 1]\n",
"[1, 1, 1, 1]\n",
"[1, 1, 1, 1, 1]\n"
]
}
],
"prompt_number": 7
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Usually, this behavior is not desired and we would write\n",
"\n",
"def f(x = None):\n",
" if x is None:\n",
" x = []\n",
" x.append(1)\n",
" return x\n",
"\n",
"print f()\n",
"print f()\n",
"print f()\n",
"print f(x = [9,9,9])\n",
"print f()\n",
"print f()"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[1]\n",
"[1]\n",
"[1]\n",
"[9, 9, 9, 1]\n",
"[1]\n",
"[1]\n"
]
}
],
"prompt_number": 8
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"However, sometimes in advanced usage, the behavior is intetnional. See <http://effbot.org/zone/default-values.htm> for details."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Higher-order functions\n",
"----\n",
"\n",
"A function that uses another function as an input argument or returns a function (HOF) is known as a higher-order function. The most familiar examples are `map` and `filter`."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# The map function applies a function to each member of a collection\n",
"\n",
"map(square, range(5))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 9,
"text": [
"[0, 1, 4, 9, 16]"
]
}
],
"prompt_number": 9
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# The filter function applies a predicate to each memmber of a collection, \n",
"# retaining only those members where the predicate is True\n",
"\n",
"def is_even(x):\n",
" return x%2 == 0\n",
"\n",
"filter(is_even, range(5))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 10,
"text": [
"[0, 2, 4]"
]
}
],
"prompt_number": 10
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# It is common to combine map and filter\n",
"\n",
"map(square, filter(is_even, range(5)))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 11,
"text": [
"[0, 4, 16]"
]
}
],
"prompt_number": 11
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# The reduce function reduces a collection using a binary operator to combine items two at a time\n",
"\n",
"def my_add(x, y):\n",
" return x + y\n",
"\n",
"# another implementation of the sum function\n",
"reduce(my_add, [1,2,3,4,5])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 12,
"text": [
"15"
]
}
],
"prompt_number": 12
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Custom functions can of couse, also be HOFs\n",
"\n",
"def custom_sum(xs, transform):\n",
" \"\"\"Returns the sum of xs after a user specified transform.\"\"\"\n",
" return sum(map(transform, xs))\n",
"\n",
"xs = range(5)\n",
"print custom_sum(xs, square)\n",
"print custom_sum(xs, cube)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"30\n",
"100\n"
]
}
],
"prompt_number": 13
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Returning a function is also useful\n",
"\n",
"# A closure\n",
"def make_logger(target):\n",
" def logger(data):\n",
" with open(target, 'a') as f:\n",
" f.write(data + '\\n')\n",
" return logger\n",
"\n",
"foo_logger = make_logger('foo.txt')\n",
"foo_logger('Hello')\n",
"foo_logger('World')"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 14
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"!cat 'foo.txt'"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Hello\r\n",
"World\r\n",
"Hello\r\n",
"World\r\n",
"Hello\r\n",
"World\r\n",
"Hello\r\n",
"World\r\n"
]
}
],
"prompt_number": 15
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Anonymous functions\n",
"----\n",
"\n",
"When using functional style, there is often the need to create small specific functions that perform a limited task as input to a HOF such as `map` or `filter`. In such cases, these functions are often written as `anonymous` or `lambda` functions. If you find it hard to understand what a `lambda` function is doing, it should probably be rewritten as a regular function."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Using standard functions\n",
"\n",
"def square(x):\n",
" return x*x\n",
"\n",
"print map(square, range(5))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[0, 1, 4, 9, 16]\n"
]
}
],
"prompt_number": 16
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Using an anonymous function\n",
"\n",
"print map(lambda x: x*x, range(5))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[0, 1, 4, 9, 16]\n"
]
}
],
"prompt_number": 17
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# what does this function do?\n",
"s1 = reduce(lambda x, y: x+y, map(lambda x: x**2, range(1,10)))\n",
"print(s1)\n",
"print\n",
"\n",
"# functional expressions and lambdas are cool \n",
"# but can be difficult to read when over-used\n",
"# Here is a more comprehensible version\n",
"s2 = sum(x**2 for x in range(1, 10))\n",
"print(s2)\n",
"\n",
"# we will revisit map-reduce when we look at high-performance computing\n",
"# where map is used to distribute jobs to multiple processors\n",
"# and reduce is used to calculate some aggreate function of the results \n",
"# returned by map"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"285\n",
"\n",
"285\n"
]
}
],
"prompt_number": 18
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Pure functions\n",
"----\n",
"\n",
"Functions are pure if they do not have any *side effects* and do not depend on global variables. Pure functions are similar to mathematical functions - each time the same input is given, the same output will be returned. This is useful for reducing bugs and in parallel programming since each function call is independent of any other function call and hence trivially parallelizable."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def pure(xs):\n",
" \"\"\"Make a new list and return that.\"\"\"\n",
" xs = [x*2 for x in xs]\n",
" return xs"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 19
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"xs = range(5)\n",
"print \"xs =\", xs\n",
"print pure(xs)\n",
"print \"xs =\", xs"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"xs = [0, 1, 2, 3, 4]\n",
"[0, 2, 4, 6, 8]\n",
"xs = [0, 1, 2, 3, 4]\n"
]
}
],
"prompt_number": 20
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def impure(xs):\n",
" for i, x in enumerate(xs):\n",
" xs[i] = x*2\n",
" return xs"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 21
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"xs = range(5)\n",
"print \"xs =\", xs\n",
"print impure(xs)\n",
"print \"xs =\", xs"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"xs = [0, 1, 2, 3, 4]\n",
"[0, 2, 4, 6, 8]\n",
"xs = [0, 2, 4, 6, 8]\n"
]
}
],
"prompt_number": 22
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Note that mutable functions are created upon function declaration, not use.\n",
"# This gives rise to a common source of beginner errors.\n",
"\n",
"def f1(x, y=[]):\n",
" \"\"\"Never give an empty list or other mutable structure as a default.\"\"\"\n",
" y.append(x)\n",
" return sum(y)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 23
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print f1(10)\n",
"print f1(10)\n",
"print f1(10, y =[1,2])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"10\n",
"20\n",
"13\n"
]
}
],
"prompt_number": 24
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Here is the correct Python idiom\n",
"\n",
"def f2(x, y=None):\n",
" \"\"\"Check if y is None - if so make it a list.\"\"\"\n",
" if y is None:\n",
" y = []\n",
" y.append(x)\n",
" return sum(y)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 25
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print f1(10)\n",
"print f1(10)\n",
"print f1(10, y =[1,2])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"30\n",
"40\n",
"13\n"
]
}
],
"prompt_number": 26
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Recursion\n",
"----\n",
"\n",
"A recursive function is one that calls itself. Recursive functions are extremely useful examples of the divide-and-conquer paradigm in algorithm development and are a direct expression of finite diffference equations. However, they can be computationally inefficient and their use in Python is quite rare in practice.\n",
"\n",
"Recursive functions generally have a set of *base cases* where the answer is obvious and can be returned immediately, and a set of recursive cases which are split into smaller pieces, each of which is given to the same function called recursively. A few examples will make this clearer."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# The factorial function is perhaps the simplest classic example of recursion.\n",
"\n",
"def fact(n):\n",
" \"\"\"Returns the factorial of n.\"\"\"\n",
" # base case\n",
" if n==0:\n",
" return 1\n",
" # recursive case\n",
" else:\n",
" return n * fact(n-1)\n",
"\n",
"print [fact(n) for n in range(10)]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]\n"
]
}
],
"prompt_number": 27
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# The Fibonacci sequence is another classic recursion example\n",
"\n",
"def fib1(n):\n",
" \"\"\"Fib with recursion.\"\"\"\n",
"\n",
" # base case\n",
" if n==0 or n==1:\n",
" return 1\n",
" # recurssive caae\n",
" else:\n",
" return fib1(n-1) + fib1(n-2)\n",
"\n",
"print [fib1(i) for i in range(10)]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]\n"
]
}
],
"prompt_number": 28
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# In Python, a more efficient version that does not use recursion is\n",
"\n",
"def fib2(n):\n",
" \"\"\"Fib without recursion.\"\"\"\n",
" a, b = 0, 1\n",
" for i in range(1, n+1):\n",
" a, b = b, a+b\n",
" return b\n",
"\n",
"print [fib2(i) for i in range(10)]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]\n"
]
}
],
"prompt_number": 29
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Note that the recursive version is much slower than the non-recursive version\n",
"\n",
"%timeit fib1(20)\n",
"%timeit fib2(20)\n",
"\n",
"# this is because it makes many duplicate function calls \n",
"# Note duplicate calls to fib(2) and fib(1) below\n",
"# fib(4) -> fib(3), fib(2)\n",
"# fib(3) -> fib(2), fib(1)\n",
"# fib(2) -> fib(1), fib(0)\n",
"# fib(1) -> 1\n",
"# fib(0) -> 1"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"100 loops, best of 3: 5.64 ms per loop\n",
"100000 loops, best of 3: 2.87 \u00b5s per loop"
]
},
{
"output_type": "stream",
"stream": "stdout",
"text": [
"\n"
]
}
],
"prompt_number": 30
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Use of cache to speed up the recursive version. \n",
"# Note biding of the (mutable) dictionary as a default at run-time.\n",
"\n",
"def fib3(n, cache={0: 1, 1: 1}):\n",
" \"\"\"Fib with recursion and caching.\"\"\"\n",
"\n",
" try:\n",
" return cache[n]\n",
" except KeyError:\n",
" cache[n] = fib3(n-1) + fib3(n-2)\n",
" return cache[n]\n",
"\n",
"print [fib3(i) for i in range(10)]\n",
"\n",
"%timeit fib1(20)\n",
"%timeit fib2(20)\n",
"%timeit fib3(20)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]\n",
"100 loops, best of 3: 5.64 ms per loop"
]
},
{
"output_type": "stream",
"stream": "stdout",
"text": [
"\n",
"100000 loops, best of 3: 2.92 \u00b5s per loop"
]
},
{
"output_type": "stream",
"stream": "stdout",
"text": [
"\n",
"1000000 loops, best of 3: 262 ns per loop"
]
},
{
"output_type": "stream",
"stream": "stdout",
"text": [
"\n"
]
}
],
"prompt_number": 31
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Recursion is used to show off the divide-and-conquer paradigm\n",
"\n",
"def almost_quick_sort(xs):\n",
" \"\"\"Almost a quick sort.\"\"\"\n",
"\n",
" # base case\n",
" if xs == []:\n",
" return xs\n",
" # recursive case\n",
" else:\n",
" pivot = xs[0]\n",
" less_than = [x for x in xs[1:] if x <= pivot]\n",
" more_than = [x for x in xs[1:] if x > pivot]\n",
" return almost_quick_sort(less_than) + [pivot] + almost_quick_sort(more_than)\n",
"\n",
"xs = [3,1,4,1,5,9,2,6,5,3,5,9]\n",
"print almost_quick_sort(xs)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9, 9]\n"
]
}
],
"prompt_number": 32
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Iterators\n",
"----\n",
"\n",
"Iterators represent streams of values. Because only one value is consumed at a time, they use very little memory. Use of iterators is very helpful for working with data sets too large to fit into RAM."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Iterators can be created from sequences with the built-in function iter()\n",
"\n",
"xs = [1,2,3]\n",
"x_iter = iter(xs)\n",
"\n",
"print x_iter.next()\n",
"print x_iter.next()\n",
"print x_iter.next()\n",
"print x_iter.next()"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"1\n",
"2\n",
"3\n"
]
},
{
"ename": "StopIteration",
"evalue": "",
"output_type": "pyerr",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mStopIteration\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-33-eb1a17442aa0>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mprint\u001b[0m \u001b[0mx_iter\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;32mprint\u001b[0m \u001b[0mx_iter\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0;32mprint\u001b[0m \u001b[0mx_iter\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mStopIteration\u001b[0m: "
]
}
],
"prompt_number": 33
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Most commonly, iterators are used (automatically) within a for loop\n",
"# which terminates when it encouters a StopIteration exception\n",
"\n",
"x_iter = iter(xs)\n",
"for x in x_iter:\n",
" print x"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"1\n",
"2\n",
"3\n"
]
}
],
"prompt_number": 34
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Generators\n",
"----\n",
"\n",
"Generators create iterator streams."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Functions containing the 'yield' keyword return iterators\n",
"# After yielding, the function retains its previous state\n",
"\n",
"def count_down(n):\n",
" for i in range(n, 0, -1):\n",
" yield i"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 35
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"counter = count_down(10)\n",
"print counter.next()\n",
"print counter.next()\n",
"for count in counter:\n",
" print count,"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"10\n",
"9\n",
"8 7 6 5 4 3 2 1\n"
]
}
],
"prompt_number": 36
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Iterators can also be created with 'generator expressions'\n",
"# which can be coded similar to list generators but with parenthesis\n",
"# in place of square brackets\n",
"\n",
"xs1 = [x*x for x in range(5)]\n",
"print xs1\n",
"\n",
"xs2 = (x*x for x in range(5))\n",
"print xs2\n",
"\n",
"for x in xs2:\n",
" print x,\n",
"print"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[0, 1, 4, 9, 16]\n",
"<generator object <genexpr> at 0x1130d09b0>\n",
"0 1 4 9 16\n"
]
}
],
"prompt_number": 37
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Iterators can be used for infinte functions\n",
"\n",
"def fib():\n",
" a, b = 0, 1\n",
" while True:\n",
" yield a\n",
" a, b = b, a+b"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 38
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"for i in fib():\n",
" # We must have a stopping condiiton since the generator returns an infinite stream\n",
" if i > 1000:\n",
" break\n",
" print i,"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987\n"
]
}
],
"prompt_number": 39
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Many built-in Python functions return iterators\n",
"# including file handlers\n",
"# so with the idiom below, you can process a 1 terabyte file line by line \n",
"# on your laptop without any problem\n",
"# Inn Pyhton 3, map and filter return itnrators, not lists\n",
"\n",
"for line in open('foo.txt'):\n",
" print line,"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Hello\n",
"World\n",
"Hello\n",
"World\n",
"Hello\n",
"World\n",
"Hello\n",
"World\n"
]
}
],
"prompt_number": 40
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Generators and comprehensions"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# A geneeratorr expression\n",
"\n",
"print (x for x in range(10))\n",
"\n",
"# A list comprehesnnion\n",
"\n",
"print [x for x in range(10)]\n",
"\n",
"# A set comprehension\n",
"\n",
"print {x for x in range(10)}\n",
"\n",
"# A dictionary comprehension\n",
"\n",
"print {x: x for x in range(10)}"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"<generator object <genexpr> at 0x1130d0960>\n",
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n",
"{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}\n"
]
}
],
"prompt_number": 41
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Utilites - enumerate, zip and the ternary if-else operator\n",
"\n",
"Two useful functions and an unusual operator."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# In many programming languages, loops use an index. \n",
"# This is possible in Python, but it is more \n",
"# idiomatic to use the enumerate function.\n",
"\n",
"# using and index in a loop\n",
"xs = [1,2,3,4]\n",
"for i in range(len(xs)):\n",
" print i, xs[i]\n",
"print\n",
"\n",
"# using enumerate\n",
"for i, x in enumerate(xs):\n",
" print i, x"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"0 1\n",
"1 2\n",
"2 3\n",
"3 4\n",
"\n",
"0 1\n",
"1 2\n",
"2 3\n",
"3 4\n"
]
}
],
"prompt_number": 42
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# zip is useful when you need to iterate over matched elements of \n",
"# multiple lists\n",
"\n",
"xs = [1, 2, 3, 4]\n",
"ys = [10, 20, 30, 40]\n",
"zs = ['a', 'b', 'c', 'd', 'e']\n",
"\n",
"for x, y, z in zip(xs, ys, zs):\n",
" print x, y, z\n",
"\n",
"# Note that zip stops when the shortest list is exhausted"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"1 10 a\n",
"2 20 b\n",
"3 30 c\n",
"4 40 d\n"
]
}
],
"prompt_number": 43
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# For list comprehensions, the ternary if-else operator is sometimes very useful\n",
"\n",
"[x**2 if x%2 == 0 else x**3 for x in range(10)]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 44,
"text": [
"[0, 1, 4, 27, 16, 125, 36, 343, 64, 729]"
]
}
],
"prompt_number": 44
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Decorators\n",
"----\n",
"\n",
"Decorators are a type of HOF that take a function and return a wrapped function that provides additional useful properties. \n",
"\n",
"Examples:\n",
"\n",
"- logging\n",
"- profiling\n",
"- Just-In-Time (JIT) compilation"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Here is a simple decorator to time an arbitrary function\n",
"\n",
"def func_timer(func):\n",
" \"\"\"Times how long the function took.\"\"\"\n",
" \n",
" def f(*args, **kwargs):\n",
" import time\n",
" start = time.time()\n",
" results = func(*args, **kwargs)\n",
" print \"Elapsed: %.2fs\" % (time.time() - start)\n",
" return results\n",
" \n",
" return f"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 45
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# There is a special shorthand notation for decorating functions\n",
"\n",
"@func_timer\n",
"def sleepy(msg, sleep=1.0):\n",
" \"\"\"Delays a while before answering.\"\"\"\n",
" import time\n",
" time.sleep(sleep)\n",
" print msg\n",
"\n",
"sleepy(\"Hello\", 1.5)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Hello\n",
"Elapsed: 1.50s\n"
]
}
],
"prompt_number": 46
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `operator` module\n",
"----\n",
"\n",
"The `operator` module provides \"function\" versions of common Python operators (+, *, [] etc) that can be easily used where a function argument is expected."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import operator as op\n",
"\n",
"# Here is another way to express the sum function\n",
"print reduce(op.add, range(10))\n",
"\n",
"# The pattern can be generalized\n",
"print reduce(op.mul, range(1, 10))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"45\n",
"362880\n"
]
}
],
"prompt_number": 47
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"my_list = [('a', 1), ('bb', 4), ('ccc', 2), ('dddd', 3)]\n",
"\n",
"# standard sort\n",
"print sorted(my_list)\n",
"\n",
"# return list sorted by element at position 1 (remember Python counts from 0)\n",
"print sorted(my_list, key=op.itemgetter(1))\n",
"\n",
"# the key argument is quite flexible\n",
"print sorted(my_list, key=lambda x: len(x[0]), reverse=True)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[('a', 1), ('bb', 4), ('ccc', 2), ('dddd', 3)]\n",
"[('a', 1), ('ccc', 2), ('dddd', 3), ('bb', 4)]\n",
"[('dddd', 3), ('ccc', 2), ('bb', 4), ('a', 1)]\n"
]
}
],
"prompt_number": 48
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `functools` module\n",
"----\n",
"\n",
"The most useful function in the `functools` module is `partial`, which allows you to create a new function from an old one with some arguments \"filled-in\"."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from functools import partial\n",
"\n",
"sum_ = partial(reduce, op.add)\n",
"prod_ = partial(reduce, op.mul)\n",
"print sum_([1,2,3,4])\n",
"print prod_([1,2,3,4])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"10\n",
"24\n"
]
}
],
"prompt_number": 49
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# This is extremely useful to create functions \n",
"# that expect a fixed number of arguments\n",
"\n",
"import scipy.stats as stats\n",
"\n",
"def compare(x, y, func):\n",
" \"\"\"Returne p-value for some appropriate comparison test.\"\"\"\n",
" return func(x, y)[1]"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 50
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"x, y = np.random.normal(0, 1, (100,2)).T\n",
"\n",
"print \"p value assuming equal variance =%.8f\" % compare(x, y, stats.ttest_ind)\n",
"test = partial(stats.ttest_ind, equal_var=False)\n",
"print \"p value not assuming equal variance=%.8f\" % compare(x, y, test)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"p value assuming equal variance =0.49425756\n",
"p value not assuming equal variance=0.49426047\n"
]
}
],
"prompt_number": 51
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `itertools` module\n",
"----\n",
"\n",
"This provides many essential functions for working with iterators. The `permuations` and `combinations` generators may be particularly useful for simulations, and the `groupby` gnerator is useful for data analyiss."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from itertools import cycle, groupby, islice, permutations, combinations\n",
"\n",
"print list(islice(cycle('abcd'), 0, 10))\n",
"print \n",
"\n",
"animals = sorted(['pig', 'cow', 'giraffe', 'elephant', \n",
" 'dog', 'cat', 'hippo', 'lion', 'tiger'], key=len)\n",
"for k, g in groupby(animals, key=len):\n",
" print k, list(g)\n",
"print\n",
"\n",
"print [''.join(p) for p in permutations('abc')]\n",
"print \n",
"\n",
"print [list(c) for c in combinations([1,2,3,4], r=2)]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b']\n",
"\n",
"3 ['pig', 'cow', 'dog', 'cat']\n",
"4 ['lion']\n",
"5 ['hippo', 'tiger']\n",
"7 ['giraffe']\n",
"8 ['elephant']\n",
"\n",
"['abc', 'acb', 'bac', 'bca', 'cab', 'cba']\n",
"\n",
"[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]\n"
]
}
],
"prompt_number": 52
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `toolz`, `fn` and `funcy` modules\n",
"----\n",
"\n",
"If you wish to program in the functional style, check out the following packages\n",
"\n",
"- [toolz](https://github.com/pytoolz/toolz)\n",
"- [fn](https://github.com/kachayev/fn.py)\n",
"- [funcy](https://github.com/Suor/funcy)"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Here is a small example to convert the DNA of a \n",
"# bacterial enzyme into the protein sequence\n",
"# using the partition function to generate \n",
"# cddons (3 nucleotides) for translation.\n",
"\n",
"codon_table = {\n",
" 'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',\n",
" 'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',\n",
" 'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',\n",
" 'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',\n",
" 'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',\n",
" 'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',\n",
" 'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',\n",
" 'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',\n",
" 'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',\n",
" 'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',\n",
" 'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',\n",
" 'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',\n",
" 'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',\n",
" 'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',\n",
" 'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_',\n",
" 'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W',\n",
" }\n",
"\n",
"gene = \"\"\"\n",
">ENA|BAE76126|BAE76126.1 Escherichia coli str. K-12 substr. W3110 beta-D-galactosidase \n",
"ATGACCATGATTACGGATTCACTGGCCGTCGTTTTACAACGTCGTGACTGGGAAAACCCT\n",
"GGCGTTACCCAACTTAATCGCCTTGCAGCACATCCCCCTTTCGCCAGCTGGCGTAATAGC\n",
"GAAGAGGCCCGCACCGATCGCCCTTCCCAACAGTTGCGCAGCCTGAATGGCGAATGGCGC\n",
"TTTGCCTGGTTTCCGGCACCAGAAGCGGTGCCGGAAAGCTGGCTGGAGTGCGATCTTCCT\n",
"GAGGCCGATACTGTCGTCGTCCCCTCAAACTGGCAGATGCACGGTTACGATGCGCCCATC\n",
"TACACCAACGTGACCTATCCCATTACGGTCAATCCGCCGTTTGTTCCCACGGAGAATCCG\n",
"ACGGGTTGTTACTCGCTCACATTTAATGTTGATGAAAGCTGGCTACAGGAAGGCCAGACG\n",
"CGAATTATTTTTGATGGCGTTAACTCGGCGTTTCATCTGTGGTGCAACGGGCGCTGGGTC\n",
"GGTTACGGCCAGGACAGTCGTTTGCCGTCTGAATTTGACCTGAGCGCATTTTTACGCGCC\n",
"GGAGAAAACCGCCTCGCGGTGATGGTGCTGCGCTGGAGTGACGGCAGTTATCTGGAAGAT\n",
"CAGGATATGTGGCGGATGAGCGGCATTTTCCGTGACGTCTCGTTGCTGCATAAACCGACT\n",
"ACACAAATCAGCGATTTCCATGTTGCCACTCGCTTTAATGATGATTTCAGCCGCGCTGTA\n",
"CTGGAGGCTGAAGTTCAGATGTGCGGCGAGTTGCGTGACTACCTACGGGTAACAGTTTCT\n",
"TTATGGCAGGGTGAAACGCAGGTCGCCAGCGGCACCGCGCCTTTCGGCGGTGAAATTATC\n",
"GATGAGCGTGGTGGTTATGCCGATCGCGTCACACTACGTCTGAACGTCGAAAACCCGAAA\n",
"CTGTGGAGCGCCGAAATCCCGAATCTCTATCGTGCGGTGGTTGAACTGCACACCGCCGAC\n",
"GGCACGCTGATTGAAGCAGAAGCCTGCGATGTCGGTTTCCGCGAGGTGCGGATTGAAAAT\n",
"GGTCTGCTGCTGCTGAACGGCAAGCCGTTGCTGATTCGAGGCGTTAACCGTCACGAGCAT\n",
"CATCCTCTGCATGGTCAGGTCATGGATGAGCAGACGATGGTGCAGGATATCCTGCTGATG\n",
"AAGCAGAACAACTTTAACGCCGTGCGCTGTTCGCATTATCCGAACCATCCGCTGTGGTAC\n",
"ACGCTGTGCGACCGCTACGGCCTGTATGTGGTGGATGAAGCCAATATTGAAACCCACGGC\n",
"ATGGTGCCAATGAATCGTCTGACCGATGATCCGCGCTGGCTACCGGCGATGAGCGAACGC\n",
"GTAACGCGAATGGTGCAGCGCGATCGTAATCACCCGAGTGTGATCATCTGGTCGCTGGGG\n",
"AATGAATCAGGCCACGGCGCTAATCACGACGCGCTGTATCGCTGGATCAAATCTGTCGAT\n",
"CCTTCCCGCCCGGTGCAGTATGAAGGCGGCGGAGCCGACACCACGGCCACCGATATTATT\n",
"TGCCCGATGTACGCGCGCGTGGATGAAGACCAGCCCTTCCCGGCTGTGCCGAAATGGTCC\n",
"ATCAAAAAATGGCTTTCGCTACCTGGAGAGACGCGCCCGCTGATCCTTTGCGAATACGCC\n",
"CACGCGATGGGTAACAGTCTTGGCGGTTTCGCTAAATACTGGCAGGCGTTTCGTCAGTAT\n",
"CCCCGTTTACAGGGCGGCTTCGTCTGGGACTGGGTGGATCAGTCGCTGATTAAATATGAT\n",
"GAAAACGGCAACCCGTGGTCGGCTTACGGCGGTGATTTTGGCGATACGCCGAACGATCGC\n",
"CAGTTCTGTATGAACGGTCTGGTCTTTGCCGACCGCACGCCGCATCCAGCGCTGACGGAA\n",
"GCAAAACACCAGCAGCAGTTTTTCCAGTTCCGTTTATCCGGGCAAACCATCGAAGTGACC\n",
"AGCGAATACCTGTTCCGTCATAGCGATAACGAGCTCCTGCACTGGATGGTGGCGCTGGAT\n",
"GGTAAGCCGCTGGCAAGCGGTGAAGTGCCTCTGGATGTCGCTCCACAAGGTAAACAGTTG\n",
"ATTGAACTGCCTGAACTACCGCAGCCGGAGAGCGCCGGGCAACTCTGGCTCACAGTACGC\n",
"GTAGTGCAACCGAACGCGACCGCATGGTCAGAAGCCGGGCACATCAGCGCCTGGCAGCAG\n",
"TGGCGTCTGGCGGAAAACCTCAGTGTGACGCTCCCCGCCGCGTCCCACGCCATCCCGCAT\n",
"CTGACCACCAGCGAAATGGATTTTTGCATCGAGCTGGGTAATAAGCGTTGGCAATTTAAC\n",
"CGCCAGTCAGGCTTTCTTTCACAGATGTGGATTGGCGATAAAAAACAACTGCTGACGCCG\n",
"CTGCGCGATCAGTTCACCCGTGCACCGCTGGATAACGACATTGGCGTAAGTGAAGCGACC\n",
"CGCATTGACCCTAACGCCTGGGTCGAACGCTGGAAGGCGGCGGGCCATTACCAGGCCGAA\n",
"GCAGCGTTGTTGCAGTGCACGGCAGATACACTTGCTGATGCGGTGCTGATTACGACCGCT\n",
"CACGCGTGGCAGCATCAGGGGAAAACCTTATTTATCAGCCGGAAAACCTACCGGATTGAT\n",
"GGTAGTGGTCAAATGGCGATTACCGTTGATGTTGAAGTGGCGAGCGATACACCGCATCCG\n",
"GCGCGGATTGGCCTGAACTGCCAGCTGGCGCAGGTAGCAGAGCGGGTAAACTGGCTCGGA\n",
"TTAGGGCCGCAAGAAAACTATCCCGACCGCCTTACTGCCGCCTGTTTTGACCGCTGGGAT\n",
"CTGCCATTGTCAGACATGTATACCCCGTACGTCTTCCCGAGCGAAAACGGTCTGCGCTGC\n",
"GGGACGCGCGAATTGAATTATGGCCCACACCAGTGGCGCGGCGACTTCCAGTTCAACATC\n",
"AGCCGCTACAGTCAACAGCAACTGATGGAAACCAGCCATCGCCATCTGCTGCACGCGGAA\n",
"GAAGGCACATGGCTGAATATCGACGGTTTCCATATGGGGATTGGTGGCGACGACTCCTGG\n",
"AGCCCGTCAGTATCGGCGGAATTCCAGCTGAGCGCCGGTCGCTACCATTACCAGTTGGTC\n",
"TGGTGTCAAAAATAA\n",
"\"\"\"\n",
"from toolz import partition\n",
"\n",
"# convert FASTA into single DNA sequence\n",
"dna = ''.join(line for line in gene.strip().split('\\n') \n",
" if not line.startswith('>'))\n",
"\n",
"# partition DNA into codons (of length 3) and translate to amino acid\n",
"codons = (''.join(c) for c in partition(3, dna))\n",
"''.join(codon_table[codon] for codon in codons)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 53,
"text": [
"'MTMITDSLAVVLQRRDWENPGVTQLNRLAAHPPFASWRNSEEARTDRPSQQLRSLNGEWRFAWFPAPEAVPESWLECDLPEADTVVVPSNWQMHGYDAPIYTNVTYPITVNPPFVPTENPTGCYSLTFNVDESWLQEGQTRIIFDGVNSAFHLWCNGRWVGYGQDSRLPSEFDLSAFLRAGENRLAVMVLRWSDGSYLEDQDMWRMSGIFRDVSLLHKPTTQISDFHVATRFNDDFSRAVLEAEVQMCGELRDYLRVTVSLWQGETQVASGTAPFGGEIIDERGGYADRVTLRLNVENPKLWSAEIPNLYRAVVELHTADGTLIEAEACDVGFREVRIENGLLLLNGKPLLIRGVNRHEHHPLHGQVMDEQTMVQDILLMKQNNFNAVRCSHYPNHPLWYTLCDRYGLYVVDEANIETHGMVPMNRLTDDPRWLPAMSERVTRMVQRDRNHPSVIIWSLGNESGHGANHDALYRWIKSVDPSRPVQYEGGGADTTATDIICPMYARVDEDQPFPAVPKWSIKKWLSLPGETRPLILCEYAHAMGNSLGGFAKYWQAFRQYPRLQGGFVWDWVDQSLIKYDENGNPWSAYGGDFGDTPNDRQFCMNGLVFADRTPHPALTEAKHQQQFFQFRLSGQTIEVTSEYLFRHSDNELLHWMVALDGKPLASGEVPLDVAPQGKQLIELPELPQPESAGQLWLTVRVVQPNATAWSEAGHISAWQQWRLAENLSVTLPAASHAIPHLTTSEMDFCIELGNKRWQFNRQSGFLSQMWIGDKKQLLTPLRDQFTRAPLDNDIGVSEATRIDPNAWVERWKAAGHYQAEAALLQCTADTLADAVLITTAHAWQHQGKTLFISRKTYRIDGSGQMAITVDVEVASDTPHPARIGLNCQLAQVAERVNWLGLGPQENYPDRLTAACFDRWDLPLSDMYTPYVFPSENGLRCGTRELNYGPHQWRGDFQFNISRYSQQQLMETSHRHLLHAEEGTWLNIDGFHMGIGGDDSWSPSVSAEFQLSAGRYHYQLVWCQK_'"
]
}
],
"prompt_number": 53
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `partition` function can also be used for doing statistics on sequence windows, for example, in calculating a moving average."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color=red>Exercises</font>\n",
"----"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**1**. Rewrite the following nested loop as a list comprehension\n",
"\n",
"```python\n",
"ans = []\n",
"for i in range(3):\n",
" for j in range(4):\n",
" ans.append((i, j))\n",
"print ans\n",
"```"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"ans = []\n",
"for i in range(3):\n",
" for j in range(4):\n",
" ans.append((i, j))\n",
"print ans"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]\n"
]
}
],
"prompt_number": 65
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# YOUR CODE HERE\n",
"\n",
"ans = [(i,j) for i in range(3) for j in range(4)]\n",
"print ans"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]\n"
]
}
],
"prompt_number": 63
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**2**. Rewrite the following as a list comprehension\n",
"\n",
"```python\n",
"ans = map(lambda x: x*x, filter(lambda x: x%2 == 0, range(5)))\n",
"print ans\n",
"```"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"ans = map(lambda x: x*x, filter(lambda x: x%2 == 0, range(5)))\n",
"print ans"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[0, 4, 16]\n"
]
}
],
"prompt_number": 67
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# YOUR CODE HERE\n",
"\n",
"ans = [x*x for x in range(5) if x%2 == 0]\n",
"print ans"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[0, 4, 16]\n"
]
}
],
"prompt_number": 64
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**3**. Convert the function below into a pure function with no global variables or side effects\n",
"\n",
"```python\n",
"x = 5\n",
"def f(alist):\n",
" for i in range(x):\n",
" alist.append(i)\n",
" return alist\n",
"\n",
"alist = [1,2,3]\n",
"ans = f(alist)\n",
"print ans\n",
"print alist # alist has been changed!\n",
"```"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"x = 5\n",
"def f(alist):\n",
" for i in range(x):\n",
" alist.append(i)\n",
" return alist\n",
"\n",
"alist = [1,2,3]\n",
"ans = f(alist)\n",
"print ans\n",
"print alist # alist has been changed!"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[1, 2, 3, 0, 1, 2, 3, 4]\n",
"[1, 2, 3, 0, 1, 2, 3, 4]\n"
]
}
],
"prompt_number": 68
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# YOUR CODE HERE\n",
"\n",
"def f(alist, x=5):\n",
" \"\"\"Append range(x) to alist.\"\"\"\n",
" return alist + range(x)\n",
"\n",
"alist = [1,2,3]\n",
"ans = f(alist)\n",
"print ans\n",
"print alist "
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[1, 2, 3, 0, 1, 2, 3, 4]\n",
"[1, 2, 3]\n"
]
}
],
"prompt_number": 72
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**4.** Write a decorator `hello` that makes every wrapped function print \"Hello!\" \n",
"\n",
"For example\n",
"\n",
"```python\n",
"@hello\n",
"def square(x):\n",
" return x*x\n",
"```\n",
"\n",
"when called will give the following result\n",
"```python\n",
"[In]\n",
"square(2)\n",
"[Out]\n",
"Hello!\n",
"4\n",
"```"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# YOUR CODE HERE\n",
"\n",
"def hello(f):\n",
" \"\"\"Decorator that prints Hello!\"\"\"\n",
" print 'Hello!'\n",
" def func(*args, **kwargs):\n",
" return f(*args, **kwargs)\n",
" return func\n",
"\n",
"@hello\n",
"def square(x):\n",
" return x*x\n",
"\n",
"print square(2)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Hello!\n",
"4\n"
]
}
],
"prompt_number": 75
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**5**. Rewrite the factorial function so that it does not use recursion.\n",
"\n",
"```python\n",
"def fact(n):\n",
" \"\"\"Returns the factorial of n.\"\"\"\n",
" # base case\n",
" if n==0:\n",
" return 1\n",
" # recursive case\n",
" else:\n",
" return n * fact(n-1)\n",
"```"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def fact(n):\n",
" \"\"\"Returns the factorial of n.\"\"\"\n",
" # base case\n",
" if n==0:\n",
" return 1\n",
" # recursive case\n",
" else:\n",
" return n * fact(n-1)\n",
"\n",
"for i in range(1,11):\n",
" print fact1(i),"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"1 2 6 24 120 720 5040 40320 362880 3628800\n"
]
}
],
"prompt_number": 87
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# YOUR CODE HERE\n",
"\n",
"def fact1(n):\n",
" \"\"\"Returns the factorial of n.\"\"\"\n",
" return reduce(lambda x, y: x*y, range(1, n+1))\n",
"\n",
"for i in range(1,11):\n",
" print fact1(i),"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"1 2 6 24 120 720 5040 40320 362880 3628800\n"
]
}
],
"prompt_number": 85
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise 6**. Rewrite the same factorail funciotn so that it uses a cache to speed up calculations"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# YOUR CODE HERE\n",
"\n",
"def fact2(n, cache={0: 1}):\n",
" \"\"\"Returns the factorial of n.\"\"\"\n",
" if n in cache:\n",
" return cache[n]\n",
" else:\n",
" cache[n] = n * fact2(n-1)\n",
" return cache[n]\n",
"\n",
"for i in range(1,11):\n",
" print fact2(i),"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"1 2 6 24 120 720 5040 40320 362880 3628800\n"
]
}
],
"prompt_number": 86
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%timeit -n3 fact(20)\n",
"%timeit -n3 fact1(20)\n",
"%timeit -n3 fact2(20)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"3 loops, best of 3: 6.6 \u00b5s per loop\n",
"3 loops, best of 3: 6.99 \u00b5s per loop\n",
"3 loops, best of 3: 318 ns per loop\n"
]
}
],
"prompt_number": 89
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**7**. Rewrite the following anonymous functiona as a regular named fucntion.\n",
"\n",
"```python\n",
"lambda x, y: x**2 + y**2\n",
"```"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# YOUR CODE HERE\n",
"\n",
"def f(x, y):\n",
" return x**2 + y**2"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 92
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**8**. Find an efficient way to extrac a subset of `dict1` into a a new dictionary `dict2` that only contains entrires with the keys given in the set `good_keys`. Note that good_keys may include keys not found in dict1 - these must be excluded when building dict2."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import numpy as np\n",
"import cPickle\n",
"\n",
"try:\n",
" dict1 = cPickle.load(open('dict1.pic'))\n",
"except:\n",
" numbers = np.arange(1e6).astype('int') # 1 million entries\n",
" dict1 = dict(zip(numbers, numbers))\n",
" cPickle.dump(dict1, open('dict1.pic', 'w'), protocol=2)\n",
"\n",
"good_keys = set(np.random.randint(1, 1e7, 1000))"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 95
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# YOUR CODE HERE\u00df\n",
"\n",
"# dictionary comprehension\n",
"dict2 = {key: dict1[key] for key in good_keys if key in dict1}\n",
"dict2"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 97,
"text": [
"{3798: 3798,\n",
" 38065: 38065,\n",
" 60534: 60534,\n",
" 62860: 62860,\n",
" 65901: 65901,\n",
" 69807: 69807,\n",
" 88291: 88291,\n",
" 93037: 93037,\n",
" 121629: 121629,\n",
" 141402: 141402,\n",
" 145747: 145747,\n",
" 148527: 148527,\n",
" 150344: 150344,\n",
" 152908: 152908,\n",
" 153980: 153980,\n",
" 159115: 159115,\n",
" 159816: 159816,\n",
" 166245: 166245,\n",
" 166775: 166775,\n",
" 204056: 204056,\n",
" 215282: 215282,\n",
" 217453: 217453,\n",
" 220327: 220327,\n",
" 234622: 234622,\n",
" 238067: 238067,\n",
" 240478: 240478,\n",
" 246595: 246595,\n",
" 257871: 257871,\n",
" 283049: 283049,\n",
" 291229: 291229,\n",
" 298025: 298025,\n",
" 303411: 303411,\n",
" 308318: 308318,\n",
" 314338: 314338,\n",
" 315854: 315854,\n",
" 326904: 326904,\n",
" 342248: 342248,\n",
" 351085: 351085,\n",
" 351709: 351709,\n",
" 368128: 368128,\n",
" 373994: 373994,\n",
" 382529: 382529,\n",
" 383056: 383056,\n",
" 385263: 385263,\n",
" 397214: 397214,\n",
" 402105: 402105,\n",
" 407302: 407302,\n",
" 410937: 410937,\n",
" 415658: 415658,\n",
" 419413: 419413,\n",
" 425844: 425844,\n",
" 427857: 427857,\n",
" 444312: 444312,\n",
" 452078: 452078,\n",
" 459387: 459387,\n",
" 463491: 463491,\n",
" 465533: 465533,\n",
" 476420: 476420,\n",
" 494457: 494457,\n",
" 505772: 505772,\n",
" 513386: 513386,\n",
" 533868: 533868,\n",
" 542111: 542111,\n",
" 549781: 549781,\n",
" 552654: 552654,\n",
" 554927: 554927,\n",
" 578321: 578321,\n",
" 585696: 585696,\n",
" 595181: 595181,\n",
" 598361: 598361,\n",
" 606851: 606851,\n",
" 616495: 616495,\n",
" 623269: 623269,\n",
" 623740: 623740,\n",
" 632592: 632592,\n",
" 635041: 635041,\n",
" 637283: 637283,\n",
" 649087: 649087,\n",
" 658653: 658653,\n",
" 670079: 670079,\n",
" 679081: 679081,\n",
" 687831: 687831,\n",
" 688321: 688321,\n",
" 696673: 696673,\n",
" 717431: 717431,\n",
" 740355: 740355,\n",
" 745659: 745659,\n",
" 746251: 746251,\n",
" 752638: 752638,\n",
" 759721: 759721,\n",
" 791255: 791255,\n",
" 791732: 791732,\n",
" 808228: 808228,\n",
" 809121: 809121,\n",
" 834173: 834173,\n",
" 844773: 844773,\n",
" 850271: 850271,\n",
" 851370: 851370,\n",
" 855436: 855436,\n",
" 857481: 857481,\n",
" 864807: 864807,\n",
" 870028: 870028,\n",
" 885796: 885796,\n",
" 898787: 898787,\n",
" 904119: 904119,\n",
" 906198: 906198,\n",
" 909435: 909435,\n",
" 942835: 942835,\n",
" 965580: 965580,\n",
" 974342: 974342,\n",
" 997183: 997183}"
]
}
],
"prompt_number": 97
},
{
"cell_type": "code",
"collapsed": false,
"input": [],
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}
}
]
} | {
"pile_set_name": "Github"
} |
#!/usr/bin/python
# vim:sw=4:ts=4:et:
# 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 script uses addr2line (part of binutils) to post-process the entries
# produced by NS_FormatCodeAddress(), which on Linux often lack a function
# name, a file name and a line number.
import subprocess
import sys
import re
import os
import pty
import termios
from StringIO import StringIO
class unbufferedLineConverter:
"""
Wrap a child process that responds to each line of input with one line of
output. Uses pty to trick the child into providing unbuffered output.
"""
def __init__(self, command, args = []):
pid, fd = pty.fork()
if pid == 0:
# We're the child. Transfer control to command.
os.execvp(command, [command] + args)
else:
# Disable echoing.
attr = termios.tcgetattr(fd)
attr[3] = attr[3] & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, attr)
# Set up a file()-like interface to the child process
self.r = os.fdopen(fd, "r", 1)
self.w = os.fdopen(os.dup(fd), "w", 1)
def convert(self, line):
self.w.write(line + "\n")
return (self.r.readline().rstrip("\r\n"), self.r.readline().rstrip("\r\n"))
@staticmethod
def test():
assert unbufferedLineConverter("rev").convert("123") == "321"
assert unbufferedLineConverter("cut", ["-c3"]).convert("abcde") == "c"
print "Pass"
objdump_section_re = re.compile("^ [0-9a-f]* ([0-9a-f ]{8}) ([0-9a-f ]{8}) ([0-9a-f ]{8}) ([0-9a-f ]{8}).*")
def elf_section(file, section):
"""
Return the requested ELF section of the file as a str, representing
a sequence of bytes.
"""
# We can read the .gnu_debuglink section using either of:
# objdump -s --section=.gnu_debuglink $file
# readelf -x .gnu_debuglink $file
# Since readelf prints things backwards on little-endian platforms
# for some versions only (backwards on Fedora Core 6, forwards on
# Fedora 7), use objdump.
objdump = subprocess.Popen(['objdump', '-s', '--section=' + section, file],
stdout=subprocess.PIPE,
# redirect stderr so errors don't get printed
stderr=subprocess.PIPE)
(objdump_stdout, objdump_stderr) = objdump.communicate()
if objdump.returncode != 0:
return None
result = ""
# Turn hexadecimal dump into the bytes it represents
for line in StringIO(objdump_stdout).readlines():
m = objdump_section_re.match(line)
if m:
for gnum in [0, 1, 2, 3]:
word = m.groups()[gnum]
if word != " ":
for idx in [0, 2, 4, 6]:
result += chr(int(word[idx:idx+2], 16))
return result
# FIXME: Hard-coded to gdb defaults (works on Fedora and Ubuntu).
global_debug_dir = '/usr/lib/debug';
endian_re = re.compile("\s*Data:\s+.*(little|big) endian.*$")
# Table of 256 values, per documentation of .gnu_debuglink sections.
gnu_debuglink_crc32_table = [
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
0x2d02ef8d
]
def gnu_debuglink_crc32(stream):
# Note that python treats bitwise operators as though integers have
# an infinite number of bits (and thus such that negative integers
# 1-pad out to infinity).
crc = 0xffffffff
while True:
# Choose to read in 4096 byte chunks.
bytes = stream.read(4096)
if len(bytes) == 0:
break
for byte in bytes:
crc = gnu_debuglink_crc32_table[(crc ^ ord(byte)) & 0xff] ^ (crc >> 8)
return ~crc & 0xffffffff
def separate_debug_file_for(file):
"""
Finds a separated file with the debug sections for a binary. Such
files are commonly installed by debug packages on linux distros.
Rules for finding them are documented in:
https://sourceware.org/gdb/current/onlinedocs/gdb/Separate-Debug-Files.html
"""
def have_debug_file(debugfile):
return os.path.isfile(debugfile)
endian = None
readelf = subprocess.Popen(['readelf', '-h', file],
stdout=subprocess.PIPE)
for line in readelf.stdout.readlines():
m = endian_re.match(line)
if m:
endian = m.groups()[0]
break
readelf.terminate()
if endian is None:
sys.stderr.write("Could not determine endianness of " + file + "\n")
return None
def word32(s):
if type(s) != str or len(s) != 4:
raise StandardError("expected 4 byte string input")
s = list(s)
if endian == "big":
s.reverse()
return sum(map(lambda idx: ord(s[idx]) * (256 ** idx), range(0, 4)))
buildid = elf_section(file, ".note.gnu.build-id");
if buildid is not None:
# The build ID is an ELF note section, so it begins with a
# name size (4), a description size (size of contents), a
# type (3), and the name "GNU\0".
note_header = buildid[0:16]
buildid = buildid[16:]
if word32(note_header[0:4]) != 4 or \
word32(note_header[4:8]) != len(buildid) or \
word32(note_header[8:12]) != 3 or \
note_header[12:16] != "GNU\0":
sys.stderr.write("malformed .note.gnu.build_id in " + file + "\n")
else:
buildid = "".join(map(lambda ch: "%02X" % ord(ch), buildid)).lower()
f = os.path.join(global_debug_dir, ".build-id", buildid[0:2], buildid[2:] + ".debug")
if have_debug_file(f):
return f
debuglink = elf_section(file, ".gnu_debuglink");
if debuglink is not None:
# The debuglink section contains a string, ending with a
# null-terminator and then 0 to three bytes of padding to fill the
# current 32-bit unit. (This padding is usually null bytes, but
# I've seen null-null-H, on Ubuntu x86_64.) This is followed by
# a 4-byte CRC.
debuglink_name = debuglink[:-4]
null_idx = debuglink_name.find("\0")
if null_idx == -1 or null_idx + 4 < len(debuglink_name):
sys.stderr.write("Malformed .gnu_debuglink in " + file + "\n")
return None
debuglink_name = debuglink_name[0:null_idx]
debuglink_crc = word32(debuglink[-4:])
dirname = os.path.dirname(file)
possible_files = [
os.path.join(dirname, debuglink_name),
os.path.join(dirname, ".debug", debuglink_name),
os.path.join(global_debug_dir, dirname.lstrip("/"), debuglink_name)
]
for f in possible_files:
if have_debug_file(f):
fio = open(f, mode="r")
file_crc = gnu_debuglink_crc32(fio)
fio.close()
if file_crc == debuglink_crc:
return f
return None
elf_type_re = re.compile("^\s*Type:\s+(\S+)")
elf_text_section_re = re.compile("^\s*\[\s*\d+\]\s+\.text\s+\w+\s+(\w+)\s+(\w+)\s+")
def address_adjustment_for(file):
"""
Return the address adjustment to use for a file.
addr2line wants offsets relative to the base address for shared
libraries, but it wants addresses including the base address offset
for executables. This returns the appropriate address adjustment to
add to an offset within file. See bug 230336.
"""
readelf = subprocess.Popen(['readelf', '-h', file],
stdout=subprocess.PIPE)
elftype = None
for line in readelf.stdout.readlines():
m = elf_type_re.match(line)
if m:
elftype = m.groups()[0]
break
readelf.terminate()
if elftype != "EXEC":
# If we're not dealing with an executable, return 0.
return 0
adjustment = 0
readelf = subprocess.Popen(['readelf', '-S', file],
stdout=subprocess.PIPE)
for line in readelf.stdout.readlines():
m = elf_text_section_re.match(line)
if m:
# Subtract the .text section's offset within the
# file from its base address.
adjustment = int(m.groups()[0], 16) - int(m.groups()[1], 16);
break
readelf.terminate()
return adjustment
addr2lines = {}
def addressToSymbol(file, address):
converter = None
address_adjustment = None
cache = None
if not file in addr2lines:
debug_file = separate_debug_file_for(file) or file
converter = unbufferedLineConverter('/usr/bin/addr2line', ['-C', '-f', '-e', debug_file])
address_adjustment = address_adjustment_for(file)
cache = {}
addr2lines[file] = (converter, address_adjustment, cache)
else:
(converter, address_adjustment, cache) = addr2lines[file]
if address in cache:
return cache[address]
result = converter.convert(hex(int(address, 16) + address_adjustment))
cache[address] = result
return result
# Matches lines produced by NS_FormatCodeAddress().
line_re = re.compile("^(.*#\d+: )(.+)\[(.+) \+(0x[0-9A-Fa-f]+)\](.*)$")
def fixSymbols(line):
result = line_re.match(line)
if result is not None:
(before, fn, file, address, after) = result.groups()
if os.path.exists(file) and os.path.isfile(file):
(name, fileline) = addressToSymbol(file, address)
# If addr2line gave us something useless, keep what we had before.
if name == "??":
name = fn
if fileline == "??:0" or fileline == "??:?":
fileline = file
nl = '\n' if line[-1] == '\n' else ''
return "%s%s (%s)%s%s" % (before, name, fileline, after, nl)
else:
sys.stderr.write("Warning: File \"" + file + "\" does not exist.\n")
return line
else:
return line
if __name__ == "__main__":
for line in sys.stdin:
sys.stdout.write(fixSymbols(line))
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>Description of medfilt1m</title>
<meta name="keywords" content="medfilt1m">
<meta name="description" content="One-dimensional adaptive median filtering with missing values.">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="generator" content="m2html © 2003 Guillaume Flandin">
<meta name="robots" content="index, follow">
<link type="text/css" rel="stylesheet" href="../m2html.css">
</head>
<body>
<a name="_top"></a>
<!-- menu.html filters -->
<h1>medfilt1m
</h1>
<h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2>
<div class="box"><strong>One-dimensional adaptive median filtering with missing values.</strong></div>
<h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2>
<div class="box"><strong>function y = medfilt1m( x, r, z ) </strong></div>
<h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2>
<div class="fragment"><pre class="comment"> One-dimensional adaptive median filtering with missing values.
Applies a width s=2*r+1 one-dimensional median filter to vector x, which
may contain missing values (elements equal to z). If x contains no
missing values, y(j) is set to the median of x(j-r:j+r). If x contains
missing values, y(j) is set to the median of x(j-R:j+R), where R is the
smallest radius such that sum(valid(x(j-R:j+R)))>=s, i.e. the number of
valid values in the window is at least s (a value x is valid x~=z). Note
that the radius R is adaptive and can vary as a function of j.
This function uses a modified version of medfilt1.m from Matlab's 'Signal
Processing Toolbox'. Note that if x contains no missing values,
medfilt1m(x) and medfilt1(x) are identical execpt at boundary regions.
USAGE
y = medfilt1m( x, r, [z] )
INPUTS
x - [nx1] length n vector with possible missing entries
r - filter radius
z - [NaN] element that represents missing entries
OUTPUTS
y - [nx1] filtered vector x
EXAMPLE
x=repmat((1:4)',1,5)'; x=x(:)'; x0=x;
n=length(x); x(rand(n,1)>.8)=NaN;
y = medfilt1m(x,2); [x0; x; y; x0-y]
See also <a href="modefilt1.html" class="code" title="function y = modefilt1( x, s )">MODEFILT1</a>, MEDFILT1
Piotr's Computer Vision Matlab Toolbox Version 2.35
Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
Licensed under the Simplified BSD License [see external/bsd.txt]</pre></div>
<!-- Start of Google Analytics Code -->
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-4884268-1");
pageTracker._initData();
pageTracker._trackPageview();
</script>
<!-- end of Google Analytics Code -->
<hr><address>Generated by <strong><a href="http://www.artefact.tk/software/matlab/m2html/" target="_parent">m2html</a></strong> © 2003</address>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*
Fingerprint NG (client version) icons module for Miranda NG
Copyright © 2006-20 ghazan, mataes, HierOS, FYR, Bio, nullbie, faith_healer and all respective contributors.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "stdafx.h"
#include <m_version.h>
/************************************************************************/
/* This file contains data about appropriate MirVer values */
/************************************************************************/
/*
* NOTE: Masks can contain '*' or '?' wild symbols
* Asterics '*' symbol covers 'empty' symbol too e.g WildCompare("Tst","T*st*"), returns TRUE
* In order to handle situation 'at least one any sybol' use '?*' combination:
* e.g WildCompare("Tst","T?*st*"), returns FALSE, but both WildCompare("Test","T?*st*") and
* WildCompare("Teeest","T?*st*") return TRUE.
*
* Function is 'dirt' case insensitive (it is ignore 5th bit (0x20) so it is no difference
* beetween some symbols. But it is faster than valid converting to uppercase.
*
* Mask can contain several submasks. In this case each submask (including first)
* should start from '|' e.g: "|first*submask|second*mask".
*
* ORDER OF RECORDS IS IMPORTANT: system search first suitable mask and returns it.
* e.g. if MirVer is "Miranda IM" and first mask is "*im*" and second is "Miranda *" the
* result will be client associated with first mask, not second!
* So in order to avoid such situation, place most generalised masks to latest place.
*
* In order to get "Unknown" client, last mask should be "?*".
*/
KN_FP_MASK def_kn_fp_mask[] =
{// {"Client_IconName", L"|^*Mask*|*names*", L"Icon caption", IDI_RESOURCE_ID, CLIENT_CASE, OVERLAY? },
//#########################################################################################################################################################################
//################################# MIRANDA ###########################################################################################################################
//#########################################################################################################################################################################
{ "client_Miranda_NG", L"|*nightly.miranda.im*" L"|*Miranda*NG*" _A2W(MIRANDA_VERSION_CORE_STRING) L"*", L"Miranda NG", IDI_MIRANDA_NG, MIRANDA_CASE },
{ "client_Miranda_NG_stbl", L"|Miranda*NG*", LPGENW("Miranda NG stable"), IDI_MIRANDA_NG_STABLE, MIRANDA_CASE },
{ "client_Miranda_010xx", L"Miranda*IM*0.10.*", L"Miranda IM v0.10.x.x", IDI_MIRANDA_010X, MIRANDA_CASE },
{ "client_Miranda_09XX", L"|*Miranda*IM*0.9*"
L"|*miranda-im.org/caps#*0.9*", L"Miranda IM v0.9.x.x", IDI_MIRANDA_09XX, MIRANDA_CASE },
{ "client_Miranda_08XX", L"|^Miranda*0.7*Jabb*"
L"|*Miranda*0.8*"
L"|*miranda-im.org/caps#*0.8*", L"Miranda IM v0.8.x.x", IDI_MIRANDA_08XX, MIRANDA_CASE },
{ "client_Miranda_07XX", L"|*Miranda*0.7*"
L"|*miranda-im.org/caps#*0.7*", L"Miranda IM v0.7.x.x", IDI_MIRANDA_07XX, MIRANDA_CASE },
{ "client_Miranda_06XX", L"*Miranda*0.6*", L"Miranda IM v0.6.x.x", IDI_MIRANDA_06XX, MIRANDA_CASE },
{ "client_Miranda_05XX", L"*Miranda*0.5*", L"Miranda IM v0.5.x.x", IDI_MIRANDA_05XX, MIRANDA_CASE },
{ "client_Miranda_04XX", L"*Miranda*0.4*", L"Miranda IM v0.4.x.x", IDI_MIRANDA_04XX, MIRANDA_CASE },
{ "client_Miranda_old", L"*Miranda*0.?*", LPGENW("Miranda IM (old versions)"), IDI_MIRANDA_OLD, MIRANDA_CASE },
{ "client_Miranda_unknown", L"*Miranda*", LPGENW("Miranda (unknown)"), IDI_MIRANDA_UNKNOWN, MIRANDA_CASE },
//#########################################################################################################################################################################
//################################# MULTI-PROTOCOL ####################################################################################################################
//#########################################################################################################################################################################
{ "client_1&1", L"|*Pocket*Web*|*1&1*|*1*?nd*1", L"1&1", IDI_1UND1, MULTI_CASE, TRUE },
{ "client_Asia", L"*Asia*", L"Asia", IDI_ASIA, MULTI_CASE, TRUE },
{ "client_Adium", L"|*Adium*"
L"|*VUFD6HcFmUT2NxJkBGCiKlZnS3M=*" // Gabble client?
L"|*DdnydQG7RGhP9E3k9Sf+b+bF0zo=*", L"Adium", IDI_ADIUM, MULTI_CASE, TRUE },
{ "client_AgileMessenger", L"*Agile Messenger*", L"Agile Messenger", IDI_AGILE, MULTI_CASE, TRUE },
{ "client_Appolo", L"*Appolo*", L"Appolo IM", IDI_APPOLO, MULTI_CASE, TRUE },
{ "client_Ayttm", L"*Ayttm*", L"Ayttm", IDI_AYTTM, MULTI_CASE, TRUE },
{ "client_BayanICQ", L"|*Bayan*ICQ*|*barobin*", L"BayanICQ", IDI_BAYANICQ, MULTI_CASE, TRUE },
{ "client_Beejive", L"*Beejive*", L"BeejiveIM", IDI_BEEJIVE, MULTI_CASE, TRUE },
{ "client_Bimoid", L"*Bimoid*", L"Bimoid", IDI_BIMOID, MULTI_CASE, TRUE },
{ "client_BitlBee", L"*BitlBee*", L"BitlBee", IDI_BITLBEE, MULTI_CASE, TRUE },
{ "client_BlackBerry", L"|*Berry*|*ICS?\?\?\?\?\?\?\?", L"BlackBerry", IDI_BLACKBERRY, MULTI_CASE, TRUE },
{ "client_Buddycloud", L"*Buddycloud*", L"Buddycloud", IDI_BUDDYCLOUD, MULTI_CASE, TRUE },
{ "client_Carrier", L"*Carrier*", L"Carrier client", IDI_CARRIER, MULTI_CASE, TRUE },
{ "client_Causerie", L"*Causerie*", L"Causerie", IDI_CAUSERIE, MULTI_CASE, TRUE },
{ "client_CenterIM", L"*CenterIM*", L"CenterIM", IDI_CENTERIM, MULTI_CASE, TRUE },
{ "client_ChatSecure", L"*ChatSecure*", L"ChatSecure", IDI_CHATSECURE, MULTI_CASE, TRUE },
{ "client_Citron", L"*Citron*", L"Citron", IDI_CITRON, MULTI_CASE, TRUE },
{ "client_climm", L"*climm*", L"climm", IDI_CLIMM, MULTI_CASE, TRUE },
{ "client_Digsby", L"*Digsby*", L"Digsby", IDI_DIGSBY, MULTI_CASE, TRUE },
{ "client_EKG2", L"*EKG*2*", L"EKG2", IDI_EKG2, MULTI_CASE, TRUE },
{ "client_EasyMessage", L"Easy*Message*", L"Easy Message", IDI_EASYMESSAGE, MULTI_CASE, TRUE },
{ "client_Empathy", L"*Empathy*", L"Empathy", IDI_EMPATHY, MULTI_CASE, TRUE },
{ "client_Eyeball", L"*Eyeball*", L"Eyeball Chat", IDI_EYEBALL_CHAT, MULTI_CASE, TRUE },
{ "client_eBuddy", L"|*eBuddy*|*eMessenger*", L"eBuddy Messenger", IDI_EBUDDY, MULTI_CASE, TRUE },
{ "client_eM_Client", L"*eM*Client*", L"eM Client", IDI_EM_CLIENT, MULTI_CASE, TRUE },
{ "client_eQo", L"*eQo*", L"eQo", IDI_EQO, MULTI_CASE, TRUE },
{ "client_emesene", L"*emesene*", L"emesene", IDI_EMESENE, MULTI_CASE, TRUE },
{ "client_Fama", L"*Fama*", L"Fama IM", IDI_FAMAIM, MULTI_CASE, TRUE },
{ "client_Fring", L"*fring*", L"Fring", IDI_FRING, MULTI_CASE, TRUE },
{ "client_GMX", L"*GMX*", L"GMX MultiMessenger", IDI_GMX, MULTI_CASE, TRUE },
{ "client_Gaim", L"*gaim*", L"Gaim (libgaim)", IDI_GAIM, MULTI_CASE, TRUE },
{ "client_Galaxium", L"*Galaxium*", L"Galaxium", IDI_GALAXIUM, MULTI_CASE, TRUE },
{ "client_GnuGadu", L"Gnu Gadu*", L"GNU Gadu", IDI_GNUGADU, MULTI_CASE, TRUE },
{ "client_IM2", L"*IM2*", L"IM2", IDI_IM2, MULTI_CASE, TRUE },
{ "client_IMPlus", L"|IM+*|IMPLUS*|*IM plus*|@mobile"
L"|*+umBU9yx9Cu+R8jvPWIZ3vWD59M=*", L"IM+", IDI_IMPLUS, MULTI_CASE, TRUE },
{ "client_IMVU", L"*IMVU*", L"IMVU", IDI_IMVU, MULTI_CASE, TRUE },
{ "client_IMadering", L"*IMadering*", L"IMadering", IDI_IMADERING, MULTI_CASE, TRUE },
{ "client_imoIM", L"|*imo.im*|*sleekxmpp.com*", L"imo.im", IDI_IMOIM, MULTI_CASE, TRUE },
{ "client_Inlux", L"*Inlux*", L"Inlux Messenger", IDI_INLUX, MULTI_CASE, TRUE },
{ "client_Instantbird", L"*Instantbird*", L"Instantbird", IDI_INSTANTBIRD, MULTI_CASE, TRUE },
{ "client_iCall", L"*iCall*", L"iCall", IDI_ICALL, MULTI_CASE, TRUE },
{ "client_iChat", L"|*iChat*|**imagent*|*iMessages*", L"iChat", IDI_ICHAT, MULTI_CASE, TRUE },
{ "client_irssi", L"*irssi*", L"irssi", IDI_IRSSI, MULTI_CASE, TRUE },
{ "client_JBother", L"*JBother*", L"JBother", IDI_JBOTHER, MULTI_CASE, TRUE },
{ "client_JBuddy", L"*JBuddy*", L"JBuddy Messenger", IDI_JBUDDY, MULTI_CASE, TRUE },
{ "client_Jabbear", L"*Jabbear*", L"Jabbear", IDI_JABBEAR, MULTI_CASE, TRUE },
{ "client_Jabbin", L"*Jabbin*", L"Jabbin", IDI_JABBIN, MULTI_CASE, TRUE },
{ "client_Jasmine_IM", L"|Jasmine*IM*|*jasmineicq.ru/caps*", L"Jasmine IM", IDI_JASMINEIM, MULTI_CASE, TRUE },
{ "client_Jimm_Aspro", L"*Jimm*Aspro*", L"Jimm Aspro", IDI_JIMM_ASPRO, MULTI_CASE, TRUE },
{ "client_Jimmy", L"*Jimmy*", L"JimmyIM", IDI_JIMMY, MULTI_CASE, TRUE },
{ "client_KMess", L"*KMess*", L"KMess", IDI_KMESS, MULTI_CASE, TRUE },
{ "client_KoolIM", L"*Kool*", L"KoolIM", IDI_KOOLIM, MULTI_CASE, TRUE },
{ "client_Kopete", L"*Kopete*", L"Kopete", IDI_KOPETE, MULTI_CASE, TRUE },
{ "client_LeechCraft", L"|*LeechCraft*"
L"|*aNjQWbtza2QtXemMfBS2bwNOtcQ=*", L"LeechCraft", IDI_LEECHCRAFT, MULTI_CASE, TRUE },
{ "client_MDC", L"*MDC*", L"MDC", IDI_MDC, MULTI_CASE, TRUE },
{ "client_Meebo", L"Meebo*", L"Meebo", IDI_MEEBO, MULTI_CASE, TRUE },
{ "client_Meetro", L"Meetro*", L"Meetro", IDI_MEETRO, MULTI_CASE, TRUE },
{ "client_mChat", L"|mChat*|gsICQ*|*mchat.mgslab.com*", L"mChat", IDI_MCHAT, MULTI_CASE, TRUE },
{ "client_Nimbuzz", L"*Nimbuzz*", L"Nimbuzz", IDI_NIMBUZZ, MULTI_CASE, TRUE },
{ "client_Palringo", L"*Palringo*", L"Palringo", IDI_PALRINGO, MULTI_CASE, TRUE },
{ "client_Pigeon", L"*PIGEON*", L"PIGEON!", IDI_PIGEON, MULTI_CASE, TRUE },
{ "client_PlayXpert", L"*PlayXpert*", L"PlayXpert", IDI_PLAYXPERT, MULTI_CASE, TRUE },
{ "client_Prelude", L"*Prelude*", L"Prelude", IDI_PRELUDE, MULTI_CASE, TRUE },
{ "client_Proteus", L"*Proteus*", L"Proteus", IDI_PROTEUS, MULTI_CASE, TRUE },
{ "client_QIP_Android", L"QIP *Android*", L"QIP Mobile Android", IDI_QIP_ANDROID, MULTI_CASE, TRUE },
{ "client_QIP_iOS", L"|QIP*iOS*|QIP*iphone*|QIP*apple*", L"QIP Mobile iOS", IDI_QIP_IOS, MULTI_CASE, TRUE },
{ "client_QIP_Symbian", L"*QIP*Symbian*", L"QIP Mobile Symbian", IDI_QIP_SYMBIAN, MULTI_CASE, TRUE },
{ "client_QIP_Java", L"*QIP*Java*", L"QIP Mobile Java", IDI_QIP_JAVA, MULTI_CASE, TRUE },
{ "client_QIP_PDA", L"|QIP *PDA*|*pda.qip.ru*|*QIP Mobile*", L"QIP Mobile", IDI_QIP_PDA, MULTI_CASE, TRUE },
{ "client_QIP_2012", L"QIP 2012*", L"QIP 2012", IDI_QIP_2012, MULTI_CASE, TRUE },
{ "client_QIP_2010", L"QIP 2010*", L"QIP 2010", IDI_QIP_2010, MULTI_CASE, TRUE },
{ "client_QIP_Infium", L"|QIP Infium*|http://*qip*", L"QIP Infium", IDI_QIP_INFIUM, MULTI_CASE, TRUE },
{ "client_qutIM", L"*qutIM*", L"qutIM", IDI_QUTIM, MULTI_CASE },
{ "client_mqutIM", L"*mqutIM*", L"mqutIM", IDI_MQUTIM, MULTI_CASE },
{ "client_Qnext", L"Qnext*", L"Qnext", IDI_QNEXT, MULTI_CASE, TRUE },
{ "client_SAPO", L"*SAPO*", L"SAPO Messenger", IDI_SAPO, MULTI_CASE, TRUE },
{ "client_SIM", L"|^*Simp*|*SIM*", L"SIM", IDI_SIM, MULTI_CASE, TRUE },
{ "client_Salut_a_Toi", L"*Salut*Toi*", L"Salut a Toi", IDI_SALUT_A_TOI, MULTI_CASE, TRUE },
{ "client_Shaim", L"*Shaim*", L"Shaim", IDI_SHAIM, MULTI_CASE, TRUE },
{ "client_SieJC", L"|SieJC*|Nat*ICQ*|Siemens*Client*", L"Siemens ICQ / Jabber client", IDI_SIEJC, MULTI_CASE, TRUE },
{ "client_Slick", L"Slick*", L"Slick", IDI_SLICK, MULTI_CASE, TRUE },
{ "client_SrevIM", L"*Srev*IM*", L"SrevIM", IDI_SREVIM, MULTI_CASE, TRUE },
{ "client_Tril_Android", L"*Trillian*Android*", L"Trillian Android", IDI_TRILLIAN_ANDROID, MULTI_CASE, TRUE },
{ "client_Tril_Astra", L"Trillian*Astra*", L"Trillian Astra", IDI_TRILLIAN_ASTRA, MULTI_CASE, TRUE },
{ "client_Trillian_Pro", L"Trillian*Pro*", L"Trillian Pro", IDI_TRILLIAN_PRO, MULTI_CASE, TRUE },
{ "client_Trillian", L"*Trillian**", L"Trillian", IDI_TRILLIAN, MULTI_CASE, TRUE },
{ "client_Tuukle_Chat", L"*Tuukle*Chat*|*IM*Gate*", L"Tuukle Chat", IDI_TUUKLE_CHAT, MULTI_CASE, TRUE },
{ "client_vBuzzer", L"*vBuzzer*", L"vBuzzer", IDI_VBUZZER, MULTI_CASE, TRUE },
{ "client_Virtus", L"*Virtus*", L"Virtus", IDI_VIRTUS, MULTI_CASE, TRUE },
{ "client_uIM", L"*uIM*", L"uIM", IDI_UIM, MULTI_CASE, TRUE },
{ "client_uTalk", L"*uTalk*", L"uTalk", IDI_UTALK, MULTI_CASE, TRUE },
{ "client_WeeChat", L"*WeeChat*", L"WeeChat", IDI_WEECHAT, MULTI_CASE, TRUE },
{ "client_Wippien", L"*Wippien*", L"Wippien", IDI_WIPPIEN, MULTI_CASE, TRUE },
{ "client_WindowsPhone", L"*Windows*Phone*", L"Windows Phone", IDI_WINDOWS_PHONE, MULTI_CASE, TRUE },
{ "client_YamiGo", L"YamiGo*", L"YamiGo", IDI_YAMIGO, MULTI_CASE, TRUE },
{ "client_Yeigo", L"*Yeigo*", L"Yeigo", IDI_YEIGO, MULTI_CASE, TRUE },
{ "client_Yoono", L"*Yoono*", L"Yoono", IDI_YOONO, MULTI_CASE, TRUE },
//#########################################################################################################################################################################
//################################# ICQ ###############################################################################################################################
//#########################################################################################################################################################################
{ "client_Mandarin_IM", L"Mandarin IM*", L"Mandarin IM", IDI_MANDARIN_IM, ICQ_CASE, TRUE },
{ "client_R&Q", L"|R&Q*|&RQ*", L"R&Q", IDI_RANDQ, ICQ_CASE, TRUE },
{ "client_ICQ_all", L"|ICQ?|ICQ?.?|ICQ *|ICQ2*|ICQ", L"ICQ client", IDI_ICQ, ICQ_CASE },
//#########################################################################################################################################################################
//################################# JABBER ############################################################################################################################
//#########################################################################################################################################################################
{ "client_Akeni", L"*Akeni*", L"Akeni", IDI_AKENI, JABBER_CASE, TRUE },
{ "client_Ambrosia", L"*Ambrosia*", L"Ambrosia XMPP Server", IDI_AMBROSIA, JABBER_CASE, TRUE },
{ "client_AnothRSSBot", L"|*Anothrbot*|*Anothr Rss Bot*", L"Anothr Rss Bot", IDI_ANOTHRSSBOT, JABBER_CASE, TRUE },
{ "client_Aqq", L"|*aqq.eu*|aqq*", L"Aqq", IDI_AQQ, JABBER_CASE, TRUE },
{ "client_BarnOwl", L"*Barn*Owl*", L"BarnOwl", IDI_BARNOWL, JABBER_CASE, TRUE },
{ "client_Beem", L"*Beem*", L"Beem", IDI_BEEM, JABBER_CASE, TRUE },
{ "client_BellSouth", L"*BellSouth*", L"BellSouth", IDI_BELLSOUTH, JABBER_CASE, TRUE },
{ "client_BitWise", L"*BitWise*", L"BitWise", IDI_BITWISE, JABBER_CASE, TRUE },
{ "client_Bombus", L"*Bombus*", L"Bombus", IDI_BOMBUS, JABBER_CASE, TRUE },
{ "client_BombusMod", L"|*Bombus*mod*|*bombusmod*", L"BombusMod", IDI_BOMBUS_MOD, JABBER_CASE, TRUE },
{ "client_BombusNG", L"*Bombus*NG*", L"Bombus NG", IDI_BOMBUS_NG, JABBER_CASE, TRUE },
{ "client_BombusQD", L"|*Bombusmod-qd*|*bombus*qd*", L"Bombus QD", IDI_BOMBUS_QD, JABBER_CASE, TRUE },
{ "client_Bowline", L"*Bow*line*", L"Bowline", IDI_BOWLINE, JABBER_CASE, TRUE },
{ "client_BuddySpace", L"Buddy*Space*", L"BuddySpace", IDI_BUDDYSPACE, JABBER_CASE, TRUE },
{ "client_CJC", L"*CJC*", L"CJC", IDI_CJC, JABBER_CASE, TRUE },
{ "client_CRoom", L"*CRoom*", L"CRoom", IDI_CROOM, JABBER_CASE, TRUE },
{ "client_Candy", L"*Candy*", L"Candy", IDI_CANDY, JABBER_CASE, TRUE },
{ "client_Chatopus", L"*Chatopus*", L"Chatopus", IDI_CHATOPUS, JABBER_CASE, TRUE },
{ "client_Chikka", L"*Chikka*", L"Chikka", IDI_CHIKKA, JABBER_CASE, TRUE },
{ "client_ChitChat", L"*Chit*Chat*", L"ChitChat", IDI_CHITCHAT, JABBER_CASE, TRUE },
{ "client_Claros_Chat", L"*Claros*", L"Claros Chat", IDI_CLAROS_CHAT, JABBER_CASE, TRUE },
{ "client_Coccinella", L"*Coccinella*", L"Coccinella", IDI_COCCINELLA, JABBER_CASE, TRUE },
{ "client_Colibry", L"Colibry*", L"Colibry", IDI_COLIBRY, JABBER_CASE, TRUE },
{ "client_Colloquy", L"Colloquy*", L"Colloquy", IDI_COLLOQUY, JABBER_CASE, TRUE },
{ "client_CommuniGate", L"*CommuniGate*", L"CommuniGate Pro", IDI_COMMUNIGATE, JABBER_CASE, TRUE },
{ "client_Conference", L"Conference*", L"Conference Bot (GMail)", IDI_CONFERENCE, JABBER_CASE, TRUE },
{ "client_Conversations", L"|*http://conversations.im*|Conversations IM*", L"Conversations", IDI_CONVERSATIONS, JABBER_CASE, TRUE },
{ "client_Crosstalk", L"*Cross*talk*", L"Crosstalk", IDI_CROSSTALK, JABBER_CASE, TRUE },
{ "client_Cudumar", L"*Cudumar*", L"Cudumar", IDI_CUDUMAR, JABBER_CASE, TRUE },
{ "client_CyclopsChat", L"*Cyclops*", L"Cyclops Chat", IDI_CYCLOPS_CHAT, JABBER_CASE, TRUE },
{ "client_Desyr", L"*Desyr*", L"Desyr Messenger", IDI_DESYR, JABBER_CASE, TRUE },
{ "client_EMess", L"*EMess*", L"EMess", IDI_EMESS, JABBER_CASE, TRUE },
{ "client_Elmer_Bot", L"*Elmer*", L"Elmer Bot", IDI_ELMER, JABBER_CASE, TRUE },
{ "client_Emacs", L"|*Jabber.el*|*Emacs*", L"Emacs (Jabber.el)", IDI_EMACS, JABBER_CASE, TRUE },
{ "client_Exodus", L"*Exodus*", L"Exodus", IDI_EXODUS, JABBER_CASE, TRUE },
{ "client_GCN", L"*GCN*", L"GCN", IDI_GCN, JABBER_CASE, TRUE },
{ "client_GMail", L"|*gmail.*|GMail*", L"GoogleMail", IDI_GMAIL, JABBER_CASE, TRUE },
{ "client_GOIM", L"*GOIM*", L"GOIM", IDI_GOIM, JABBER_CASE, TRUE },
{ "client_GTalk", L"|*Talk.v*|*Google*Talk*" L"|*Gtalk*", L"GoogleTalk", IDI_GTALK, JABBER_CASE, TRUE },
{ "client_GTalk_Gadget", L"|^messaging-*|*Talk*Gadget*", L"GTalk Gadget", IDI_GTALK_GADGET, JABBER_CASE, TRUE },
{ "client_Gabber", L"*Gabber*", L"Gabber", IDI_GABBER, JABBER_CASE, TRUE },
{ "client_Gajim", L"*Gajim*", L"Gajim", IDI_GAJIM, JABBER_CASE, TRUE },
{ "client_Gibberbot", L"*Gibber*", L"Gibberbot", IDI_GIBBERBOT, JABBER_CASE, TRUE },
{ "client_Glu", L"|glu*|*glu.net*", L"Glu", IDI_GLU, JABBER_CASE, TRUE },
{ "client_Gnome", L"*Gnome*", L"Gnome", IDI_GNOME, JABBER_CASE, TRUE },
{ "client_GoTalkMobile", L"*Go*Talk*Mobile*", L"GoTalkMobile", IDI_GOTALKMOBILE, JABBER_CASE, TRUE },
{ "client_Gossip", L"*Gossip*", L"Gossip", IDI_GOSSIP, JABBER_CASE, TRUE },
{ "client_GreenThumb", L"gReeNtHumB*", L"GreenThumb", IDI_GREENTHUMB, JABBER_CASE, TRUE },
{ "client_Gush", L"*Gush*", L"Gush", IDI_GUSH, JABBER_CASE, TRUE },
{ "client_IMCom", L"*IMCom*", L"IMCom", IDI_IMCOM, JABBER_CASE, TRUE },
{ "client_IM_Friendly", L"*IM*Friendly*", L"IM Friendly!", IDI_IM_FRIENDLY, JABBER_CASE, TRUE },
{ "client_Imified", L"*someresource*", L"Imified", IDI_IMIFIED, JABBER_CASE, TRUE },
{ "client_Importal", L"*Importal*", L"Importal", IDI_IMPORTAL, JABBER_CASE, TRUE },
{ "client_InstanT", L"*Instan-t*", L"Instan-t", IDI_INSTANT, JABBER_CASE, TRUE },
{ "client_Interaction", L"*Interaction*", L"Interaction", IDI_INTERACTION, JABBER_CASE, TRUE },
{ "client_iruka", L"*Iruka*", L"Iruka", IDI_IRUKA, JABBER_CASE, TRUE },
{ "client_J2J_Transport", L"*J2J*Transport*", L"J2J Transport", IDI_J2J_TRANSPORT, JABBER_CASE, TRUE },
{ "client_Jamm", L"*Jamm*", L"Jamm", IDI_JAMM, JABBER_CASE, TRUE },
{ "client_JClaim", L"*JClaim*", L"JClaim", IDI_JCLAIM, JABBER_CASE, TRUE },
{ "client_JMC", L"JMC*", L"JMC (Jabber Mix Client)", IDI_JMC, JABBER_CASE, TRUE },
{ "client_JWChat", L"*JWChat*", L"JWChat", IDI_JWCHAT, JABBER_CASE, TRUE },
{ "client_JWGC", L"|*JWGC*|Jabber *Gram*", L"Jabber WindowGram Client", IDI_JWGC, JABBER_CASE, TRUE },
{ "client_Jabba", L"*Jabba*", L"Jabba", IDI_JABBA, JABBER_CASE, TRUE },
{ "client_JabberApplet", L"Jabber*Applet*", L"JabberApplet", IDI_JABBER_APPLET, JABBER_CASE, TRUE },
{ "client_JabberBeOS", L"Jabber*BeOS*", L"Jabber (BeOS)", IDI_JABBER_BEOS, JABBER_CASE, TRUE },
{ "client_JabberFoX", L"*fox*", L"JabberFoX", IDI_JABBERFOX, JABBER_CASE, TRUE },
{ "client_JabberMSNGR", L"Jabber Messenger*", L"Jabber Messenger", IDI_JABBER_MESSENGER, JABBER_CASE, TRUE },
{ "client_JabberNaut", L"*Jabber*Naut*", L"JabberNaut", IDI_JABBERNAUT, JABBER_CASE, TRUE },
{ "client_JabberZilla", L"*Zilla*", L"JabberZilla", IDI_JABBERZILLA, JABBER_CASE, TRUE },
{ "client_Jabber_Net", L"|*Jabber*Net*|*cursive.net*|*csharp*", L"Jabber-Net", IDI_JABBER_NET, JABBER_CASE, TRUE },
{ "client_Jabberwocky", L"Jabberwocky*", L"Jabberwocky (Amiga)", IDI_JABBERWOCKY, JABBER_CASE, TRUE },
{ "client_Jabbroid", L"*Jabbroid*", L"Jabbroid", IDI_JABBROID, JABBER_CASE, TRUE },
{ "client_Jajc", L"|*Jajc*|Just Another Jabber Client", L"JAJC", IDI_JAJC, JABBER_CASE, TRUE },
{ "client_Jeti", L"*Jeti*", L"Jeti", IDI_JETI, JABBER_CASE, TRUE },
{ "client_Jitsi", L"*Jitsi*", L"Jitsi", IDI_JITSI, JABBER_CASE, TRUE },
{ "client_Joost", L"*Joost*", L"Joost", IDI_JOOST, JABBER_CASE, TRUE },
{ "client_Kadu", L"*Kadu*", L"Kadu", IDI_KADU, JABBER_CASE, TRUE },
{ "client_Konnekt", L"Konnekt*", L"Konnekt", IDI_KONNEKT, JABBER_CASE, TRUE },
{ "client_LLuna", L"LLuna*", L"LLuna", IDI_LLUNA, JABBER_CASE, TRUE },
{ "client_Lamp", L"*Lamp*IM*", L"Lamp IM", IDI_LAMP_IM, JABBER_CASE, TRUE },
{ "client_Lampiro", L"*Lampiro*", L"Lampiro", IDI_LAMPIRO, JABBER_CASE, TRUE },
{ "client_Landell", L"*Landell*", L"Landell", IDI_LANDELL, JABBER_CASE, TRUE },
{ "client_Leaf", L"*Leaf*", L"Leaf Messenger", IDI_LEAF, JABBER_CASE, TRUE },
{ "client_LinQ", L"*LinQ*", L"LinQ", IDI_LINQ, JABBER_CASE, TRUE },
{ "client_M8Jabber", L"*M8Jabber*", L"M8Jabber", IDI_M8JABBER, JABBER_CASE, TRUE },
{ "client_MCabber", L"*mcabber*", L"MCabber", IDI_MCABBER, JABBER_CASE, TRUE },
{ "client_MGTalk", L"|*MGTalk*|*Mobile?\?\?\?\?\?\?\?", L"MGTalk", IDI_MGTALK, JABBER_CASE, TRUE },
{ "client_MUCkl", L"*MUCkl*", L"MUCkl", IDI_MUCKL, JABBER_CASE, TRUE },
{ "client_Mango", L"*Mango*", L"Mango", IDI_MANGO, JABBER_CASE, TRUE },
{ "client_Mercury", L"*Mercury*", L"Mercury Messenger", IDI_MERCURY_MESSENGER, JABBER_CASE, TRUE },
{ "client_Monal", L"*Monal*", L"Monal", IDI_MONAL, JABBER_CASE, TRUE },
{ "client_MozillaChat", L"*Mozilla*Chat*", L"MozillaChat", IDI_MOZILLACHAT, JABBER_CASE, TRUE },
{ "client_Neos", L"Neos*", L"Neos", IDI_NEOS, JABBER_CASE, TRUE },
{ "client_Nitro", L"Nitro*", L"Nitro", IDI_NITRO, JABBER_CASE, TRUE },
{ "client_Nostromo", L"*USCSS*Nostromo*", L"USCSS Nostromo", IDI_NOSTROMO, JABBER_CASE, TRUE },
{ "client_OM", L"OM*", L"OM aka Online Messenger", IDI_OM, JABBER_CASE, TRUE },
{ "client_OctroTalk", L"*Octro*", L"OctroTalk", IDI_OCTROTALK, JABBER_CASE, TRUE },
{ "client_OneTeam", L"*OneTeam*", L"OneTeam", IDI_ONETEAM, JABBER_CASE, TRUE },
{ "client_Openfire", L"*Openfire*", L"Openfire", IDI_OPENFIRE, JABBER_CASE, TRUE },
{ "client_Fire", L"Fire*", L"Fire", IDI_FIRE, JABBER_CASE, TRUE },
{ "client_Paltalk", L"*Paltalk*", L"Paltalk", IDI_PALTALK, JABBER_CASE, TRUE },
{ "client_Pandion", L"|*Pandion*|*Пандион*", L"Pandion", IDI_PANDION, JABBER_CASE, TRUE },
{ "client_Papla", L"*Papla*", L"Papla", IDI_PAPLA, JABBER_CASE, TRUE },
{ "client_Poezio", L"*Poezio*", L"Poezio", IDI_POEZIO, JABBER_CASE, TRUE },
{ "client_Prosody", L"*Prosody*", L"Prosody", IDI_PROSODY, JABBER_CASE, TRUE },
{ "client_Psi_plus", L"|*PSI+*|*psi-dev.googlecode*", L"PSI+", IDI_PSIPLUS, JABBER_CASE, TRUE },
{ "client_Psi", L"*Psi*", L"PSI", IDI_PSI, JABBER_CASE, TRUE },
{ "client_Psto", L"*Psto*", L"Psto.net", IDI_PSTO, JABBER_CASE, TRUE },
{ "client_Psyc", L"*Psyc*", L"Psyc", IDI_PSYC, JABBER_CASE, TRUE },
{ "client_Pygeon", L"*Pygeon*", L"Pygeon", IDI_PYGEON, JABBER_CASE, TRUE },
{ "client_QTJim", L"*QTJim*", L"QTJim", IDI_QTJIM, JABBER_CASE, TRUE },
{ "client_QuteCom", L"*Qute*Com*", L"QuteCom", IDI_QUTECOM, JABBER_CASE, TRUE },
{ "client_RenRen", L"|*WTalkProxy0_0*|*talk.xiaonei.com*", L"RenRen", IDI_RENREN, JABBER_CASE, TRUE },
{ "client_SBot", L"*SBot*", L"SBot", IDI_SBOT, JABBER_CASE, TRUE },
{ "client_SMTP_Transport", L"*smtp*transport*", L"SMTP Transport", IDI_SMTP_TRANSPORT, JABBER_CASE, TRUE },
{ "client_SamePlace", L"*SamePlace*", L"SamePlace", IDI_SAMEPLACE, JABBER_CASE, TRUE },
{ "client_Sky_Messager", L"Sky*Mess*", L"Sky Messager", IDI_SKYMESSAGER, JABBER_CASE, TRUE },
{ "client_Sky_Messager", L"*Sky*Messager*", L"Sky Messager", IDI_SKYMESSAGER, JABBER_CASE, TRUE },
{ "client_xabber", L"|*xabber*"
L"|*GyIX*", L"xabber", IDI_XABBER, JABBER_CASE, TRUE },
{ "client_Gabble", L"*Gabble*", L"Gabble", IDI_GABBLE, JABBER_CASE, TRUE },
{ "client_Smack", L"|*igniterealtime.*smack*|*smack*", L"Smack", IDI_SMACK, JABBER_CASE, TRUE },
{ "client_SoapBox", L"*SoapBox*", L"SoapBox", IDI_SOAPBOX, JABBER_CASE, TRUE },
{ "client_Spark", L"*Spark*", L"Spark", IDI_SPARK, JABBER_CASE, TRUE },
{ "client_Speakall", L"*Speak*all*", L"Speakall", IDI_SPEAKALL, JABBER_CASE, TRUE },
{ "client_Speeqe", L"*Speeqe*", L"Speeqe", IDI_SPEEQE, JABBER_CASE, TRUE },
{ "client_Spik", L"*Spik*", L"Spik", IDI_SPIK, JABBER_CASE, TRUE },
{ "client_Swift", L"*Swift*", L"Swift", IDI_SWIFT, JABBER_CASE, TRUE },
{ "client_SworIM", L"*Swor*IM*", L"SworIM", IDI_SWORIM, JABBER_CASE, TRUE },
{ "client_Synapse", L"*Synapse*", L"Synapse", IDI_SYNAPSE, JABBER_CASE, TRUE },
{ "client_Talkdroid", L"*Talkdroid*", L"Talkdroid", IDI_TALKDROID, JABBER_CASE, TRUE },
{ "client_Talkonaut", L"*Talkonaut*", L"Talkonaut", IDI_TALKONAUT, JABBER_CASE, TRUE },
{ "client_Tapioca", L"*Tapioca*", L"Tapioca", IDI_TAPIOCA, JABBER_CASE, TRUE },
{ "client_Teabot", L"|*teabot*|*teabot.org/bot*", L"Teabot", IDI_TEABOT, JABBER_CASE, TRUE },
{ "client_Telepathy", L"*Telepathy*", L"Telepathy", IDI_TELEPATHY, JABBER_CASE, TRUE },
{ "client_The_Bee", L"*The*Bee*", L"The Bee", IDI_THEBEE, JABBER_CASE, TRUE },
{ "client_Thunderbird", L"*Thunderbi*", L"Thunderbird", IDI_THUNDERBIRD, JABBER_CASE, TRUE },
{ "client_Tigase", L"*Tigase*", L"Tigase", IDI_TIGASE, JABBER_CASE, TRUE },
{ "client_TipicIM", L"Tipic*", L"TipicIM", IDI_TIPICIM, JABBER_CASE, TRUE },
{ "client_Tkabber", L"*Tkabber*", L"Tkabber", IDI_TKABBER, JABBER_CASE, TRUE },
{ "client_TransactIM", L"*Transact*", L"TransactIM", IDI_TRANSACTIM, JABBER_CASE, TRUE },
{ "client_Translate", L"*Translate*", L"Translate component", IDI_TRANSLATE, JABBER_CASE, TRUE },
{ "client_Triple", L"Triple*", L"TripleSoftwareIM (TSIM)", IDI_TRIPLE_SOFTWARE, JABBER_CASE, TRUE },
{ "client_Vacuum", L"*Vacuum*", L"Vacuum IM", IDI_VACUUM, JABBER_CASE, TRUE },
{ "client_V&V", L"*V&V*", L"V&V Messenger", IDI_VANDV, JABBER_CASE, TRUE },
{ "client_Vayusphere", L"*Vayusphere*", L"Vayusphere", IDI_VAYUSPHERE, JABBER_CASE, TRUE },
{ "client_Vysper", L"*Vysper*", L"Vysper", IDI_VYSPER, JABBER_CASE, TRUE },
{ "client_WTW", L"**WTW**|*wtw.k2t.eu*", L"WTW", IDI_WTW, JABBER_CASE, TRUE },
{ "client_WannaChat", L"Wanna*Chat*", L"WannaChat", IDI_WANNACHAT, JABBER_CASE, TRUE },
{ "client_WebEx", L"*webex.com*", L"Cisco WebEx Connect", IDI_WEBEX, JABBER_CASE, TRUE },
{ "client_WhisperIM", L"*Whisper*", L"WhisperIM", IDI_WHISPERIM, JABBER_CASE, TRUE },
{ "client_Wija", L"*wija*", L"Wija", IDI_WIJA, JABBER_CASE, TRUE },
{ "client_Wildfire", L"Wildfire*", L"Wildfire", IDI_WILDFIRE, JABBER_CASE, TRUE },
{ "client_WinJab", L"*WinJab*", L"WinJab", IDI_WINJAB, JABBER_CASE, TRUE },
{ "client_Xiffian", L"*Xiffian*", L"Xiffian", IDI_XIFFIAN, JABBER_CASE, TRUE },
{ "client_Yambi", L"*Yambi*", L"Yambi", IDI_YAMBI, JABBER_CASE, TRUE },
{ "client_chat_bots", L"*chat*bot*", L"chat bot", IDI_CHAT_BOT, JABBER_CASE, TRUE },
{ "client_dziObber", L"*dzi?bber*", L"dziObber", IDI_DZIOBBER, JABBER_CASE, TRUE },
{ "client_ejabberd", L"*ejabberd*", L"ejabberd", IDI_EJABBERD, JABBER_CASE, TRUE },
{ "client_emite", L"*emite*", L"emite", IDI_EMITE, JABBER_CASE, TRUE },
{ "client_gYaber", L"gYaber*", L"gYaber", IDI_GYABER, JABBER_CASE, TRUE },
{ "client_glu", L"*glu*", L"glu", IDI_GLU, JABBER_CASE, TRUE },
{ "client_iGoogle", L"iGoogle*", L"iGoogle", IDI_IGOOGLE, JABBER_CASE, TRUE },
{ "client_iJab", L"*iJab*", L"iJab", IDI_IJAB, JABBER_CASE, TRUE },
{ "client_iMeem", L"iMeem*", L"iMeem", IDI_IMEEM, JABBER_CASE, TRUE },
{ "client_iMov", L"*imov*", L"iMov", IDI_IMOV, JABBER_CASE, TRUE },
{ "client_jTalk", L"|*jTalk*|http://jtalk*", L"jTalk", IDI_JTALK, JABBER_CASE, TRUE },
{ "client_jTalkmod", L"|*jTalkmod*"
L"|*glSvJ3yM3M2f53oregNy6fYwocY=*"
L"|*XEssZlSs8oF4EcTHU1b8BsVxcPg=*", L"jTalkmod", IDI_JTALKMOD, JABBER_CASE, TRUE },
{ "client_jabberDisk", L"|*jdisk*|*jabber*Disk*", L"jabberDisk", IDI_JABBER_DISK, JABBER_CASE, TRUE },
{ "client_jabbim", L"*jabbim*", L"Jabbim", IDI_JABBIM, JABBER_CASE, TRUE },
{ "client_jabiru", L"*jabiru*", L"Jabiru", IDI_JABIRU, JABBER_CASE, TRUE },
{ "client_jappix", L"*jappix*", L"jappix", IDI_JAPPIX, JABBER_CASE, TRUE },
{ "client_jrudevels", L"*jrudevels*", L"Jrudevels", IDI_JRUDEVELS, JABBER_CASE, TRUE },
{ "client_juick", L"*juick*", L"Juick", IDI_JUICK, JABBER_CASE, TRUE },
{ "client_kf", L"|^*smack*|*kf*", L"kf jabber", IDI_KF, JABBER_CASE, TRUE },
{ "client_laffer", L"*laffer*", L"Laffer", IDI_LAFFER, JABBER_CASE, TRUE },
{ "client_mJabber", L"*mJabber*", L"mJabber", IDI_MJABBER, JABBER_CASE, TRUE },
{ "client_meinvz", L"*meinvz*", L"MeinVZ", IDI_MEINVZ, JABBER_CASE, TRUE },
{ "client_moJab", L"*moJab*", L"moJab", IDI_MOJAB, JABBER_CASE, TRUE },
{ "client_mobber", L"*mobber*", L"mobber", IDI_MOBBER, JABBER_CASE, TRUE },
{ "client_myJabber", L"*myJabber*", L"myJabber", IDI_MYJABBER, JABBER_CASE, TRUE },
{ "client_orkut", L"*orkut*", L"orkut", IDI_ORKUT, JABBER_CASE, TRUE },
{ "client_pjc", L"|*PJC*|*pjc.googlecode.com*", LPGENW("PHP Jabber Client"), IDI_PJC, JABBER_CASE, TRUE },
{ "client_saje", L"*saje*", L"saje", IDI_SAJE, JABBER_CASE, TRUE },
{ "client_schuelervz", L"*schuelervz*", L"SchulerVZ", IDI_SCHULERVZ, JABBER_CASE, TRUE },
{ "client_studivz", L"*studivz*", L"StudiVZ", IDI_STUDIVZ, JABBER_CASE, TRUE },
{ "client_tkchat", L"*tkchat*", L"tkchat", IDI_TKCHAT, JABBER_CASE, TRUE },
// {"client_uJabber", L"*uJabber*", L"uJabber", IDI_UJABBER, JABBER_CASE, TRUE },
{ "client_uKeeper", L"*uKeeper*", L"uKeeper", IDI_UKEEPER, JABBER_CASE, TRUE },
{ "client_whoisbot", L"whoisbot", L"Swissjabber Whois Bot", IDI_WHOISBOT, JABBER_CASE, TRUE },
{ "client_xeus2", L"*xeus 2*", L"xeus 2", IDI_XEUS2, JABBER_CASE, TRUE },
{ "client_xeus", L"*xeus*", L"xeus", IDI_XEUS, JABBER_CASE, TRUE },
{ "client_yaonline", L"|*yandex*|*yaonline*"
L"|*Я.Онлайн*|*Яндекс*", L"Ya.Online", IDI_YAONLINE, JABBER_CASE, TRUE },
{ "client_yaxim", L"*yaxim*", L"yaxim", IDI_YAXIM, JABBER_CASE, TRUE },
//#########################################################################################################################################################################
//################################# IRC ###############################################################################################################################
//#########################################################################################################################################################################
{ "client_AmIRC", L"*AmIRC*", L"AmIRC", IDI_AMIRC, IRC_CASE, TRUE },
{ "client_Babbel", L"*Babbel*", L"Babbel", IDI_BABBEL, IRC_CASE, TRUE },
{ "client_BersIRC", L"*BersIRC*", L"BersIRC", IDI_BERSIRC, IRC_CASE, TRUE },
{ "client_ChatZilla", L"*ChatZilla*", L"ChatZilla", IDI_CHATZILLA, IRC_CASE, TRUE },
{ "client_Conversation", L"*Conversation*", L"Conversation", IDI_CONVERSATION, IRC_CASE, TRUE },
{ "client_Eggdrop", L"*Eggdrop*", L"Eggdrop", IDI_EGGDROP, IRC_CASE, TRUE },
{ "client_EggdropRacBot", L"*Eggdrop*RacBot*", L"Eggdrop RacBot", IDI_EGGDROP_RACBOT, IRC_CASE, TRUE },
{ "client_FChat", L"*FChat*", L"FChat", IDI_FCHAT, IRC_CASE, TRUE },
{ "client_GDPChat", L"*GDPChat*", L"GDP Web Chat", IDI_GDPCHAT, IRC_CASE, TRUE },
{ "client_GoPowerTools", L"*Go*PowerTools*", L"GoPowerTools", IDI_GOPOWERTOOLS, IRC_CASE, TRUE },
{ "client_HydraIRC", L"*Hydra*IRC*", L"HydraIRC", IDI_HYDRA_IRC, IRC_CASE, TRUE },
{ "client_IRCXpro", L"*IRCXpro*", L"IRCXpro", IDI_IRCXPRO, IRC_CASE, TRUE },
{ "client_IceChat", L"*Ice*Chat*", L"IceChat", IDI_ICECHAT, IRC_CASE, TRUE },
{ "client_KSirc", L"*ksirk*", L"KSirc", IDI_KSIRC, IRC_CASE, TRUE },
{ "client_KVIrc", L"*KVIrc*", L"KVIrc", IDI_KVIRC, IRC_CASE, TRUE },
{ "client_Klient", L"*Klient*", L"Klient", IDI_KLIENT, IRC_CASE, TRUE },
{ "client_Konversation", L"*Konversation*", L"Konversation", IDI_KONVERSATION, IRC_CASE, TRUE },
{ "client_MP3Script", L"*MP3*Script*", LPGENW("MP3 Script for mIRC"), IDI_MP3_SCRIPT, IRC_CASE, TRUE },
{ "client_NeoRaTrion", L"*NeoRa*Trion*", L"NeoRa Trion", IDI_NEORATRION, IRC_CASE, TRUE },
{ "client_Nettalk", L"*Nettalk*", L"Nettalk", IDI_NETTALK, IRC_CASE, TRUE },
{ "client_NoNameScript", L"*NoName*Script*", L"NoNameScript", IDI_NONAME_SCRIPT, IRC_CASE, TRUE },
{ "client_Opera", L"*Opera*", L"Opera", IDI_OPERA, IRC_CASE, TRUE },
{ "client_PJIRC", L"*PJIRC*", L"PJIRC", IDI_PJIRC, IRC_CASE, TRUE },
{ "client_Pirch", L"*Pirch*", L"Pirch", IDI_PIRCH, IRC_CASE, TRUE },
{ "client_PocketIRC", L"*Pocket*IRC*", L"Pocket IRC", IDI_POCKET_IRC, IRC_CASE, TRUE },
{ "client_ProChat", L"*Pro*Chat*", L"ProChat", IDI_PROCHAT, IRC_CASE, TRUE },
{ "client_SmartIRC", L"*Smart*IRC*", L"SmartIRC", IDI_SMART_IRC, IRC_CASE, TRUE },
{ "client_Snak", L"*Snak*", L"Snak", IDI_SNAK, IRC_CASE, TRUE },
{ "client_SysReset", L"*Sys*Reset*", L"SysReset", IDI_SYSRESET, IRC_CASE, TRUE },
{ "client_VircaIRC", L"*VircaIRC*", L"VircaIRC", IDI_VIRCAIRC, IRC_CASE, TRUE },
{ "client_VisionIRC", L"*VisionIRC*", L"VisionIRC", IDI_VISIONIRC, IRC_CASE, TRUE },
{ "client_VisualIRC", L"*VisualIRC*", L"VisualIRC", IDI_VISUALIRC, IRC_CASE, TRUE },
{ "client_VortecIRC", L"*VortecIRC*", L"VortecIRC", IDI_VORTECIRC, IRC_CASE, TRUE },
{ "client_WLIrc", L"*WLIrc*", L"WLIrc", IDI_WLIRC, IRC_CASE, TRUE },
{ "client_XChatAqua", L"*X*Chat*Aqua*", L"X-Chat Aqua", IDI_XCHATAQUA, IRC_CASE, TRUE },
{ "client_XiRCON", L"*XiRCON*", L"XiRCON", IDI_XIRCON, IRC_CASE, TRUE },
{ "client_Xirc", L"*Xirc*", L"Xirc", IDI_XIRC, IRC_CASE, TRUE },
{ "client_cbirc", L"*cbirc*", L"cbirc", IDI_CBIRC, IRC_CASE, TRUE },
{ "client_dIRC", L"*dIRC*", L"dIRC", IDI_DIRC, IRC_CASE, TRUE },
{ "client_iroffer_dinoex", L"*iroffer*dinoex*", L"iroffer dinoex", IDI_IROFFER_DINOEX, IRC_CASE, TRUE },
{ "client_iroffer", L"*iroffer*", L"iroffer", IDI_IROFFER, IRC_CASE, TRUE },
{ "client_ircle", L"*ircle*", L"ircle", IDI_IRCLE, IRC_CASE, TRUE },
{ "client_jircii", L"*jircii*", L"jircii", IDI_JIRCII, IRC_CASE, TRUE },
{ "client_jmIrc", L"*jmIrc*", L"jmIrc", IDI_JMIRC, IRC_CASE, TRUE },
{ "client_mIRC", L"*mIRC*", L"mIRC", IDI_MIRC, IRC_CASE, TRUE },
{ "client_pIRC", L"*pIRC*", L"pIRC", IDI_PIRC, IRC_CASE, TRUE },
{ "client_piorun", L"*piorun*", L"Piorun", IDI_PIORUN, IRC_CASE, TRUE },
{ "client_psyBNC", L"*psyBNC*", L"psyBNC", IDI_PSYBNC, IRC_CASE, TRUE },
{ "client_savIRC", L"*savIRC*", L"savIRC", IDI_SAVIRC, IRC_CASE, TRUE },
{ "client_wmIRC", L"*wmIRC*", L"wmIRC", IDI_WMIRC, IRC_CASE, TRUE },
{ "client_xBitch", L"*xBitch*", L"xBitch", IDI_XBITCH, IRC_CASE, TRUE },
{ "client_xChat", L"*xChat*", L"xChat", IDI_XCHAT, IRC_CASE, TRUE },
{ "client_zsIRC", L"*zsIRC*", L"zsIRC", IDI_ZSIRC, IRC_CASE, TRUE },
{ "client_ZNC", L"*ZNC*", L"ZNC", IDI_ZNC, IRC_CASE, TRUE },
{ "client_aMule", L"*aMule*", L"aMule", IDI_AMULE, IRC_CASE, TRUE },
{ "client_eMuleMorphXT", L"eMule*MorphXT*", L"eMule MorphXT", IDI_EMULE_MORPHXT, IRC_CASE, TRUE },
{ "client_eMuleNeo", L"eMule*Neo*", L"eMule Neo", IDI_EMULE_NEO, IRC_CASE, TRUE },
{ "client_eMulePlus", L"|eMule*plus*|eMule*+*", L"eMule+", IDI_EMULE_PLUS, IRC_CASE, TRUE },
{ "client_eMuleXtreme", L"eMule*Xtreme*", L"eMule Xtreme", IDI_EMULE_XTREME, IRC_CASE, TRUE },
{ "client_eMule", L"*eMule*", L"eMule", IDI_EMULE, IRC_CASE, TRUE },
{ "client_IRCUnknown", L"*IRC*", L"Unknown IRC client", IDI_IRC, IRC_CASE, TRUE },
//#########################################################################################################################################################################
//################################# WEATHER ###########################################################################################################################
//#########################################################################################################################################################################
{ "client_accu", L"*accuweather*", L"AccuWeather", IDI_ACCU, WEATHER_CASE, TRUE },
{ "client_gismeteo", L"*gismeteo*", L"GisMeteo", IDI_GISMETEO, WEATHER_CASE, TRUE },
{ "client_intelli", L"*intellicast*", L"Intellicast", IDI_INTELLI, WEATHER_CASE, TRUE },
{ "client_meteogid", L"|*meteo-gid*|*meteogid*", L"Meteo-Gid", IDI_METEOGID, WEATHER_CASE, TRUE },
{ "client_meteonovosti", L"*meteonovosti*", L"Meteonovosti", IDI_METEONOVOSTI, WEATHER_CASE, TRUE },
{ "client_noaa", L"*noaa*", L"NOAA Weather", IDI_NOAA, WEATHER_CASE, TRUE },
{ "client_real", L"*realmeteo*", L"RealMeteo", IDI_REALMETEO, WEATHER_CASE, TRUE },
{ "client_under", L"Weather Underground*", L"Weather Underground", IDI_UNDERGROUND, WEATHER_CASE, TRUE },
{ "client_weatherxml", L"*WeatherXML*", L"WeatherXML", IDI_WEATHERXML, WEATHER_CASE, TRUE },
{ "client_wetter", L"*wetter*", L"Wetter", IDI_WETTER, WEATHER_CASE, TRUE },
{ "client_yweather", L"*Yahoo Weather*", L"Yahoo Weather", IDI_YWEATHER, WEATHER_CASE, TRUE },
{ "client_weather_cn", L"*weather.com.cn*", L"Weather CN", IDI_WEATHER_CN, WEATHER_CASE, TRUE },
{ "client_weather", L"*weather*", L"Weather", IDI_WEATHER, WEATHER_CASE, TRUE },
//#########################################################################################################################################################################
//################################# RSS ###############################################################################################################################
//#########################################################################################################################################################################
{ "client_rss09x", L"*RSS*0.9*", L"RSS 0.9x", IDI_RSS09, RSS_CASE, TRUE },
{ "client_rss2", L"*RSS*2.*", L"RSS 2", IDI_RSS2, RSS_CASE, TRUE },
{ "client_rss1", L"*RSS*1.*", L"RSS 1", IDI_RSS1, RSS_CASE, TRUE },
{ "client_atom3", L"*Atom*3*", L"Atom 3", IDI_ATOM3, RSS_CASE, TRUE },
{ "client_atom1", L"*Atom*1*", L"Atom 1", IDI_ATOM1, RSS_CASE, TRUE },
//#########################################################################################################################################################################
//################################# GADU-GADU #########################################################################################################################
//#########################################################################################################################################################################
{ "client_GG", L"|Gadu-Gadu*|GG*", LPGENW("Gadu-Gadu client"), IDI_GG, GG_CASE },
//#########################################################################################################################################################################
//################################# Facebook ##########################################################################################################################
//#########################################################################################################################################################################
{ "client_Facebook_other", L"*Facebook*other*", L"Facebook (other)", IDI_FACEBOOK_OTHER, FACEBOOK_CASE },
{ "client_Facebook_app", L"*Facebook*App*", L"Facebook App", IDI_FACEBOOK_APP, FACEBOOK_CASE },
{ "client_Facebook_mess", L"*Facebook*Messenger*", L"Facebook Messenger", IDI_FACEBOOK_MESSENGER, FACEBOOK_CASE },
{ "client_Facebook", L"*Facebook*", L"Facebook", IDI_FACEBOOK, FACEBOOK_CASE },
//#########################################################################################################################################################################
//################################# VKontakte #########################################################################################################################
//#########################################################################################################################################################################
{ "client_VK", L"|*VKontakte*|*vk.com*", L"VKontakte", IDI_VK, VK_CASE },
{ "client_VK_Kate", L"*Kate*Mobile*", L"Kate Mobile", IDI_VK_KATE, VK_CASE },
{ "client_VK_Messenger", L"VK Messenger*", L"VK Messenger", IDI_VK_MESSENGER, VK_CASE },
{ "client_VK_Phoenix_Full", L"Phoenix*Full*", L"Phoenix Full", IDI_VK_PHOENIX_FULL, VK_CASE },
{ "client_VK_Phoenix_Lite", L"Phoenix*Lite*", L"Phoenix Lite", IDI_VK_PHOENIX_LITE, VK_CASE },
//#########################################################################################################################################################################
//################################# OTHER CLIENTS #####################################################################################################################
//#########################################################################################################################################################################
{ "client_Android", L"Android*", L"Android", IDI_ANDROID, MULTI_CASE, TRUE },
{ "client_Pidgin", L"|*Pidgin*|*libpurple*|Purple*", L"Pidgin (libpurple)", IDI_PIDGIN, MULTI_CASE },
{ "client_Python", L"|*Python*|Py*|*ταλιςμαη*", LPGENW("Python-based clients"), IDI_PYTHON, MULTI_CASE },
{ "client_Jabber", L"*Jabber*client*", LPGENW("Jabber client"), IDI_JABBER, JABBER_CASE, TRUE },
{ "client_XMPP", L"|*XMPP*|Mrim*|*DRQZ00fz5WPn1gH+*", LPGENW("XMPP client"), IDI_XMPP, JABBER_CASE },
{ "client_Hangouts", L"messaging-*", L"Google+ Hangouts", IDI_HANGOUTS, OTHER_PROTOS_CASE, TRUE },
{ "client_Twitter", L"*Twitter*", L"Twitter", IDI_TWITTER, OTHER_PROTOS_CASE, TRUE },
{ "client_Skype", L"*Skype**", L"Skype", IDI_SKYPE, OTHER_PROTOS_CASE },
{ "client_Steam", L"*Steam*", L"Steam", IDI_STEAM, OTHER_PROTOS_CASE },
//#########################################################################################################################################################################
//################################# UNDEFINED CLIENTS #################################################################################################################
//#########################################################################################################################################################################
{ "client_Notfound", L"Notfound", LPGENW("Client not found"), IDI_NOTFOUND, OTHERS_CASE, TRUE },
{ "client_Unknown", L"|*Unknown*|...", LPGENW("Unknown client"), IDI_UNKNOWN, OTHERS_CASE, TRUE },
{ "client_Undetected", L"?*", LPGENW("Undetected client"), IDI_UNDETECTED, OTHERS_CASE, TRUE },
};
int DEFAULT_KN_FP_MASK_COUNT = _countof(def_kn_fp_mask);
//#########################################################################################################################################################################
//################################# OVERLAYS LAYER #1 #################################################################################################################
//#########################################################################################################################################################################
KN_FP_MASK def_kn_fp_overlays_mask[] =
{// {"Client_IconName", L"|^*Mask*|*names*", L"Icon caption", IDI_RESOURCE_ID, CLIENT_CASE, OVERLAY? },
//#########################################################################################################################################################################
//################################# MIRANDA PACKS OVERLAYS ############################################################################################################
//#########################################################################################################################################################################
{ "client_AF_pack", L"*AF*Pack*", L"AF", IDI_MIRANDA_AF, MIRANDA_PACKS_CASE },
{ "client_AlfaMaR_pack", L"*AlfaMaR*", L"AlfaMaR", IDI_MIRANDA_ALFAMAR, MIRANDA_PACKS_CASE },
{ "client_Amatory_pack", L"*Amatory*", L"Amatory", IDI_MIRANDA_AMATORY, MIRANDA_PACKS_CASE },
{ "client_BRI_pack", L"*bri*edition*", L"Bri edition", IDI_MIRANDA_BRI, MIRANDA_PACKS_CASE },
{ "client_Devil_pack", L"*6.6.6*", L"Devil Suite", IDI_MIRANDA_DEVIL, MIRANDA_PACKS_CASE },
{ "client_E33_pack", L"*[E33*]*", L"E33", IDI_MIRANDA_E33, MIRANDA_PACKS_CASE },
{ "client_FR_pack", L"*FR*Pack*", L"Miranda FR", IDI_MIRANDA_FR, MIRANDA_PACKS_CASE },
{ "client_Faith_pack", L"*Faith*Pack*", L"FaithPack", IDI_MIRANDA_FAITH, MIRANDA_PACKS_CASE },
{ "client_Final_pack", L"*[Final*Pack]*", L"Final pack", IDI_MIRANDA_FINAL, MIRANDA_PACKS_CASE },
{ "client_Freize_pack", L"*Freize*", L"Freize", IDI_MIRANDA_FREIZE, MIRANDA_PACKS_CASE },
{ "client_Ghost_pack", L"*Ghost's*", L"Ghost's pack", IDI_MIRANDA_GHOST, MIRANDA_PACKS_CASE },
{ "client_HotCoffee_pack", L"*HotCoffee*", L"HotCoffee", IDI_MIRANDA_CAPPUCCINO, MIRANDA_PACKS_CASE },
{ "client_HierOS_pack", L"*HierOS*", L"HierOS", IDI_MIRANDA_HIEROS, MIRANDA_PACKS_CASE },
{ "client_ICE_pack", L"|*miranda*[ice*]|*induction*", L"iCE / Induction", IDI_MIRANDA_INDUCTION, MIRANDA_PACKS_CASE },
{ "client_KDL_pack", L"|*KDL*|*КДЛ*", L"KDL", IDI_MIRANDA_KDL, MIRANDA_PACKS_CASE },
{ "client_Kolich_pack", L"*Kolich*", L"Kolich", IDI_MIRANDA_KOLICH, MIRANDA_PACKS_CASE },
{ "client_Kuzzman_pack", L"*kuzzman*", L"Kuzzman", IDI_MIRANDA_KUZZMAN, MIRANDA_PACKS_CASE },
{ "client_Lenin_pack", L"*[Lenin*]*", L"Lenin pack", IDI_MIRANDA_LENINPACK, MIRANDA_PACKS_CASE },
{ "client_Lestat_pack", L"*[Lpack*]*", L"Lestat pack", IDI_MIRANDA_LESTAT, MIRANDA_PACKS_CASE },
{ "client_LexSys_pack", L"|*Miranda*LS*|*LexSys*", L"LexSys", IDI_MIRANDA_LEXSYS, MIRANDA_PACKS_CASE },
{ "client_MD_pack", L"*MDpack*", L"MDpack", IDI_MIRANDA_MD, MIRANDA_PACKS_CASE },
{ "client_Mataes_pack", L"*Mataes*", L"Mataes pack", IDI_MIRANDA_MATAES, MIRANDA_PACKS_CASE },
{ "client_Mir_ME_pack", L"*[Miranda*ME]*", L"Miranda ME", IDI_MIRANDA_ME, MIRANDA_PACKS_CASE },
{ "client_Native_pack", L"*Native*", L"Native", IDI_MIRANDA_NATIVE, MIRANDA_PACKS_CASE },
{ "client_New_Style_pack", L"*New*Style*", L"New Style", IDI_MIRANDA_NEW_STYLE, MIRANDA_PACKS_CASE },
{ "client_Pilot_pack", L"*Pilot*", L"Pilot", IDI_MIRANDA_PILOT, MIRANDA_PACKS_CASE },
{ "client_Razunter_pack", L"*Razunter*", L"Razunter's Pk", IDI_MIRANDA_RAZUNTER, MIRANDA_PACKS_CASE },
{ "client_Robyer_pack", L"*Robyer*Pack*", L"Robyer pack", IDI_MIRANDA_ROBYER, MIRANDA_PACKS_CASE },
{ "client_SSS_pack", L"*sss*pack*", L"SSS build", IDI_MIRANDA_SSS_MOD, MIRANDA_PACKS_CASE },
{ "client_Se7ven_pack", L"|^*sss*|*[S7*pack]*|*[*S7*]*", L"Se7ven", IDI_MIRANDA_SE7VEN, MIRANDA_PACKS_CASE },
{ "client_SpellhowleR_pack", L"*Spellhowler*", L"xSpellhowleRx pack", IDI_MIRANDA_SPELLHOWLER, MIRANDA_PACKS_CASE },
{ "client_Stalker_pack", L"*Stalker*", L"Stalker", IDI_MIRANDA_STALKER, MIRANDA_PACKS_CASE },
{ "client_Tweety_pack", L"*tweety*", L"Tweety", IDI_MIRANDA_TWEETY, MIRANDA_PACKS_CASE },
{ "client_Umedon_pack", L"*Miranda*Umedon*", L"Umedon", IDI_MIRANDA_UMEDON, MIRANDA_PACKS_CASE },
{ "client_ValeraVi_pack", L"*Valera*Vi*", L"ValeraVi", IDI_MIRANDA_VALERAVI, MIRANDA_PACKS_CASE },
{ "client_Watcher_pack", L"*Watcher*", L"Watcher pack", IDI_MIRANDA_WATCHER, MIRANDA_PACKS_CASE },
{ "client_YAOL_pack", L"*yaol*", L"YAOL", IDI_MIRANDA_YAOL, MIRANDA_PACKS_CASE },
{ "client_dar_veter_pack", L"*Dar*veter*", L"Dar_veter pack", IDI_MIRANDA_DAR, MIRANDA_PACKS_CASE },
{ "client_dmikos_pack", L"*dmikos*", L"Dmikos", IDI_MIRANDA_DMIKOS, MIRANDA_PACKS_CASE },
{ "client_zeleboba_pack", L"*zeleboba*", L"zeleboba's", IDI_MIRANDA_ZELEBOBA, MIRANDA_PACKS_CASE },
//#########################################################################################################################################################################
//################################# PROTO OVERLAYS ####################################################################################################################
//#########################################################################################################################################################################
{ "client_ICQ_overlay", L"|^ICQ|^ICQ*|*ICQ*", LPGENW("ICQ overlay"), IDI_ICQ_OVERLAY, OVERLAYS_PROTO_CASE },
{ "client_IRC_overlay", L"|^IRC*|Miranda*IRC*", LPGENW("IRC overlay"), IDI_IRC_OVERLAY, OVERLAYS_PROTO_CASE },
{ "client_JGmail_overlay", L"*JGmail*", LPGENW("JGmail overlay"), IDI_GMAIL_OVERLAY, OVERLAYS_PROTO_CASE },
{ "client_JGTalk_overlay", L"*JGTalk*", LPGENW("JGTalk overlay"), IDI_JGTALK_OVERLAY, OVERLAYS_PROTO_CASE },
{ "client_Jabber_overlay", L"|^jabber*|Miranda*Jabber*|py*jabb*", LPGENW("Jabber overlay"), IDI_JABBER_OVERLAY, OVERLAYS_PROTO_CASE },
{ "client_VK_overlay", L"|Miranda*VKontakte*", LPGENW("VK overlay"), IDI_VK_OVERLAY, OVERLAYS_PROTO_CASE },
{ "client_Skype_overlay", L"|Miranda*Skype*", LPGENW("Skype overlay"), IDI_SKYPE_OVERLAY, OVERLAYS_PROTO_CASE },
//#########################################################################################################################################################################
//################################# CLIENT VERSION OVERLAYS ###########################################################################################################
//#########################################################################################################################################################################
{ "client_ICQ8_over", L"ICQ*8*", LPGENW("ICQ v8.x overlay"), IDI_ICQ8_OVERLAY, ICQ_CASE },
{ "client_GG_11", L"|Gadu-Gadu*11*|GG*11*", LPGENW("Gadu-Gadu v11 client"), IDI_GG11_OVERLAY, GG_CASE },
{ "client_GG_10", L"|Gadu-Gadu*10*|GG*10", LPGENW("Gadu-Gadu v10 client"), IDI_GG10_OVERLAY, GG_CASE },
{ "client_GG_9", L"|Gadu-Gadu*9*|GG*9*", LPGENW("Gadu-Gadu v9 client"), IDI_GG9_OVERLAY, GG_CASE },
{ "client_GG_8", L"|Gadu-Gadu*8*|GG*8*", LPGENW("Gadu-Gadu v8 client"), IDI_GG8_OVERLAY, GG_CASE },
//#########################################################################################################################################################################
//################################# PLATFORM OVERLAYS #################################################################################################################
//#########################################################################################################################################################################
{ "client_on_Win32", L"|*Win*|* WM *|wmagent*|*Vista*", LPGENW("Windows overlay"), IDI_PLATFORM_WIN, OVERLAYS_PLATFORM_CASE },
{ "client_on_iOS", L"|*ipad*|*iphone*|*iOS*", LPGENW("iOS overlay (iPhone/iPad)"), IDI_PLATFORM_IOS, OVERLAYS_PLATFORM_CASE },
{ "client_on_Mac", L"|^*smack*|* Mac *|*mac*|*OSX*", LPGENW("MacOS overlay"), IDI_PLATFORM_MAC, OVERLAYS_PLATFORM_CASE },
{ "client_on_Linux", L"*Linux*", LPGENW("Linux overlay"), IDI_PLATFORM_LINUX, OVERLAYS_PLATFORM_CASE },
{ "client_on_Flash", L"|*Flash*|*Web*ICQ*", LPGENW("Flash overlay"), IDI_PLATFORM_FLASH, OVERLAYS_PLATFORM_CASE },
{ "client_on_Java", L"|*Java*|jagent*|ICQ2Go!*", LPGENW("Java overlay"), IDI_PLATFORM_JAVA, OVERLAYS_PLATFORM_CASE },
{ "client_on_Symbian", L"|*Symbian*|sagent*", LPGENW("Symbian overlay"), IDI_PLATFORM_SYMBIAN, OVERLAYS_PLATFORM_CASE },
{ "client_on_Amiga", L"*Amiga*", LPGENW("Amiga overlay"), IDI_PLATFORM_AMIGA, OVERLAYS_PLATFORM_CASE },
{ "client_on_Android", L"|*Android*|*(android)*", LPGENW("Android overlay"), IDI_PLATFORM_ANDROID, OVERLAYS_PLATFORM_CASE },
{ "client_on_Website", L"|*(website)*|*(Web)*", LPGENW("Website overlay"), IDI_PLATFORM_WEBSITE, OVERLAYS_PLATFORM_CASE },
{ "client_on_WinPhone", L"|*(wphone)*|*(WP)*", LPGENW("Windows Phone overlay"), IDI_PLATFORM_WINPHONE, OVERLAYS_PLATFORM_CASE },
{ "client_on_mobile", L"*(mobile)*", LPGENW("Mobile overlay"), IDI_PLATFORM_MOBILE, OVERLAYS_PLATFORM_CASE },
};
int DEFAULT_KN_FP_OVERLAYS_COUNT = _countof(def_kn_fp_overlays_mask);
//#########################################################################################################################################################################
//#########################################################################################################################################################################
//################################# OVERLAYS LAYER #2 #################################################################################################################
//#########################################################################################################################################################################
//#########################################################################################################################################################################
KN_FP_MASK def_kn_fp_overlays2_mask[] =
{// {"Client_IconName", L"|^*Mask*|*names*", L"Icon caption", IDI_RESOURCE_ID, CLIENT_CASE, OVERLAY? },
{ "client_debug_overlay", L"|*[*debug*]*|*test*|*тест*", LPGENW("debug overlay"), IDI_DEBUG_OVERLAY, OVERLAYS_RESOURCE_CASE },
{ "client_office_overlay", L"|*[*office*]*|*[*офис*]*", LPGENW("office overlay"), IDI_OFFICE_OVERLAY, OVERLAYS_RESOURCE_CASE },
{ "client_mobile_overlay", L"|*[*mobile*]*|*[*pda*]*", LPGENW("mobile overlay"), IDI_MOBILE_OVERLAY, OVERLAYS_RESOURCE_CASE },
{ "client_home_overlay", L"|*[*home*]*|*[*дом*]*|*[*хоме*]*", LPGENW("home overlay"), IDI_HOME_OVERLAY, OVERLAYS_RESOURCE_CASE },
{ "client_work_overlay", L"|*[*work*]*|*wrk*"
L"|*[*работа*]*|*ворк*", LPGENW("work overlay"), IDI_WORK_OVERLAY, OVERLAYS_RESOURCE_CASE },
{ "client_note_overlay", L"|*[*note*]*|*[*laptop*]*"
L"|*[*нетбу*]*|*[*ноут*]*|*[*ноте*]*"
L"|*[*кирпич*]*|*[*portable*]*"
L"|*[*flash*]*|*[*usb*]*", LPGENW("notebook overlay"), IDI_NOTEBOOK_OVERLAY, OVERLAYS_RESOURCE_CASE },
// {"client_MirNG_09_over", L"*Miranda*NG*\?.\?\?.9.*", L"Miranda NG v0.9 #2 overlay", IDI_MIRANDA_NG_V9, MIRANDA_VERSION_CASE },
// {"client_MirNG_08_over", L"*Miranda*NG*\?.\?\?.8.*", L"Miranda NG v0.8 #2 overlay", IDI_MIRANDA_NG_V8, MIRANDA_VERSION_CASE },
// {"client_MirNG_07_over", L"*Miranda*NG*\?.\?\?.7.*", L"Miranda NG v0.7 #2 overlay", IDI_MIRANDA_NG_V7, MIRANDA_VERSION_CASE },
{ "client_MirNG_06_over", L"*Miranda*NG*\?.\?\?.6.*", LPGENW("Miranda NG v0.6 #2 overlay"), IDI_MIRANDA_NG_V6, MIRANDA_VERSION_CASE },
{ "client_MirNG_05_over", L"*Miranda*NG*\?.\?\?.5.*", LPGENW("Miranda NG v0.5 #2 overlay"), IDI_MIRANDA_NG_V5, MIRANDA_VERSION_CASE },
{ "client_MirNG_04_over", L"*Miranda*NG*\?.\?\?.4.*", LPGENW("Miranda NG v0.4 #2 overlay"), IDI_MIRANDA_NG_V4, MIRANDA_VERSION_CASE },
{ "client_MirNG_03_over", L"*Miranda*NG*\?.\?\?.3.*", LPGENW("Miranda NG v0.3 #2 overlay"), IDI_MIRANDA_NG_V3, MIRANDA_VERSION_CASE },
{ "client_MirNG_02_over", L"*Miranda*NG*\?.\?\?.2.*", LPGENW("Miranda NG v0.2 #2 overlay"), IDI_MIRANDA_NG_V2, MIRANDA_VERSION_CASE },
{ "client_MirNG_01_over", L"*Miranda*NG*\?.\?\?.1.*", LPGENW("Miranda NG v0.1 #2 overlay"), IDI_MIRANDA_NG_V1, MIRANDA_VERSION_CASE },
{ "client_MirIM_010_over", L"*Miranda*0.10.*", LPGENW("Miranda IM v0.10 #2 overlay"), IDI_MIRANDA_IM_V10, MIRANDA_VERSION_CASE },
{ "client_MirIM_09_over", L"*Miranda*0.9.*", LPGENW("Miranda IM v0.9 #2 overlay"), IDI_MIRANDA_IM_V9, MIRANDA_VERSION_CASE },
{ "client_MirIM_08_over", L"*Miranda*0.8.*", LPGENW("Miranda IM v0.8 #2 overlay"), IDI_MIRANDA_IM_V8, MIRANDA_VERSION_CASE },
{ "client_MirIM_07_over", L"*Miranda*0.7.*", LPGENW("Miranda IM v0.7 #2 overlay"), IDI_MIRANDA_IM_V7, MIRANDA_VERSION_CASE },
{ "client_MirIM_06_over", L"*Miranda*0.6.*", LPGENW("Miranda IM v0.6 #2 overlay"), IDI_MIRANDA_IM_V6, MIRANDA_VERSION_CASE },
{ "client_MirIM_05_over", L"*Miranda*0.5.*", LPGENW("Miranda IM v0.5 #2 overlay"), IDI_MIRANDA_IM_V5, MIRANDA_VERSION_CASE },
{ "client_MirIM_04_over", L"*Miranda*0.4.*", LPGENW("Miranda IM v0.4 #2 overlay"), IDI_MIRANDA_IM_V4, MIRANDA_VERSION_CASE },
};
int DEFAULT_KN_FP_OVERLAYS2_COUNT = _countof(def_kn_fp_overlays2_mask);
//#########################################################################################################################################################################
//#########################################################################################################################################################################
//############################## OVERLAYS LAYER #3 ####################################################################################################################
//#########################################################################################################################################################################
KN_FP_MASK def_kn_fp_overlays3_mask[] =
{// {"Client_IconName", L"|^*Mask*|*names*", L"Icon caption", IDI_RESOURCE_ID, CLIENT_CASE, OVERLAY? },
{ "client_platform_x64", L"|*x64*|*64*bit*", LPGENW("x64 overlay"), IDI_PLATFORM_X64, OVERLAYS_PLATFORM_CASE },
{ "client_platform_x32", L"|*x32*|*32*bit*|*x86*", LPGENW("x32 overlay"), IDI_PLATFORM_X32, OVERLAYS_PLATFORM_CASE },
{ "client_Unicode", L"*unicode*", LPGENW("Unicode overlay"), IDI_UNICODE_CLIENT, OVERLAYS_UNICODE_CASE },
};
int DEFAULT_KN_FP_OVERLAYS3_COUNT = _countof(def_kn_fp_overlays3_mask);
//#########################################################################################################################################################################
//#########################################################################################################################################################################
//############################## OVERLAYS LAYER #4 ####################################################################################################################
//#########################################################################################################################################################################
KN_FP_MASK def_kn_fp_overlays4_mask[] =
{// {"Client_IconName", L"|^*Mask*|*names*", L"Icon caption", IDI_RESOURCE_ID, CLIENT_CASE, OVERLAY? },
{ "client_NewGPG_over", L"*New*GPG*", LPGENW("NewGPG overlay"), IDI_NEWGPG_OVERLAY, OVERLAYS_SECURITY_CASE },
{ "client_MirOTR_over", L"*Mir*OTR*", LPGENW("MirOTR overlay"), IDI_MIROTR_OVERLAY, OVERLAYS_SECURITY_CASE },
{ "client_SecureIM_over", L"*Secure*IM*", LPGENW("SecureIM overlay"), IDI_SECUREIM_OVERLAY, OVERLAYS_SECURITY_CASE },
};
int DEFAULT_KN_FP_OVERLAYS4_COUNT = _countof(def_kn_fp_overlays4_mask);
| {
"pile_set_name": "Github"
} |
data_base_url = 'https://raw.githubusercontent.com/jmcohen/taste/master/data/'
def get_favorites():
mldb.log('creating dataset')
mldb.perform('PUT', '/v1/datasets/rcp_raw', [], {
'type': 'text.csv.tabular',
'params': {
'limit': 1000,
'headers': ['user_id', 'recipe_id'],
'dataFileUrl': data_base_url + 'favorites.csv'}})
mldb.log('pivoting')
mldb.perform('PUT', '/v1/procedures/rcp_import', [], {
"type": "transform",
"params": {
"inputData": "select pivot(recipe_id, 1) as * named user_id from rcp_raw group by user_id",
"outputDataset": "recipes",
"runOnCreation": True
}
})
def do_svd():
mldb.log('svd')
mldb.perform('PUT', '/v1/procedures/rcp_do_svd', [], {
"type" : "svd.train",
"params" : {
"trainingData": "select * from recipes",
"columnOutputDataset" : "rcp_svd_embedding_raw",
"runOnCreation": True
}
})
mldb.log('clean_svd')
mldb.perform('PUT', '/v1/procedures/rcp_clean_svd', [], {
'type': 'transform',
'params': {
'inputData': '''select * named jseval(
'return s.substr(0, s.indexOf("|"))',
's', rowName()) from rcp_svd_embedding_raw''',
'outputDataset': 'rcp_svd_embedding',
'runOnCreation': True}})
def do_kmeans():
mldb.log('kmeans')
mldb.perform('PUT', '/v1/procedures/rcp_kmeans', [], {
"type" : "kmeans.train",
"params" : {
"trainingData" : "select * from rcp_svd_embedding",
"outputDataset" : "rcp_kmeans_clusters",
"centroidsDataset" : "rcp_kmeans_centroids",
"numClusters" : 20,
"runOnCreation": True
}
})
def get_recipes():
mldb.log('creating name dataset')
mldb.perform('PUT', '/v1/datasets/rcp_names_raw', [], {
'type': 'text.line',
'params': {
'dataFileUrl': data_base_url + 'recipes.csv'}})
mldb.log('transforming name dataset')
mldb.perform('PUT', '/v1/procedures/rcp_names_import', [], {
'type': 'transform',
'params': {
'inputData': '''select
jseval('return s.substr(s.indexOf(",")+1).toLowerCase();',
's', regex_replace(lineText, '"', '"')) as name
named implicit_cast(rowName()) - 1
from rcp_names_raw''',
'outputDataset': 'rcp_names',
'runOnCreation': True}})
def do_tfidf():
mldb.perform('PUT', '/v1/functions/stem', [], {
'type': 'stemmer',
'params': {
'language': 'english'}})
q = '''
SELECT sum(stem({words: {tokenize(name, {splitChars:' '}) as *}})[words]) as *
NAMED cluster
FROM merge(rcp_names, rcp_kmeans_clusters)
GROUP BY cluster
'''
mldb.log('this query wont run!')
mldb.perform('PUT', '/v1/procedures/make_word_cluster', [], {
'type': 'transform',
'params': {
'inputData': q,
'outputDataset': 'rcp_cluster_word',
'runOnCreation': True}})
get_favorites()
get_recipes()
do_svd()
do_kmeans()
do_tfidf()
| {
"pile_set_name": "Github"
} |
#ifndef _CFIFO_H_
#define _CFIFO_H_
#ifdef __cplusplus
extern "C" {
#endif
void *new_fifo();
void delete_fifo(void *);
char *fifo_pop(void *);
void fifo_push(void *, char *);
int fifo_size(void *);
#ifdef __cplusplus
}
#endif
#endif
| {
"pile_set_name": "Github"
} |
'use strict';
var isPlainArray = require('../../is-plain-array')
, callable = require('../../../object/valid-callable')
, isArray = Array.isArray, map = Array.prototype.map
, forEach = Array.prototype.forEach, call = Function.prototype.call;
module.exports = function (callbackFn/*, thisArg*/) {
var result, thisArg;
if (!this || !isArray(this) || isPlainArray(this)) {
return map.apply(this, arguments);
}
callable(callbackFn);
thisArg = arguments[1];
result = new this.constructor(this.length);
forEach.call(this, function (val, i, self) {
result[i] = call.call(callbackFn, thisArg, val, i, self);
});
return result;
};
| {
"pile_set_name": "Github"
} |
# A module to collect utility functions.
require 'English'
require 'puppet/util/monkey_patches'
require 'sync'
require 'tempfile'
require 'puppet/external/lock'
require 'monitor'
require 'puppet/util/execution_stub'
require 'uri'
module Puppet
# A command failed to execute.
require 'puppet/error'
class ExecutionFailure < Puppet::Error
end
module Util
require 'benchmark'
# These are all for backward compatibility -- these are methods that used
# to be in Puppet::Util but have been moved into external modules.
require 'puppet/util/posix'
extend Puppet::Util::POSIX
@@sync_objects = {}.extend MonitorMixin
def self.activerecord_version
if (defined?(::ActiveRecord) and defined?(::ActiveRecord::VERSION) and defined?(::ActiveRecord::VERSION::MAJOR) and defined?(::ActiveRecord::VERSION::MINOR))
([::ActiveRecord::VERSION::MAJOR, ::ActiveRecord::VERSION::MINOR].join('.').to_f)
else
0
end
end
def self.synchronize_on(x,type)
sync_object,users = 0,1
begin
@@sync_objects.synchronize {
(@@sync_objects[x] ||= [Sync.new,0])[users] += 1
}
@@sync_objects[x][sync_object].synchronize(type) { yield }
ensure
@@sync_objects.synchronize {
@@sync_objects.delete(x) unless (@@sync_objects[x][users] -= 1) > 0
}
end
end
# Change the process to a different user
def self.chuser
if group = Puppet[:group]
begin
Puppet::Util::SUIDManager.change_group(group, true)
rescue => detail
Puppet.warning "could not change to group #{group.inspect}: #{detail}"
$stderr.puts "could not change to group #{group.inspect}"
# Don't exit on failed group changes, since it's
# not fatal
#exit(74)
end
end
if user = Puppet[:user]
begin
Puppet::Util::SUIDManager.change_user(user, true)
rescue => detail
$stderr.puts "Could not change to user #{user}: #{detail}"
exit(74)
end
end
end
# Create instance methods for each of the log levels. This allows
# the messages to be a little richer. Most classes will be calling this
# method.
def self.logmethods(klass, useself = true)
Puppet::Util::Log.eachlevel { |level|
klass.send(:define_method, level, proc { |args|
args = args.join(" ") if args.is_a?(Array)
if useself
Puppet::Util::Log.create(
:level => level,
:source => self,
:message => args
)
else
Puppet::Util::Log.create(
:level => level,
:message => args
)
end
})
}
end
# Proxy a bunch of methods to another object.
def self.classproxy(klass, objmethod, *methods)
classobj = class << klass; self; end
methods.each do |method|
classobj.send(:define_method, method) do |*args|
obj = self.send(objmethod)
obj.send(method, *args)
end
end
end
# Proxy a bunch of methods to another object.
def self.proxy(klass, objmethod, *methods)
methods.each do |method|
klass.send(:define_method, method) do |*args|
obj = self.send(objmethod)
obj.send(method, *args)
end
end
end
# XXX this should all be done using puppet objects, not using
# normal mkdir
def self.recmkdir(dir,mode = 0755)
if FileTest.exist?(dir)
return false
else
tmp = dir.sub(/^\//,'')
path = [File::SEPARATOR]
tmp.split(File::SEPARATOR).each { |dir|
path.push dir
if ! FileTest.exist?(File.join(path))
Dir.mkdir(File.join(path), mode)
elsif FileTest.directory?(File.join(path))
next
else FileTest.exist?(File.join(path))
raise "Cannot create #{dir}: basedir #{File.join(path)} is a file"
end
}
return true
end
end
# Execute a given chunk of code with a new umask.
def self.withumask(mask)
cur = File.umask(mask)
begin
yield
ensure
File.umask(cur)
end
end
def benchmark(*args)
msg = args.pop
level = args.pop
object = nil
if args.empty?
if respond_to?(level)
object = self
else
object = Puppet
end
else
object = args.pop
end
raise Puppet::DevError, "Failed to provide level to :benchmark" unless level
unless level == :none or object.respond_to? level
raise Puppet::DevError, "Benchmarked object does not respond to #{level}"
end
# Only benchmark if our log level is high enough
if level != :none and Puppet::Util::Log.sendlevel?(level)
result = nil
seconds = Benchmark.realtime {
yield
}
object.send(level, msg + (" in %0.2f seconds" % seconds))
return seconds
else
yield
end
end
def which(bin)
if absolute_path?(bin)
return bin if FileTest.file? bin and FileTest.executable? bin
else
ENV['PATH'].split(File::PATH_SEPARATOR).each do |dir|
dest = File.expand_path(File.join(dir, bin))
if Puppet.features.microsoft_windows? && File.extname(dest).empty?
exts = ENV['PATHEXT']
exts = exts ? exts.split(File::PATH_SEPARATOR) : %w[.COM .EXE .BAT .CMD]
exts.each do |ext|
destext = File.expand_path(dest + ext)
return destext if FileTest.file? destext and FileTest.executable? destext
end
end
return dest if FileTest.file? dest and FileTest.executable? dest
end
end
nil
end
module_function :which
# Determine in a platform-specific way whether a path is absolute. This
# defaults to the local platform if none is specified.
def absolute_path?(path, platform=nil)
# Escape once for the string literal, and once for the regex.
slash = '[\\\\/]'
name = '[^\\\\/]+'
regexes = {
:windows => %r!^(([A-Z]:#{slash})|(#{slash}#{slash}#{name}#{slash}#{name})|(#{slash}#{slash}\?#{slash}#{name}))!i,
:posix => %r!^/!,
}
require 'puppet'
platform ||= Puppet.features.microsoft_windows? ? :windows : :posix
!! (path =~ regexes[platform])
end
module_function :absolute_path?
# Convert a path to a file URI
def path_to_uri(path)
return unless path
params = { :scheme => 'file' }
if Puppet.features.microsoft_windows?
path = path.gsub(/\\/, '/')
if unc = /^\/\/([^\/]+)(\/[^\/]+)/.match(path)
params[:host] = unc[1]
path = unc[2]
elsif path =~ /^[a-z]:\//i
path = '/' + path
end
end
params[:path] = URI.escape(path)
begin
URI::Generic.build(params)
rescue => detail
raise Puppet::Error, "Failed to convert '#{path}' to URI: #{detail}"
end
end
module_function :path_to_uri
# Get the path component of a URI
def uri_to_path(uri)
return unless uri.is_a?(URI)
path = URI.unescape(uri.path)
if Puppet.features.microsoft_windows? and uri.scheme == 'file'
if uri.host
path = "//#{uri.host}" + path # UNC
else
path.sub!(/^\//, '')
end
end
path
end
module_function :uri_to_path
# Execute the provided command in a pipe, yielding the pipe object.
def execpipe(command, failonfail = true)
if respond_to? :debug
debug "Executing '#{command}'"
else
Puppet.debug "Executing '#{command}'"
end
command_str = command.respond_to?(:join) ? command.join('') : command
output = open("| #{command_str} 2>&1") do |pipe|
yield pipe
end
if failonfail
unless $CHILD_STATUS == 0
raise ExecutionFailure, output
end
end
output
end
def execfail(command, exception)
output = execute(command)
return output
rescue ExecutionFailure
raise exception, output
end
def execute_posix(command, arguments, stdin, stdout, stderr)
child_pid = Kernel.fork do
# We can't just call Array(command), and rely on it returning
# things like ['foo'], when passed ['foo'], because
# Array(command) will call command.to_a internally, which when
# given a string can end up doing Very Bad Things(TM), such as
# turning "/tmp/foo;\r\n /bin/echo" into ["/tmp/foo;\r\n", " /bin/echo"]
command = [command].flatten
Process.setsid
begin
$stdin.reopen(stdin)
$stdout.reopen(stdout)
$stderr.reopen(stderr)
3.upto(256){|fd| IO::new(fd).close rescue nil}
Puppet::Util::SUIDManager.change_group(arguments[:gid], true) if arguments[:gid]
Puppet::Util::SUIDManager.change_user(arguments[:uid], true) if arguments[:uid]
ENV['LANG'] = ENV['LC_ALL'] = ENV['LC_MESSAGES'] = ENV['LANGUAGE'] = 'C'
Kernel.exec(*command)
rescue => detail
puts detail.to_s
exit!(1)
end
end
child_pid
end
module_function :execute_posix
def execute_windows(command, arguments, stdin, stdout, stderr)
command = command.map do |part|
part.include?(' ') ? %Q["#{part.gsub(/"/, '\"')}"] : part
end.join(" ") if command.is_a?(Array)
process_info = Process.create( :command_line => command, :startup_info => {:stdin => stdin, :stdout => stdout, :stderr => stderr} )
process_info.process_id
end
module_function :execute_windows
# Execute the desired command, and return the status and output.
# def execute(command, failonfail = true, uid = nil, gid = nil)
# :combine sets whether or not to combine stdout/stderr in the output
# :stdinfile sets a file that can be used for stdin. Passing a string
# for stdin is not currently supported.
def execute(command, arguments = {:failonfail => true, :combine => true})
if command.is_a?(Array)
command = command.flatten.map(&:to_s)
str = command.join(" ")
elsif command.is_a?(String)
str = command
end
if respond_to? :debug
debug "Executing '#{str}'"
else
Puppet.debug "Executing '#{str}'"
end
null_file = Puppet.features.microsoft_windows? ? 'NUL' : '/dev/null'
stdin = File.open(arguments[:stdinfile] || null_file, 'r')
stdout = arguments[:squelch] ? File.open(null_file, 'w') : Tempfile.new('puppet')
stderr = arguments[:combine] ? stdout : File.open(null_file, 'w')
exec_args = [command, arguments, stdin, stdout, stderr]
if execution_stub = Puppet::Util::ExecutionStub.current_value
return execution_stub.call(*exec_args)
elsif Puppet.features.posix?
child_pid = execute_posix(*exec_args)
exit_status = Process.waitpid2(child_pid).last.exitstatus
elsif Puppet.features.microsoft_windows?
child_pid = execute_windows(*exec_args)
exit_status = Process.waitpid2(child_pid).last
# $CHILD_STATUS is not set when calling win32/process Process.create
# and since it's read-only, we can't set it. But we can execute a
# a shell that simply returns the desired exit status, which has the
# desired effect.
%x{#{ENV['COMSPEC']} /c exit #{exit_status}}
end
[stdin, stdout, stderr].each {|io| io.close rescue nil}
# read output in if required
unless arguments[:squelch]
output = wait_for_output(stdout)
Puppet.warning "Could not get output" unless output
end
if arguments[:failonfail] and exit_status != 0
raise ExecutionFailure, "Execution of '#{str}' returned #{exit_status}: #{output}"
end
output
end
module_function :execute
def wait_for_output(stdout)
# Make sure the file's actually been written. This is basically a race
# condition, and is probably a horrible way to handle it, but, well, oh
# well.
2.times do |try|
if File.exists?(stdout.path)
output = stdout.open.read
stdout.close(true)
return output
else
time_to_sleep = try / 2.0
Puppet.warning "Waiting for output; will sleep #{time_to_sleep} seconds"
sleep(time_to_sleep)
end
end
nil
end
module_function :wait_for_output
# Create an exclusive lock.
def threadlock(resource, type = Sync::EX)
Puppet::Util.synchronize_on(resource,type) { yield }
end
# Because some modules provide their own version of this method.
alias util_execute execute
module_function :benchmark
def memory
unless defined?(@pmap)
@pmap = which('pmap')
end
if @pmap
%x{#{@pmap} #{Process.pid}| grep total}.chomp.sub(/^\s*total\s+/, '').sub(/K$/, '').to_i
else
0
end
end
def symbolize(value)
if value.respond_to? :intern
value.intern
else
value
end
end
def symbolizehash(hash)
newhash = {}
hash.each do |name, val|
if name.is_a? String
newhash[name.intern] = val
else
newhash[name] = val
end
end
end
def symbolizehash!(hash)
hash.each do |name, val|
if name.is_a? String
hash[name.intern] = val
hash.delete(name)
end
end
hash
end
module_function :symbolize, :symbolizehash, :symbolizehash!
# Just benchmark, with no logging.
def thinmark
seconds = Benchmark.realtime {
yield
}
seconds
end
module_function :memory, :thinmark
def secure_open(file,must_be_w,&block)
raise Puppet::DevError,"secure_open only works with mode 'w'" unless must_be_w == 'w'
raise Puppet::DevError,"secure_open only requires a block" unless block_given?
Puppet.warning "#{file} was a symlink to #{File.readlink(file)}" if File.symlink?(file)
if File.exists?(file) or File.symlink?(file)
wait = File.symlink?(file) ? 5.0 : 0.1
File.delete(file)
sleep wait # give it a chance to reappear, just in case someone is actively trying something.
end
begin
File.open(file,File::CREAT|File::EXCL|File::TRUNC|File::WRONLY,&block)
rescue Errno::EEXIST
desc = File.symlink?(file) ? "symlink to #{File.readlink(file)}" : File.stat(file).ftype
puts "Warning: #{file} was apparently created by another process (as"
puts "a #{desc}) as soon as it was deleted by this process. Someone may be trying"
puts "to do something objectionable (such as tricking you into overwriting system"
puts "files if you are running as root)."
raise
end
end
module_function :secure_open
# Because IO#binread is only available in 1.9
def binread(file)
File.open(file, 'rb') { |f| f.read }
end
module_function :binread
end
end
require 'puppet/util/errors'
require 'puppet/util/methodhelper'
require 'puppet/util/metaid'
require 'puppet/util/classgen'
require 'puppet/util/docs'
require 'puppet/util/execution'
require 'puppet/util/logging'
require 'puppet/util/package'
require 'puppet/util/warnings'
| {
"pile_set_name": "Github"
} |
"""
WSGI config for CrazyEye project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CrazyEye.settings")
application = get_wsgi_application()
| {
"pile_set_name": "Github"
} |
{:act-103
{:args [42.445389 -71.227733 3.0 260],
:argsmap {"alt" 3.0, "lat" 42.445389, "lon" -71.227733, "yaw" 260},
:command "location",
:constraints #{:tc-98},
:controllable false,
:cost 0,
:display-args [42.445389 -71.227733 3.0 260],
:display-name "Location",
:end-node :node-114,
:htn-node :hem-85,
:name "Location(42.445389 -71.227733 3.0 260)",
:plant-id "qc3",
:plant-part "pp3",
:reward 0,
:tpn-type :activity,
:uid :act-103},
:act-113
{:args [42.445327 -71.227784 4.0 350],
:argsmap {"alt" 4.0, "lat" 42.445327, "lon" -71.227784, "yaw" 350},
:command "location",
:constraints #{:tc-108},
:controllable false,
:cost 0,
:display-args [42.445327 -71.227784 4.0 350],
:display-name "Location",
:end-node :node-124,
:htn-node :hem-87,
:name "Location(42.445327 -71.227784 4.0 350)",
:plant-id "qc3",
:plant-part "pp3",
:reward 0,
:tpn-type :activity,
:uid :act-113},
:act-123
{:args [42.44537 -71.227891 1.0 80],
:argsmap {"alt" 1.0, "lat" 42.44537, "lon" -71.227891, "yaw" 80},
:command "location",
:constraints #{:tc-118},
:controllable false,
:cost 0,
:display-args [42.44537 -71.227891 1.0 80],
:display-name "Location",
:end-node :node-134,
:htn-node :hem-89,
:name "Location(42.44537 -71.227891 1.0 80)",
:plant-id "qc3",
:plant-part "pp3",
:reward 0,
:tpn-type :activity,
:uid :act-123},
:act-13
{:args [42.44537 -71.227895 1.0 80],
:argsmap {"alt" 1.0, "lat" 42.44537, "lon" -71.227895, "yaw" 80},
:command "location",
:constraints #{:tc-12},
:controllable false,
:cost 0,
:display-args [42.44537 -71.227895 1.0 80],
:display-name "Location",
:end-node :node-19,
:htn-node :hem-58,
:name "Location(42.44537 -71.227895 1.0 80)",
:plant-id "qc1",
:plant-interface "RMQ",
:plant-part "pp1",
:reward 0,
:tpn-type :activity,
:uid :act-13},
:act-133
{:args [42.445435 -71.227842 2.0 170],
:argsmap {"alt" 2.0, "lat" 42.445435, "lon" -71.227842, "yaw" 170},
:command "location",
:constraints #{:tc-128},
:controllable false,
:cost 0,
:display-args [42.445435 -71.227842 2.0 170],
:display-name "Location",
:end-node :node-145,
:htn-node :hem-91,
:name "Location(42.445435 -71.227842 2.0 170)",
:plant-id "qc3",
:plant-part "pp3",
:reward 0,
:tpn-type :activity,
:uid :act-133},
:act-144
{:args [42.445389 -71.227733 3.0 260],
:argsmap {"alt" 3.0, "lat" 42.445389, "lon" -71.227733, "yaw" 260},
:command "location",
:constraints #{:tc-138},
:controllable false,
:cost 0,
:display-args [42.445389 -71.227733 3.0 260],
:display-name "Location",
:end-node :node-92,
:htn-node :hem-93,
:name "Location(42.445389 -71.227733 3.0 260)",
:plant-id "qc3",
:plant-part "pp3",
:reward 0,
:tpn-type :activity,
:uid :act-144},
:act-18
{:args [42.445435 -71.227846 2.0 170],
:argsmap {"alt" 2.0, "lat" 42.445435, "lon" -71.227846, "yaw" 170},
:command "location",
:constraints #{:tc-17},
:controllable false,
:cost 0,
:display-args [42.445435 -71.227846 2.0 170],
:display-name "Location",
:end-node :node-24,
:htn-node :hem-58,
:name "Location(42.445435 -71.227846 2.0 170)",
:plant-id "qc1",
:plant-interface "RMQ",
:plant-part "pp1",
:reward 0,
:tpn-type :activity,
:uid :act-18},
:act-23
{:args [42.445389 -71.227737 3.0 260],
:argsmap {"alt" 3.0, "lat" 42.445389, "lon" -71.227737, "yaw" 260},
:command "location",
:constraints #{:tc-22},
:controllable false,
:cost 0,
:display-args [42.445389 -71.227737 3.0 260],
:display-name "Location",
:end-node :node-29,
:htn-node :hem-58,
:name "Location(42.445389 -71.227737 3.0 260)",
:plant-id "qc1",
:plant-interface "RMQ",
:plant-part "pp1",
:reward 0,
:tpn-type :activity,
:uid :act-23},
:act-28
{:args [42.445327 -71.227788 4.0 350],
:argsmap {"alt" 4.0, "lat" 42.445327, "lon" -71.227788, "yaw" 350},
:command "location",
:constraints #{:tc-27},
:controllable false,
:cost 0,
:display-args [42.445327 -71.227788 4.0 350],
:display-name "Location",
:end-node :node-34,
:htn-node :hem-58,
:name "Location(42.445327 -71.227788 4.0 350)",
:plant-id "qc1",
:plant-interface "RMQ",
:plant-part "pp1",
:reward 0,
:tpn-type :activity,
:uid :act-28},
:act-33
{:args [42.44537 -71.227899 1.0 80],
:argsmap {"alt" 1.0, "lat" 42.44537, "lon" -71.227899, "yaw" 80},
:command "location",
:constraints #{:tc-32},
:controllable false,
:cost 0,
:display-args [42.44537 -71.227899 1.0 80],
:display-name "Location",
:end-node :node-4,
:htn-node :hem-58,
:name "Location(42.44537 -71.227899 1.0 80)",
:plant-id "qc1",
:plant-interface "RMQ",
:plant-part "pp1",
:reward 0,
:tpn-type :activity,
:uid :act-33},
:act-47
{:args [42.445435 -71.227842 2.0 170],
:argsmap {"alt" 2.0, "lat" 42.445435, "lon" -71.227842, "yaw" 170},
:command "location",
:constraints #{:tc-42},
:controllable false,
:cost 0,
:display-args [42.445435 -71.227842 2.0 170],
:display-name "Location",
:end-node :node-58,
:htn-node :hem-68,
:name "Location(42.445435 -71.227842 2.0 170)",
:plant-id "qc2",
:plant-interface "ZMQ",
:plant-part "pp2",
:reward 0,
:tpn-type :activity,
:uid :act-47},
:act-57
{:args [42.445389 -71.227733 3.0 260],
:argsmap {"alt" 3.0, "lat" 42.445389, "lon" -71.227733, "yaw" 260},
:command "location",
:constraints #{:tc-52},
:controllable false,
:cost 0,
:display-args [42.445389 -71.227733 3.0 260],
:display-name "Location",
:end-node :node-68,
:htn-node :hem-70,
:name "Location(42.445389 -71.227733 3.0 260)",
:plant-id "qc2",
:plant-interface "ZMQ",
:plant-part "pp2",
:reward 0,
:tpn-type :activity,
:uid :act-57},
:act-67
{:args [42.445327 -71.227784 4.0 350],
:argsmap {"alt" 4.0, "lat" 42.445327, "lon" -71.227784, "yaw" 350},
:command "location",
:constraints #{:tc-62},
:controllable false,
:cost 0,
:display-args [42.445327 -71.227784 4.0 350],
:display-name "Location",
:end-node :node-78,
:htn-node :hem-72,
:name "Location(42.445327 -71.227784 4.0 350)",
:plant-id "qc2",
:plant-interface "ZMQ",
:plant-part "pp2",
:reward 0,
:tpn-type :activity,
:uid :act-67},
:act-77
{:args [42.44537 -71.227891 1.0 80],
:argsmap {"alt" 1.0, "lat" 42.44537, "lon" -71.227891, "yaw" 80},
:command "location",
:constraints #{:tc-72},
:controllable false,
:cost 0,
:display-args [42.44537 -71.227891 1.0 80],
:display-name "Location",
:end-node :node-89,
:htn-node :hem-74,
:name "Location(42.44537 -71.227891 1.0 80)",
:plant-id "qc2",
:plant-interface "ZMQ",
:plant-part "pp2",
:reward 0,
:tpn-type :activity,
:uid :act-77},
:act-88
{:args [42.445435 -71.227842 2.0 170],
:argsmap {"alt" 2.0, "lat" 42.445435, "lon" -71.227842, "yaw" 170},
:command "location",
:constraints #{:tc-82},
:controllable false,
:cost 0,
:display-args [42.445435 -71.227842 2.0 170],
:display-name "Location",
:end-node :node-37,
:htn-node :hem-76,
:name "Location(42.445435 -71.227842 2.0 170)",
:plant-id "qc2",
:plant-interface "ZMQ",
:plant-part "pp2",
:reward 0,
:tpn-type :activity,
:uid :act-88},
:na-10
{:constraints #{},
:end-node :node-6,
:tpn-type :null-activity,
:uid :na-10},
:na-105
{:constraints #{},
:end-node :node-104,
:tpn-type :null-activity,
:uid :na-105},
:na-15
{:constraints #{},
:end-node :node-14,
:tpn-type :null-activity,
:uid :na-15},
:na-40
{:constraints #{},
:end-node :node-6,
:tpn-type :null-activity,
:uid :na-40},
:na-49
{:constraints #{},
:end-node :node-48,
:tpn-type :null-activity,
:uid :na-49},
:na-96
{:constraints #{},
:end-node :node-6,
:tpn-type :null-activity,
:uid :na-96},
:net-3
{:begin-node :node-7,
:end-node :node-6,
:tpn-type :network,
:uid :net-3},
:network-id :net-3,
:node-104
{:activities #{:act-103},
:constraints #{},
:end-node :node-92,
:htn-node :hem-82,
:incidence-set #{:na-105},
:tpn-type :state,
:uid :node-104},
:node-114
{:activities #{:act-113},
:constraints #{},
:htn-node :hem-87,
:incidence-set #{:act-103},
:tpn-type :state,
:uid :node-114},
:node-124
{:activities #{:act-123},
:constraints #{},
:htn-node :hem-89,
:incidence-set #{:act-113},
:tpn-type :state,
:uid :node-124},
:node-134
{:activities #{:act-133},
:constraints #{},
:htn-node :hem-91,
:incidence-set #{:act-123},
:tpn-type :state,
:uid :node-134},
:node-14
{:activities #{:act-13},
:constraints #{},
:end-node :node-4,
:htn-node :hem-58,
:incidence-set #{:na-15},
:tpn-type :state,
:uid :node-14},
:node-145
{:activities #{:act-144},
:constraints #{},
:htn-node :hem-93,
:incidence-set #{:act-133},
:tpn-type :state,
:uid :node-145},
:node-19
{:activities #{:act-18},
:constraints #{},
:htn-node :hem-58,
:incidence-set #{:act-13},
:tpn-type :state,
:uid :node-19},
:node-24
{:activities #{:act-23},
:constraints #{},
:htn-node :hem-58,
:incidence-set #{:act-18},
:tpn-type :state,
:uid :node-24},
:node-29
{:activities #{:act-28},
:constraints #{},
:htn-node :hem-58,
:incidence-set #{:act-23},
:tpn-type :state,
:uid :node-29},
:node-34
{:activities #{:act-33},
:constraints #{},
:htn-node :hem-58,
:incidence-set #{:act-28},
:tpn-type :state,
:uid :node-34},
:node-37
{:activities #{:na-40},
:constraints #{},
:incidence-set #{:act-88},
:tpn-type :state,
:uid :node-37},
:node-4
{:activities #{:na-10},
:constraints #{},
:incidence-set #{:act-33},
:tpn-type :state,
:uid :node-4},
:node-48
{:activities #{:act-47},
:constraints #{},
:end-node :node-37,
:htn-node :hem-65,
:incidence-set #{:na-49},
:tpn-type :state,
:uid :node-48},
:node-58
{:activities #{:act-57},
:constraints #{},
:htn-node :hem-70,
:incidence-set #{:act-47},
:tpn-type :state,
:uid :node-58},
:node-6
{:activities #{},
:constraints #{},
:incidence-set #{:na-96 :na-40 :na-10},
:tpn-type :p-end,
:uid :node-6},
:node-68
{:activities #{:act-67},
:constraints #{},
:htn-node :hem-72,
:incidence-set #{:act-57},
:tpn-type :state,
:uid :node-68},
:node-7
{:activities #{:na-105 :na-15 :na-49},
:constraints #{},
:end-node :node-6,
:htn-node :hem-52,
:incidence-set #{},
:tpn-type :p-begin,
:uid :node-7},
:node-78
{:activities #{:act-77},
:constraints #{},
:htn-node :hem-74,
:incidence-set #{:act-67},
:tpn-type :state,
:uid :node-78},
:node-89
{:activities #{:act-88},
:constraints #{},
:htn-node :hem-76,
:incidence-set #{:act-77},
:tpn-type :state,
:uid :node-89},
:node-92
{:activities #{:na-96},
:constraints #{},
:incidence-set #{:act-144},
:tpn-type :state,
:uid :node-92},
:tc-101
{:end-node :node-114,
:tpn-type :temporal-constraint,
:uid :tc-101,
:value [13 50]},
:tc-108
{:end-node :node-124,
:tpn-type :temporal-constraint,
:uid :tc-108,
:value [14 50]},
:tc-111
{:end-node :node-124,
:tpn-type :temporal-constraint,
:uid :tc-111,
:value [14 50]},
:tc-118
{:end-node :node-134,
:tpn-type :temporal-constraint,
:uid :tc-118,
:value [11 50]},
:tc-12
{:end-node :node-19,
:tpn-type :temporal-constraint,
:uid :tc-12,
:value [5 20]},
:tc-121
{:end-node :node-134,
:tpn-type :temporal-constraint,
:uid :tc-121,
:value [11 50]},
:tc-128
{:end-node :node-145,
:tpn-type :temporal-constraint,
:uid :tc-128,
:value [12 50]},
:tc-131
{:end-node :node-145,
:tpn-type :temporal-constraint,
:uid :tc-131,
:value [12 50]},
:tc-138
{:end-node :node-92,
:tpn-type :temporal-constraint,
:uid :tc-138,
:value [13 50]},
:tc-142
{:end-node :node-92,
:tpn-type :temporal-constraint,
:uid :tc-142,
:value [13 50]},
:tc-17
{:end-node :node-24,
:tpn-type :temporal-constraint,
:uid :tc-17,
:value [5 20]},
:tc-22
{:end-node :node-29,
:tpn-type :temporal-constraint,
:uid :tc-22,
:value [5 20]},
:tc-27
{:end-node :node-34,
:tpn-type :temporal-constraint,
:uid :tc-27,
:value [5 20]},
:tc-32
{:end-node :node-4,
:tpn-type :temporal-constraint,
:uid :tc-32,
:value [5 20]},
:tc-42
{:end-node :node-58,
:tpn-type :temporal-constraint,
:uid :tc-42,
:value [12 50]},
:tc-45
{:end-node :node-58,
:tpn-type :temporal-constraint,
:uid :tc-45,
:value [12 50]},
:tc-52
{:end-node :node-68,
:tpn-type :temporal-constraint,
:uid :tc-52,
:value [13 50]},
:tc-55
{:end-node :node-68,
:tpn-type :temporal-constraint,
:uid :tc-55,
:value [13 50]},
:tc-62
{:end-node :node-78,
:tpn-type :temporal-constraint,
:uid :tc-62,
:value [14 50]},
:tc-65
{:end-node :node-78,
:tpn-type :temporal-constraint,
:uid :tc-65,
:value [14 50]},
:tc-72
{:end-node :node-89,
:tpn-type :temporal-constraint,
:uid :tc-72,
:value [11 50]},
:tc-75
{:end-node :node-89,
:tpn-type :temporal-constraint,
:uid :tc-75,
:value [11 50]},
:tc-82
{:end-node :node-37,
:tpn-type :temporal-constraint,
:uid :tc-82,
:value [12 50]},
:tc-86
{:end-node :node-37,
:tpn-type :temporal-constraint,
:uid :tc-86,
:value [12 50]},
:tc-98
{:end-node :node-114,
:tpn-type :temporal-constraint,
:uid :tc-98,
:value [13 50]}}
| {
"pile_set_name": "Github"
} |
//--------------------------------------------------------------------------------------------------
// Copyright (c) YugaByte, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations
// under the License.
//
//--------------------------------------------------------------------------------------------------
#include <boost/algorithm/string.hpp>
#include "yb/master/catalog_manager.h"
#include "yb/master/master.h"
#include "yb/master/master_defaults.h"
#include "yb/yql/cql/ql/test/ql-test-base.h"
#include "yb/common/ql_value.h"
DECLARE_int32(TEST_simulate_slow_table_create_secs);
DECLARE_bool(master_enable_metrics_snapshotter);
DECLARE_bool(tserver_enable_metrics_snapshotter);
DECLARE_int32(metrics_snapshotter_interval_ms);
DECLARE_string(metrics_snapshotter_table_metrics_whitelist);
DECLARE_string(metrics_snapshotter_tserver_metrics_whitelist);
namespace yb {
namespace master {
class CatalogManager;
class Master;
}
namespace ql {
#define EXEC_DUPLICATE_OBJECT_CREATE_STMT(stmt) \
EXEC_INVALID_STMT_WITH_ERROR(stmt, "Duplicate Object. Object")
class TestQLCreateTable : public QLTestBase {
public:
TestQLCreateTable() : QLTestBase() {
}
inline const string CreateStmt(string params) {
return "CREATE TABLE " + params;
}
inline const string CreateIfNotExistsStmt(string params) {
return "CREATE TABLE IF NOT EXISTS " + params;
}
};
TEST_F(TestQLCreateTable, TestQLCreateTableSimple) {
// Init the simulated cluster.
ASSERT_NO_FATALS(CreateSimulatedCluster());
// Get an available processor.
TestQLProcessor *processor = GetQLProcessor();
const string table1 = "human_resource1(id int, name varchar, primary key(id));";
const string table2 = "human_resource2(id int primary key, name varchar);";
const string table3 = "human_resource3(id int, name varchar primary key);";
const string table4 = "human_resource4(id int, name varchar, primary key(id, name));";
const string table5 = "human_resource5(id int, name varchar, primary key((id), name));";
const string table6 =
"human_resource6(id int, name varchar, salary int, primary key((id, name), salary));";
const string table7 = "human_resource7(id int, name varchar, primary key(id));";
const string table8 = "human_resource8(id int primary key, name varchar);";
const string table9 = "human_resource9(id int, name varchar primary key);";
const string table10 = "human_resource10(id int, name varchar, primary key(id, name));";
const string table11 = "human_resource11(id int, name varchar, primary key((id), name));";
const string table12 =
"human_resource12(id int, name varchar, salary int, primary key((id, name), salary));";
// Define primary key before defining columns.
const string table13 =
"human_resource13(id int, primary key((id, name), salary), name varchar, salary int);";
// Create the table 1.
EXEC_VALID_STMT(CreateStmt(table1));
// Create the table 2. Use "id" as primary key.
EXEC_VALID_STMT(CreateStmt(table2));
// Create the table 3. Use "name" as primary key.
EXEC_VALID_STMT(CreateStmt(table3));
// Create the table 4. Use both "id" and "name" as primary key.
EXEC_VALID_STMT(CreateStmt(table4));
// Create the table 5. Use both "id" as hash primary key.
EXEC_VALID_STMT(CreateStmt(table5));
// Create the table 6. Use both "id" and "name" as hash primary key.
EXEC_VALID_STMT(CreateStmt(table6));;
// Create table 7.
EXEC_VALID_STMT(CreateIfNotExistsStmt(table7));
// Create the table 8. Use "id" as primary key.
EXEC_VALID_STMT(CreateIfNotExistsStmt(table8));
// Create the table 9. Use "name" as primary key.
EXEC_VALID_STMT(CreateIfNotExistsStmt(table9));
// Create the table 10. Use both "id" and "name" as primary key.
EXEC_VALID_STMT(CreateIfNotExistsStmt(table10));
// Create the table 11. Use both "id" as hash primary key.
EXEC_VALID_STMT(CreateIfNotExistsStmt(table11));
// Create the table 12. Use both "id" and "name" as hash primary key.
EXEC_VALID_STMT(CreateIfNotExistsStmt(table12));
// Create the table 13. Define primary key before the columns.
EXEC_VALID_STMT(CreateIfNotExistsStmt(table13));
// Verify that all 'CREATE TABLE' statements fail for tables that have already been created.
EXEC_DUPLICATE_OBJECT_CREATE_STMT(CreateStmt(table1));
EXEC_DUPLICATE_OBJECT_CREATE_STMT(CreateStmt(table2));
EXEC_DUPLICATE_OBJECT_CREATE_STMT(CreateStmt(table3));
EXEC_DUPLICATE_OBJECT_CREATE_STMT(CreateStmt(table4));
EXEC_DUPLICATE_OBJECT_CREATE_STMT(CreateStmt(table5));
EXEC_DUPLICATE_OBJECT_CREATE_STMT(CreateStmt(table6));
EXEC_DUPLICATE_OBJECT_CREATE_STMT(CreateStmt(table7));
EXEC_DUPLICATE_OBJECT_CREATE_STMT(CreateStmt(table8));
EXEC_DUPLICATE_OBJECT_CREATE_STMT(CreateStmt(table9));
EXEC_DUPLICATE_OBJECT_CREATE_STMT(CreateStmt(table10));
EXEC_DUPLICATE_OBJECT_CREATE_STMT(CreateStmt(table11));
EXEC_DUPLICATE_OBJECT_CREATE_STMT(CreateStmt(table12));
// Verify that all 'CREATE TABLE IF EXISTS' statements succeed for tables that have already been
// created.
EXEC_VALID_STMT(CreateIfNotExistsStmt(table1));
EXEC_VALID_STMT(CreateIfNotExistsStmt(table2));
EXEC_VALID_STMT(CreateIfNotExistsStmt(table3));
EXEC_VALID_STMT(CreateIfNotExistsStmt(table4));
EXEC_VALID_STMT(CreateIfNotExistsStmt(table5));
EXEC_VALID_STMT(CreateIfNotExistsStmt(table6));
EXEC_VALID_STMT(CreateIfNotExistsStmt(table7));
EXEC_VALID_STMT(CreateIfNotExistsStmt(table8));
EXEC_VALID_STMT(CreateIfNotExistsStmt(table9));
EXEC_VALID_STMT(CreateIfNotExistsStmt(table10));
EXEC_VALID_STMT(CreateIfNotExistsStmt(table11));
EXEC_VALID_STMT(CreateIfNotExistsStmt(table12));
const string drop_stmt = "DROP TABLE human_resource1;";
EXEC_VALID_STMT(drop_stmt);
}
// Tests fix for https://github.com/YugaByte/yugabyte-db/issues/798.
// In order to reproduce the issue consistently, we have inserted a sleep after the table has been
// inserted in the master's memory map so that a subsequent request can find it and return an
// AlreadyPresent error. Before the fix, a CREATE TABLE IF NOT EXISTS will immediately return
// after encountering the error without waiting for the table to be ready to serve read/write
// requests which happens when a CREATE TABLE statement succeeds.
// This test creates a new thread to simulate two concurrent CREATE TABLE statements. In the main
// thread we issue a CREATE TABLE IF NOT EXIST statement which should wait until the master is done
// sleeping and the table is in a ready state. Without the fix, the INSERT statement always fails
// with a "Table Not Found" error.
TEST_F(TestQLCreateTable, TestQLConcurrentCreateTableAndCreateTableIfNotExistsStmts) {
FLAGS_TEST_simulate_slow_table_create_secs = 10;
// Init the simulated cluster.
ASSERT_NO_FATALS(CreateSimulatedCluster());
// Get an available processor.
TestQLProcessor *processor1 = GetQLProcessor();
TestQLProcessor *processor2 = GetQLProcessor();
auto s = processor1->Run("create keyspace k;");
std::thread t1([&] {
auto s2 = processor1->Run("CREATE TABLE k.t(k int PRIMARY KEY);");
CHECK_OK(s2);
LOG(INFO) << "Created keyspace table t";
});
// Sleep for 5 sec to give the previous statement a head start.
SleepFor(MonoDelta::FromSeconds(5));
// Before the fix, this would return immediately with Status::OK() without waiting for the table
// to be ready to serve read/write requests. With the fix, this statement shouldn't return until
// the table is ready, which happens after FLAGS_TEST_simulate_slow_table_create_secs seconds have
// elapsed.
s = processor2->Run("CREATE TABLE IF NOT EXISTS k.t(k int PRIMARY KEY);");
CHECK_OK(s);
s = processor2->Run("INSERT INTO k.t(k) VALUES (1)");
CHECK_OK(s);
t1.join();
}
// Same test as TestQLConcurrentCreateTableAndCreateTableIfNotExistsStmts, but this time we verify
// that whenever a CREATE TABLE statement returns "Duplicate Table. Already present", the table
// is ready to accept write requests.
TEST_F(TestQLCreateTable, TestQLConcurrentCreateTableStmt) {
FLAGS_TEST_simulate_slow_table_create_secs = 10;
// Init the simulated cluster.
ASSERT_NO_FATALS(CreateSimulatedCluster());
// Get an available processor.
TestQLProcessor *processor1 = GetQLProcessor();
TestQLProcessor *processor2 = GetQLProcessor();
auto s = processor1->Run("create keyspace k;");
std::thread t1([&] {
auto s2 = processor1->Run("CREATE TABLE k.t(k int PRIMARY KEY);");
CHECK_OK(s2);
LOG(INFO) << "Created keyspace table t";
});
// Sleep for 5 sec to give the previous statement a head start.
SleepFor(MonoDelta::FromSeconds(5));
// Wait until the table is already present in the tables map of the master.
s = processor2->Run("CREATE TABLE k.t(k int PRIMARY KEY);");
EXPECT_FALSE(s.ToString().find("Duplicate Object. Object ") == string::npos);
s = processor2->Run("INSERT INTO k.t(k) VALUES (1)");
EXPECT_OK(s);
t1.join();
}
TEST_F(TestQLCreateTable, TestQLCreateTableWithTTL) {
// Init the simulated cluster.
ASSERT_NO_FATALS(CreateSimulatedCluster());
// Get an available processor.
TestQLProcessor *processor = GetQLProcessor();
// Create the table 1.
const string table1 = "human_resource100(id int, name varchar, PRIMARY KEY(id));";
EXEC_VALID_STMT(CreateStmt(table1));
EXEC_VALID_STMT("CREATE TABLE table_with_ttl (c1 int, c2 int, c3 int, PRIMARY KEY(c1)) WITH "
"default_time_to_live = 1;");
// Query the table schema.
master::Master *master = cluster_->mini_master()->master();
master::CatalogManager *catalog_manager = master->catalog_manager();
master::GetTableSchemaRequestPB request_pb;
master::GetTableSchemaResponsePB response_pb;
request_pb.mutable_table()->mutable_namespace_()->set_name(kDefaultKeyspaceName);
request_pb.mutable_table()->set_table_name("table_with_ttl");
// Verify ttl was stored in syscatalog table.
CHECK_OK(catalog_manager->GetTableSchema(&request_pb, &response_pb));
const TablePropertiesPB& properties_pb = response_pb.schema().table_properties();
EXPECT_TRUE(properties_pb.has_default_time_to_live());
// We store ttl in milliseconds internally.
EXPECT_EQ(1000, properties_pb.default_time_to_live());
}
TEST_F(TestQLCreateTable, TestQLCreateTableWithClusteringOrderBy) {
// Init the simulated cluster.
ASSERT_NO_FATALS(CreateSimulatedCluster());
// Get an available processor.
TestQLProcessor *processor = GetQLProcessor();
const string table1 = "human_resource1(id int, first_name varchar, last_name varchar, "
"primary key(id, first_name, last_name)) WITH CLUSTERING ORDER BY(first_name ASC);";
const string table2 = "human_resource2(id int, first_name varchar, last_name varchar, "
"primary key(id, first_name, last_name)) WITH CLUSTERING ORDER BY(first_name ASC) AND "
"CLUSTERING ORDER BY (last_name DESC);";
const string table3 = "human_resource3(id int, first_name varchar, last_name varchar, "
"primary key(id, first_name, last_name)) "
"WITH CLUSTERING ORDER BY(first_name ASC, last_name DESC);";
const string table4 = "human_resource4(id int, first_name varchar, last_name varchar, "
"primary key(id, last_name, first_name)) "
"WITH CLUSTERING ORDER BY(last_name ASC, last_name DESC);";
const string table5 = "human_resource5(id int, first_name varchar, last_name varchar, "
"primary key(id, last_name, first_name)) "
"WITH CLUSTERING ORDER BY(last_name ASC, first_name DESC, last_name DESC);";
const string table6 = "human_resource6(id int, first_name varchar, last_name varchar, "
"primary key(id, first_name, last_name)) "
"WITH CLUSTERING ORDER BY(last_name DESC, first_name DESC);";
const string table7 = "human_resource7(id int, first_name varchar, last_name varchar, "
"primary key(id, first_name, last_name)) "
"WITH CLUSTERING ORDER BY(last_name DESC) AND "
"CLUSTERING ORDER BY (first_name DESC);";
const string table8 = "human_resource8(id int, first_name varchar, last_name varchar, "
"primary key(id, first_name, last_name)) "
"WITH CLUSTERING ORDER BY(last_name DESC, last_name DESC);";
const string table9 = "human_resource9(id int, first_name varchar, last_name varchar, "
"primary key(id, first_name, last_name)) "
"WITH CLUSTERING ORDER BY(first_name DESC, last_name DESC, something DESC);";
const string table10 = "human_resource10(id int, first_name varchar, last_name varchar, "
"primary key(id, last_name, first_name)) "
"WITH CLUSTERING ORDER BY(something ASC);";
const string table11 = "human_resource10(id int, first_name varchar, last_name varchar, age int, "
"primary key(id, last_name, first_name)) "
"WITH CLUSTERING ORDER BY(age ASC);";
const string table12 = "human_resource10(id int, first_name varchar, last_name varchar, "
"primary key(id, last_name, first_name)) "
"WITH CLUSTERING ORDER BY(id);";
// Create the table 1.
EXEC_VALID_STMT(CreateStmt(table1));
EXEC_VALID_STMT(CreateStmt(table2));
EXEC_VALID_STMT(CreateStmt(table3));
EXEC_VALID_STMT(CreateStmt(table4));
EXEC_VALID_STMT(CreateStmt(table5));
EXEC_INVALID_STMT_WITH_ERROR(CreateStmt(table6),
"Invalid Table Property. Columns in the CLUSTERING ORDER directive must be in same order "
"as the clustering key columns order (first_name must appear before last_name)");
EXEC_INVALID_STMT_WITH_ERROR(CreateStmt(table7),
"Invalid Table Property. Columns in the CLUSTERING ORDER directive must be in same order "
"as the clustering key columns order (first_name must appear before last_name)");
EXEC_INVALID_STMT_WITH_ERROR(CreateStmt(table8),
"Invalid Table Property. Missing CLUSTERING ORDER for column first_name");
EXEC_INVALID_STMT_WITH_ERROR(CreateStmt(table9),
"Invalid Table Property. Not a clustering key colum");
EXEC_INVALID_STMT_WITH_ERROR(CreateStmt(table10),
"Invalid Table Property. Not a clustering key colum");
EXEC_INVALID_STMT_WITH_ERROR(CreateStmt(table11),
"Invalid Table Property. Not a clustering key colum");
EXEC_INVALID_STMT_WITH_ERROR(CreateStmt(table12),
"Invalid Table Property. Not a clustering key colum");
}
TEST_F(TestQLCreateTable, TestQLCreateTableWithPartitionScemeOf) {
// Init the simulated cluster.
ASSERT_NO_FATALS(CreateSimulatedCluster());
// Get an available processor.
TestQLProcessor *processor = GetQLProcessor();
const string table1 = "devices(supplier_id INT, device_id DOUBLE, model_year INT, "
"device_name TEXT, PRIMARY KEY((supplier_id, device_id), model_year));";
const string table2 = "descriptions1(supplier_id INT, device_id DOUBLE, description TEXT, "
"PRIMARY KEY((supplier_id, device_id))) with partition scheme of devices;";
const string table3 = "descriptions2(supp_id INT, dev_id DOUBLE, description TEXT, "
"image_id INT, PRIMARY KEY((supp_id, dev_id), image_id)) "
"with partition scheme of devices;";
const string table4 = "descriptions3(supplier_id INT, device_id DOUBLE, description TEXT, "
"PRIMARY KEY(supplier_id, device_id)) with partition scheme of devices;";
const string table5 = "descriptions4(supplier_id INT, device_id DOUBLE, model_year INT, "
"description TEXT, PRIMARY KEY((supplier_id, device_id, model_year))) "
"with partition scheme of devices;";
const string table6 = "descriptions5(supplier_id INT, device_id DOUBLE, description TEXT, "
"PRIMARY KEY((supplier_id, device_id))) with partition scheme of non_existing_table;";
const string table7 = "descriptions6(supp_id INT, dev_id DOUBLE, description TEXT, "
"image_id INT, PRIMARY KEY((supp_id, description))) with partition scheme of devices;";
const string table8 = "descriptions7(supp_id INT, dev_id DOUBLE, description TEXT, "
"image_id INT, PRIMARY KEY((dev_id, supp_id))) with partition scheme of devices;";
const string table9 = "descriptions8(supp_id INT, dev_id DOUBLE, description TEXT, "
"image_id INT, PRIMARY KEY((supp_id, image_id))) with partition scheme of devices;";
const string table10 = "descriptions9(supp_id INT, dev_id DOUBLE, description TEXT, "
"image_id INT, PRIMARY KEY((description, image_id))) with partition scheme of devices;";
const string table11 = "descriptions10(supp_id INT, dev_id DOUBLE, description TEXT, "
"image_id INT, PRIMARY KEY((supp_id, dev_id))) with partition scheme devices;";
const string table12 = "descriptions11(supp_id INT, dev_id DOUBLE, description TEXT, "
"image_id INT, PRIMARY KEY((supp_id, dev_id))) with partition schema of devices;";
const string table13 = "descriptions12(supp_id INT, dev_id DOUBLE, description TEXT, "
"image_id INT, PRIMARY KEY((supp_id, dev_id))) with partitioning scheme of devices;";
// Create the devices tables.
EXEC_VALID_STMT(CreateStmt(table1));
EXEC_VALID_STMT(CreateStmt(table2));
EXEC_VALID_STMT(CreateStmt(table3));
EXEC_INVALID_STMT_WITH_ERROR(CreateStmt(table4),
"The number of hash keys in the current table "
"differ from the number of hash keys in 'devices'");
EXEC_INVALID_STMT_WITH_ERROR(CreateStmt(table5),
"The number of hash keys in the current table "
"differ from the number of hash keys in 'devices'");
EXEC_INVALID_STMT_WITH_ERROR(CreateStmt(table6),
"Object Not Found");
EXEC_INVALID_STMT_WITH_ERROR(CreateStmt(table7),
"The hash key 'description' in the current table has a different "
"datatype from the corresponding hash key in 'devices'");
EXEC_INVALID_STMT_WITH_ERROR(CreateStmt(table8),
"The hash key 'dev_id' in the current table has a different "
"datatype from the corresponding hash key in 'devices'");
EXEC_INVALID_STMT_WITH_ERROR(CreateStmt(table9),
"The hash key 'image_id' in the current table has a different "
"datatype from the corresponding hash key in 'devices'");
EXEC_INVALID_STMT_WITH_ERROR(CreateStmt(table10),
"The hash key 'description' in the current table has a different "
"datatype from the corresponding hash key in 'devices'");
EXEC_INVALID_STMT_WITH_ERROR(CreateStmt(table11),
"syntax error");
EXEC_INVALID_STMT_WITH_ERROR(CreateStmt(table12),
"syntax error");
EXEC_INVALID_STMT_WITH_ERROR(CreateStmt(table13),
"syntax error");
}
// Check for presence of rows in system.metrics table.
TEST_F(TestQLCreateTable, TestMetrics) {
FLAGS_master_enable_metrics_snapshotter = true;
FLAGS_tserver_enable_metrics_snapshotter = true;
std::vector<std::string> table_metrics =
{"rocksdb_db_write_stall_sum", "rocksdb_db_write_stall_count"};
FLAGS_metrics_snapshotter_table_metrics_whitelist = boost::algorithm::join(table_metrics, ",");
std::vector<std::string> tserver_metrics = {
"handler_latency_yb_tserver_TabletServerService_ListTablets_sum",
"handler_latency_yb_tserver_TabletServerService_ListTablets_count",
"handler_latency_yb_tserver_TabletServerService_ListTabletsForTabletServer_sum"};
FLAGS_metrics_snapshotter_tserver_metrics_whitelist =
boost::algorithm::join(tserver_metrics, ",");
// rf1 cluster.
ASSERT_NO_FATALS(CreateSimulatedCluster(1));
TestQLProcessor* processor = GetQLProcessor();
ASSERT_OK(processor->Run("create keyspace k"));
auto table_name = "tmptable";
ASSERT_OK(processor->Run(Format("CREATE TABLE k.$0(id int PRIMARY KEY)", table_name)));
// Sleep for 5 sec to give the previous statement a head start.
SleepFor(MonoDelta::FromSeconds(5));
int num_inserts = 100;
for (int i = 0; i < num_inserts; i++) {
ASSERT_OK(processor->Run(Format("INSERT INTO k.$0 (id) VALUES ($1)", table_name, i)));
}
// Read from table, ignore output.
ASSERT_OK(processor->Run(Format("SELECT * FROM k.$0", table_name)));
// Sleep enough for one tick of metrics snapshotter (and a bit more).
SleepFor(MonoDelta::FromMilliseconds(2 * FLAGS_metrics_snapshotter_interval_ms));
// Verify whitelist functionality for table metrics.
{
ASSERT_OK(processor->Run(Format("SELECT metric FROM $0.$1 WHERE entity_type=\'table\'",
yb::master::kSystemNamespaceName, kMetricsSnapshotsTableName)));
auto row_block = processor->row_block();
std::unordered_set<std::string> t;
for (int i = 0; i < row_block->row_count(); i++) {
QLRow &row = row_block->row(i);
t.insert(row.column(0).string_value());
}
EXPECT_EQ(t.size(), table_metrics.size());
for (const auto& table_metric : table_metrics) {
EXPECT_NE(t.find(table_metric), t.end());
}
}
// Verify whitelist functionality for tserver metrics.
{
ASSERT_OK(processor->Run(Format("SELECT metric FROM $0.$1 WHERE entity_type=\'tserver\'",
yb::master::kSystemNamespaceName, kMetricsSnapshotsTableName)));
auto row_block = processor->row_block();
std::unordered_set<std::string> t;
for (int i = 0; i < row_block->row_count(); i++) {
QLRow &row = row_block->row(i);
t.insert(row.column(0).string_value());
}
EXPECT_EQ(t.size(), tserver_metrics.size());
for (const auto& tserver_metric : tserver_metrics) {
EXPECT_NE(t.find(tserver_metric), t.end());
}
}
ASSERT_OK(processor->Run(Format("DROP TABLE k.$0", table_name)));
}
} // namespace ql
} // namespace yb
| {
"pile_set_name": "Github"
} |
import aarForm from 'mk-aar-form'
function actionCreator(option){
return {
formAction: new aarForm.action(option)
}
}
export default {
actionCreator
} | {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2015-2017 PÂRIS Quentin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.phoenicis.tools.gpg;
import org.junit.Test;
import static org.junit.Assert.*;
public class SignatureCheckerTest {
private static final String SCRIPT = "#!/bin/bash\n" + "if [ \"$PLAYONLINUX\" = \"\" ]\n" + "then\n" + "exit 0\n"
+ "fi\n" + "source \"$PLAYONLINUX/lib/sources\"\n" + "\n" + "POL_SetupWindow_Init \n"
+ "POL_SetupWindow_free_presentation \"Anti-aliasing\" \"This script will enable anti-aliasing\"\n"
+ "POL_SetupWindow_games \"Choose an application\" \"Anti-aliasing\"\n" + "if [ \"$APP_ANSWER\" == \"\" ]\n"
+ "then\n" + "POL_SetupWindow_Close\n" + "exit\n" + "fi\n" + "PREFIX=$(detect_wineprefix \"$APP_ANSWER\")\n"
+ "select_prefix \"$PREFIX\"\n" + "fonts_to_prefix\n"
+ "POL_SetupWindow_wait_next_signal \"Processing\" \"Anti aliasing\"\n" + "REGEDIT4\n" + "\n"
+ "cat << EOF > \"$REPERTOIRE/tmp/fontsaa.reg\"\n" + "[HKEY_CURRENT_USER\\Control Panel\\Desktop]\n"
+ "\"FontSmoothing\"=\"2\"\n" + "\"FontSmoothingType\"=dword:00000002\n"
+ "\"FontSmoothingGamma\"=dword:00000578\n" + "\"FontSmoothingOrientation\"=dword:00000001\n" + "EOF\n"
+ "regedit \"$REPERTOIRE/tmp/fontsaa.reg\"\n" + "\n" + "POL_SetupWindow_detect_exit\n"
+ "POL_SetupWindow_message \"Anti-aliasing has been successfully enabled\" \"Anti-aliasing\"\n"
+ "POL_SetupWindow_Close\n" + "exit\n";
private static final String SIGNATURE = "-----BEGIN PGP SIGNATURE-----\n" + "Version: GnuPG v1.4.9 (GNU/Linux)\n"
+ "\n" + "iEYEABECAAYFAk1cJE4ACgkQ5TH6yaoTykcNqQCdEECsTszINVdQRtPYZFU9Dat6\n"
+ "EoUAni+IJF9wAvjdYHviiiDNVflQKmYA\n" + "=v/ss\n" + "-----END PGP SIGNATURE-----";
private static final String PUBLIC_KEY = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n"
+ "Comment: GPGTools - http://gpgtools.org\n" + "\n"
+ "mQGiBE0ozSYRBADdPem93uvIqrZGpkM8pSxKjyK5PmXhfBsCTRowU09b3OL1eqXP\n"
+ "s1k+waRy6YFK+jwA+wp8vPeGUUDeINMPayL+g+5hXitgoMWrna/64PPLaDf0cqSP\n"
+ "A/2kFxx3vdWaTHwqQRaSx4k68O/8yAJKK4K9FlpUSq3hvOIUYH3ze2XvvwCgszn3\n"
+ "awTWpcnuZZaeZn7E88CGTu8D/iHSLnkBvF8AGcnJUw8SyPSyKiGnBH6rssOpjy/0\n"
+ "Mkx7yfbjXrpiYWsEbvgmgPWGf1cnTELUFosQNR8rv4W7KS8KyYjDR6agc4ek1P6J\n"
+ "bQu2VGUoBhNm//LITwh4ZdOR9aZ1ewUQFksOPFnd/1peFu13MFduZCAHGCpCeoXI\n"
+ "ZE/VA/4/Akh2diRNb9DIAB3Mqxx1ZjhnLl/elb8wCWRo/YLPXiLQNdEHK9c8M+sn\n"
+ "pt/1zbRlg306n8N5C6s6z7HwbfZaA8fDL2UMkmuJrycO2YRWjx8GDhfoocmcQw6b\n"
+ "OXls6f2ZBeGAkj9l1ueDTL3IVClJftK53EjzPeSv84Onw46cK7RMUGxheU9uTGlu\n"
+ "dXggKFBsYXlPbkxpbnV4IGFuZCBQbGF5T25NYWMgc2NyaXB0aW5nIGtleXMpIDxn\n"
+ "cGdAcGxheW9ubGludXguY29tPohgBBMRAgAgBQJNKM0mAhsDBgsJCAcDAgQVAggD\n"
+ "BBYCAwECHgECF4AACgkQ5TH6yaoTykdOxQCfR8Y6HVG1FvNRuXDFKAN9O5eHrOEA\n"
+ "oKEt7Et07dALQnEA099qQOqCZxnQuQINBE0ozSYQCAC7JscaD6ompySGIRR3BmpY\n"
+ "mlwdJDbk0ptZPFi2PKK87oJc2r/fGwKZZw/hHBv46R0zDay8X1r/7a452scZ8SiP\n"
+ "Y2m02pXv1y+cS/c8jPUWNUG39BdzqD6SdgFjsuvgjeQGRpjVrh/K0SKrzLmmdV/9\n"
+ "85b8mbPjWpfn3iwaq/zmbLFZdGY/gcbihTfHNRDys4DX3UrOnQgq/X7psit1pDYT\n"
+ "qVX2gzZvwaXoCIAa0aw1/JAVi/H689bAAuASKkI57u4OdCfvdlMnA5DOcPRR8ttP\n"
+ "9z9wQC/Gsu1VkOsJ4Mfcu0Hh42e6Ta05TDIg+nZQ/iREJjHTnptOTNqeE4K6908D\n"
+ "AAMFB/9UlG6ab0kAXNKsmgeev3P5B1c9g/BgD9TuHF8fONQ04z2ar6n9iwJTxV8W\n"
+ "e7oTZkqS/Zq4dKdYTlhxck16g6CZHVDu4yWVIq7QSz8E5NLi0xhXLWciK3Tw3soQ\n"
+ "QZrfjoQnEuXCCXCWw/1B3odATjfpvRfRxbHZ5kUwwoiRUs3Y1pvRyHpvpBem72Lj\n"
+ "orYJSHh0B76atJG1o21LnsDQCILbANbqyF2BaT6mp7fH3v2f0fliLYTphd6T2i0/\n"
+ "5vDg5JymoIRJY7cjegprA1KIo1n5mvfv2zTARVNO3IyFVIaD7fdn3zW3Pzh75WKx\n"
+ "ghoOaMtjdexZKpJnEpkqbe8Qs2/qiEkEGBECAAkFAk0ozSYCGwwACgkQ5TH6yaoT\n"
+ "ykftZQCfTCroby2HAxhIFRO9+3ACr6bIDkYAnjS2zGBJ44bNFBYHet4DmI9JfEw1\n" + "=PAJ4\n"
+ "-----END PGP PUBLIC KEY BLOCK-----\n";
@Test
public void testSignatureCheckerWithValidSignatureReturnTrue() {
SignatureChecker signatureChecker = new SignatureChecker().withSignature(SIGNATURE).withData(SCRIPT)
.withPublicKey(PUBLIC_KEY);
assertTrue(signatureChecker.check());
}
@Test
public void testSignatureCheckerWithInvalidValidSignatureReturnFalse() {
SignatureChecker signatureChecker = new SignatureChecker().withSignature(SIGNATURE)
.withData(SCRIPT.replace("a", "b")).withPublicKey(PUBLIC_KEY);
assertFalse(signatureChecker.check());
}
@Test
public void testGetPublicKey() {
assertEquals(PUBLIC_KEY, SignatureChecker.getPublicKey());
}
} | {
"pile_set_name": "Github"
} |
/*
Document : view
Created on : Sep 7, 2013, 3:53:58 PM
Author : dasn
Description:
Purpose of the stylesheet follows.
*/
ul#sql_query li{
display: inline-block;
}
ul.view_filters{
display: block;
clear: both;
}
ul.view_filters li{
display: inline-block;
margin-right: 30px;
}
#display_div ul li{
display: inline-block;
margin: 5px 2px;
}
#logical_settings li label{
padding : 0 5px 5px 10px;
background: none repeat scroll 0% 0% rgba(147, 45, 174, 0.25);
}
#logical_settings li.field_records label{
padding : 0 5px 5px 10px;
background: none repeat scroll 0% 0% rgba(147, 195, 174, 0.3);
}
#logical_settings {
margin : 10px 0;
border: 1px solid #ccc;
}
#condition_li table{
margin: 5px 0;
width: 100%;
}
#condition_li table th{
background : #eee;
}
#condition_li table tr td{
min-width: 200px;
width: 33%;
border: 1px solid #ddd;
padding: 2px 10px;
}
li#show_field_li{
display: block;
margin : 20px 0;
}
li#condition_li {
display: block;
margin: 20px 0px;
}
#show_field_buttons input, #condition_buttons_table input,
#sort_sqlQuery input{
width: 270px;
}
li#sort_sqlQuery ul li{
display: inline-block;
vertical-align: top;
}
li#sort_sqlQuery {
display: block;
border:1px solid #ccc;
}
li#sort_sqlQuery ul li{
display: inline-block;
border-right:2px solid #ccc;
}
li#sort_sqlQuery ul li#sorting_li{
width: 49.5%;
}
.select.all_table_names{
background: rgba(111,20,193,0.15);
border: none;
padding: 2px; /* If you add too much padding here, the options won't show in IE */
}
span.view_name{
display: inline-block;
width: 250px;
font-size: 15px;
vertical-align:baseline;
float: left;
}
table#sort_fields_table tr td, table#group_by_table tr td, table#group_by_table tr th{
border: 1px solid #ccc;
width: 100%;
}
table#group_by_table td {
display: block;
min-height: 18px;
min-width: 540px;
}
.ui-draggable{
margin:5px;
background : lightgreen;
width: 310px;
}
.draggable_element{
display: inline-block;
}
#view_divId .draggable_element input[type="text"], #view_divId .draggable_element select {
width: 280px;
} | {
"pile_set_name": "Github"
} |
{
"type": "Program",
"body": [
{
"type": "ExpressionStatement",
"expression": {
"type": "BinaryExpression",
"operator": "!==",
"left": {
"type": "Identifier",
"name": "x",
"range": [
0,
1
],
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 1
}
}
},
"right": {
"type": "Identifier",
"name": "y",
"range": [
6,
7
],
"loc": {
"start": {
"line": 1,
"column": 6
},
"end": {
"line": 1,
"column": 7
}
}
},
"range": [
0,
7
],
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 7
}
}
},
"range": [
0,
7
],
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 7
}
}
}
],
"sourceType": "script",
"tokens": [
{
"type": "Identifier",
"value": "x",
"range": [
0,
1
],
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 1
}
}
},
{
"type": "Punctuator",
"value": "!==",
"range": [
2,
5
],
"loc": {
"start": {
"line": 1,
"column": 2
},
"end": {
"line": 1,
"column": 5
}
}
},
{
"type": "Identifier",
"value": "y",
"range": [
6,
7
],
"loc": {
"start": {
"line": 1,
"column": 6
},
"end": {
"line": 1,
"column": 7
}
}
}
],
"range": [
0,
7
],
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 7
}
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{02c67056-795c-4dfe-be83-989e6a16dee3}</ProjectGuid>
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
<Name>OrvidTest</Name>
<BinFormat>elf</BinFormat>
<RootNamespace>OrvidTest</RootNamespace>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\Debug\</OutputPath>
<Framework>MicrosoftNET</Framework>
<UseInternalAssembler>False</UseInternalAssembler>
<EnableGDB>False</EnableGDB>
<DebugMode>None</DebugMode>
<TraceMode>User</TraceMode>
<BuildTarget>VMWare</BuildTarget>
<VMWareFlavor>Workstation</VMWareFlavor>
<StartCosmosGDB>False</StartCosmosGDB>
<TraceAssemblies>All</TraceAssemblies>
<ExternalLibsForArgs>D:\Documents and Settings\Orvid\Desktop\Cosmos\Trunk\source2\Users\Orvid\StructTest\bin\Debug\StructTest.obj</ExternalLibsForArgs>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\Debug\</OutputPath>
<Framework>MicrosoftNET</Framework>
<UseInternalAssembler>False</UseInternalAssembler>
<EnableGDB>False</EnableGDB>
<DebugMode>None</DebugMode>
<TraceMode>User</TraceMode>
<BuildTarget>VMWare</BuildTarget>
<VMWareFlavor>Workstation</VMWareFlavor>
<StartCosmosGDB>false</StartCosmosGDB>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Orvid.Graphics.Cosmos\Orvid.Graphics.Cosmos.csproj">
<Name>Orvid.Graphics.Cosmos</Name>
<Project>{167d46d2-f0f2-4f59-ba0f-2452941e0450}</Project>
<Private>True</Private>
</ProjectReference>
<ProjectReference Include="..\Orvid.Graphics\Orvid.Graphics.csproj">
<Name>Orvid.Graphics</Name>
<Project>{c9e995cf-cb65-4410-a7d2-63ebbe02aabb}</Project>
<Private>True</Private>
</ProjectReference>
<ProjectReference Include="..\OrvidTestOS\OrvidKernel.csproj">
<Name>OrvidKernel</Name>
<Project>{2e14eed0-f7e9-4e7c-aa21-6e519c28457d}</Project>
<Private>True</Private>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Reference Include="Cosmos.Core_Plugs, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5ae71220097cb983">
<Name>Cosmos.Core_Plugs</Name>
<AssemblyName>Cosmos.Core_Plugs.dll</AssemblyName>
<HintPath>..\..\..\..\..\..\Users\Orvid\AppData\Roaming\Cosmos User Kit\Kernel\Cosmos.Core_Plugs.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Cosmos.System_Plugs, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5ae71220097cb983">
<Name>Cosmos.System_Plugs</Name>
<AssemblyName>Cosmos.System_Plugs.dll</AssemblyName>
<HintPath>..\..\..\..\..\..\Users\Orvid\AppData\Roaming\Cosmos User Kit\Kernel\Cosmos.System_Plugs.dll</HintPath>
<Private>True</Private>
</Reference>
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Cosmos\Cosmos.targets" />
<Target Name="BeforeBuild">
</Target>
</Project> | {
"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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
title: "Cayenne Getting Started ROP"
description: "Tutorial how to quick start new Cayenne ROP project"
cayenneVersion: "4.2"
docsMenuTitle: "Getting Started ROP"
weight: 40
---
| {
"pile_set_name": "Github"
} |
<?php
/**
* DO NOT EDIT THIS FILE!
*
* This file was automatically generated from external sources.
*
* Any manual change here will be lost the next time the SDK
* is updated. You've been warned!
*/
namespace DTS\eBaySDK\Test\Trading\Types;
use DTS\eBaySDK\Trading\Types\GetSellerTransactionsResponseType;
class GetSellerTransactionsResponseTypeTest extends \PHPUnit_Framework_TestCase
{
private $obj;
protected function setUp()
{
$this->obj = new GetSellerTransactionsResponseType();
}
public function testCanBeCreated()
{
$this->assertInstanceOf('\DTS\eBaySDK\Trading\Types\GetSellerTransactionsResponseType', $this->obj);
}
public function testExtendsAbstractResponseType()
{
$this->assertInstanceOf('\DTS\eBaySDK\Trading\Types\AbstractResponseType', $this->obj);
}
}
| {
"pile_set_name": "Github"
} |
/* GLIB - Library of useful routines for C programming
* Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
/*
* Modified by the GLib Team and others 1997-2000. See the AUTHORS
* file for a list of people on the GLib Team. See the ChangeLog
* files for a list of changes. These files are distributed with
* GLib at ftp://ftp.gtk.org/pub/gtk/.
*/
/*
* MT safe
*/
#include "config.h"
#include <string.h>
#include "gstringchunk.h"
#include "ghash.h"
#include "gslist.h"
#include "gmessages.h"
#include "gutils.h"
/**
* SECTION:string_chunks
* @title: String Chunks
* @short_description: efficient storage of groups of strings
*
* String chunks are used to store groups of strings. Memory is
* allocated in blocks, and as strings are added to the #GStringChunk
* they are copied into the next free position in a block. When a block
* is full a new block is allocated.
*
* When storing a large number of strings, string chunks are more
* efficient than using g_strdup() since fewer calls to malloc() are
* needed, and less memory is wasted in memory allocation overheads.
*
* By adding strings with g_string_chunk_insert_const() it is also
* possible to remove duplicates.
*
* To create a new #GStringChunk use g_string_chunk_new().
*
* To add strings to a #GStringChunk use g_string_chunk_insert().
*
* To add strings to a #GStringChunk, but without duplicating strings
* which are already in the #GStringChunk, use
* g_string_chunk_insert_const().
*
* To free the entire #GStringChunk use g_string_chunk_free(). It is
* not possible to free individual strings.
*/
/**
* GStringChunk:
*
* An opaque data structure representing String Chunks.
* It should only be accessed by using the following functions.
*/
struct _GStringChunk
{
GHashTable *const_table;
GSList *storage_list;
gsize storage_next;
gsize this_size;
gsize default_size;
};
#define MY_MAXSIZE ((gsize)-1)
static inline gsize
nearest_power (gsize base,
gsize num)
{
if (num > MY_MAXSIZE / 2)
{
return MY_MAXSIZE;
}
else
{
gsize n = base;
while (n < num)
n <<= 1;
return n;
}
}
/**
* g_string_chunk_new:
* @size: the default size of the blocks of memory which are
* allocated to store the strings. If a particular string
* is larger than this default size, a larger block of
* memory will be allocated for it.
*
* Creates a new #GStringChunk.
*
* Returns: a new #GStringChunk
*/
GStringChunk *
g_string_chunk_new (gsize size)
{
GStringChunk *new_chunk = g_new (GStringChunk, 1);
gsize actual_size = 1;
actual_size = nearest_power (1, size);
new_chunk->const_table = NULL;
new_chunk->storage_list = NULL;
new_chunk->storage_next = actual_size;
new_chunk->default_size = actual_size;
new_chunk->this_size = actual_size;
return new_chunk;
}
/**
* g_string_chunk_free:
* @chunk: a #GStringChunk
*
* Frees all memory allocated by the #GStringChunk.
* After calling g_string_chunk_free() it is not safe to
* access any of the strings which were contained within it.
*/
void
g_string_chunk_free (GStringChunk *chunk)
{
g_return_if_fail (chunk != NULL);
if (chunk->storage_list)
g_slist_free_full (chunk->storage_list, g_free);
if (chunk->const_table)
g_hash_table_destroy (chunk->const_table);
g_free (chunk);
}
/**
* g_string_chunk_clear:
* @chunk: a #GStringChunk
*
* Frees all strings contained within the #GStringChunk.
* After calling g_string_chunk_clear() it is not safe to
* access any of the strings which were contained within it.
*
* Since: 2.14
*/
void
g_string_chunk_clear (GStringChunk *chunk)
{
g_return_if_fail (chunk != NULL);
if (chunk->storage_list)
{
g_slist_free_full (chunk->storage_list, g_free);
chunk->storage_list = NULL;
chunk->storage_next = chunk->default_size;
chunk->this_size = chunk->default_size;
}
if (chunk->const_table)
g_hash_table_remove_all (chunk->const_table);
}
/**
* g_string_chunk_insert:
* @chunk: a #GStringChunk
* @string: the string to add
*
* Adds a copy of @string to the #GStringChunk.
* It returns a pointer to the new copy of the string
* in the #GStringChunk. The characters in the string
* can be changed, if necessary, though you should not
* change anything after the end of the string.
*
* Unlike g_string_chunk_insert_const(), this function
* does not check for duplicates. Also strings added
* with g_string_chunk_insert() will not be searched
* by g_string_chunk_insert_const() when looking for
* duplicates.
*
* Returns: a pointer to the copy of @string within
* the #GStringChunk
*/
gchar*
g_string_chunk_insert (GStringChunk *chunk,
const gchar *string)
{
g_return_val_if_fail (chunk != NULL, NULL);
return g_string_chunk_insert_len (chunk, string, -1);
}
/**
* g_string_chunk_insert_const:
* @chunk: a #GStringChunk
* @string: the string to add
*
* Adds a copy of @string to the #GStringChunk, unless the same
* string has already been added to the #GStringChunk with
* g_string_chunk_insert_const().
*
* This function is useful if you need to copy a large number
* of strings but do not want to waste space storing duplicates.
* But you must remember that there may be several pointers to
* the same string, and so any changes made to the strings
* should be done very carefully.
*
* Note that g_string_chunk_insert_const() will not return a
* pointer to a string added with g_string_chunk_insert(), even
* if they do match.
*
* Returns: a pointer to the new or existing copy of @string
* within the #GStringChunk
*/
gchar*
g_string_chunk_insert_const (GStringChunk *chunk,
const gchar *string)
{
char* lookup;
g_return_val_if_fail (chunk != NULL, NULL);
if (!chunk->const_table)
chunk->const_table = g_hash_table_new (g_str_hash, g_str_equal);
lookup = (char*) g_hash_table_lookup (chunk->const_table, (gchar *)string);
if (!lookup)
{
lookup = g_string_chunk_insert (chunk, string);
g_hash_table_add (chunk->const_table, lookup);
}
return lookup;
}
/**
* g_string_chunk_insert_len:
* @chunk: a #GStringChunk
* @string: bytes to insert
* @len: number of bytes of @string to insert, or -1 to insert a
* nul-terminated string
*
* Adds a copy of the first @len bytes of @string to the #GStringChunk.
* The copy is nul-terminated.
*
* Since this function does not stop at nul bytes, it is the caller's
* responsibility to ensure that @string has at least @len addressable
* bytes.
*
* The characters in the returned string can be changed, if necessary,
* though you should not change anything after the end of the string.
*
* Returns: a pointer to the copy of @string within the #GStringChunk
*
* Since: 2.4
*/
gchar*
g_string_chunk_insert_len (GStringChunk *chunk,
const gchar *string,
gssize len)
{
gssize size;
gchar* pos;
g_return_val_if_fail (chunk != NULL, NULL);
if (len < 0)
size = strlen (string);
else
size = len;
if ((chunk->storage_next + size + 1) > chunk->this_size)
{
gsize new_size = nearest_power (chunk->default_size, size + 1);
chunk->storage_list = g_slist_prepend (chunk->storage_list,
g_new (gchar, new_size));
chunk->this_size = new_size;
chunk->storage_next = 0;
}
pos = ((gchar *) chunk->storage_list->data) + chunk->storage_next;
*(pos + size) = '\0';
memcpy (pos, string, size);
chunk->storage_next += size + 1;
return pos;
}
| {
"pile_set_name": "Github"
} |
=head1 NAME
AnyEvent::HTTP - simple but non-blocking HTTP/HTTPS client
=head1 SYNOPSIS
use AnyEvent::HTTP;
http_get "http://www.nethype.de/", sub { print $_[1] };
# ... do something else here
=head1 DESCRIPTION
This module is an L<AnyEvent> user, you need to make sure that you use and
run a supported event loop.
This module implements a simple, stateless and non-blocking HTTP
client. It supports GET, POST and other request methods, cookies and more,
all on a very low level. It can follow redirects supports proxies and
automatically limits the number of connections to the values specified in
the RFC.
It should generally be a "good client" that is enough for most HTTP
tasks. Simple tasks should be simple, but complex tasks should still be
possible as the user retains control over request and response headers.
The caller is responsible for authentication management, cookies (if
the simplistic implementation in this module doesn't suffice), referer
and other high-level protocol details for which this module offers only
limited support.
=head2 METHODS
=over 4
=cut
package AnyEvent::HTTP;
use strict;
no warnings;
use Errno ();
use AnyEvent 5.0 ();
use AnyEvent::Util ();
use AnyEvent::Socket ();
use AnyEvent::Handle ();
use base Exporter::;
our $VERSION = '1.46';
our @EXPORT = qw(http_get http_post http_head http_request);
our $USERAGENT = "Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)";
our $MAX_RECURSE = 10;
our $MAX_PERSISTENT = 8;
our $PERSISTENT_TIMEOUT = 2;
our $TIMEOUT = 300;
# changing these is evil
our $MAX_PERSISTENT_PER_HOST = 0;
our $MAX_PER_HOST = 4;
our $PROXY;
our $ACTIVE = 0;
my %KA_COUNT; # number of open keep-alive connections per host
my %CO_SLOT; # number of open connections, and wait queue, per host
=item http_get $url, key => value..., $cb->($data, $headers)
Executes an HTTP-GET request. See the http_request function for details on
additional parameters and the return value.
=item http_head $url, key => value..., $cb->($data, $headers)
Executes an HTTP-HEAD request. See the http_request function for details
on additional parameters and the return value.
=item http_post $url, $body, key => value..., $cb->($data, $headers)
Executes an HTTP-POST request with a request body of C<$body>. See the
http_request function for details on additional parameters and the return
value.
=item http_request $method => $url, key => value..., $cb->($data, $headers)
Executes a HTTP request of type C<$method> (e.g. C<GET>, C<POST>). The URL
must be an absolute http or https URL.
When called in void context, nothing is returned. In other contexts,
C<http_request> returns a "cancellation guard" - you have to keep the
object at least alive until the callback get called. If the object gets
destroyed before the callbakc is called, the request will be cancelled.
The callback will be called with the response body data as first argument
(or C<undef> if an error occured), and a hash-ref with response headers as
second argument.
All the headers in that hash are lowercased. In addition to the response
headers, the "pseudo-headers" (uppercase to avoid clashing with possible
response headers) C<HTTPVersion>, C<Status> and C<Reason> contain the
three parts of the HTTP Status-Line of the same name.
The pseudo-header C<URL> contains the actual URL (which can differ from
the requested URL when following redirects - for example, you might get
an error that your URL scheme is not supported even though your URL is a
valid http URL because it redirected to an ftp URL, in which case you can
look at the URL pseudo header).
The pseudo-header C<Redirect> only exists when the request was a result
of an internal redirect. In that case it is an array reference with
the C<($data, $headers)> from the redirect response. Note that this
response could in turn be the result of a redirect itself, and C<<
$headers->{Redirect}[1]{Redirect} >> will then contain the original
response, and so on.
If the server sends a header multiple times, then their contents will be
joined together with a comma (C<,>), as per the HTTP spec.
If an internal error occurs, such as not being able to resolve a hostname,
then C<$data> will be C<undef>, C<< $headers->{Status} >> will be C<59x>
(usually C<599>) and the C<Reason> pseudo-header will contain an error
message.
A typical callback might look like this:
sub {
my ($body, $hdr) = @_;
if ($hdr->{Status} =~ /^2/) {
... everything should be ok
} else {
print "error, $hdr->{Status} $hdr->{Reason}\n";
}
}
Additional parameters are key-value pairs, and are fully optional. They
include:
=over 4
=item recurse => $count (default: $MAX_RECURSE)
Whether to recurse requests or not, e.g. on redirects, authentication
retries and so on, and how often to do so.
=item headers => hashref
The request headers to use. Currently, C<http_request> may provide its
own C<Host:>, C<Content-Length:>, C<Connection:> and C<Cookie:> headers
and will provide defaults for C<User-Agent:> and C<Referer:> (this can be
suppressed by using C<undef> for these headers in which case they won't be
sent at all).
=item timeout => $seconds
The time-out to use for various stages - each connect attempt will reset
the timeout, as will read or write activity, i.e. this is not an overall
timeout.
Default timeout is 5 minutes.
=item proxy => [$host, $port[, $scheme]] or undef
Use the given http proxy for all requests. If not specified, then the
default proxy (as specified by C<$ENV{http_proxy}>) is used.
C<$scheme> must be either missing, C<http> for HTTP or C<https> for
HTTPS.
=item body => $string
The request body, usually empty. Will be-sent as-is (future versions of
this module might offer more options).
=item cookie_jar => $hash_ref
Passing this parameter enables (simplified) cookie-processing, loosely
based on the original netscape specification.
The C<$hash_ref> must be an (initially empty) hash reference which will
get updated automatically. It is possible to save the cookie_jar to
persistent storage with something like JSON or Storable, but this is not
recommended, as expiry times are currently being ignored.
Note that this cookie implementation is not of very high quality, nor
meant to be complete. If you want complete cookie management you have to
do that on your own. C<cookie_jar> is meant as a quick fix to get some
cookie-using sites working. Cookies are a privacy disaster, do not use
them unless required to.
=item tls_ctx => $scheme | $tls_ctx
Specifies the AnyEvent::TLS context to be used for https connections. This
parameter follows the same rules as the C<tls_ctx> parameter to
L<AnyEvent::Handle>, but additionally, the two strings C<low> or
C<high> can be specified, which give you a predefined low-security (no
verification, highest compatibility) and high-security (CA and common-name
verification) TLS context.
The default for this option is C<low>, which could be interpreted as "give
me the page, no matter what".
=item on_prepare => $callback->($fh)
In rare cases you need to "tune" the socket before it is used to
connect (for exmaple, to bind it on a given IP address). This parameter
overrides the prepare callback passed to C<AnyEvent::Socket::tcp_connect>
and behaves exactly the same way (e.g. it has to provide a
timeout). See the description for the C<$prepare_cb> argument of
C<AnyEvent::Socket::tcp_connect> for details.
=item on_header => $callback->($headers)
When specified, this callback will be called with the header hash as soon
as headers have been successfully received from the remote server (not on
locally-generated errors).
It has to return either true (in which case AnyEvent::HTTP will continue),
or false, in which case AnyEvent::HTTP will cancel the download (and call
the finish callback with an error code of C<598>).
This callback is useful, among other things, to quickly reject unwanted
content, which, if it is supposed to be rare, can be faster than first
doing a C<HEAD> request.
Example: cancel the request unless the content-type is "text/html".
on_header => sub {
$_[0]{"content-type"} =~ /^text\/html\s*(?:;|$)/
},
=item on_body => $callback->($partial_body, $headers)
When specified, all body data will be passed to this callback instead of
to the completion callback. The completion callback will get the empty
string instead of the body data.
It has to return either true (in which case AnyEvent::HTTP will continue),
or false, in which case AnyEvent::HTTP will cancel the download (and call
the completion callback with an error code of C<598>).
This callback is useful when the data is too large to be held in memory
(so the callback writes it to a file) or when only some information should
be extracted, or when the body should be processed incrementally.
It is usually preferred over doing your own body handling via
C<want_body_handle>, but in case of streaming APIs, where HTTP is
only used to create a connection, C<want_body_handle> is the better
alternative, as it allows you to install your own event handler, reducing
resource usage.
=item want_body_handle => $enable
When enabled (default is disabled), the behaviour of AnyEvent::HTTP
changes considerably: after parsing the headers, and instead of
downloading the body (if any), the completion callback will be
called. Instead of the C<$body> argument containing the body data, the
callback will receive the L<AnyEvent::Handle> object associated with the
connection. In error cases, C<undef> will be passed. When there is no body
(e.g. status C<304>), the empty string will be passed.
The handle object might or might not be in TLS mode, might be connected to
a proxy, be a persistent connection etc., and configured in unspecified
ways. The user is responsible for this handle (it will not be used by this
module anymore).
This is useful with some push-type services, where, after the initial
headers, an interactive protocol is used (typical example would be the
push-style twitter API which starts a JSON/XML stream).
If you think you need this, first have a look at C<on_body>, to see if
that doesn't solve your problem in a better way.
=back
Example: make a simple HTTP GET request for http://www.nethype.de/
http_request GET => "http://www.nethype.de/", sub {
my ($body, $hdr) = @_;
print "$body\n";
};
Example: make a HTTP HEAD request on https://www.google.com/, use a
timeout of 30 seconds.
http_request
GET => "https://www.google.com",
timeout => 30,
sub {
my ($body, $hdr) = @_;
use Data::Dumper;
print Dumper $hdr;
}
;
Example: make another simple HTTP GET request, but immediately try to
cancel it.
my $request = http_request GET => "http://www.nethype.de/", sub {
my ($body, $hdr) = @_;
print "$body\n";
};
undef $request;
=cut
sub _slot_schedule;
sub _slot_schedule($) {
my $host = shift;
while ($CO_SLOT{$host}[0] < $MAX_PER_HOST) {
if (my $cb = shift @{ $CO_SLOT{$host}[1] }) {
# somebody wants that slot
++$CO_SLOT{$host}[0];
++$ACTIVE;
$cb->(AnyEvent::Util::guard {
--$ACTIVE;
--$CO_SLOT{$host}[0];
_slot_schedule $host;
});
} else {
# nobody wants the slot, maybe we can forget about it
delete $CO_SLOT{$host} unless $CO_SLOT{$host}[0];
last;
}
}
}
# wait for a free slot on host, call callback
sub _get_slot($$) {
push @{ $CO_SLOT{$_[0]}[1] }, $_[1];
_slot_schedule $_[0];
}
our $qr_nlnl = qr{(?<![^\012])\015?\012};
our $TLS_CTX_LOW = { cache => 1, sslv2 => 1 };
our $TLS_CTX_HIGH = { cache => 1, verify => 1, verify_peername => "https" };
sub http_request($$@) {
my $cb = pop;
my ($method, $url, %arg) = @_;
my %hdr;
$arg{tls_ctx} = $TLS_CTX_LOW if $arg{tls_ctx} eq "low" || !exists $arg{tls_ctx};
$arg{tls_ctx} = $TLS_CTX_HIGH if $arg{tls_ctx} eq "high";
$method = uc $method;
if (my $hdr = $arg{headers}) {
while (my ($k, $v) = each %$hdr) {
$hdr{lc $k} = $v;
}
}
# pseudo headers for all subsequent responses
my @pseudo = (URL => $url);
push @pseudo, Redirect => delete $arg{Redirect} if exists $arg{Redirect};
my $handle_class = 'AnyEvent::Handle';
if (exists $arg{handle_class}) {
$handle_class = $arg{handle_class};
eval "require $handle_class";
return $cb->(undef, { Status => 599, Reason => $@, @pseudo }) if $@;
}
my $recurse = exists $arg{recurse} ? delete $arg{recurse} : $MAX_RECURSE;
return $cb->(undef, { Status => 599, Reason => "Too many redirections", @pseudo })
if $recurse < 0;
my $proxy = $arg{proxy} || $PROXY;
my $timeout = $arg{timeout} || $TIMEOUT;
my ($uscheme, $uauthority, $upath, $query, $fragment) =
$url =~ m|(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:(\?[^#]*))?(?:#(.*))?|;
$uscheme = lc $uscheme;
my $uport = $uscheme eq "http" ? 80
: $uscheme eq "https" ? 443
: return $cb->(undef, { Status => 599, Reason => "Only http and https URL schemes supported", @pseudo });
$uauthority =~ /^(?: .*\@ )? ([^\@:]+) (?: : (\d+) )?$/x
or return $cb->(undef, { Status => 599, Reason => "Unparsable URL", @pseudo });
my $uhost = $1;
$uport = $2 if defined $2;
$hdr{host} = defined $2 ? "$uhost:$2" : "$uhost"
unless exists $hdr{host};
$uhost =~ s/^\[(.*)\]$/$1/;
$upath .= $query if length $query;
$upath =~ s%^/?%/%;
# cookie processing
if (my $jar = $arg{cookie_jar}) {
%$jar = () if $jar->{version} != 1;
my @cookie;
while (my ($chost, $v) = each %$jar) {
if ($chost =~ /^\./) {
next unless $chost eq substr $uhost, -length $chost;
} elsif ($chost =~ /\./) {
next unless $chost eq $uhost;
} else {
next;
}
while (my ($cpath, $v) = each %$v) {
next unless $cpath eq substr $upath, 0, length $cpath;
while (my ($k, $v) = each %$v) {
next if $uscheme ne "https" && exists $v->{secure};
my $value = $v->{value};
$value =~ s/([\\"])/\\$1/g;
$value = '"'.$value.'"' if $value =~ m%["\\=;,[:space:]]%;
push @cookie, "$k=$value";
}
}
}
$hdr{cookie} = join "; ", @cookie
if @cookie;
}
my ($rhost, $rport, $rscheme, $rpath); # request host, port, path
if ($proxy) {
($rpath, $rhost, $rport, $rscheme) = ($url, @$proxy);
$rscheme = "http" unless defined $rscheme;
# don't support https requests over https-proxy transport,
# can't be done with tls as spec'ed, unless you double-encrypt.
$rscheme = "http" if $uscheme eq "https" && $rscheme eq "https";
} else {
($rhost, $rport, $rscheme, $rpath) = ($uhost, $uport, $uscheme, $upath);
}
# leave out fragment and query string, just a heuristic
$hdr{referer} ||= "$uscheme://$uauthority$upath" unless exists $hdr{referer};
$hdr{"user-agent"} ||= $USERAGENT unless exists $hdr{"user-agent"};
$hdr{"content-length"} = length $arg{body}
if length $arg{body} || $method ne "GET";
my %state = (connect_guard => 1);
_get_slot $uhost, sub {
$state{slot_guard} = shift;
return unless $state{connect_guard};
$state{connect_guard} = AnyEvent::Socket::tcp_connect $rhost, $rport, sub {
$state{fh} = shift
or do {
my $err = "$!";
%state = ();
return $cb->(undef, { Status => 599, Reason => $err, @pseudo });
};
pop; # free memory, save a tree
return unless delete $state{connect_guard};
# get handle
$state{handle} = new $handle_class
fh => $state{fh},
peername => $rhost,
tls_ctx => $arg{tls_ctx},
# these need to be reconfigured on keepalive handles
timeout => $timeout,
on_error => sub {
%state = ();
$cb->(undef, { Status => 599, Reason => $_[2], @pseudo });
},
on_eof => sub {
%state = ();
$cb->(undef, { Status => 599, Reason => "Unexpected end-of-file", @pseudo });
},
;
# limit the number of persistent connections
# keepalive not yet supported
# if ($KA_COUNT{$_[1]} < $MAX_PERSISTENT_PER_HOST) {
# ++$KA_COUNT{$_[1]};
# $state{handle}{ka_count_guard} = AnyEvent::Util::guard {
# --$KA_COUNT{$_[1]}
# };
# $hdr{connection} = "keep-alive";
# } else {
delete $hdr{connection};
# }
$state{handle}->starttls ("connect") if $rscheme eq "https";
# handle actual, non-tunneled, request
my $handle_actual_request = sub {
$state{handle}->starttls ("connect") if $uscheme eq "https" && !exists $state{handle}{tls};
# send request
$state{handle}->push_write (
"$method $rpath HTTP/1.0\015\012"
. (join "", map "\u$_: $hdr{$_}\015\012", grep defined $hdr{$_}, keys %hdr)
. "\015\012"
. (delete $arg{body})
);
# return if error occured during push_write()
return unless %state;
%hdr = (); # reduce memory usage, save a kitten, also make it possible to re-use
# status line and headers
$state{handle}->push_read (line => $qr_nlnl, sub {
for ("$_[1]") {
y/\015//d; # weed out any \015, as they show up in the weirdest of places.
/^(?:HTTP|ICY)(?:\/([0-9\.]+))? \s+ ([0-9]{3}) (?: \s+ ([^\015\012]*) )? \015?\012/igxc
or return (%state = (), $cb->(undef, { Status => 599, Reason => "Invalid server response", @pseudo }));
push @pseudo,
HTTPVersion => $1,
Status => $2,
Reason => $3,
;
# things seen, not parsed:
# p3pP="NON CUR OTPi OUR NOR UNI"
$hdr{lc $1} .= ",$2"
while /\G
([^:\000-\037]*):
[\011\040]*
((?: [^\012]+ | \012[\011\040] )*)
\012
/gxc;
/\G$/
or return (%state = (), $cb->(undef, { Status => 599, Reason => "Garbled response headers", @pseudo }));
}
# remove the "," prefix we added to all headers above
substr $_, 0, 1, ""
for values %hdr;
# patch in all pseudo headers
%hdr = (%hdr, @pseudo);
# redirect handling
# microsoft and other shitheads don't give a shit for following standards,
# try to support some common forms of broken Location headers.
if ($hdr{location} !~ /^(?: $ | [^:\/?\#]+ : )/x) {
$hdr{location} =~ s/^\.\/+//;
my $url = "$rscheme://$uhost:$uport";
unless ($hdr{location} =~ s/^\///) {
$url .= $upath;
$url =~ s/\/[^\/]*$//;
}
$hdr{location} = "$url/$hdr{location}";
}
my $redirect;
if ($recurse) {
my $status = $hdr{Status};
# industry standard is to redirect POST as GET for
# 301, 302 and 303, in contrast to http/1.0 and 1.1.
# also, the UA should ask the user for 301 and 307 and POST,
# industry standard seems to be to simply follow.
# we go with the industry standard.
if ($status == 301 or $status == 302 or $status == 303) {
# HTTP/1.1 is unclear on how to mutate the method
$method = "GET" unless $method eq "HEAD";
$redirect = 1;
} elsif ($status == 307) {
$redirect = 1;
}
}
my $finish = sub {
$state{handle}->destroy if $state{handle};
%state = ();
# set-cookie processing
if ($arg{cookie_jar}) {
for ($_[1]{"set-cookie"}) {
# parse NAME=VALUE
my @kv;
# AWY - updated from AnyEvent::HTTP 2.15
# expires is not http-compliant in the original cookie-spec,
# we support the official date format and some extensions
while (
m{
\G\s*
(?:
expires \s*=\s* ([A-Z][a-z][a-z]+,\ [^,;]+)
| ([^=;,[:space:]]+) (?: \s*=\s* (?: "((?:[^\\"]+|\\.)*)" | ([^;,[:space:]]*) ) )?
)
}gcxsi
) {
my $name = $2;
my $value = $4;
if (defined $1) {
# expires
$name = "expires";
$value = $1;
} elsif (defined $3) {
# quoted
$value = $3;
$value =~ s/\\(.)/$1/gs;
}
push @kv, @kv ? lc $name : $name, $value;
last unless /\G\s*;/gc;
}
last unless @kv;
my $name = shift @kv;
my %kv = (value => shift @kv, @kv);
my $cdom;
my $cpath = (delete $kv{path}) || "/";
if (exists $kv{domain}) {
$cdom = delete $kv{domain};
$cdom =~ s/^\.?/./; # make sure it starts with a "."
next if $cdom =~ /\.$/;
# this is not rfc-like and not netscape-like. go figure.
my $ndots = $cdom =~ y/.//;
next if $ndots < ($cdom =~ /\.[^.][^.]\.[^.][^.]$/ ? 3 : 2);
} else {
$cdom = $uhost;
}
# store it
$arg{cookie_jar}{version} = 1;
$arg{cookie_jar}{$cdom}{$cpath}{$name} = \%kv;
redo if /\G\s*,/gc;
}
}
if ($redirect && exists $hdr{location}) {
# we ignore any errors, as it is very common to receive
# Content-Length != 0 but no actual body
# we also access %hdr, as $_[1] might be an erro
http_request (
$method => $hdr{location},
%arg,
recurse => $recurse - 1,
Redirect => \@_,
$cb);
} else {
$cb->($_[0], $_[1]);
}
};
my $len = $hdr{"content-length"};
if (!$redirect && $arg{on_header} && !$arg{on_header}(\%hdr)) {
$finish->(undef, { Status => 598, Reason => "Request cancelled by on_header", @pseudo });
} elsif (
$hdr{Status} =~ /^(?:1..|[23]04)$/
or $method eq "HEAD"
or (defined $len && !$len)
) {
# no body
$finish->("", \%hdr);
} else {
# body handling, four different code paths
# for want_body_handle, on_body (2x), normal (2x)
# we might read too much here, but it does not matter yet (no pers. connections)
if (!$redirect && $arg{want_body_handle}) {
$_[0]->on_eof (undef);
$_[0]->on_error (undef);
$_[0]->on_read (undef);
$finish->(delete $state{handle}, \%hdr);
} elsif ($arg{on_body}) {
$_[0]->on_error (sub { $finish->(undef, { Status => 599, Reason => $_[2], @pseudo }) });
if ($len) {
$_[0]->on_eof (undef);
$_[0]->on_read (sub {
$len -= length $_[0]{rbuf};
$arg{on_body}(delete $_[0]{rbuf}, \%hdr)
or $finish->(undef, { Status => 598, Reason => "Request cancelled by on_body", @pseudo });
$len > 0
or $finish->("", \%hdr);
});
} else {
$_[0]->on_eof (sub {
$finish->("", \%hdr);
});
$_[0]->on_read (sub {
$arg{on_body}(delete $_[0]{rbuf}, \%hdr)
or $finish->(undef, { Status => 598, Reason => "Request cancelled by on_body", @pseudo });
});
}
} else {
$_[0]->on_eof (undef);
if ($len) {
$_[0]->on_error (sub { $finish->(undef, { Status => 599, Reason => $_[2], @pseudo }) });
$_[0]->on_read (sub {
$finish->((substr delete $_[0]{rbuf}, 0, $len, ""), \%hdr)
if $len <= length $_[0]{rbuf};
});
} else {
$_[0]->on_error (sub {
($! == Errno::EPIPE || !$!)
? $finish->(delete $_[0]{rbuf}, \%hdr)
: $finish->(undef, { Status => 599, Reason => $_[2], @pseudo });
});
$_[0]->on_read (sub { });
}
}
}
});
};
# now handle proxy-CONNECT method
if ($proxy && $uscheme eq "https") {
# oh dear, we have to wrap it into a connect request
# maybe re-use $uauthority with patched port?
$state{handle}->push_write ("CONNECT $uhost:$uport HTTP/1.0\015\012Host: $uhost\015\012\015\012");
$state{handle}->push_read (line => $qr_nlnl, sub {
$_[1] =~ /^HTTP\/([0-9\.]+) \s+ ([0-9]{3}) (?: \s+ ([^\015\012]*) )?/ix
or return (%state = (), $cb->(undef, { Status => 599, Reason => "Invalid proxy connect response ($_[1])", @pseudo }));
if ($2 == 200) {
$rpath = $upath;
&$handle_actual_request;
} else {
%state = ();
$cb->(undef, { Status => $2, Reason => $3, @pseudo });
}
});
} else {
&$handle_actual_request;
}
}, $arg{on_prepare} || sub { $timeout };
};
defined wantarray && AnyEvent::Util::guard { %state = () }
}
sub http_get($@) {
unshift @_, "GET";
&http_request
}
sub http_head($@) {
unshift @_, "HEAD";
&http_request
}
sub http_post($$@) {
my $url = shift;
unshift @_, "POST", $url, "body";
&http_request
}
=back
=head2 DNS CACHING
AnyEvent::HTTP uses the AnyEvent::Socket::tcp_connect function for
the actual connection, which in turn uses AnyEvent::DNS to resolve
hostnames. The latter is a simple stub resolver and does no caching
on its own. If you want DNS caching, you currently have to provide
your own default resolver (by storing a suitable resolver object in
C<$AnyEvent::DNS::RESOLVER>).
=head2 GLOBAL FUNCTIONS AND VARIABLES
=over 4
=item AnyEvent::HTTP::set_proxy "proxy-url"
Sets the default proxy server to use. The proxy-url must begin with a
string of the form C<http://host:port> (optionally C<https:...>), croaks
otherwise.
To clear an already-set proxy, use C<undef>.
=item $AnyEvent::HTTP::MAX_RECURSE
The default value for the C<recurse> request parameter (default: C<10>).
=item $AnyEvent::HTTP::USERAGENT
The default value for the C<User-Agent> header (the default is
C<Mozilla/5.0 (compatible; U; AnyEvent-HTTP/$VERSION; +http://software.schmorp.de/pkg/AnyEvent)>).
=item $AnyEvent::HTTP::MAX_PER_HOST
The maximum number of concurrent connections to the same host (identified
by the hostname). If the limit is exceeded, then the additional requests
are queued until previous connections are closed.
The default value for this is C<4>, and it is highly advisable to not
increase it.
=item $AnyEvent::HTTP::ACTIVE
The number of active connections. This is not the number of currently
running requests, but the number of currently open and non-idle TCP
connections. This number of can be useful for load-leveling.
=back
=cut
sub set_proxy($) {
if (length $_[0]) {
$_[0] =~ m%^(https?):// ([^:/]+) (?: : (\d*) )?%ix
or Carp::croak "$_[0]: invalid proxy URL";
$PROXY = [$2, $3 || 3128, $1]
} else {
undef $PROXY;
}
}
# initialise proxy from environment
eval {
set_proxy $ENV{http_proxy};
};
=head1 SEE ALSO
L<AnyEvent>.
=head1 AUTHOR
Marc Lehmann <[email protected]>
http://home.schmorp.de/
With many thanks to Дмитрий Шалашов, who provided countless
testcases and bugreports.
=cut
1
| {
"pile_set_name": "Github"
} |
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "Menu 2-66.png",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
} | {
"pile_set_name": "Github"
} |
[
{ "keys": ["ctrl+alt+x"], "command": "prefixr" }
] | {
"pile_set_name": "Github"
} |
require 'tty-prompt'
require 'terjira/utils/file_cache'
module Terjira
module Client
module AuthOptionBuilder
AUTH_CACHE_KEY = 'auth'.freeze
def build_auth_options(options = {})
cache_key = options[:cache_key] || AUTH_CACHE_KEY
auth_file_cache.fetch cache_key do
build_auth_options_by_tty(options)
end
end
def build_auth_options_by_cached(options = {})
cache_key = options[:cache_key] || AUTH_CACHE_KEY
auth_file_cache.get(cache_key)
end
def expire_auth_options
Terjira::FileCache.clear_all
end
def build_auth_options_by_tty(options = {})
puts 'Login will be required...'
prompt = TTY::Prompt.new
result = prompt.collect do
key(:site).ask('Site (ex: https://myjira.atlassian.net):', required: true)
key(:context_path).ask('Jira path in your site (just press enter if you don\'t have):', default: '')
key(:username).ask('Username:', required: true)
key(:password).mask('Password (Server) / API Token (Cloud):', required: true)
if options['ssl-config']
key(:use_ssl).yes?('Use SSL?')
key(:ssl_verify_mode).select('Verify mode:') do |menu|
menu.choice 'Verify peer', OpenSSL::SSL::VERIFY_PEER
menu.choice 'Verify client once', OpenSSL::SSL::VERIFY_CLIENT_ONCE
menu.choice 'Verify fail if no peer cert', OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT
menu.choice 'Verify none', OpenSSL::SSL::VERIFY_NONE
end
end
if options['proxy-config']
key(:proxy_address).ask("Proxy address: ", default: nil)
key(:proxy_port).ask("Proxy port: ", default: nil)
end
end
result[:auth_type] = :basic
result[:use_ssl] ||= false if result[:site] =~ /http\:\/\//
result
end
def auth_file_cache
@auth_file_cache ||= Terjira::FileCache.new('profile')
end
end
end
end
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import <UIKit/UIKit.h>
#import <IGListKit/IGListKit.h>
@interface IGTestStoryboardSupplementarySource : NSObject <IGListSupplementaryViewSource>
@property (nonatomic, copy, readwrite) NSArray<NSString *> *supportedElementKinds;
@property (nonatomic, weak) id<IGListCollectionContext> collectionContext;
@property (nonatomic, weak) IGListSectionController *sectionController;
@end
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Automatically generated file. Do not edit. -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Antialiasing</title>
<link rel="stylesheet" type="text/css" href="../../../../style.css" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" /></head>
<body style="font-family:Arial, Helvetica, sans-serif">
<p style="text-align:right;"><a href="/doc/qcad/latest/reference/it/index.php?page=scripts/View/AntialiasingMode/doc/AntialiasingMode">      </a></p>
<p style="font-style: italic;">Questa è una traduzione automatica.</p>
<div class="nobreak">
<h2>Antialiasing</h2>
<p class="toolinfo">
<b>Barra degli strumenti / Icona:</b>
<br /><img src="../../doc/View.png" width="40" height="40" />
   
<img src="../doc/AntialiasingMode.png" width="40" height="40" />
   
<br/>
<b>Menù:</b> <font face="courier new">Vista > Antialiasing</font>
<br /><b>Scorciatoia:</b> <font face="courier new">N, T</font>
<br /><b>Comandi:</b> <font face="courier new">antialiasing | nt</font>
</p>
</div>
<h3>Descrizione</h3>
<p>Commuta l'anti-aliasing per il disegno corrente. Con l'anti-aliasing, le
linee oblique, gli archi e i testi vengono visualizzati in modo più
uniforme.</p>
</body>
</html>
| {
"pile_set_name": "Github"
} |
---
title: Facebook を ID プロバイダーとして追加する - Azure AD
description: Facebook とフェデレーションして、外部ユーザー (ゲスト) が自分の Facebook アカウントで Azure AD アプリにサインインできるようにします。
services: active-directory
ms.service: active-directory
ms.subservice: B2B
ms.topic: how-to
ms.date: 05/19/2020
ms.author: mimart
author: msmimart
manager: celestedg
ms.reviewer: mal
ms.custom: it-pro, seo-update-azuread-jan
ms.collection: M365-identity-device-management
ms.openlocfilehash: 0b5e1db2c86f6118c3cd333974c9cfd64f747128
ms.sourcegitcommit: 4e5560887b8f10539d7564eedaff4316adb27e2c
ms.translationtype: HT
ms.contentlocale: ja-JP
ms.lasthandoff: 08/06/2020
ms.locfileid: "87907509"
---
# <a name="add-facebook-as-an-identity-provider-for-external-identities"></a>外部 ID のために Facebook を ID プロバイダーとして追加する
Facebook をセルフサービス サインアップのユーザー フロー (プレビュー) に追加して、ユーザーが自分の Facebook アカウントを使用してアプリケーションにサインインできるようにすることができます。 ユーザーが Facebook を使用してサインインできるようにするには、まず、テナントに対して[セルフサービス サインアップ](self-service-sign-up-user-flow.md)を有効にする必要があります。 Facebook を ID プロバイダーとして追加した後、アプリケーションに対するユーザー フローを設定し、サインイン オプションの 1 つとして Facebook を選択します。
> [!NOTE]
> ユーザーは、セルフサービス サインアップおよびユーザー フローを使用したアプリ経由のサインアップに限り、Facebook アカウントを使用できます。 ユーザーは招待されても、Facebook アカウントを使用して招待を利用することはできません。
## <a name="create-an-app-in-the-facebook-developers-console"></a>Facebook 開発者コンソールでアプリを作成する
[ID プロバイダー](identity-providers.md)として Facebook アカウントを使用するには、Facebook 開発者コンソールでアプリケーションを作成する必要があります。 まだ Facebook アカウントを持っていない場合は、[https://www.facebook.com/](https://www.facebook.com) でサインアップできます。
> [!NOTE]
> 以下のステップ 9 と 16 では、次の URL を使用します。
> - **[サイトの URL]** には、`https://contoso.com` など、アプリケーションのアドレスを入力します。
> - **[Valid OAuth redirect URIs]\(有効な OAuth リダイレクト URI\)** には、「`https://login.microsoftonline.com/te/<tenant-id>/oauth2/authresp`」と入力します。 自分の `<tenant-ID>` は、Azure Active Directory の [概要] ブレードで確認できます。
1. Facebook アカウントの資格情報を使用して、[開発者向けの Facebook](https://developers.facebook.com/)にサインインします。
2. まだ登録していない場合は、Facebook 開発者として登録する必要があります。 これを行うには、ページの右上隅にある **[Get Started]\(スタートガイド\)** を選択し、Facebook のポリシーに同意して登録手順を完了します。
3. **[マイ アプリ]** を選択し、 **[アプリの作成]** を選択します。
4. **[表示名]** および有効な **[連絡先の電子メール]** を入力します。
5. **[Create App ID]\(アプリ ID の作成\)** を選択します。 Facebook プラットフォームのポリシーを受け入れ、オンライン セキュリティ チェックを完了する必要があります。
6. **[設定]** > **[基本]** を選択します。
7. **[Category]\(カテゴリ\)** を選択します (たとえば [Business and Pages]\(ビジネスとページ\))。 この値は Facebook では必須ですが、Azure AD では使用されません。
8. ページの下部で、 **[プラットフォームの追加]** 、 **[Web サイト]** の順に選択します。
9. **[Site URL]\(サイトの URL\)** に、適切な URL を入力します (上に記載)。
10. **[Privacy Policy URL]\(プライバシー ポリシーの URL\)** に、アプリケーションのプライバシー情報が保持されているページの URL を入力します (例: `http://www.contoso.com`)。
11. **[変更の保存]** を選択します。
12. ページの上部で、 **[App ID] (アプリ ID)** の値をコピーします。
13. **[Show (表示)]** を選択し、 **[App Secret (アプリ シークレット)]** の値をコピーします。 テナントで ID プロバイダーとして Facebook を構成するには、この両方を使用します。 **[App Secret]** は、重要なセキュリティ資格情報です。
14. **[Products]\(製品\)** を選択し、 **[Facebook Login]\(Facebook ログイン\)** で **[Set up]\(セットアップ\)** を選択します。
15. **[Facebook Login]\(Facebook ログイン\)** の **[Settings]\(設定\)** を選択します。
16. **[Valid OAuth redirect URIs]\(有効な OAuth リダイレクト URI\)** に、適切な URL を入力します (上に記載)。
17. ページの下部にある **[Save Changes]\(変更の保存\)** を選択します。
18. Facebook アプリケーションを Azure AD で使用できるようにするには、ページの右上にある状態セレクターを選択し、それを **[オン]** にしてアプリケーションをパブリックにした後、 **[Switch Mode]\(モードの切り替え\)** を選択します。 この時点で、状態は**開発**から**ライブ**に変更されます。
## <a name="configure-a-facebook-account-as-an-identity-provider"></a>ID プロバイダーとして Facebook アカウントを構成する
次に、Azure AD ポータルで入力するか、または PowerShell を使用して、Facebook クライアント ID とクライアント シークレットを設定します。 セルフサービス サインアップが有効になっているアプリでユーザー フローを使用してサインアップすることで、Facebook の構成をテストすることができます。
### <a name="to-configure-facebook-federation-in-the-azure-ad-portal"></a>Azure AD ポータルで Facebook フェデレーションを構成するには
1. Azure AD テナントの全体管理者として [Azure portal](https://portal.azure.com) にサインインします。
2. **[Azure サービス]** で **[Azure Active Directory]** を選択します。
3. 左側のメニューで、 **[External Identities]** を選択します。
4. **[All identity providers]\(すべての ID プロバイダー\)** を選択してから、 **[Facebook]** を選択します。
5. **[クライアント ID]** には、前に作成した Facebook アプリケーションの**アプリ ID** を入力します。
6. **[クライアント シークレット]** には、記録した**アプリ シークレット**を入力します。
![[ソーシャル ID プロバイダーの追加] ページを示すスクリーンショット](media/facebook-federation/add-social-identity-provider-page.png)
7. **[保存]** を選択します。
### <a name="to-configure-facebook-federation-by-using-powershell"></a>PowerShell を使用して Facebook フェデレーションを構成するには
1. 最新バージョンの Azure AD PowerShell for Graph モジュールをインストールします ([AzureADPreview](https://www.powershellgallery.com/packages/AzureADPreview))。
2. コマンド `Connect-AzureAD` を実行します。
3. サインイン プロンプトで、マネージド グローバル管理者アカウントを使用してサインインします。
4. 次のコマンドを実行します。
`New-AzureADMSIdentityProvider -Type Facebook -Name Facebook -ClientId [Client ID] -ClientSecret [Client secret]`
> [!NOTE]
> Facebook 開発者コンソールで、前の手順で作成したアプリのクライアント ID とクライアント シークレットを使用します。 詳細については、記事「[New-AzureADMSIdentityProvider](https://docs.microsoft.com/powershell/module/azuread/new-azureadmsidentityprovider?view=azureadps-2.0-preview)」を参照してください。
## <a name="how-do-i-remove-facebook-federation"></a>Facebook フェデレーションを削除する方法
Facebook フェデレーション セットアップは削除できます。 それを行った場合、Facebook アカウントを使用してユーザー フローを通じてサインアップしたユーザーは、ログインできなくなります。
### <a name="to-delete-facebook-federation-in-the-azure-ad-portal"></a>Azure AD ポータルで Facebook フェデレーションを削除するには:
1. [Azure ポータル](https://portal.azure.com)にアクセスします。 左ウィンドウで、 **[Azure Active Directory]** を選択します。
2. **[外部 ID]** を選択します。
3. **[すべての ID プロバイダー]** を選択します。
4. **[Facebook]** 行で、コンテキスト メニュー ( **...** ) を選択してから **[Delete]\(削除\)** を選択します。
5. **[はい]** を選択して削除を確定します。
### <a name="to-delete-facebook-federation-by-using-powershell"></a>PowerShell を使用して Facebook フェデレーションを削除するには:
1. 最新バージョンの Azure AD PowerShell for Graph モジュールをインストールします ([AzureADPreview](https://www.powershellgallery.com/packages/AzureADPreview))。
2. `Connect-AzureAD` を実行します。
4. サインイン プロンプトで、マネージド グローバル管理者アカウントを使用してサインインします。
5. 次のコマンドを入力します。
`Remove-AzureADMSIdentityProvider -Id Facebook-OAUTH`
> [!NOTE]
> 詳細については、「[Remove-AzureADMSIdentityProvider](https://docs.microsoft.com/powershell/module/azuread/Remove-AzureADMSIdentityProvider?view=azureadps-2.0-preview)」を参照してください。
## <a name="next-steps"></a>次のステップ
- [セルフサービス サインアップをアプリに追加する](self-service-sign-up-user-flow.md)
| {
"pile_set_name": "Github"
} |
//| Copyright Inria May 2015
//| This project has received funding from the European Research Council (ERC) under
//| the European Union's Horizon 2020 research and innovation programme (grant
//| agreement No 637972) - see http://www.resibots.eu
//|
//| Contributor(s):
//| - Jean-Baptiste Mouret ([email protected])
//| - Antoine Cully ([email protected])
//| - Konstantinos Chatzilygeroudis ([email protected])
//| - Federico Allocati ([email protected])
//| - Vaios Papaspyros ([email protected])
//| - Roberto Rama ([email protected])
//|
//| This software is a computer library whose purpose is to optimize continuous,
//| black-box functions. It mainly implements Gaussian processes and Bayesian
//| optimization.
//| Main repository: http://github.com/resibots/limbo
//| Documentation: http://www.resibots.eu/limbo
//|
//| This software is governed by the CeCILL-C license under French law and
//| abiding by the rules of distribution of free software. You can use,
//| modify and/ or redistribute the software under the terms of the CeCILL-C
//| license as circulated by CEA, CNRS and INRIA at the following URL
//| "http://www.cecill.info".
//|
//| As a counterpart to the access to the source code and rights to copy,
//| modify and redistribute granted by the license, users are provided only
//| with a limited warranty and the software's author, the holder of the
//| economic rights, and the successive licensors have only limited
//| liability.
//|
//| In this respect, the user's attention is drawn to the risks associated
//| with loading, using, modifying and/or developing or reproducing the
//| software by the user in light of its specific status of free software,
//| that may mean that it is complicated to manipulate, and that also
//| therefore means that it is reserved for developers and experienced
//| professionals having in-depth computer knowledge. Users are therefore
//| encouraged to load and test the software's suitability as regards their
//| requirements in conditions enabling the security of their systems and/or
//| data to be ensured and, more generally, to use and operate it in the
//| same conditions as regards security.
//|
//| The fact that you are presently reading this means that you have had
//| knowledge of the CeCILL-C license and that you accept its terms.
//|
#include <fstream>
#include <limbo/kernel/exp.hpp>
#include <limbo/kernel/squared_exp_ard.hpp>
#include <limbo/mean/data.hpp>
#include <limbo/model/gp.hpp>
#include <limbo/model/gp/kernel_lf_opt.hpp>
#include <limbo/tools.hpp>
#include <limbo/tools/macros.hpp>
#include <limbo/serialize/text_archive.hpp>
// this tutorials shows how to use a Gaussian process for regression
using namespace limbo;
struct Params {
struct kernel_exp {
BO_PARAM(double, sigma_sq, 1.0);
BO_PARAM(double, l, 0.2);
};
struct kernel : public defaults::kernel {
};
struct kernel_squared_exp_ard : public defaults::kernel_squared_exp_ard {
};
struct opt_rprop : public defaults::opt_rprop {
};
};
int main(int argc, char** argv)
{
// our data (1-D inputs, 1-D outputs)
std::vector<Eigen::VectorXd> samples;
std::vector<Eigen::VectorXd> observations;
size_t N = 8;
for (size_t i = 0; i < N; i++) {
Eigen::VectorXd s = tools::random_vector(1).array() * 4.0 - 2.0;
samples.push_back(s);
observations.push_back(tools::make_vector(std::cos(s(0))));
}
// the type of the GP
using Kernel_t = kernel::Exp<Params>;
using Mean_t = mean::Data<Params>;
using GP_t = model::GP<Params, Kernel_t, Mean_t>;
// 1-D inputs, 1-D outputs
GP_t gp(1, 1);
// compute the GP
gp.compute(samples, observations);
// write the predicted data in a file (e.g. to be plotted)
std::ofstream ofs("gp.dat");
for (int i = 0; i < 100; ++i) {
Eigen::VectorXd v = tools::make_vector(i / 100.0).array() * 4.0 - 2.0;
Eigen::VectorXd mu;
double sigma;
std::tie(mu, sigma) = gp.query(v);
// an alternative (slower) is to query mu and sigma separately:
// double mu = gp.mu(v)[0]; // mu() returns a 1-D vector
// double s2 = gp.sigma(v);
ofs << v.transpose() << " " << mu[0] << " " << sqrt(sigma) << std::endl;
}
// an alternative is to optimize the hyper-parameters
// in that case, we need a kernel with hyper-parameters that are designed to be optimized
using Kernel2_t = kernel::SquaredExpARD<Params>;
using Mean_t = mean::Data<Params>;
using GP2_t = model::GP<Params, Kernel2_t, Mean_t, model::gp::KernelLFOpt<Params>>;
GP2_t gp_ard(1, 1);
// do not forget to call the optimization!
gp_ard.compute(samples, observations, false);
gp_ard.optimize_hyperparams();
// write the predicted data in a file (e.g. to be plotted)
std::ofstream ofs_ard("gp_ard.dat");
for (int i = 0; i < 100; ++i) {
Eigen::VectorXd v = tools::make_vector(i / 100.0).array() * 4.0 - 2.0;
Eigen::VectorXd mu;
double sigma;
std::tie(mu, sigma) = gp_ard.query(v);
ofs_ard << v.transpose() << " " << mu[0] << " " << sqrt(sigma) << std::endl;
}
// write the data to a file (useful for plotting)
std::ofstream ofs_data("data.dat");
for (size_t i = 0; i < samples.size(); ++i)
ofs_data << samples[i].transpose() << " " << observations[i].transpose() << std::endl;
// Sometimes is useful to save an optimized GP
gp_ard.save<serialize::TextArchive>("myGP");
// Later we can load -- we need to make sure that the type is identical to the one saved
gp_ard.load<serialize::TextArchive>("myGP");
return 0;
}
| {
"pile_set_name": "Github"
} |
.wrapper{margin: 5px 10px;}
.searchBar{height:30px;padding:7px 0 3px;text-align:center;}
.searchBtn{font-size:13px;height:24px;}
.resultBar{width:460px;margin:5px auto;border: 1px solid #CCC;border-radius: 5px;box-shadow: 2px 2px 5px #D3D6DA;overflow: hidden;}
.listPanel{overflow: hidden;}
.panelon{display:block;}
.paneloff{display:none}
.page{width:220px;margin:20px auto;overflow: hidden;}
.pageon{float:right;width:24px;line-height:24px;height:24px;margin-right: 5px;background: none;border: none;color: #000;font-weight: bold;text-align:center}
.pageoff{float:right;width:24px;line-height:24px;height:24px;cursor:pointer;background-color: #fff;
border: 1px solid #E7ECF0;color: #2D64B3;margin-right: 5px;text-decoration: none;text-align:center;}
.m-box{width:460px;}
.m-m{float: left;line-height: 20px;height: 20px;}
.m-h{height:24px;line-height:24px;padding-left: 46px;background-color:#FAFAFA;border-bottom: 1px solid #DAD8D8;font-weight: bold;font-size: 12px;color: #333;}
.m-l{float:left;width:40px; }
.m-t{float:left;width:140px;}
.m-s{float:left;width:110px;}
.m-z{float:left;width:100px;}
.m-try-t{float: left;width: 60px;;}
.m-try{float:left;width:20px;height:20px;background:url('http://static.tieba.baidu.com/tb/editor/images/try_music.gif') no-repeat ;}
.m-trying{float:left;width:20px;height:20px;background:url('http://static.tieba.baidu.com/tb/editor/images/stop_music.gif') no-repeat ;}
.loading{width:95px;height:7px;font-size:7px;margin:60px auto;background:url(http://static.tieba.baidu.com/tb/editor/images/loading.gif) no-repeat}
.empty{width:300px;height:40px;padding:2px;margin:50px auto;line-height:40px; color:#006699;text-align:center;} | {
"pile_set_name": "Github"
} |
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Imports System
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("RemoteApp_Tool.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set
resourceCulture = value
End Set
End Property
End Module
End Namespace
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
| {
"pile_set_name": "Github"
} |
#pragma once
#include <vector>
template<typename tVal, typename tAlloc = std::allocator<tVal>>
class cCircularBuffer
{
public:
cCircularBuffer();
cCircularBuffer(size_t capacity);
virtual ~cCircularBuffer();
virtual void Reserve(size_t capacity);
virtual void Clear();
virtual size_t GetSize() const;
virtual size_t GetCapacity() const;
virtual void Add(const tVal& val);
virtual const tVal& operator[](size_t i) const;
virtual tVal& operator[](size_t i);
protected:
size_t mHead;
size_t mSize;
std::vector<tVal, tAlloc> mData;
virtual size_t CalcIdx(size_t i) const;
};
template<typename tVal, typename tAlloc>
cCircularBuffer<tVal, tAlloc>::cCircularBuffer() :
cCircularBuffer(0)
{
}
template<typename tVal, typename tAlloc>
cCircularBuffer<tVal, tAlloc>::cCircularBuffer(size_t capacity)
{
mHead = 0;
mSize = 0;
Reserve(capacity);
}
template<typename tVal, typename tAlloc>
cCircularBuffer<tVal, tAlloc>::~cCircularBuffer()
{
}
template<typename tVal, typename tAlloc>
void cCircularBuffer<tVal, tAlloc>::Reserve(size_t capacity)
{
size_t prev_size = mData.size();
mData.resize(capacity);
if (prev_size > 0)
{
for (size_t i = prev_size - 1; i >= mHead; --i)
{
size_t new_idx = capacity - (prev_size - i);
mData[new_idx] = mData[i];
}
}
if (prev_size != mHead)
{
mSize = capacity;
}
}
template<typename tVal, typename tAlloc>
void cCircularBuffer<tVal, tAlloc>::Clear()
{
mHead = 0;
mSize = 0;
}
template<typename tVal, typename tAlloc>
size_t cCircularBuffer<tVal, tAlloc>::GetSize() const
{
return mSize;
}
template<typename tVal, typename tAlloc>
size_t cCircularBuffer<tVal, tAlloc>::GetCapacity() const
{
return mData.size();
}
template<typename tVal, typename tAlloc>
void cCircularBuffer<tVal, tAlloc>::Add(const tVal& val)
{
mData[mHead] = val;
size_t capacity = GetCapacity();
mHead = (mHead + 1) % capacity;
mSize = std::min((mSize + 1), capacity);
}
template<typename tVal, typename tAlloc>
const tVal& cCircularBuffer<tVal, tAlloc>::operator[](size_t i) const
{
size_t idx = CalcIdx(i);
return mData[idx];
}
template<typename tVal, typename tAlloc>
tVal& cCircularBuffer<tVal, tAlloc>::operator[](size_t i)
{
size_t idx = CalcIdx(i);
return mData[idx];
}
template<typename tVal, typename tAlloc>
size_t cCircularBuffer<tVal, tAlloc>::CalcIdx(size_t i) const
{
size_t idx = (mHead + i) % GetSize();
return idx;
} | {
"pile_set_name": "Github"
} |
# Example STAN app
In this example app you can find several different ways of instrumenting NATS Streaming functions using New Relic. In order to run the app, make sure the following assumptions are correct:
* Your New Relic license key is available as an environment variable named `NEW_RELIC_LICENSE_KEY`
* A NATS Streaming Server is running with the cluster id `test-cluster` | {
"pile_set_name": "Github"
} |
package internal
import (
"fmt"
"net"
)
// AddressManager allocates a new address (interface & port) a process
// can bind and keeps track of that.
type AddressManager struct {
port int
host string
}
// Initialize returns a address a process can listen on. It returns
// a tuple consisting of a free port and the hostname resolved to its IP.
func (d *AddressManager) Initialize() (port int, resolvedHost string, err error) {
if d.port != 0 {
return 0, "", fmt.Errorf("this AddressManager is already initialized")
}
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return
}
d.port = l.Addr().(*net.TCPAddr).Port
defer func() {
err = l.Close()
}()
d.host = addr.IP.String()
return d.port, d.host, nil
}
// Port returns the port that this AddressManager is managing. Port returns an
// error if this AddressManager has not yet been initialized.
func (d *AddressManager) Port() (int, error) {
if d.port == 0 {
return 0, fmt.Errorf("this AdressManager is not initialized yet")
}
return d.port, nil
}
// Host returns the host that this AddressManager is managing. Host returns an
// error if this AddressManager has not yet been initialized.
func (d *AddressManager) Host() (string, error) {
if d.host == "" {
return "", fmt.Errorf("this AdressManager is not initialized yet")
}
return d.host, nil
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet href="coverage.xsl" type="text/xsl"?>
<!-- saved from url=(0022)http://www.ncover.org/ -->
<coverage profilerVersion="1.5.8 Beta" driverVersion="1.5.8.0" startTime="2011-12-12T22:44:49.7762531+01:00" measureTime="2011-12-12T22:44:49.8563683+01:00">
<module moduleId="2" name="C:\temp\Test.exe" assembly="Test" assemblyIdentity="Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null, processorArchitecture=MSIL">
<method name="ExecutedMethod_1" excluded="false" instrumented="true" class="Test.PartialClass">
<seqpnt visitcount="1" line="9" column="13" endline="9" endcolumn="39" excluded="false" document="C:\temp\PartialClass.cs" />
<seqpnt visitcount="1" line="10" column="9" endline="10" endcolumn="10" excluded="false" document="C:\temp\PartialClass.cs" />
</method>
<method name="ExecutedMethod_2" excluded="false" instrumented="true" class="Test.PartialClass">
<seqpnt visitcount="1" line="9" column="13" endline="9" endcolumn="39" excluded="false" document="C:\temp\PartialClass2.cs" />
<seqpnt visitcount="1" line="10" column="9" endline="10" endcolumn="10" excluded="false" document="C:\temp\PartialClass2.cs" />
</method>
<method name="UnExecutedMethod_2" excluded="false" instrumented="true" class="Test.PartialClass">
<seqpnt visitcount="0" line="14" column="13" endline="14" endcolumn="39" excluded="false" document="C:\temp\PartialClass2.cs" />
<seqpnt visitcount="0" line="15" column="9" endline="15" endcolumn="10" excluded="false" document="C:\temp\PartialClass2.cs" />
</method>
<method name="UnExecutedMethod_1" excluded="false" instrumented="true" class="Test.PartialClass">
<seqpnt visitcount="0" line="14" column="13" endline="14" endcolumn="39" excluded="false" document="C:\temp\PartialClass.cs" />
<seqpnt visitcount="0" line="15" column="9" endline="15" endcolumn="10" excluded="false" document="C:\temp\PartialClass.cs" />
</method>
<method name="get_SomeProperty" excluded="false" instrumented="true" class="Test.PartialClass">
<seqpnt visitcount="0" line="21" column="19" endline="21" endcolumn="44" excluded="false" document="C:\temp\PartialClass.cs" />
<seqpnt visitcount="0" line="21" column="45" endline="21" endcolumn="46" excluded="false" document="C:\temp\PartialClass.cs" />
</method>
<method name="set_SomeProperty" excluded="false" instrumented="true" class="Test.PartialClass">
<seqpnt visitcount="1" line="25" column="17" endline="25" endcolumn="31" excluded="false" document="C:\temp\PartialClass.cs" />
<seqpnt visitcount="1" line="27" column="21" endline="27" endcolumn="43" excluded="false" document="C:\temp\PartialClass.cs" />
<seqpnt visitcount="0" line="31" column="21" endline="31" endcolumn="47" excluded="false" document="C:\temp\PartialClass.cs" />
<seqpnt visitcount="1" line="33" column="13" endline="33" endcolumn="14" excluded="false" document="C:\temp\PartialClass.cs" />
</method>
<method name="Main" excluded="false" instrumented="true" class="Test.Program">
<seqpnt visitcount="1" line="8" column="13" endline="8" endcolumn="46" excluded="false" document="C:\temp\Program.cs" />
<seqpnt visitcount="1" line="10" column="13" endline="10" endcolumn="53" excluded="false" document="C:\temp\Program.cs" />
<seqpnt visitcount="1" line="11" column="13" endline="11" endcolumn="61" excluded="false" document="C:\temp\Program.cs" />
<seqpnt visitcount="1" line="13" column="13" endline="13" endcolumn="51" excluded="false" document="C:\temp\Program.cs" />
<seqpnt visitcount="1" line="14" column="13" endline="14" endcolumn="51" excluded="false" document="C:\temp\Program.cs" />
<seqpnt visitcount="1" line="15" column="13" endline="15" endcolumn="51" excluded="false" document="C:\temp\Program.cs" />
<seqpnt visitcount="1" line="17" column="13" endline="17" endcolumn="69" excluded="false" document="C:\temp\Program.cs" />
<seqpnt visitcount="1" line="18" column="13" endline="18" endcolumn="69" excluded="false" document="C:\temp\Program.cs" />
<seqpnt visitcount="1" line="20" column="13" endline="20" endcolumn="48" excluded="false" document="C:\temp\Program.cs" />
<seqpnt visitcount="1" line="21" column="9" endline="21" endcolumn="10" excluded="false" document="C:\temp\Program.cs" />
</method>
<method name="SampleFunction" excluded="false" instrumented="true" class="Test.TestClass">
<seqpnt visitcount="1" line="9" column="13" endline="9" endcolumn="47" excluded="false" document="C:\temp\TestClass.cs" />
<seqpnt visitcount="1" line="10" column="13" endline="10" endcolumn="24" excluded="false" document="C:\temp\TestClass.cs" />
<seqpnt visitcount="1" line="12" column="13" endline="12" endcolumn="23" excluded="false" document="C:\temp\TestClass.cs" />
<seqpnt visitcount="1" line="14" column="17" endline="14" endcolumn="61" excluded="false" document="C:\temp\TestClass.cs" />
<seqpnt visitcount="0" line="18" column="17" endline="18" endcolumn="65" excluded="false" document="C:\temp\TestClass.cs" />
<seqpnt visitcount="1" line="20" column="9" endline="20" endcolumn="10" excluded="false" document="C:\temp\TestClass.cs" />
</method>
<method name="SampleFunction" excluded="false" instrumented="false" class="Test.TestClass+NestedClass">
<seqpnt visitcount="0" line="25" column="13" endline="25" endcolumn="14" excluded="false" document="C:\temp\TestClass.cs" />
<seqpnt visitcount="0" line="26" column="17" endline="26" endcolumn="50" excluded="false" document="C:\temp\TestClass.cs" />
<seqpnt visitcount="0" line="27" column="13" endline="27" endcolumn="14" excluded="false" document="C:\temp\TestClass.cs" />
</method>
<method name=".ctor" excluded="false" instrumented="true" class="Test.TestClass2">
<seqpnt visitcount="0" line="11" column="9" endline="11" endcolumn="78" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="0" line="17" column="9" endline="17" endcolumn="28" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="0" line="19" column="13" endline="19" endcolumn="34" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="0" line="20" column="13" endline="20" endcolumn="46" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="0" line="21" column="9" endline="21" endcolumn="10" excluded="false" document="C:\temp\TestClass2.cs" />
</method>
<method name=".ctor" excluded="false" instrumented="true" class="Test.TestClass2">
<seqpnt visitcount="2" line="11" column="9" endline="11" endcolumn="78" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="2" line="23" column="9" endline="23" endcolumn="39" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="2" line="25" column="13" endline="25" endcolumn="30" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="2" line="26" column="13" endline="26" endcolumn="49" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="2" line="27" column="9" endline="27" endcolumn="10" excluded="false" document="C:\temp\TestClass2.cs" />
</method>
<method name="ExecutedMethod" excluded="false" instrumented="true" class="Test.TestClass2">
<seqpnt visitcount="1" line="31" column="13" endline="31" endcolumn="42" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="1" line="32" column="13" endline="32" endcolumn="54" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="1" line="33" column="9" endline="33" endcolumn="10" excluded="false" document="C:\temp\TestClass2.cs" />
</method>
<method name="UnExecutedMethod" excluded="false" instrumented="true" class="Test.TestClass2">
<seqpnt visitcount="0" line="37" column="13" endline="37" endcolumn="42" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="0" line="38" column="13" endline="38" endcolumn="54" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="0" line="39" column="9" endline="39" endcolumn="10" excluded="false" document="C:\temp\TestClass2.cs" />
</method>
<method name="SampleFunction" excluded="false" instrumented="true" class="Test.TestClass2">
<seqpnt visitcount="1" line="43" column="13" endline="43" endcolumn="53" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="1" line="45" column="13" endline="45" endcolumn="53" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="1" line="47" column="34" endline="47" endcolumn="41" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="4" line="47" column="22" endline="47" endcolumn="30" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="4" line="49" column="17" endline="49" endcolumn="41" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="5" line="47" column="31" endline="47" endcolumn="33" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="1" line="52" column="13" endline="52" endcolumn="76" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="1" line="54" column="13" endline="54" endcolumn="105" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="1" line="56" column="17" endline="56" endcolumn="52" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="1" line="58" column="9" endline="58" endcolumn="10" excluded="false" document="C:\temp\TestClass2.cs" />
</method>
<method name="<SampleFunction>b__0" excluded="false" instrumented="true" class="Test.TestClass2">
<seqpnt visitcount="4" line="45" column="46" endline="45" endcolumn="51" excluded="false" document="C:\temp\TestClass2.cs" />
</method>
<method name="DoSomething" excluded="false" instrumented="true" class="Test.TestClass2">
<seqpnt visitcount="0" line="81" column="13" endline="81" endcolumn="19" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="0" line="82" column="13" endline="82" endcolumn="25" excluded="false" document="C:\temp\TestClass2.cs" />
<seqpnt visitcount="0" line="83" column="9" endline="83" endcolumn="10" excluded="false" document="C:\temp\TestClass2.cs" />
</method>
<method name="<SampleFunction>b__1" excluded="false" instrumented="true" class="Test.TestClass2+<>c__DisplayClass3">
<seqpnt visitcount="3" line="54" column="45" endline="54" endcolumn="95" excluded="false" document="C:\temp\TestClass2.cs" />
</method>
</module>
</coverage> | {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0-only
/*
* wm8988.c -- WM8988 ALSA SoC audio driver
*
* Copyright 2009 Wolfson Microelectronics plc
* Copyright 2005 Openedhand Ltd.
*
* Author: Mark Brown <[email protected]>
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/i2c.h>
#include <linux/spi/spi.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/tlv.h>
#include <sound/soc.h>
#include <sound/initval.h>
#include "wm8988.h"
/*
* wm8988 register cache
* We can't read the WM8988 register space when we
* are using 2 wire for device control, so we cache them instead.
*/
static const struct reg_default wm8988_reg_defaults[] = {
{ 0, 0x0097 },
{ 1, 0x0097 },
{ 2, 0x0079 },
{ 3, 0x0079 },
{ 5, 0x0008 },
{ 7, 0x000a },
{ 8, 0x0000 },
{ 10, 0x00ff },
{ 11, 0x00ff },
{ 12, 0x000f },
{ 13, 0x000f },
{ 16, 0x0000 },
{ 17, 0x007b },
{ 18, 0x0000 },
{ 19, 0x0032 },
{ 20, 0x0000 },
{ 21, 0x00c3 },
{ 22, 0x00c3 },
{ 23, 0x00c0 },
{ 24, 0x0000 },
{ 25, 0x0000 },
{ 26, 0x0000 },
{ 27, 0x0000 },
{ 31, 0x0000 },
{ 32, 0x0000 },
{ 33, 0x0000 },
{ 34, 0x0050 },
{ 35, 0x0050 },
{ 36, 0x0050 },
{ 37, 0x0050 },
{ 40, 0x0079 },
{ 41, 0x0079 },
{ 42, 0x0079 },
};
static bool wm8988_writeable(struct device *dev, unsigned int reg)
{
switch (reg) {
case WM8988_LINVOL:
case WM8988_RINVOL:
case WM8988_LOUT1V:
case WM8988_ROUT1V:
case WM8988_ADCDAC:
case WM8988_IFACE:
case WM8988_SRATE:
case WM8988_LDAC:
case WM8988_RDAC:
case WM8988_BASS:
case WM8988_TREBLE:
case WM8988_RESET:
case WM8988_3D:
case WM8988_ALC1:
case WM8988_ALC2:
case WM8988_ALC3:
case WM8988_NGATE:
case WM8988_LADC:
case WM8988_RADC:
case WM8988_ADCTL1:
case WM8988_ADCTL2:
case WM8988_PWR1:
case WM8988_PWR2:
case WM8988_ADCTL3:
case WM8988_ADCIN:
case WM8988_LADCIN:
case WM8988_RADCIN:
case WM8988_LOUTM1:
case WM8988_LOUTM2:
case WM8988_ROUTM1:
case WM8988_ROUTM2:
case WM8988_LOUT2V:
case WM8988_ROUT2V:
case WM8988_LPPB:
return true;
default:
return false;
}
}
/* codec private data */
struct wm8988_priv {
struct regmap *regmap;
unsigned int sysclk;
const struct snd_pcm_hw_constraint_list *sysclk_constraints;
};
#define wm8988_reset(c) snd_soc_component_write(c, WM8988_RESET, 0)
/*
* WM8988 Controls
*/
static const char *bass_boost_txt[] = {"Linear Control", "Adaptive Boost"};
static SOC_ENUM_SINGLE_DECL(bass_boost,
WM8988_BASS, 7, bass_boost_txt);
static const char *bass_filter_txt[] = { "130Hz @ 48kHz", "200Hz @ 48kHz" };
static SOC_ENUM_SINGLE_DECL(bass_filter,
WM8988_BASS, 6, bass_filter_txt);
static const char *treble_txt[] = {"8kHz", "4kHz"};
static SOC_ENUM_SINGLE_DECL(treble,
WM8988_TREBLE, 6, treble_txt);
static const char *stereo_3d_lc_txt[] = {"200Hz", "500Hz"};
static SOC_ENUM_SINGLE_DECL(stereo_3d_lc,
WM8988_3D, 5, stereo_3d_lc_txt);
static const char *stereo_3d_uc_txt[] = {"2.2kHz", "1.5kHz"};
static SOC_ENUM_SINGLE_DECL(stereo_3d_uc,
WM8988_3D, 6, stereo_3d_uc_txt);
static const char *stereo_3d_func_txt[] = {"Capture", "Playback"};
static SOC_ENUM_SINGLE_DECL(stereo_3d_func,
WM8988_3D, 7, stereo_3d_func_txt);
static const char *alc_func_txt[] = {"Off", "Right", "Left", "Stereo"};
static SOC_ENUM_SINGLE_DECL(alc_func,
WM8988_ALC1, 7, alc_func_txt);
static const char *ng_type_txt[] = {"Constant PGA Gain",
"Mute ADC Output"};
static SOC_ENUM_SINGLE_DECL(ng_type,
WM8988_NGATE, 1, ng_type_txt);
static const char *deemph_txt[] = {"None", "32Khz", "44.1Khz", "48Khz"};
static SOC_ENUM_SINGLE_DECL(deemph,
WM8988_ADCDAC, 1, deemph_txt);
static const char *adcpol_txt[] = {"Normal", "L Invert", "R Invert",
"L + R Invert"};
static SOC_ENUM_SINGLE_DECL(adcpol,
WM8988_ADCDAC, 5, adcpol_txt);
static const DECLARE_TLV_DB_SCALE(pga_tlv, -1725, 75, 0);
static const DECLARE_TLV_DB_SCALE(adc_tlv, -9750, 50, 1);
static const DECLARE_TLV_DB_SCALE(dac_tlv, -12750, 50, 1);
static const DECLARE_TLV_DB_SCALE(out_tlv, -12100, 100, 1);
static const DECLARE_TLV_DB_SCALE(bypass_tlv, -1500, 300, 0);
static const struct snd_kcontrol_new wm8988_snd_controls[] = {
SOC_ENUM("Bass Boost", bass_boost),
SOC_ENUM("Bass Filter", bass_filter),
SOC_SINGLE("Bass Volume", WM8988_BASS, 0, 15, 1),
SOC_SINGLE("Treble Volume", WM8988_TREBLE, 0, 15, 0),
SOC_ENUM("Treble Cut-off", treble),
SOC_SINGLE("3D Switch", WM8988_3D, 0, 1, 0),
SOC_SINGLE("3D Volume", WM8988_3D, 1, 15, 0),
SOC_ENUM("3D Lower Cut-off", stereo_3d_lc),
SOC_ENUM("3D Upper Cut-off", stereo_3d_uc),
SOC_ENUM("3D Mode", stereo_3d_func),
SOC_SINGLE("ALC Capture Target Volume", WM8988_ALC1, 0, 7, 0),
SOC_SINGLE("ALC Capture Max Volume", WM8988_ALC1, 4, 7, 0),
SOC_ENUM("ALC Capture Function", alc_func),
SOC_SINGLE("ALC Capture ZC Switch", WM8988_ALC2, 7, 1, 0),
SOC_SINGLE("ALC Capture Hold Time", WM8988_ALC2, 0, 15, 0),
SOC_SINGLE("ALC Capture Decay Time", WM8988_ALC3, 4, 15, 0),
SOC_SINGLE("ALC Capture Attack Time", WM8988_ALC3, 0, 15, 0),
SOC_SINGLE("ALC Capture NG Threshold", WM8988_NGATE, 3, 31, 0),
SOC_ENUM("ALC Capture NG Type", ng_type),
SOC_SINGLE("ALC Capture NG Switch", WM8988_NGATE, 0, 1, 0),
SOC_SINGLE("ZC Timeout Switch", WM8988_ADCTL1, 0, 1, 0),
SOC_DOUBLE_R_TLV("Capture Digital Volume", WM8988_LADC, WM8988_RADC,
0, 255, 0, adc_tlv),
SOC_DOUBLE_R_TLV("Capture Volume", WM8988_LINVOL, WM8988_RINVOL,
0, 63, 0, pga_tlv),
SOC_DOUBLE_R("Capture ZC Switch", WM8988_LINVOL, WM8988_RINVOL, 6, 1, 0),
SOC_DOUBLE_R("Capture Switch", WM8988_LINVOL, WM8988_RINVOL, 7, 1, 1),
SOC_ENUM("Playback De-emphasis", deemph),
SOC_ENUM("Capture Polarity", adcpol),
SOC_SINGLE("Playback 6dB Attenuate", WM8988_ADCDAC, 7, 1, 0),
SOC_SINGLE("Capture 6dB Attenuate", WM8988_ADCDAC, 8, 1, 0),
SOC_DOUBLE_R_TLV("PCM Volume", WM8988_LDAC, WM8988_RDAC, 0, 255, 0, dac_tlv),
SOC_SINGLE_TLV("Left Mixer Left Bypass Volume", WM8988_LOUTM1, 4, 7, 1,
bypass_tlv),
SOC_SINGLE_TLV("Left Mixer Right Bypass Volume", WM8988_LOUTM2, 4, 7, 1,
bypass_tlv),
SOC_SINGLE_TLV("Right Mixer Left Bypass Volume", WM8988_ROUTM1, 4, 7, 1,
bypass_tlv),
SOC_SINGLE_TLV("Right Mixer Right Bypass Volume", WM8988_ROUTM2, 4, 7, 1,
bypass_tlv),
SOC_DOUBLE_R("Output 1 Playback ZC Switch", WM8988_LOUT1V,
WM8988_ROUT1V, 7, 1, 0),
SOC_DOUBLE_R_TLV("Output 1 Playback Volume", WM8988_LOUT1V, WM8988_ROUT1V,
0, 127, 0, out_tlv),
SOC_DOUBLE_R("Output 2 Playback ZC Switch", WM8988_LOUT2V,
WM8988_ROUT2V, 7, 1, 0),
SOC_DOUBLE_R_TLV("Output 2 Playback Volume", WM8988_LOUT2V, WM8988_ROUT2V,
0, 127, 0, out_tlv),
};
/*
* DAPM Controls
*/
static int wm8988_lrc_control(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_component *component = snd_soc_dapm_to_component(w->dapm);
u16 adctl2 = snd_soc_component_read(component, WM8988_ADCTL2);
/* Use the DAC to gate LRC if active, otherwise use ADC */
if (snd_soc_component_read(component, WM8988_PWR2) & 0x180)
adctl2 &= ~0x4;
else
adctl2 |= 0x4;
return snd_soc_component_write(component, WM8988_ADCTL2, adctl2);
}
static const char *wm8988_line_texts[] = {
"Line 1", "Line 2", "PGA", "Differential"};
static const unsigned int wm8988_line_values[] = {
0, 1, 3, 4};
static const struct soc_enum wm8988_lline_enum =
SOC_VALUE_ENUM_SINGLE(WM8988_LOUTM1, 0, 7,
ARRAY_SIZE(wm8988_line_texts),
wm8988_line_texts,
wm8988_line_values);
static const struct snd_kcontrol_new wm8988_left_line_controls =
SOC_DAPM_ENUM("Route", wm8988_lline_enum);
static const struct soc_enum wm8988_rline_enum =
SOC_VALUE_ENUM_SINGLE(WM8988_ROUTM1, 0, 7,
ARRAY_SIZE(wm8988_line_texts),
wm8988_line_texts,
wm8988_line_values);
static const struct snd_kcontrol_new wm8988_right_line_controls =
SOC_DAPM_ENUM("Route", wm8988_rline_enum);
/* Left Mixer */
static const struct snd_kcontrol_new wm8988_left_mixer_controls[] = {
SOC_DAPM_SINGLE("Playback Switch", WM8988_LOUTM1, 8, 1, 0),
SOC_DAPM_SINGLE("Left Bypass Switch", WM8988_LOUTM1, 7, 1, 0),
SOC_DAPM_SINGLE("Right Playback Switch", WM8988_LOUTM2, 8, 1, 0),
SOC_DAPM_SINGLE("Right Bypass Switch", WM8988_LOUTM2, 7, 1, 0),
};
/* Right Mixer */
static const struct snd_kcontrol_new wm8988_right_mixer_controls[] = {
SOC_DAPM_SINGLE("Left Playback Switch", WM8988_ROUTM1, 8, 1, 0),
SOC_DAPM_SINGLE("Left Bypass Switch", WM8988_ROUTM1, 7, 1, 0),
SOC_DAPM_SINGLE("Playback Switch", WM8988_ROUTM2, 8, 1, 0),
SOC_DAPM_SINGLE("Right Bypass Switch", WM8988_ROUTM2, 7, 1, 0),
};
static const char *wm8988_pga_sel[] = {"Line 1", "Line 2", "Differential"};
static const unsigned int wm8988_pga_val[] = { 0, 1, 3 };
/* Left PGA Mux */
static const struct soc_enum wm8988_lpga_enum =
SOC_VALUE_ENUM_SINGLE(WM8988_LADCIN, 6, 3,
ARRAY_SIZE(wm8988_pga_sel),
wm8988_pga_sel,
wm8988_pga_val);
static const struct snd_kcontrol_new wm8988_left_pga_controls =
SOC_DAPM_ENUM("Route", wm8988_lpga_enum);
/* Right PGA Mux */
static const struct soc_enum wm8988_rpga_enum =
SOC_VALUE_ENUM_SINGLE(WM8988_RADCIN, 6, 3,
ARRAY_SIZE(wm8988_pga_sel),
wm8988_pga_sel,
wm8988_pga_val);
static const struct snd_kcontrol_new wm8988_right_pga_controls =
SOC_DAPM_ENUM("Route", wm8988_rpga_enum);
/* Differential Mux */
static const char *wm8988_diff_sel[] = {"Line 1", "Line 2"};
static SOC_ENUM_SINGLE_DECL(diffmux,
WM8988_ADCIN, 8, wm8988_diff_sel);
static const struct snd_kcontrol_new wm8988_diffmux_controls =
SOC_DAPM_ENUM("Route", diffmux);
/* Mono ADC Mux */
static const char *wm8988_mono_mux[] = {"Stereo", "Mono (Left)",
"Mono (Right)", "Digital Mono"};
static SOC_ENUM_SINGLE_DECL(monomux,
WM8988_ADCIN, 6, wm8988_mono_mux);
static const struct snd_kcontrol_new wm8988_monomux_controls =
SOC_DAPM_ENUM("Route", monomux);
static const struct snd_soc_dapm_widget wm8988_dapm_widgets[] = {
SND_SOC_DAPM_SUPPLY("Mic Bias", WM8988_PWR1, 1, 0, NULL, 0),
SND_SOC_DAPM_MUX("Differential Mux", SND_SOC_NOPM, 0, 0,
&wm8988_diffmux_controls),
SND_SOC_DAPM_MUX("Left ADC Mux", SND_SOC_NOPM, 0, 0,
&wm8988_monomux_controls),
SND_SOC_DAPM_MUX("Right ADC Mux", SND_SOC_NOPM, 0, 0,
&wm8988_monomux_controls),
SND_SOC_DAPM_MUX("Left PGA Mux", WM8988_PWR1, 5, 0,
&wm8988_left_pga_controls),
SND_SOC_DAPM_MUX("Right PGA Mux", WM8988_PWR1, 4, 0,
&wm8988_right_pga_controls),
SND_SOC_DAPM_MUX("Left Line Mux", SND_SOC_NOPM, 0, 0,
&wm8988_left_line_controls),
SND_SOC_DAPM_MUX("Right Line Mux", SND_SOC_NOPM, 0, 0,
&wm8988_right_line_controls),
SND_SOC_DAPM_ADC("Right ADC", "Right Capture", WM8988_PWR1, 2, 0),
SND_SOC_DAPM_ADC("Left ADC", "Left Capture", WM8988_PWR1, 3, 0),
SND_SOC_DAPM_DAC("Right DAC", "Right Playback", WM8988_PWR2, 7, 0),
SND_SOC_DAPM_DAC("Left DAC", "Left Playback", WM8988_PWR2, 8, 0),
SND_SOC_DAPM_MIXER("Left Mixer", SND_SOC_NOPM, 0, 0,
&wm8988_left_mixer_controls[0],
ARRAY_SIZE(wm8988_left_mixer_controls)),
SND_SOC_DAPM_MIXER("Right Mixer", SND_SOC_NOPM, 0, 0,
&wm8988_right_mixer_controls[0],
ARRAY_SIZE(wm8988_right_mixer_controls)),
SND_SOC_DAPM_PGA("Right Out 2", WM8988_PWR2, 3, 0, NULL, 0),
SND_SOC_DAPM_PGA("Left Out 2", WM8988_PWR2, 4, 0, NULL, 0),
SND_SOC_DAPM_PGA("Right Out 1", WM8988_PWR2, 5, 0, NULL, 0),
SND_SOC_DAPM_PGA("Left Out 1", WM8988_PWR2, 6, 0, NULL, 0),
SND_SOC_DAPM_POST("LRC control", wm8988_lrc_control),
SND_SOC_DAPM_OUTPUT("LOUT1"),
SND_SOC_DAPM_OUTPUT("ROUT1"),
SND_SOC_DAPM_OUTPUT("LOUT2"),
SND_SOC_DAPM_OUTPUT("ROUT2"),
SND_SOC_DAPM_OUTPUT("VREF"),
SND_SOC_DAPM_INPUT("LINPUT1"),
SND_SOC_DAPM_INPUT("LINPUT2"),
SND_SOC_DAPM_INPUT("RINPUT1"),
SND_SOC_DAPM_INPUT("RINPUT2"),
};
static const struct snd_soc_dapm_route wm8988_dapm_routes[] = {
{ "Left Line Mux", "Line 1", "LINPUT1" },
{ "Left Line Mux", "Line 2", "LINPUT2" },
{ "Left Line Mux", "PGA", "Left PGA Mux" },
{ "Left Line Mux", "Differential", "Differential Mux" },
{ "Right Line Mux", "Line 1", "RINPUT1" },
{ "Right Line Mux", "Line 2", "RINPUT2" },
{ "Right Line Mux", "PGA", "Right PGA Mux" },
{ "Right Line Mux", "Differential", "Differential Mux" },
{ "Left PGA Mux", "Line 1", "LINPUT1" },
{ "Left PGA Mux", "Line 2", "LINPUT2" },
{ "Left PGA Mux", "Differential", "Differential Mux" },
{ "Right PGA Mux", "Line 1", "RINPUT1" },
{ "Right PGA Mux", "Line 2", "RINPUT2" },
{ "Right PGA Mux", "Differential", "Differential Mux" },
{ "Differential Mux", "Line 1", "LINPUT1" },
{ "Differential Mux", "Line 1", "RINPUT1" },
{ "Differential Mux", "Line 2", "LINPUT2" },
{ "Differential Mux", "Line 2", "RINPUT2" },
{ "Left ADC Mux", "Stereo", "Left PGA Mux" },
{ "Left ADC Mux", "Mono (Left)", "Left PGA Mux" },
{ "Left ADC Mux", "Digital Mono", "Left PGA Mux" },
{ "Right ADC Mux", "Stereo", "Right PGA Mux" },
{ "Right ADC Mux", "Mono (Right)", "Right PGA Mux" },
{ "Right ADC Mux", "Digital Mono", "Right PGA Mux" },
{ "Left ADC", NULL, "Left ADC Mux" },
{ "Right ADC", NULL, "Right ADC Mux" },
{ "Left Line Mux", "Line 1", "LINPUT1" },
{ "Left Line Mux", "Line 2", "LINPUT2" },
{ "Left Line Mux", "PGA", "Left PGA Mux" },
{ "Left Line Mux", "Differential", "Differential Mux" },
{ "Right Line Mux", "Line 1", "RINPUT1" },
{ "Right Line Mux", "Line 2", "RINPUT2" },
{ "Right Line Mux", "PGA", "Right PGA Mux" },
{ "Right Line Mux", "Differential", "Differential Mux" },
{ "Left Mixer", "Playback Switch", "Left DAC" },
{ "Left Mixer", "Left Bypass Switch", "Left Line Mux" },
{ "Left Mixer", "Right Playback Switch", "Right DAC" },
{ "Left Mixer", "Right Bypass Switch", "Right Line Mux" },
{ "Right Mixer", "Left Playback Switch", "Left DAC" },
{ "Right Mixer", "Left Bypass Switch", "Left Line Mux" },
{ "Right Mixer", "Playback Switch", "Right DAC" },
{ "Right Mixer", "Right Bypass Switch", "Right Line Mux" },
{ "Left Out 1", NULL, "Left Mixer" },
{ "LOUT1", NULL, "Left Out 1" },
{ "Right Out 1", NULL, "Right Mixer" },
{ "ROUT1", NULL, "Right Out 1" },
{ "Left Out 2", NULL, "Left Mixer" },
{ "LOUT2", NULL, "Left Out 2" },
{ "Right Out 2", NULL, "Right Mixer" },
{ "ROUT2", NULL, "Right Out 2" },
};
struct _coeff_div {
u32 mclk;
u32 rate;
u16 fs;
u8 sr:5;
u8 usb:1;
};
/* codec hifi mclk clock divider coefficients */
static const struct _coeff_div coeff_div[] = {
/* 8k */
{12288000, 8000, 1536, 0x6, 0x0},
{11289600, 8000, 1408, 0x16, 0x0},
{18432000, 8000, 2304, 0x7, 0x0},
{16934400, 8000, 2112, 0x17, 0x0},
{12000000, 8000, 1500, 0x6, 0x1},
/* 11.025k */
{11289600, 11025, 1024, 0x18, 0x0},
{16934400, 11025, 1536, 0x19, 0x0},
{12000000, 11025, 1088, 0x19, 0x1},
/* 16k */
{12288000, 16000, 768, 0xa, 0x0},
{18432000, 16000, 1152, 0xb, 0x0},
{12000000, 16000, 750, 0xa, 0x1},
/* 22.05k */
{11289600, 22050, 512, 0x1a, 0x0},
{16934400, 22050, 768, 0x1b, 0x0},
{12000000, 22050, 544, 0x1b, 0x1},
/* 32k */
{12288000, 32000, 384, 0xc, 0x0},
{18432000, 32000, 576, 0xd, 0x0},
{12000000, 32000, 375, 0xa, 0x1},
/* 44.1k */
{11289600, 44100, 256, 0x10, 0x0},
{16934400, 44100, 384, 0x11, 0x0},
{12000000, 44100, 272, 0x11, 0x1},
/* 48k */
{12288000, 48000, 256, 0x0, 0x0},
{18432000, 48000, 384, 0x1, 0x0},
{12000000, 48000, 250, 0x0, 0x1},
/* 88.2k */
{11289600, 88200, 128, 0x1e, 0x0},
{16934400, 88200, 192, 0x1f, 0x0},
{12000000, 88200, 136, 0x1f, 0x1},
/* 96k */
{12288000, 96000, 128, 0xe, 0x0},
{18432000, 96000, 192, 0xf, 0x0},
{12000000, 96000, 125, 0xe, 0x1},
};
static inline int get_coeff(int mclk, int rate)
{
int i;
for (i = 0; i < ARRAY_SIZE(coeff_div); i++) {
if (coeff_div[i].rate == rate && coeff_div[i].mclk == mclk)
return i;
}
return -EINVAL;
}
/* The set of rates we can generate from the above for each SYSCLK */
static const unsigned int rates_12288[] = {
8000, 12000, 16000, 24000, 32000, 48000, 96000,
};
static const struct snd_pcm_hw_constraint_list constraints_12288 = {
.count = ARRAY_SIZE(rates_12288),
.list = rates_12288,
};
static const unsigned int rates_112896[] = {
8000, 11025, 22050, 44100,
};
static const struct snd_pcm_hw_constraint_list constraints_112896 = {
.count = ARRAY_SIZE(rates_112896),
.list = rates_112896,
};
static const unsigned int rates_12[] = {
8000, 11025, 12000, 16000, 22050, 24000, 32000, 41100, 48000,
48000, 88235, 96000,
};
static const struct snd_pcm_hw_constraint_list constraints_12 = {
.count = ARRAY_SIZE(rates_12),
.list = rates_12,
};
/*
* Note that this should be called from init rather than from hw_params.
*/
static int wm8988_set_dai_sysclk(struct snd_soc_dai *codec_dai,
int clk_id, unsigned int freq, int dir)
{
struct snd_soc_component *component = codec_dai->component;
struct wm8988_priv *wm8988 = snd_soc_component_get_drvdata(component);
switch (freq) {
case 11289600:
case 18432000:
case 22579200:
case 36864000:
wm8988->sysclk_constraints = &constraints_112896;
wm8988->sysclk = freq;
return 0;
case 12288000:
case 16934400:
case 24576000:
case 33868800:
wm8988->sysclk_constraints = &constraints_12288;
wm8988->sysclk = freq;
return 0;
case 12000000:
case 24000000:
wm8988->sysclk_constraints = &constraints_12;
wm8988->sysclk = freq;
return 0;
}
return -EINVAL;
}
static int wm8988_set_dai_fmt(struct snd_soc_dai *codec_dai,
unsigned int fmt)
{
struct snd_soc_component *component = codec_dai->component;
u16 iface = 0;
/* set master/slave audio interface */
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
iface = 0x0040;
break;
case SND_SOC_DAIFMT_CBS_CFS:
break;
default:
return -EINVAL;
}
/* interface format */
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
iface |= 0x0002;
break;
case SND_SOC_DAIFMT_RIGHT_J:
break;
case SND_SOC_DAIFMT_LEFT_J:
iface |= 0x0001;
break;
case SND_SOC_DAIFMT_DSP_A:
iface |= 0x0003;
break;
case SND_SOC_DAIFMT_DSP_B:
iface |= 0x0013;
break;
default:
return -EINVAL;
}
/* clock inversion */
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
break;
case SND_SOC_DAIFMT_IB_IF:
iface |= 0x0090;
break;
case SND_SOC_DAIFMT_IB_NF:
iface |= 0x0080;
break;
case SND_SOC_DAIFMT_NB_IF:
iface |= 0x0010;
break;
default:
return -EINVAL;
}
snd_soc_component_write(component, WM8988_IFACE, iface);
return 0;
}
static int wm8988_pcm_startup(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct snd_soc_component *component = dai->component;
struct wm8988_priv *wm8988 = snd_soc_component_get_drvdata(component);
/* The set of sample rates that can be supported depends on the
* MCLK supplied to the CODEC - enforce this.
*/
if (!wm8988->sysclk) {
dev_err(component->dev,
"No MCLK configured, call set_sysclk() on init\n");
return -EINVAL;
}
snd_pcm_hw_constraint_list(substream->runtime, 0,
SNDRV_PCM_HW_PARAM_RATE,
wm8988->sysclk_constraints);
return 0;
}
static int wm8988_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_component *component = dai->component;
struct wm8988_priv *wm8988 = snd_soc_component_get_drvdata(component);
u16 iface = snd_soc_component_read(component, WM8988_IFACE) & 0x1f3;
u16 srate = snd_soc_component_read(component, WM8988_SRATE) & 0x180;
int coeff;
coeff = get_coeff(wm8988->sysclk, params_rate(params));
if (coeff < 0) {
coeff = get_coeff(wm8988->sysclk / 2, params_rate(params));
srate |= 0x40;
}
if (coeff < 0) {
dev_err(component->dev,
"Unable to configure sample rate %dHz with %dHz MCLK\n",
params_rate(params), wm8988->sysclk);
return coeff;
}
/* bit size */
switch (params_width(params)) {
case 16:
break;
case 20:
iface |= 0x0004;
break;
case 24:
iface |= 0x0008;
break;
case 32:
iface |= 0x000c;
break;
}
/* set iface & srate */
snd_soc_component_write(component, WM8988_IFACE, iface);
if (coeff >= 0)
snd_soc_component_write(component, WM8988_SRATE, srate |
(coeff_div[coeff].sr << 1) | coeff_div[coeff].usb);
return 0;
}
static int wm8988_mute(struct snd_soc_dai *dai, int mute, int direction)
{
struct snd_soc_component *component = dai->component;
u16 mute_reg = snd_soc_component_read(component, WM8988_ADCDAC) & 0xfff7;
if (mute)
snd_soc_component_write(component, WM8988_ADCDAC, mute_reg | 0x8);
else
snd_soc_component_write(component, WM8988_ADCDAC, mute_reg);
return 0;
}
static int wm8988_set_bias_level(struct snd_soc_component *component,
enum snd_soc_bias_level level)
{
struct wm8988_priv *wm8988 = snd_soc_component_get_drvdata(component);
u16 pwr_reg = snd_soc_component_read(component, WM8988_PWR1) & ~0x1c1;
switch (level) {
case SND_SOC_BIAS_ON:
break;
case SND_SOC_BIAS_PREPARE:
/* VREF, VMID=2x50k, digital enabled */
snd_soc_component_write(component, WM8988_PWR1, pwr_reg | 0x00c0);
break;
case SND_SOC_BIAS_STANDBY:
if (snd_soc_component_get_bias_level(component) == SND_SOC_BIAS_OFF) {
regcache_sync(wm8988->regmap);
/* VREF, VMID=2x5k */
snd_soc_component_write(component, WM8988_PWR1, pwr_reg | 0x1c1);
/* Charge caps */
msleep(100);
}
/* VREF, VMID=2*500k, digital stopped */
snd_soc_component_write(component, WM8988_PWR1, pwr_reg | 0x0141);
break;
case SND_SOC_BIAS_OFF:
snd_soc_component_write(component, WM8988_PWR1, 0x0000);
break;
}
return 0;
}
#define WM8988_RATES SNDRV_PCM_RATE_8000_96000
#define WM8988_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE |\
SNDRV_PCM_FMTBIT_S24_LE)
static const struct snd_soc_dai_ops wm8988_ops = {
.startup = wm8988_pcm_startup,
.hw_params = wm8988_pcm_hw_params,
.set_fmt = wm8988_set_dai_fmt,
.set_sysclk = wm8988_set_dai_sysclk,
.mute_stream = wm8988_mute,
.no_capture_mute = 1,
};
static struct snd_soc_dai_driver wm8988_dai = {
.name = "wm8988-hifi",
.playback = {
.stream_name = "Playback",
.channels_min = 1,
.channels_max = 2,
.rates = WM8988_RATES,
.formats = WM8988_FORMATS,
},
.capture = {
.stream_name = "Capture",
.channels_min = 1,
.channels_max = 2,
.rates = WM8988_RATES,
.formats = WM8988_FORMATS,
},
.ops = &wm8988_ops,
.symmetric_rates = 1,
};
static int wm8988_probe(struct snd_soc_component *component)
{
int ret = 0;
ret = wm8988_reset(component);
if (ret < 0) {
dev_err(component->dev, "Failed to issue reset\n");
return ret;
}
/* set the update bits (we always update left then right) */
snd_soc_component_update_bits(component, WM8988_RADC, 0x0100, 0x0100);
snd_soc_component_update_bits(component, WM8988_RDAC, 0x0100, 0x0100);
snd_soc_component_update_bits(component, WM8988_ROUT1V, 0x0100, 0x0100);
snd_soc_component_update_bits(component, WM8988_ROUT2V, 0x0100, 0x0100);
snd_soc_component_update_bits(component, WM8988_RINVOL, 0x0100, 0x0100);
return 0;
}
static const struct snd_soc_component_driver soc_component_dev_wm8988 = {
.probe = wm8988_probe,
.set_bias_level = wm8988_set_bias_level,
.controls = wm8988_snd_controls,
.num_controls = ARRAY_SIZE(wm8988_snd_controls),
.dapm_widgets = wm8988_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(wm8988_dapm_widgets),
.dapm_routes = wm8988_dapm_routes,
.num_dapm_routes = ARRAY_SIZE(wm8988_dapm_routes),
.suspend_bias_off = 1,
.idle_bias_on = 1,
.use_pmdown_time = 1,
.endianness = 1,
.non_legacy_dai_naming = 1,
};
static const struct regmap_config wm8988_regmap = {
.reg_bits = 7,
.val_bits = 9,
.max_register = WM8988_LPPB,
.writeable_reg = wm8988_writeable,
.cache_type = REGCACHE_RBTREE,
.reg_defaults = wm8988_reg_defaults,
.num_reg_defaults = ARRAY_SIZE(wm8988_reg_defaults),
};
#if defined(CONFIG_SPI_MASTER)
static int wm8988_spi_probe(struct spi_device *spi)
{
struct wm8988_priv *wm8988;
int ret;
wm8988 = devm_kzalloc(&spi->dev, sizeof(struct wm8988_priv),
GFP_KERNEL);
if (wm8988 == NULL)
return -ENOMEM;
wm8988->regmap = devm_regmap_init_spi(spi, &wm8988_regmap);
if (IS_ERR(wm8988->regmap)) {
ret = PTR_ERR(wm8988->regmap);
dev_err(&spi->dev, "Failed to init regmap: %d\n", ret);
return ret;
}
spi_set_drvdata(spi, wm8988);
ret = devm_snd_soc_register_component(&spi->dev,
&soc_component_dev_wm8988, &wm8988_dai, 1);
return ret;
}
static struct spi_driver wm8988_spi_driver = {
.driver = {
.name = "wm8988",
},
.probe = wm8988_spi_probe,
};
#endif /* CONFIG_SPI_MASTER */
#if IS_ENABLED(CONFIG_I2C)
static int wm8988_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct wm8988_priv *wm8988;
int ret;
wm8988 = devm_kzalloc(&i2c->dev, sizeof(struct wm8988_priv),
GFP_KERNEL);
if (wm8988 == NULL)
return -ENOMEM;
i2c_set_clientdata(i2c, wm8988);
wm8988->regmap = devm_regmap_init_i2c(i2c, &wm8988_regmap);
if (IS_ERR(wm8988->regmap)) {
ret = PTR_ERR(wm8988->regmap);
dev_err(&i2c->dev, "Failed to init regmap: %d\n", ret);
return ret;
}
ret = devm_snd_soc_register_component(&i2c->dev,
&soc_component_dev_wm8988, &wm8988_dai, 1);
return ret;
}
static const struct i2c_device_id wm8988_i2c_id[] = {
{ "wm8988", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, wm8988_i2c_id);
static struct i2c_driver wm8988_i2c_driver = {
.driver = {
.name = "wm8988",
},
.probe = wm8988_i2c_probe,
.id_table = wm8988_i2c_id,
};
#endif
static int __init wm8988_modinit(void)
{
int ret = 0;
#if IS_ENABLED(CONFIG_I2C)
ret = i2c_add_driver(&wm8988_i2c_driver);
if (ret != 0) {
printk(KERN_ERR "Failed to register WM8988 I2C driver: %d\n",
ret);
}
#endif
#if defined(CONFIG_SPI_MASTER)
ret = spi_register_driver(&wm8988_spi_driver);
if (ret != 0) {
printk(KERN_ERR "Failed to register WM8988 SPI driver: %d\n",
ret);
}
#endif
return ret;
}
module_init(wm8988_modinit);
static void __exit wm8988_exit(void)
{
#if IS_ENABLED(CONFIG_I2C)
i2c_del_driver(&wm8988_i2c_driver);
#endif
#if defined(CONFIG_SPI_MASTER)
spi_unregister_driver(&wm8988_spi_driver);
#endif
}
module_exit(wm8988_exit);
MODULE_DESCRIPTION("ASoC WM8988 driver");
MODULE_AUTHOR("Mark Brown <[email protected]>");
MODULE_LICENSE("GPL");
| {
"pile_set_name": "Github"
} |
/*=============================================================================
Copyright (c) 2006 Tobias Schwinger
http://spirit.sourceforge.net/
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)
=============================================================================*/
#if !defined(BOOST_SPIRIT_DYNAMIC_TYPEOF_HPP)
#define BOOST_SPIRIT_DYNAMIC_TYPEOF_HPP
#include <boost/typeof/typeof.hpp>
#include <boost/spirit/home/classic/namespace.hpp>
#include <boost/spirit/home/classic/core/typeof.hpp>
#include <boost/spirit/home/classic/dynamic/stored_rule_fwd.hpp>
namespace boost { namespace spirit {
BOOST_SPIRIT_CLASSIC_NAMESPACE_BEGIN
// if.hpp
template <class ParsableT, typename CondT> struct if_parser;
template <class ParsableTrueT, class ParsableFalseT, typename CondT>
struct if_else_parser;
// for.hpp
namespace impl {
template<typename InitF, typename CondT, typename StepF, class ParsableT>
struct for_parser;
}
// while.hpp
template<typename ParsableT, typename CondT, bool is_do_parser>
struct while_parser;
// lazy.hpp
template<typename ActorT> struct lazy_parser;
// rule_alias.hpp
template <typename ParserT> class rule_alias;
// switch.hpp
template <typename CaseT, typename CondT> struct switch_parser;
template <int N, class ParserT, bool IsDefault> struct case_parser;
// select.hpp
template <typename TupleT, typename BehaviourT, typename T>
struct select_parser;
BOOST_SPIRIT_CLASSIC_NAMESPACE_END
}} // namespace BOOST_SPIRIT_CLASSIC_NS
#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
// if.hpp
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::if_parser,2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::if_else_parser,3)
// for.hpp
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::impl::for_parser,4)
// while.hpp
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::while_parser,(class)(class)(bool))
// lazy.hpp
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::lazy_parser,1)
// stored_rule.hpp (has forward header)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::stored_rule,(typename)(typename)(typename)(bool))
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::stored_rule,3)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::stored_rule,2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::stored_rule,1)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::stored_rule<>)
// rule_alias.hpp
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::rule_alias,1)
// switch.hpp
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::switch_parser,2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::case_parser,(int)(class)(bool))
// select.hpp
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::select_parser,3)
#endif
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="Covid19Radar.Views.PrivacyPolicyPage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
xmlns:prism="http://prismlibrary.com"
xmlns:resources="clr-namespace:Covid19Radar.Resources;assembly=Covid19Radar"
xmlns:views="clr-namespace:Covid19Radar.Views"
Title="{x:Static resources:AppResources.PrivacyPolicyPageTitle}"
ios:Page.UseSafeArea="true"
prism:ViewModelLocator.AutowireViewModel="True"
Style="{StaticResource DefaultPageStyle}"
Visual="Material">
<Grid Style="{StaticResource DefaultGridLayout}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label
Grid.Row="0"
Margin="0,0,0,20"
Style="{StaticResource DefaultTitleLabel}"
Text="{x:Static resources:AppResources.PrivacyPolicyPageTitle}" />
<views:NavigatePopoverWebView
Grid.Row="1"
Source="{x:Static resources:AppResources.UrlPrivacyPolicy}"
Style="{StaticResource DefaultWebView}" />
<Button
Grid.Row="2"
AutomationId="ButtonAgree"
Command="{Binding Path=OnClickAgree}"
Style="{StaticResource DefaultButton}"
Text="{x:Static resources:AppResources.ButtonAgree}" />
</Grid>
</ContentPage> | {
"pile_set_name": "Github"
} |
/**
* Copyright 2010-2015 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package playn.android;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Looper;
import playn.core.Exec;
import playn.core.Log;
import playn.core.Platform;
public class AndroidExec extends Exec.Default {
private final Activity activity;
public AndroidExec (Platform plat, Activity activity) {
super(plat);
this.activity = activity;
}
protected boolean isPaused () { return false; }
@Override public boolean isMainThread () {
return Thread.currentThread() == Looper.getMainLooper().getThread();
}
@Override public void invokeLater (Runnable action) {
// if we're paused, we need to run these on the main app thread instead of queueing them up for
// processing on the run queue, because the run queue isn't processed while we're paused; the
// main thread will ensure they're run serially, but also that they don't linger until the next
// time the app is resumed (if that happens at all)
if (isPaused()) activity.runOnUiThread(action);
else super.invokeLater(action);
}
@Override public boolean isAsyncSupported () { return true; }
@Override public void invokeAsync (final Runnable action) {
activity.runOnUiThread(new Runnable() {
public void run () {
new AsyncTask<Void,Void,Void>() {
@Override public Void doInBackground(Void... params) {
try {
action.run();
} catch (Throwable t) {
plat.reportError("Async task failure [task=" + action + "]", t);
}
return null;
}
}.execute();
}
});
}
}
| {
"pile_set_name": "Github"
} |
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "main" {
name = "${var.prefix}-resources"
location = "${var.location}"
}
resource "azurerm_app_service_plan" "main" {
name = "${var.prefix}-asp"
location = "${azurerm_resource_group.main.location}"
resource_group_name = "${azurerm_resource_group.main.name}"
kind = "Linux"
reserved = true
sku {
tier = "Standard"
size = "S1"
}
}
resource "azurerm_app_service" "main" {
name = "${var.prefix}-appservice"
location = "${azurerm_resource_group.main.location}"
resource_group_name = "${azurerm_resource_group.main.name}"
app_service_plan_id = "${azurerm_app_service_plan.main.id}"
site_config {
app_command_line = ""
linux_fx_version = "DOCKER|appsvcsample/python-helloworld:latest"
}
app_settings = {
"WEBSITES_ENABLE_APP_SERVICE_STORAGE" = "false"
"DOCKER_REGISTRY_SERVER_URL" = "https://index.docker.io"
}
auth_settings {
enabled = true
issuer = "https://sts.windows.net/d13958f6-b541-4dad-97b9-5a39c6b01297"
default_provider = "AzureActiveDirectory"
unauthenticated_client_action = "RedirectToLoginPage"
active_directory {
client_id = "aadclientid"
client_secret = "aadsecret"
allowed_audiences = [
"someallowedaudience",
]
}
microsoft {
client_id = "microsoftclientid"
client_secret = "microsoftclientsecret"
oauth_scopes = [
"somescope",
]
}
}
}
| {
"pile_set_name": "Github"
} |
// Platform-specific entrypoints (e.g. mac/SDLMain.m) do early platform-specific
// setup and establish a uniform 'SDL' environment. Then they invoke SDL_main
// (see below) which does platform-independent SDL setup and calls the main
// game entrypoint wi::GameMain.
//
// Further platform-specific setup is done as the game calls Host* interfaces
// as it initializes.
#include "game/ht.h"
#include "game/sdl/sdleventserver.h"
#include "base/thread.h"
#if 0
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void quit(int rc)
{
SDL_Quit();
exit(rc);
}
#endif
#ifdef __cplusplus
extern "C"
#endif
#ifdef __LINUX__
int main (int argc, char *argv[])
#else
int SDL_main(int argc, char *argv[])
#endif
{
// Create the main thread
base::Thread *main_thread = new base::Thread();
// Set up the main thread as the SDL event thread.
base::Thread::current().set_ss(new wi::SdlEventServer());
// Let the host have a pointer to the thread
wi::HostSetGameThread(main_thread);
// TODO(darrinm): pass args through
wi::GameMain((char *)"");
return 0;
}
| {
"pile_set_name": "Github"
} |
-----BEGIN CERTIFICATE REQUEST-----
MIIFCTCCAvMCAQAwgYYxCzAJBgNVBAYTAlVTMRMwEQYDVQQKEwpDbG91ZEZsYXJl
MRwwGgYDVQQLExNTeXN0ZW1zIEVuZ2luZWVyaW5nMRYwFAYDVQQHEw1TYW4gRnJh
bmNpc2NvMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRcwFQYDVQQDEw5jbG91ZGZsYXJl
LmNvbTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANkKL22jMn3eFCpj
T6lbeq4nC3aEqwTGrLARidAmO29WIhzs6LxRpM6xSMoPI6DvJVUGpMFEKF4xNTc5
X9/gSFrw2eI5Q3U3aGcaToSCxH4hXejwIzX8Ftlb/LfpXhbSsFr5MS3kiTY4zZxM
n3dSy2gZljD/g0tlQf5BdHdR4WKRhWnqRiGng+BmW4rjbcO7SoN33jSXsMcguCg5
8dmYuf5G5KVXsqwEoCQBeKGnca9orcm4i90VnGt4qZUpfAn1cADzYGpRzX79USJ6
tol4ovgGPN08LJFqcVl+dK8VzJ03JWBhI1jePbWS4Bz5oNtkhQQXilU+G6FQxc6a
UPf6KcFyOB+qMJmEwJZD9yaNK1YbsKfSztQEsb1JEezQnVHxp91Ch3AcWoikuOiY
yCg0V5lcK15SLv1+5sj9YzF7ngMmThcIJ6B5gS3swpD5AX6FJaI1BrGwT/RXKKQP
tRX1BySLx8RcINjFb5wv3q9QIE8vrW1BOk9f4dfmxiFYnc+6bCCbIrg7APQVtKTa
ixNJFSqZz7fm9loeNPHHXfUT5RoW5yzVa8igc+yv4qeYsWHcZ4c/Y91OJp19HMjM
bYm2alt8XagBgJjO0FW8wvsKwhhlhWK0WO6sQ7Fkl7fH1GtxEpc248hAW24SZMmS
led3LblCT8IC3a9BLhqJ2q8cfPp9AgMBAAGgPzA9BgkqhkiG9w0BCQ4xMDAuMCwG
A1UdEQQlMCOCDmNsb3VkZmxhcmUuY29tghF3d3djbG91ZGZsYXJlLmNvbTALBgkq
hkiG9w0BAQ0DggIBAAgz3NuN43+F+8+WhQ9hb7DOp6Amut7XubOkEBtBVgP3R8U1
uSsgocR1rvnZ1/bhkeGyTly0eQPhcSEdMo/GgIrcn+co0KLcDyV6Rf3Cgksx9dUZ
TzHSkxmFkxlxYfIGes6abH+2OPiacwK2gLvvmXFYIxEhv+LKzzteQi0xlinewv7R
FnSykZ4QialsFyCgOjOxa11aEdRv6T8qKwhjUOk0VedtzOkt/k95aydTNLjXl2OV
jloeTsbB00yWIqdyhG12+TgcJOa0pNP1zTjgFPodMuRUuiAcbT7Mt7sLCefKNzvZ
Ln6b4y7e6N3YLOHALTIP+LI4y8ar47WlXCNw/zeOM2sW8udjYrukN6WOV3X68oMf
Zsv6jqyGSaCDwdImR4VECUVvkabg9Sq4pz+ijTT+9cNA66omYL+/QAh0GahlROgW
kDGI8zeEUoAC8RkAbFGMJA8jEbAfbT000ZwnLX2SZ8YRQX4Jd1FTmAH99FkvvT8N
ovaGRSQQI5rWQGQYqF67So7PywEaEXeUHTBrv41Msva6CdaWHn7bh/fj4B21ETS7
VJvrk5DLJTyruqon7EVJU1pn38ppaXF4Z6a9n3C8TqudT/gdJUYn/SBo5jx20uGJ
d9k6vDqixntvk/TRZ848k1AXiv5uUJTdnoPPhzSGjxEaeKuB0R1ZHomVdjU4
-----END CERTIFICATE REQUEST-----
| {
"pile_set_name": "Github"
} |
stdout of test 'sqlitelogictest-in-cast-null.Bug-6529` in directory 'sql/test/BugTracker-2018` itself:
# 19:12:38 >
# 19:12:38 > "mserver5" "--debug=10" "--set" "gdk_nr_threads=0" "--set" "mapi_open=true" "--set" "mapi_port=32688" "--set" "mapi_usock=/var/tmp/mtest-29155/.s.monetdb.32688" "--set" "monet_prompt=" "--forcemito" "--dbpath=/home/niels/scratch/rc-monetdb/Linux-x86_64/var/MonetDB/mTests_sql_test_BugTracker-2018"
# 19:12:38 >
# MonetDB 5 server v11.29.0
# This is an unreleased version
# Serving database 'mTests_sql_test_BugTracker-2018', using 4 threads
# Compiled for x86_64-unknown-linux-gnu/64bit with 128bit integers
# Found 7.324 GiB available main-memory.
# Copyright (c) 1993 - July 2008 CWI.
# Copyright (c) August 2008 - 2018 MonetDB B.V., all rights reserved
# Visit https://www.monetdb.org/ for further information
# Listening for connection requests on mapi:monetdb://localhost.nes.nl:32688/
# Listening for UNIX domain connection requests on mapi:monetdb:///var/tmp/mtest-29155/.s.monetdb.32688
# MonetDB/GIS module loaded
# MonetDB/SQL module loaded
# 19:12:38 >
# 19:12:38 > "mclient" "-lsql" "-ftest" "-tnone" "-Eutf-8" "-i" "-e" "--host=/var/tmp/mtest-29155" "--port=32688"
# 19:12:38 >
#CREATE TABLE tab2(col0 INTEGER, col1 INTEGER, col2 INTEGER);
#INSERT INTO tab2 VALUES (64,77,40), (75,67,58), (46,51,23);
[ 3 ]
#SELECT * FROM tab2 cor0 WHERE col1 IN ( + CAST ( NULL AS INTEGER ) + - CAST ( NULL AS INTEGER ), col2 * + col1 + - - 30 );
% sys.cor0, sys.cor0, sys.cor0 # table_name
% col0, col1, col2 # name
% int, int, int # type
% 1, 1, 1 # length
#DROP TABLE tab2;
# 19:12:38 >
# 19:12:38 > "Done."
# 19:12:38 >
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
# Copyright (C) 2008-2020 German Aerospace Center (DLR) and others.
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# https://www.eclipse.org/legal/epl-2.0/
# This Source Code may also be made available under the following Secondary
# Licenses when the conditions for such availability set forth in the Eclipse
# Public License 2.0 are satisfied: GNU General Public License, version 2
# or later which is available at
# https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
# @file runner.py
# @author Daniel Krajzewicz
# @author Michael Behrisch
# @date 2015-02-03
from __future__ import print_function
from __future__ import absolute_import
import os
import subprocess
import sys
from optparse import OptionParser, BadOptionError, AmbiguousOptionError
sys.path.append(
os.path.join(os.path.dirname(__file__), '..', '..', '..', "tools"))
from sumolib import checkBinary # noqa
class PassThroughOptionParser(OptionParser):
"""
An unknown option pass-through implementation of OptionParser.
see http://stackoverflow.com/questions/1885161/how-can-i-get-optparses-optionparser-to-ignore-invalid-options
When unknown arguments are encountered, bundle with largs and try again,
until rargs is depleted.
sys.exit(status) will still be called if a known argument is passed
incorrectly (e.g. missing arguments or bad argument types, etc.)
"""
def _process_args(self, largs, rargs, values):
while rargs:
try:
OptionParser._process_args(self, largs, rargs, values)
except (BadOptionError, AmbiguousOptionError) as e:
largs.append(e.opt_str)
def runInstance(elem, attrSet, childSet, depart):
print(elem, attrSet, childSet)
sys.stdout.flush()
with open("routes.xml", "w") as routes:
routes.write('''<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" \
xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/routes_file.xsd">
<route id="a" edges="1fi 1si 2o 2fi 2si"/>
<%s id="v" %s''' % (elem, depart))
for idx, attr in enumerate(attrs):
if attrSet & (2 ** idx):
routes.write(attr)
routes.write('>\n')
for idx, child in enumerate(childs):
if childSet & (2 ** idx):
routes.write((8 * " ") + child)
routes.write(' </%s>\n</routes>\n' % elem)
retCode = subprocess.call(
call + ["-n", "input_net.net.xml", "-r", routes.name], stdout=sys.stdout, stderr=sys.stdout)
retCodeTaz = subprocess.call(
call + ["-n", "input_net.net.xml", "-r", routes.name, "--with-taz"], stdout=sys.stdout, stderr=sys.stdout)
if retCode < 0 or retCodeTaz < 0:
sys.stdout.write(open(routes.name).read())
sys.exit()
optParser = PassThroughOptionParser()
optParser.add_option("-e", "--element", help="xml element to choose")
optParser.add_option(
"-a", "--attr", type="int", default=0, help="attribute set to use")
optParser.add_option(
"-c", "--child", type="int", default=0, help="child set to use")
options, args = optParser.parse_args()
if len(args) == 0 or args[0] == "sumo":
call = [checkBinary('sumo'), "--no-step-log", "--no-duration-log",
"-a", "input_additional.add.xml"]
elif args[0] == "dfrouter":
call = [checkBinary('dfrouter'),
"--detector-files", "input_additional.add.xml"]
elif args[0] == "duarouter":
call = [checkBinary('duarouter'), "--no-step-log",
"-o", "dummy.xml", "-a", "input_additional.add.xml"]
elif args[0] == "jtrrouter":
call = [checkBinary('jtrrouter'), "--no-step-log",
"-o", "dummy.xml", "-a", "input_additional.add.xml"]
else:
print("Unsupported application defined", file=sys.stderr)
call += args[1:]
elements = {'vehicle': 'depart="0"',
'flow': 'begin="0" end="1" number="1"', 'trip': 'depart="0"'}
attrs = [' from="1fi"', ' to="2si"',
' fromTaz="1"', ' toTaz="2"', ' route="a"']
childs = ['<route edges="1fi 1si 2o 2fi 2si"/>\n', '<stop lane="1fi_0" duration="10"/>\n',
'<stop lane="1si_0" duration="10"/>\n', '<stop lane="2si_0" duration="10"/>\n']
# check route processing
if options.element:
runInstance(
options.element, options.attr, options.child, elements[options.element])
else:
for elem, depart in sorted(elements.iteritems()):
for attrSet in range(2 ** len(attrs)):
for childSet in range(2 ** len(childs)):
runInstance(elem, attrSet, childSet, depart)
| {
"pile_set_name": "Github"
} |
{
"callcallcode_01_SuicideEnd" : {
"_info" : {
"comment" : "",
"filling-rpc-server" : "Geth-1.9.6-unstable-63b18027-20190920",
"filling-tool-version" : "retesteth-0.0.1+commit.0ae18aef.Linux.g++",
"lllcversion" : "Version: 0.5.12-develop.2019.9.13+commit.2d601a4f.Linux.g++",
"source" : "src/GeneralStateTestsFiller/stCallCodes/callcallcode_01_SuicideEndFiller.json",
"sourceHash" : "b9d240cc662a99d7bb389c9d9242b5cff8bb4ab8cb99ccb87a792b98426073c4"
},
"env" : {
"currentCoinbase" : "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"currentDifficulty" : "0x020000",
"currentGasLimit" : "0x01c9c380",
"currentNumber" : "0x01",
"currentTimestamp" : "0x03e8",
"previousHash" : "0x5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
},
"post" : {
"Istanbul" : [
{
"indexes" : {
"data" : 0,
"gas" : 0,
"value" : 0
},
"hash" : "0xde1ce501df43bc76c05505bcbb20cebae576515b8d1d0f2707fbb3c5d768e4a2",
"logs" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
}
]
},
"pre" : {
"0x1000000000000000000000000000000000000000" : {
"balance" : "0x0de0b6b3a7640000",
"code" : "0x60406000604060006000731000000000000000000000000000000000000001620249f0f160005500",
"nonce" : "0x00",
"storage" : {
}
},
"0x1000000000000000000000000000000000000001" : {
"balance" : "0x02540be400",
"code" : "0x6040600060406000600073100000000000000000000000000000000000000261c350f2600155731000000000000000000000000000000000000000ff00",
"nonce" : "0x00",
"storage" : {
}
},
"0x1000000000000000000000000000000000000002" : {
"balance" : "0x02540be400",
"code" : "0x600160025500",
"nonce" : "0x00",
"storage" : {
}
},
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "0x0de0b6b3a7640000",
"code" : "0x",
"nonce" : "0x00",
"storage" : {
}
}
},
"transaction" : {
"data" : [
"0x"
],
"gasLimit" : [
"0x2dc6c0"
],
"gasPrice" : "0x01",
"nonce" : "0x00",
"secretKey" : "0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8",
"to" : "0x1000000000000000000000000000000000000000",
"value" : [
"0x00"
]
}
}
} | {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require("react");
const CompLibrary = require("../../core/CompLibrary.js");
const MarkdownBlock = CompLibrary.MarkdownBlock; /* Used to read markdown */
const Container = CompLibrary.Container;
const GridBlock = CompLibrary.GridBlock;
const siteConfig = require(process.cwd() + "/siteConfig.js");
function imgUrl(img) {
return siteConfig.baseUrl + "img/" + img;
}
function docUrl(doc, language) {
return (
siteConfig.baseUrl + "docs/" + (language ? language + "/" : "") + doc
);
}
function pageUrl(page, language) {
return siteConfig.baseUrl + (language ? language + "/" : "") + page;
}
class Button extends React.Component {
render() {
return (
<div className="pluginWrapper buttonWrapper">
<a
className="button homeButton"
href={this.props.href}
target={this.props.target}
>
{this.props.children}
</a>
</div>
);
}
}
Button.defaultProps = {
target: "_self"
};
const SplashContainer = props => (
<div className="homeSection homeContainer">
<div className="homeSectionContent homeSplashFade">
<div className="wrapper homeWrapper">{props.children}</div>
</div>
</div>
);
const Logo = props => (
<div className="logo homeLogo">
<img src={props.img_src} />
</div>
);
const ProjectTitle = props => (
<h2 className="projectTitle">
{siteConfig.title}
<small>{siteConfig.tagline}</small>
</h2>
);
const PromoSection = props => (
<div className="section promoSection">
<div className="promoRow">
<div className="pluginRowBlock">{props.children}</div>
</div>
</div>
);
class HomeSplash extends React.Component {
render() {
let language = this.props.language || "";
return (
<SplashContainer>
<Logo img_src={imgUrl("treats.png")} />
<div className="inner">
<ProjectTitle />
<Button href={docUrl("installation.html", language)}>
Getting Started
</Button>
</div>
</SplashContainer>
);
}
}
class Index extends React.Component {
render() {
let language = this.props.language || "";
return (
<div>
<HomeSplash language={language} />
</div>
);
}
}
module.exports = Index;
| {
"pile_set_name": "Github"
} |
---
Title: Gesetz zu dem Übereinkommen vom 10. März 1988 zur Bekämpfung widerrechtlicher
Handlungen gegen die Sicherheit der Seeschiffahrt und zum Protokoll vom 10. März
1988 zur Bekämpfung widerrechtlicher Handlungen gegen die Sicherheit fester Plattformen,
die sich auf dem Festlandsockel befinden
jurabk: SeeSchSiÜbkG
layout: default
origslug: seeschsi_bkg
slug: seeschsiuebkg
---
# Gesetz zu dem Übereinkommen vom 10. März 1988 zur Bekämpfung widerrechtlicher Handlungen gegen die Sicherheit der Seeschiffahrt und zum Protokoll vom 10. März 1988 zur Bekämpfung widerrechtlicher Handlungen gegen die Sicherheit fester Plattformen, die sich auf dem Festlandsockel befinden (SeeSchSiÜbkG)
Ausfertigungsdatum
: 1990-06-13
Fundstelle
: BGBl II: 1990, 494
## Art 1
Dem Beitritt der Bundesrepublik Deutschland zu dem Übereinkommen von
Rom vom 10. März 1988 zur Bekämpfung widerrechtlicher Handlungen gegen
die Sicherheit der Seeschiffahrt sowie zu dem Protokoll vom 10. März
1988 zur Bekämpfung widerrechtlicher Handlungen gegen die Sicherheit
fester Plattformen, die sich auf dem Festlandsockel befinden, wird
zugestimmt. Das Übereinkommen sowie das Protokoll werden nachstehend
mit einer amtlichen deutschen Übersetzung veröffentlicht.
## Art 2
-
## Art 3
(1) Hat der Kapitän eines Schiffes unter der Bundesflagge begründeten
Anlass zu der Annahme, dass eine Person, die er an Bord mitführt, eine
der in Artikel 3 des Übereinkommens genannten Straftaten begangen hat,
und will er diese Person übergeben, so ist er verpflichtet, die
Behörden des Empfangsstaates, sofern durchführbar, nach Möglichkeit
vor Einlaufen in das Küstenmeer dieses Staates von dieser Absicht
sowie den Gründen zu unterrichten.
(2) Der Kapitän eines Schiffes unter der Bundesflagge kann
Gegenstände, die sich auf eine solche Straftat beziehen und deren
Verbleib an Bord eine unmittelbare Gefahr für die Sicherheit des
Schiffes oder seiner Besatzung darstellen würde, den Behörden eines
Empfangsstaates zur Verfügung stellen.
## Art 4
(1) Dieses Gesetz tritt am Tag nach seiner Verkündung in Kraft.
(2) Der Tag, an dem das Übereinkommen nach seinem Artikel 18 und das
Protokoll nach seinem Artikel 6 für die Bundesrepublik Deutschland in
Kraft tritt, ist im Bundesgesetzblatt bekanntzugeben.
| {
"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.jackrabbit.oak.segment.spi.persistence;
import java.io.IOException;
import java.util.Properties;
/**
* Manifest is a properties files, providing the information about the segment
* store (eg. the schema version number).
* <p>
* The implementation <b>doesn't need to be</b> thread-safe.
*/
public interface ManifestFile {
/**
* Check if the manifest already exists.
* @return {@code true} if the manifest exists
*/
boolean exists();
/**
* Load the properties from the manifest file.
* @return properties describing the segmentstore
* @throws IOException
*/
Properties load() throws IOException;
/**
* Store the properties to the manifest file.
* @param properties describing the segmentstore
* @throws IOException
*/
void save(Properties properties) throws IOException;
}
| {
"pile_set_name": "Github"
} |
sbt.version=0.13.7
| {
"pile_set_name": "Github"
} |
"use strict";
let datafire = require('datafire');
let openapi = require('./openapi.json');
module.exports = datafire.Integration.fromOpenAPI(openapi, "google_vault"); | {
"pile_set_name": "Github"
} |
/*
Language: JavaScript
*/
function(hljs) {
return {
aliases: ['js'],
keywords: {
keyword:
'in if for while finally var new function do return void else break catch ' +
'instanceof with throw case default try this switch continue typeof delete ' +
'let yield const class',
literal:
'true false null undefined NaN Infinity',
built_in:
'eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent ' +
'encodeURI encodeURIComponent escape unescape Object Function Boolean Error ' +
'EvalError InternalError RangeError ReferenceError StopIteration SyntaxError ' +
'TypeError URIError Number Math Date String RegExp Array Float32Array ' +
'Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array ' +
'Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require ' +
'module console window document'
},
contains: [
{
className: 'pi',
begin: /^\s*('|")use strict('|")/,
relevance: 10
},
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.C_NUMBER_MODE,
{ // "value" container
begin: '(' + hljs.RE_STARTERS_RE + '|\\b(case|return|throw)\\b)\\s*',
keywords: 'return throw case',
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.REGEXP_MODE,
{ // E4X
begin: /</, end: />;/,
relevance: 0,
subLanguage: 'xml'
}
],
relevance: 0
},
{
className: 'function',
beginKeywords: 'function', end: /\{/, excludeEnd: true,
contains: [
hljs.inherit(hljs.TITLE_MODE, {begin: /[A-Za-z$_][0-9A-Za-z$_]*/}),
{
className: 'params',
begin: /\(/, end: /\)/,
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE
],
illegal: /["'\(]/
}
],
illegal: /\[|%/
},
{
begin: /\$[(.]/ // relevance booster for a pattern common to JS libs: `$(something)` and `$.something`
},
{
begin: '\\.' + hljs.IDENT_RE, relevance: 0 // hack: prevents detection of keywords after dots
}
]
};
}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/perl -w
use strict;
# $Id: motelist-linux,v 1.1 2007/05/29 19:34:30 adam Exp $
# @author Cory Sharp <[email protected]>
# @author Joe Polastre
my $help = <<'EOF';
usage: motelist [options]
$Revision: 1.1 $
options:
-h display this help
-c compact format, not pretty but easier for parsing
-f specify the usb-serial file (for smote.cs)
-k kernel version: 2.4, 2.6, auto (default)
-m method to scan usb: procfs, sysfs, auto (default)
-dev_prefix force the device prefix for the serial device
-usb display extra usb information
EOF
my %Opt = (
compact => 0,
usb => 0,
method => "auto",
kernel => "auto",
dev_prefix => [ "/dev/usb/tts/", "/dev/ttyUSB", "/dev/tts/USB" ],
usbserial => "sudo cat /proc/tty/driver/usbserial |",
);
while (@ARGV) {
last unless $ARGV[0] =~ /^-/;
my $opt = shift @ARGV;
if( $opt eq "-h" ) { print "$help\n"; exit 0; }
elsif( $opt eq "-c" ) { $Opt{compact} = 1; }
elsif( $opt eq "-f" ) { $Opt{usbserial} = shift @ARGV; }
elsif( $opt eq "-k" ) { $Opt{kernel} = shift @ARGV; }
elsif( $opt eq "-m" ) { $Opt{method} = shift @ARGV; }
elsif( $opt eq "-dev_prefix" ) { $Opt{dev_prefix} = shift @ARGV; }
elsif( $opt eq "-usb" ) { $Opt{usb} = 1; }
else { print STDERR "$help\nerror, unknown command line option $opt\n"; exit 1; }
}
if( $Opt{kernel} eq "auto" ) {
$Opt{kernel} = "unknown";
$Opt{kernel} = $1 if snarf("/proc/version") =~ /\bLinux version (\d+\.\d+)/;
}
if( $Opt{method} eq "auto" ) {
$Opt{method} = ($Opt{kernel} eq "2.4") ? "procfs" : "sysfs";
}
my @devs = $Opt{method} eq "procfs" ? scan_procfs() : scan_sysfs();
print_motelist( sort { cmp_usbdev($a,$b) } @devs );
#
# SysFS
#
sub scan_sysfs {
# Scan /sys/bus/usb/drivers/usb for FTDI devices
my @ftdidevs =
grep { ($_->{UsbVendor}||"") eq "0403" && ($_->{UsbProduct}||"") eq "6001" }
map { {
SysPath => $_,
UsbVendor => snarf("$_/idVendor",1),
UsbProduct => snarf("$_/idProduct",1),
} }
glob("/sys/bus/usb/drivers/usb/*");
# Gather information about each FTDI device
for my $f (@ftdidevs) {
my $syspath = $f->{SysPath};
$f->{InfoManufacturer} = snarf("$syspath/manufacturer",1);
$f->{InfoProduct} = snarf("$syspath/product",1);
$f->{InfoSerial} = snarf("$syspath/serial",1);
$f->{UsbDevNum} = snarf("$syspath/devnum",1);
my $devstr = readlink($syspath);
if( $devstr =~ m{([^/]+)/usb(\d+)/.*-([^/]+)$} ) {
$f->{UsbPath} = "usb-$1-$3";
$f->{UsbBusNum} = $2;
}
($f->{SysDev} = $syspath) =~ s{^.*/}{};
my $port = "$syspath/$f->{SysDev}:1.0";
($f->{DriverName} = readlink("$port/driver")) =~ s{^.*/}{} if -l "$port/driver";
($f->{SerialDevName} = (glob("$port/tty*"),undef)[0]) =~ s{^.*/}{};
$f->{SerialDevNum} = $1 if $f->{SerialDevName} =~ /(\d+)/;
$f->{SerialDevName} = getSerialDevName( $f->{SerialDevNum} ) || " (none)";
}
return @ftdidevs;
}
#
# Scan Procfs
#
sub scan_procfs {
my $text_devs = snarf("< /proc/bus/usb/devices");
my $text_serial = snarf($Opt{usbserial});
my @usbdevs = map { {parse_usb_devices_text($_)} }
grep { !/^\s*$/ } split /\n+(?=T:)/, $text_devs;
my %usbtree = build_usb_tree( @usbdevs );
my %usbserialtree = build_usbserial_tree( $text_serial );
for my $tts ( values %usbserialtree ) {
$usbtree{usbkey($tts->{path})}{usbserial} = $tts if defined $tts->{path};
}
my @ftdidevs = map { {
UsbVendor => $_->{Vendor},
UsbProduct => $_->{ProdID},
InfoManufacturer => $_->{Manufacturer},
InfoProduct => $_->{Product},
InfoSerial => $_->{SerialNumber},
UsbBusNum => $_->{nbus},
UsbDevNum => $_->{ndev},
UsbPath => (($Opt{kernel} eq "2.4") ? $_->{usbserial}{path} : $_->{usbpath}),
DriverName => $_->{driver},
SerialDevNum => $_->{usbserial}{tts},
SerialDevName => getSerialDevName($_->{usbserial}{tts}) || " (none)",
} }
grep { ($_->{Vendor}||"") eq "0403" && ($_->{ProdID}||"") eq "6001" }
values %usbtree;
return @ftdidevs;
}
sub build_usb_tree {
my @devs = @_;
my %tree = ();
for my $dev (sort { $a->{Lev} <=> $b->{Lev} } @devs) {
my ($bus,$lev,$prnt) = ( $dev->{Bus}+0, $dev->{Lev}+0, $dev->{Prnt}+0 );
my $devnum = $dev->{"Dev#"}+0;
$dev->{nbus} = $bus;
$dev->{ndev} = $devnum;
$tree{"bus$bus"} = {} unless exists $tree{"bus$bus"};
$tree{"bus$bus"}{"dev$devnum"} = $dev;
if( $lev == 0 ) {
$dev->{usbpath} = "usb-$dev->{SerialNumber}";
} else {
my $sep = ($lev==1) ? "-" : ".";
$dev->{parent} = $tree{"bus$bus"}{"dev$prnt"};
$dev->{usbpath} = $dev->{parent}{usbpath} . $sep . ($dev->{Port}+1);
}
$tree{usbkey($dev->{usbpath})} = $dev;
}
return %tree;
}
sub parse_usb_devices_text {
my $text = shift;
$text =~ s/^\S+\s*//gm;
$text =~ s/\s*(\S+=)/\001$1/g;
return map { m/(.*?)=(.*)/ } split /\001/, $text;
}
sub build_usbserial_tree {
my $text = shift;
my %tree = ();
while( $text =~ /^([^:]+):(.*)/mg ) {
my ($tts,$params) = ($1,$2);
$tree{$tts} = { tts => $tts };
while ($params =~ m/\s+([^:]+):(?:"([^"]*)"|(\S+))/g) {
$tree{$tts}{$1} = $2||$3;
}
}
return %tree;
}
sub usbkey {
if( $Opt{kernel} eq "2.4" ) {
(my $key = $_[0]) =~ s/^.*-//;
return $key;
}
return $_[0];
}
#
# getSerialDevName
#
# For each device, force to use dev_prefix if it's not an array. Otherwise,
# assume it's a list of candidate prefixes. Check them and commit to the
# first one that actually exists.
#
sub getSerialDevName {
my $devnum = shift;
my $devname = undef;
if( defined $devnum ) {
if( ref($Opt{dev_prefix}) eq "ARRAY" ) {
$devname = $devnum;
for my $prefix (@{$Opt{dev_prefix}}) {
my $file = $prefix . $devnum;
if( -e $file ) { $devname = $file; last; }
}
} else {
$devname = $Opt{dev_prefix} . $devnum;
}
}
return $devname;
}
#
# Print motelist
#
sub print_motelist {
my @devs = @_;
# If none were found, quit
if( @devs == 0 ) {
print "No devices found.\n";
return;
}
# Print a header
if( !$Opt{compact} ) {
if( $Opt{usb} ) {
print << "EOF" unless $Opt{compact};
Bus Dev USB Path Reference Device Description
--- --- ------------------------ ---------- ---------------- -------------------------------------
EOF
} else {
print << "EOF" unless $Opt{compact};
Reference Device Description
---------- ---------------- ---------------------------------------------
EOF
}
}
# Print the usb information
for my $dev (sort { cmp_usbdev($a,$b) } @devs) {
my $desc = join( " ", $dev->{InfoManufacturer}||"", $dev->{InfoProduct}||"" ) || " (none)";
my @output = ( $dev->{InfoSerial}||" (none)", $dev->{SerialDevName}, $desc );
@output = ( $dev->{UsbBusNum}, $dev->{UsbDevNum}, $dev->{UsbPath}, @output ) if $Opt{usb};
if( $Opt{compact} ) {
print join(",",@output) . "\n";
} else {
printf( ($Opt{usb}?"%3d %3d %-24s ":"")."%-10s %-16s %s\n", @output );
}
}
}
#
# Cmp Usbdev's
#
sub cmp_usbdev {
my ($a,$b) = @_;
if( defined $a->{SerialDevNum} ) {
if( defined $b->{SerialDevNum} ) {
return $a->{SerialDevNum} <=> $b->{SerialDevNum};
}
return -1;
}
return 1 if defined $b->{SerialDevNum};
return ($a->{InfoSerial}||"") cmp ($b->{InfoSerial}||"");
}
#
# Read a file in
#
sub snarf {
open my $fh, $_[0] or return undef;
my $text = do{local $/;<$fh>};
close $fh;
$text =~ s/\s+$// if $_[1];
return $text;
}
| {
"pile_set_name": "Github"
} |
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = require('./_iobject');
var defined = require('./_defined');
module.exports = function (it) {
return IObject(defined(it));
};
| {
"pile_set_name": "Github"
} |
BDEPEND=>=dev-vcs/git-1.8.2.1[curl]
DEFINED_PHASES=install unpack
DESCRIPTION=Spectre & Meltdown vulnerability/mitigation checker for Linux
EAPI=7
HOMEPAGE=https://github.com/speed47/spectre-meltdown-checker
LICENSE=GPL-3+
PROPERTIES=live
SLOT=0
_eclasses_=git-r3 3e7ec3d6619213460c85e2aa48398441
_md5_=e1ba05af44ffdd7512278801a5e5aa63
| {
"pile_set_name": "Github"
} |
/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
#ifndef __LIBBPF_STR_ERROR_H
#define __LIBBPF_STR_ERROR_H
char *libbpf_strerror_r(int err, char *dst, int len);
#endif /* __LIBBPF_STR_ERROR_H */
| {
"pile_set_name": "Github"
} |
package org.hisp.dhis.analytics;
/*
* Copyright (c) 2004-2020, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project 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.
*/
/**
* Analytics output formats.
*
* @author Lars Helge Overland
*/
public enum OutputFormat
{
ANALYTICS,
DATA_VALUE_SET
}
| {
"pile_set_name": "Github"
} |
main = return $ 1 + 2
-- putStrLn "Hello, world!"
a1 x = let y = 1
in x + y
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env node
var fs = require('fs');
var querystring = require('querystring');
var child_process = require('child_process');
function run(command, callback) {
console.log(command);
child_process.exec(command, callback);
}
// Use browserify to package up source-map-support.js
fs.writeFileSync('.temp.js', 'sourceMapSupport = require("./source-map-support");');
run('node_modules/browserify/bin/cmd.js .temp.js', function(error, stdout) {
if (error) throw error;
// Wrap the code so it works both as a normal <script> module and as an AMD module
var header = [
'/*',
' * Support for source maps in V8 stack traces',
' * https://github.com/evanw/node-source-map-support',
' */',
].join('\n');
var code = [
'(this["define"] || function(name, callback) { this["sourceMapSupport"] = callback(); })("browser-source-map-support", function(sourceMapSupport) {',
stdout.replace(/\bbyte\b/g, 'bite').replace(new RegExp(__dirname + '/', 'g'), '').replace(/@license/g, 'license'),
'return sourceMapSupport});',
].join('\n');
// Use the online Google Closure Compiler service for minification
fs.writeFileSync('.temp.js', querystring.stringify({
compilation_level: 'SIMPLE_OPTIMIZATIONS',
output_info: 'compiled_code',
output_format: 'text',
js_code: code
}));
run('curl -d @.temp.js "http://closure-compiler.appspot.com/compile"', function(error, stdout) {
if (error) throw error;
var code = header + '\n' + stdout;
fs.unlinkSync('.temp.js');
fs.writeFileSync('browser-source-map-support.js', code);
fs.writeFileSync('amd-test/browser-source-map-support.js', code);
});
});
// Build the AMD test
run('node_modules/coffee-script/bin/coffee --map --compile amd-test/script.coffee', function(error) {
if (error) throw error;
});
// Build the browserify test
run('node_modules/coffee-script/bin/coffee --map --compile browserify-test/script.coffee', function(error) {
if (error) throw error;
run('node_modules/browserify/bin/cmd.js --debug browserify-test/script.js > browserify-test/compiled.js', function(error) {
if (error) throw error;
})
});
// Build the browser test
run('node_modules/coffee-script/bin/coffee --map --compile browser-test/script.coffee', function(error) {
if (error) throw error;
});
// Build the header test
run('node_modules/coffee-script/bin/coffee --map --compile header-test/script.coffee', function(error) {
if (error) throw error;
var contents = fs.readFileSync('header-test/script.js', 'utf8');
fs.writeFileSync('header-test/script.js', contents.replace(/\/\/# sourceMappingURL=.*/g, ''))
});
| {
"pile_set_name": "Github"
} |
[[preface]]
= Preface
[[project]]
[preface]
== Project metadata
* Version control - http://github.com/paulcwarren/spring-content/
* Bugtracker - http://github.com/paulcwarren/spring-content/issues
* Release repository - https://repo1.maven.org/maven2/
* Snapshots repository - https://oss.sonatype.org/content/repositories/snapshots
| {
"pile_set_name": "Github"
} |
% File src/library/stats/man/glm.Rd
% Part of the R package, https://www.R-project.org
% Copyright 1995-2015 R Core Team
% Distributed under GPL 2 or later
\name{glm}
\title{Fitting Generalized Linear Models}
\alias{glm}
\alias{glm.fit}
\alias{weights.glm}
%\alias{print.glm}
\concept{regression}
\concept{logistic}
\concept{log-linear}
\concept{loglinear}
\description{
\code{glm} is used to fit generalized linear models, specified by
giving a symbolic description of the linear predictor and a
description of the error distribution.
}
\usage{
glm(formula, family = gaussian, data, weights, subset,
na.action, start = NULL, etastart, mustart, offset,
control = list(\dots), model = TRUE, method = "glm.fit",
x = FALSE, y = TRUE, contrasts = NULL, \dots)
glm.fit(x, y, weights = rep(1, nobs),
start = NULL, etastart = NULL, mustart = NULL,
offset = rep(0, nobs), family = gaussian(),
control = list(), intercept = TRUE)
\method{weights}{glm}(object, type = c("prior", "working"), \dots)
}
\arguments{
\item{formula}{an object of class \code{"\link{formula}"} (or one that
can be coerced to that class): a symbolic description of the
model to be fitted. The details of model specification are given
under \sQuote{Details}.}
\item{family}{a description of the error distribution and link
function to be used in the model. For \code{glm} this can be a
character string naming a family function, a family function or the
result of a call to a family function. For \code{glm.fit} only the
third option is supported. (See \code{\link{family}} for details of
family functions.)}
\item{data}{an optional data frame, list or environment (or object
coercible by \code{\link{as.data.frame}} to a data frame) containing
the variables in the model. If not found in \code{data}, the
variables are taken from \code{environment(formula)},
typically the environment from which \code{glm} is called.}
\item{weights}{an optional vector of \sQuote{prior weights} to be used
in the fitting process. Should be \code{NULL} or a numeric vector.}
\item{subset}{an optional vector specifying a subset of observations
to be used in the fitting process.}
\item{na.action}{a function which indicates what should happen
when the data contain \code{NA}s. The default is set by
the \code{na.action} setting of \code{\link{options}}, and is
\code{\link{na.fail}} if that is unset. The \sQuote{factory-fresh}
default is \code{\link{na.omit}}. Another possible value is
\code{NULL}, no action. Value \code{\link{na.exclude}} can be useful.}
\item{start}{starting values for the parameters in the linear predictor.}
\item{etastart}{starting values for the linear predictor.}
\item{mustart}{starting values for the vector of means.}
\item{offset}{this can be used to specify an \emph{a priori} known
component to be included in the linear predictor during fitting.
This should be \code{NULL} or a numeric vector of length equal to
the number of cases. One or more \code{\link{offset}} terms can be
included in the formula instead or as well, and if more than one is
specified their sum is used. See \code{\link{model.offset}}.}
\item{control}{a list of parameters for controlling the fitting
process. For \code{glm.fit} this is passed to
\code{\link{glm.control}}.}
\item{model}{a logical value indicating whether \emph{model frame}
should be included as a component of the returned value.}
\item{method}{the method to be used in fitting the model. The default
method \code{"glm.fit"} uses iteratively reweighted least squares
(IWLS): the alternative \code{"model.frame"} returns the model frame
and does no fitting.
User-supplied fitting functions can be supplied either as a function
or a character string naming a function, with a function which takes
the same arguments as \code{glm.fit}. If specified as a character
string it is looked up from within the \pkg{stats} namespace.
}
\item{x, y}{For \code{glm}:
logical values indicating whether the response vector and model
matrix used in the fitting process should be returned as components
of the returned value.
For \code{glm.fit}: \code{x} is a design matrix of dimension
\code{n * p}, and \code{y} is a vector of observations of length
\code{n}.
}
\item{contrasts}{an optional list. See the \code{contrasts.arg}
of \code{model.matrix.default}.}
\item{intercept}{logical. Should an intercept be included in the
\emph{null} model?}
\item{object}{an object inheriting from class \code{"glm"}.}
\item{type}{character, partial matching allowed. Type of weights to
extract from the fitted model object. Can be abbreviated.}
\item{\dots}{
For \code{glm}: arguments to be used to form the default
\code{control} argument if it is not supplied directly.
For \code{weights}: further arguments passed to or from other methods.
}
}
\details{
A typical predictor has the form \code{response ~ terms} where
\code{response} is the (numeric) response vector and \code{terms} is a
series of terms which specifies a linear predictor for
\code{response}. For \code{binomial} and \code{quasibinomial}
families the response can also be specified as a \code{\link{factor}}
(when the first level denotes failure and all others success) or as a
two-column matrix with the columns giving the numbers of successes and
failures. A terms specification of the form \code{first + second}
indicates all the terms in \code{first} together with all the terms in
\code{second} with any duplicates removed.
A specification of the form \code{first:second} indicates the set
of terms obtained by taking the interactions of all terms in
\code{first} with all terms in \code{second}. The specification
\code{first*second} indicates the \emph{cross} of \code{first} and
\code{second}. This is the same as \code{first + second +
first:second}.
The terms in the formula will be re-ordered so that main effects come
first, followed by the interactions, all second-order, all third-order
and so on: to avoid this pass a \code{terms} object as the formula.
Non-\code{NULL} \code{weights} can be used to indicate that different
observations have different dispersions (with the values in
\code{weights} being inversely proportional to the dispersions); or
equivalently, when the elements of \code{weights} are positive
integers \eqn{w_i}, that each response \eqn{y_i} is the mean of
\eqn{w_i} unit-weight observations. For a binomial GLM prior weights
are used to give the number of trials when the response is the
proportion of successes: they would rarely be used for a Poisson GLM.
\code{glm.fit} is the workhorse function: it is not normally called
directly but can be more efficient where the response vector, design
matrix and family have already been calculated.
If more than one of \code{etastart}, \code{start} and \code{mustart}
is specified, the first in the list will be used. It is often
advisable to supply starting values for a \code{\link{quasi}} family,
and also for families with unusual links such as \code{gaussian("log")}.
All of \code{weights}, \code{subset}, \code{offset}, \code{etastart}
and \code{mustart} are evaluated in the same way as variables in
\code{formula}, that is first in \code{data} and then in the
environment of \code{formula}.
For the background to warning messages about \sQuote{fitted probabilities
numerically 0 or 1 occurred} for binomial GLMs, see Venables &
Ripley (2002, pp.\sspace{}197--8).
}
\section{Fitting functions}{
The argument \code{method} serves two purposes. One is to allow the
model frame to be recreated with no fitting. The other is to allow
the default fitting function \code{glm.fit} to be replaced by a
function which takes the same arguments and uses a different fitting
algorithm. If \code{glm.fit} is supplied as a character string it is
used to search for a function of that name, starting in the
\pkg{stats} namespace.
The class of the object return by the fitter (if any) will be
prepended to the class returned by \code{glm}.
}
\value{
\code{glm} returns an object of class inheriting from \code{"glm"}
which inherits from the class \code{"lm"}. See later in this section.
If a non-standard \code{method} is used, the object will also inherit
from the class (if any) returned by that function.
The function \code{\link{summary}} (i.e., \code{\link{summary.glm}}) can
be used to obtain or print a summary of the results and the function
\code{\link{anova}} (i.e., \code{\link{anova.glm}})
to produce an analysis of variance table.
The generic accessor functions \code{\link{coefficients}},
\code{effects}, \code{fitted.values} and \code{residuals} can be used to
extract various useful features of the value returned by \code{glm}.
\code{weights} extracts a vector of weights, one for each case in the
fit (after subsetting and \code{na.action}).
An object of class \code{"glm"} is a list containing at least the
following components:
\item{coefficients}{a named vector of coefficients}
\item{residuals}{the \emph{working} residuals, that is the residuals
in the final iteration of the IWLS fit. Since cases with zero
weights are omitted, their working residuals are \code{NA}.}
\item{fitted.values}{the fitted mean values, obtained by transforming
the linear predictors by the inverse of the link function.}
\item{rank}{the numeric rank of the fitted linear model.}
\item{family}{the \code{\link{family}} object used.}
\item{linear.predictors}{the linear fit on link scale.}
\item{deviance}{up to a constant, minus twice the maximized
log-likelihood. Where sensible, the constant is chosen so that a
saturated model has deviance zero.}
\item{aic}{A version of Akaike's \emph{An Information Criterion},
minus twice the maximized log-likelihood plus twice the number of
parameters, computed by the \code{aic} component of the family.
For binomial and Poison families the dispersion is
fixed at one and the number of parameters is the number of
coefficients. For gaussian, Gamma and inverse gaussian families the
dispersion is estimated from the residual deviance, and the number
of parameters is the number of coefficients plus one. For a
gaussian family the MLE of the dispersion is used so this is a valid
value of AIC, but for Gamma and inverse gaussian families it is not.
For families fitted by quasi-likelihood the value is \code{NA}.}
\item{null.deviance}{The deviance for the null model, comparable with
\code{deviance}. The null model will include the offset, and an
intercept if there is one in the model. Note that this will be
incorrect if the link function depends on the data other than
through the fitted mean: specify a zero offset to force a correct
calculation.}
\item{iter}{the number of iterations of IWLS used.}
\item{weights}{the \emph{working} weights, that is the weights
in the final iteration of the IWLS fit.}
\item{prior.weights}{the weights initially supplied, a vector of
\code{1}s if none were.}
\item{df.residual}{the residual degrees of freedom.}
\item{df.null}{the residual degrees of freedom for the null model.}
\item{y}{if requested (the default) the \code{y} vector
used. (It is a vector even for a binomial model.)}
\item{x}{if requested, the model matrix.}
\item{model}{if requested (the default), the model frame.}
\item{converged}{logical. Was the IWLS algorithm judged to have converged?}
\item{boundary}{logical. Is the fitted value on the boundary of the
attainable values?}
\item{call}{the matched call.}
\item{formula}{the formula supplied.}
\item{terms}{the \code{\link{terms}} object used.}
\item{data}{the \code{data argument}.}
\item{offset}{the offset vector used.}
\item{control}{the value of the \code{control} argument used.}
\item{method}{the name of the fitter function used, currently always
\code{"glm.fit"}.}
\item{contrasts}{(where relevant) the contrasts used.}
\item{xlevels}{(where relevant) a record of the levels of the factors
used in fitting.}
\item{na.action}{(where relevant) information returned by
\code{\link{model.frame}} on the special handling of \code{NA}s.}
In addition, non-empty fits will have components \code{qr}, \code{R}
and \code{effects} relating to the final weighted linear fit.
Objects of class \code{"glm"} are normally of class \code{c("glm",
"lm")}, that is inherit from class \code{"lm"}, and well-designed
methods for class \code{"lm"} will be applied to the weighted linear
model at the final iteration of IWLS. However, care is needed, as
extractor functions for class \code{"glm"} such as
\code{\link{residuals}} and \code{weights} do \bold{not} just pick out
the component of the fit with the same name.
If a \code{\link{binomial}} \code{glm} model was specified by giving a
two-column response, the weights returned by \code{prior.weights} are
the total numbers of cases (factored by the supplied case weights) and
the component \code{y} of the result is the proportion of successes.
}
\seealso{
\code{\link{anova.glm}}, \code{\link{summary.glm}}, etc. for
\code{glm} methods,
and the generic functions \code{\link{anova}}, \code{\link{summary}},
\code{\link{effects}}, \code{\link{fitted.values}},
and \code{\link{residuals}}.
\code{\link{lm}} for non-generalized \emph{linear} models (which SAS
calls GLMs, for \sQuote{general} linear models).
\code{\link{loglin}} and \code{\link[MASS]{loglm}} (package
\CRANpkg{MASS}) for fitting log-linear models (which binomial and
Poisson GLMs are) to contingency tables.
\code{bigglm} in package \CRANpkg{biglm} for an alternative
way to fit GLMs to large datasets (especially those with many cases).
\code{\link{esoph}}, \code{\link{infert}} and
\code{\link{predict.glm}} have examples of fitting binomial glms.
}
\author{
The original \R implementation of \code{glm} was written by Simon
Davies working for Ross Ihaka at the University of Auckland, but has
since been extensively re-written by members of the R Core team.
The design was inspired by the S function of the same name described
in Hastie & Pregibon (1992).
}
\references{
Dobson, A. J. (1990)
\emph{An Introduction to Generalized Linear Models.}
London: Chapman and Hall.
Hastie, T. J. and Pregibon, D. (1992)
\emph{Generalized linear models.}
Chapter 6 of \emph{Statistical Models in S}
eds J. M. Chambers and T. J. Hastie, Wadsworth & Brooks/Cole.
McCullagh P. and Nelder, J. A. (1989)
\emph{Generalized Linear Models.}
London: Chapman and Hall.
Venables, W. N. and Ripley, B. D. (2002)
\emph{Modern Applied Statistics with S.}
New York: Springer.
}
\examples{
## Dobson (1990) Page 93: Randomized Controlled Trial :
counts <- c(18,17,15,20,10,20,25,13,12)
outcome <- gl(3,1,9)
treatment <- gl(3,3)
print(d.AD <- data.frame(treatment, outcome, counts))
glm.D93 <- glm(counts ~ outcome + treatment, family = poisson())
anova(glm.D93)
\donttest{summary(glm.D93)}
\donttest{## an example with offsets from Venables & Ripley (2002, p.189)
utils::data(anorexia, package = "MASS")
anorex.1 <- glm(Postwt ~ Prewt + Treat + offset(Prewt),
family = gaussian, data = anorexia)
summary(anorex.1)
}
# A Gamma example, from McCullagh & Nelder (1989, pp. 300-2)
clotting <- data.frame(
u = c(5,10,15,20,30,40,60,80,100),
lot1 = c(118,58,42,35,27,25,21,19,18),
lot2 = c(69,35,26,21,18,16,13,12,12))
summary(glm(lot1 ~ log(u), data = clotting, family = Gamma))
summary(glm(lot2 ~ log(u), data = clotting, family = Gamma))
\dontrun{
## for an example of the use of a terms object as a formula
demo(glm.vr)
}}
\keyword{models}
\keyword{regression}
| {
"pile_set_name": "Github"
} |
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"reflect"
"sort"
"sync"
)
type Set interface {
Add(string)
Remove(string)
Contains(string) bool
Equals(Set) bool
Length() int
Values() []string
Copy() Set
Sub(Set) Set
}
func NewUnsafeSet(values ...string) *unsafeSet {
set := &unsafeSet{make(map[string]struct{})}
for _, v := range values {
set.Add(v)
}
return set
}
func NewThreadsafeSet(values ...string) *tsafeSet {
us := NewUnsafeSet(values...)
return &tsafeSet{us, sync.RWMutex{}}
}
type unsafeSet struct {
d map[string]struct{}
}
// Add adds a new value to the set (no-op if the value is already present)
func (us *unsafeSet) Add(value string) {
us.d[value] = struct{}{}
}
// Remove removes the given value from the set
func (us *unsafeSet) Remove(value string) {
delete(us.d, value)
}
// Contains returns whether the set contains the given value
func (us *unsafeSet) Contains(value string) (exists bool) {
_, exists = us.d[value]
return
}
// ContainsAll returns whether the set contains all given values
func (us *unsafeSet) ContainsAll(values []string) bool {
for _, s := range values {
if !us.Contains(s) {
return false
}
}
return true
}
// Equals returns whether the contents of two sets are identical
func (us *unsafeSet) Equals(other Set) bool {
v1 := sort.StringSlice(us.Values())
v2 := sort.StringSlice(other.Values())
v1.Sort()
v2.Sort()
return reflect.DeepEqual(v1, v2)
}
// Length returns the number of elements in the set
func (us *unsafeSet) Length() int {
return len(us.d)
}
// Values returns the values of the Set in an unspecified order.
func (us *unsafeSet) Values() (values []string) {
values = make([]string, 0)
for val := range us.d {
values = append(values, val)
}
return
}
// Copy creates a new Set containing the values of the first
func (us *unsafeSet) Copy() Set {
cp := NewUnsafeSet()
for val := range us.d {
cp.Add(val)
}
return cp
}
// Sub removes all elements in other from the set
func (us *unsafeSet) Sub(other Set) Set {
oValues := other.Values()
result := us.Copy().(*unsafeSet)
for _, val := range oValues {
if _, ok := result.d[val]; !ok {
continue
}
delete(result.d, val)
}
return result
}
type tsafeSet struct {
us *unsafeSet
m sync.RWMutex
}
func (ts *tsafeSet) Add(value string) {
ts.m.Lock()
defer ts.m.Unlock()
ts.us.Add(value)
}
func (ts *tsafeSet) Remove(value string) {
ts.m.Lock()
defer ts.m.Unlock()
ts.us.Remove(value)
}
func (ts *tsafeSet) Contains(value string) (exists bool) {
ts.m.RLock()
defer ts.m.RUnlock()
return ts.us.Contains(value)
}
func (ts *tsafeSet) Equals(other Set) bool {
ts.m.RLock()
defer ts.m.RUnlock()
return ts.us.Equals(other)
}
func (ts *tsafeSet) Length() int {
ts.m.RLock()
defer ts.m.RUnlock()
return ts.us.Length()
}
func (ts *tsafeSet) Values() (values []string) {
ts.m.RLock()
defer ts.m.RUnlock()
return ts.us.Values()
}
func (ts *tsafeSet) Copy() Set {
ts.m.RLock()
defer ts.m.RUnlock()
usResult := ts.us.Copy().(*unsafeSet)
return &tsafeSet{usResult, sync.RWMutex{}}
}
func (ts *tsafeSet) Sub(other Set) Set {
ts.m.RLock()
defer ts.m.RUnlock()
usResult := ts.us.Sub(other).(*unsafeSet)
return &tsafeSet{usResult, sync.RWMutex{}}
}
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
"""Automated tests (as opposed to human-verified test patterns)
It was tempting to mock out curses to get predictable output from ``tigetstr``,
but there are concrete integration-testing benefits in not doing so. For
instance, ``tigetstr`` changed its return type in Python 3.2.3. So instead, we
simply create all our test ``Terminal`` instances with a known terminal type.
All we require from the host machine is that a standard terminfo definition of
xterm-256color exists.
"""
from __future__ import with_statement # Make 2.5-compatible
from curses import tigetstr, tparm
from functools import partial
from StringIO import StringIO
import sys
from nose import SkipTest
from nose.tools import eq_
# This tests that __all__ is correct, since we use below everything that should
# be imported:
from blessings import *
TestTerminal = partial(Terminal, kind='xterm-256color')
def unicode_cap(cap):
"""Return the result of ``tigetstr`` except as Unicode."""
return tigetstr(cap).decode('utf-8')
def unicode_parm(cap, *parms):
"""Return the result of ``tparm(tigetstr())`` except as Unicode."""
return tparm(tigetstr(cap), *parms).decode('utf-8')
def test_capability():
"""Check that a capability lookup works.
Also test that Terminal grabs a reasonable default stream. This test
assumes it will be run from a tty.
"""
t = TestTerminal()
sc = unicode_cap('sc')
eq_(t.save, sc)
eq_(t.save, sc) # Make sure caching doesn't screw it up.
def test_capability_without_tty():
"""Assert capability templates are '' when stream is not a tty."""
t = TestTerminal(stream=StringIO())
eq_(t.save, u'')
eq_(t.red, u'')
def test_capability_with_forced_tty():
"""If we force styling, capabilities had better not (generally) be empty."""
t = TestTerminal(stream=StringIO(), force_styling=True)
eq_(t.save, unicode_cap('sc'))
def test_parametrization():
"""Test parametrizing a capability."""
eq_(TestTerminal().cup(3, 4), unicode_parm('cup', 3, 4))
def height_and_width():
"""Assert that ``height_and_width()`` returns ints."""
t = TestTerminal() # kind shouldn't matter.
assert isinstance(int, t.height)
assert isinstance(int, t.width)
def test_stream_attr():
"""Make sure Terminal exposes a ``stream`` attribute that defaults to something sane."""
eq_(Terminal().stream, sys.__stdout__)
def test_location():
"""Make sure ``location()`` does what it claims."""
t = TestTerminal(stream=StringIO(), force_styling=True)
with t.location(3, 4):
t.stream.write(u'hi')
eq_(t.stream.getvalue(), unicode_cap('sc') +
unicode_parm('cup', 4, 3) +
u'hi' +
unicode_cap('rc'))
def test_horizontal_location():
"""Make sure we can move the cursor horizontally without changing rows."""
t = TestTerminal(stream=StringIO(), force_styling=True)
with t.location(x=5):
pass
eq_(t.stream.getvalue(), unicode_cap('sc') +
unicode_parm('hpa', 5) +
unicode_cap('rc'))
def test_null_fileno():
"""Make sure ``Terminal`` works when ``fileno`` is ``None``.
This simulates piping output to another program.
"""
out = StringIO()
out.fileno = None
t = TestTerminal(stream=out)
eq_(t.save, u'')
def test_mnemonic_colors():
"""Make sure color shortcuts work."""
def color(num):
return unicode_parm('setaf', num)
def on_color(num):
return unicode_parm('setab', num)
# Avoid testing red, blue, yellow, and cyan, since they might someday
# change depending on terminal type.
t = TestTerminal()
eq_(t.white, color(7))
eq_(t.green, color(2)) # Make sure it's different than white.
eq_(t.on_black, on_color(0))
eq_(t.on_green, on_color(2))
eq_(t.bright_black, color(8))
eq_(t.bright_green, color(10))
eq_(t.on_bright_black, on_color(8))
eq_(t.on_bright_green, on_color(10))
def test_callable_numeric_colors():
"""``color(n)`` should return a formatting wrapper."""
t = TestTerminal()
eq_(t.color(5)('smoo'), t.magenta + 'smoo' + t.normal)
eq_(t.color(5)('smoo'), t.color(5) + 'smoo' + t.normal)
eq_(t.on_color(2)('smoo'), t.on_green + 'smoo' + t.normal)
eq_(t.on_color(2)('smoo'), t.on_color(2) + 'smoo' + t.normal)
def test_null_callable_numeric_colors():
"""``color(n)`` should be a no-op on null terminals."""
t = TestTerminal(stream=StringIO())
eq_(t.color(5)('smoo'), 'smoo')
eq_(t.on_color(6)('smoo'), 'smoo')
def test_naked_color_cap():
"""``term.color`` should return a stringlike capability."""
t = TestTerminal()
eq_(t.color + '', t.setaf + '')
def test_number_of_colors_without_tty():
"""``number_of_colors`` should return 0 when there's no tty."""
# Hypothesis: once setupterm() has run and decided the tty supports 256
# colors, it never changes its mind.
raise SkipTest
t = TestTerminal(stream=StringIO())
eq_(t.number_of_colors, 0)
t = TestTerminal(stream=StringIO(), force_styling=True)
eq_(t.number_of_colors, 0)
def test_number_of_colors_with_tty():
"""``number_of_colors`` should work."""
t = TestTerminal()
eq_(t.number_of_colors, 256)
def test_formatting_functions():
"""Test crazy-ass formatting wrappers, both simple and compound."""
t = TestTerminal()
# By now, it should be safe to use sugared attributes. Other tests test those.
eq_(t.bold(u'hi'), t.bold + u'hi' + t.normal)
eq_(t.green('hi'), t.green + u'hi' + t.normal) # Plain strs for Python 2.x
# Test some non-ASCII chars, probably not necessary:
eq_(t.bold_green(u'boö'), t.bold + t.green + u'boö' + t.normal)
eq_(t.bold_underline_green_on_red('boo'),
t.bold + t.underline + t.green + t.on_red + u'boo' + t.normal)
# Don't spell things like this:
eq_(t.on_bright_red_bold_bright_green_underline('meh'),
t.on_bright_red + t.bold + t.bright_green + t.underline + u'meh' + t.normal)
def test_formatting_functions_without_tty():
"""Test crazy-ass formatting wrappers when there's no tty."""
t = TestTerminal(stream=StringIO())
eq_(t.bold(u'hi'), u'hi')
eq_(t.green('hi'), u'hi')
# Test non-ASCII chars, no longer really necessary:
eq_(t.bold_green(u'boö'), u'boö')
eq_(t.bold_underline_green_on_red('loo'), u'loo')
eq_(t.on_bright_red_bold_bright_green_underline('meh'), u'meh')
def test_nice_formatting_errors():
"""Make sure you get nice hints if you misspell a formatting wrapper."""
t = TestTerminal()
try:
t.bold_misspelled('hey')
except TypeError, e:
assert 'probably misspelled' in e.args[0]
try:
t.bold_misspelled(u'hey') # unicode
except TypeError, e:
assert 'probably misspelled' in e.args[0]
try:
t.bold_misspelled(None) # an arbitrary non-string
except TypeError, e:
assert 'probably misspelled' not in e.args[0]
try:
t.bold_misspelled('a', 'b') # >1 string arg
except TypeError, e:
assert 'probably misspelled' not in e.args[0]
def test_init_descriptor_always_initted():
"""We should be able to get a height and width even on no-tty Terminals."""
t = Terminal(stream=StringIO())
eq_(type(t.height), int)
| {
"pile_set_name": "Github"
} |
[kakao](../../index.md) / [com.agoda.kakao.common.matchers](../index.md) / [ListViewAdapterSizeMatcher](index.md) / [<init>](./-init-.md)
# <init>
`ListViewAdapterSizeMatcher(size: `[`Int`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)`)`
Matches ListView with count of children
### Parameters
`size` - of children count in ListView | {
"pile_set_name": "Github"
} |
An Introduction to SLI
======================
Introduction
------------
NEST can be started by typing
::
<nest_install_dir>
at the command prompt. You should then see something like this:
::
gewaltig@jasmin-vm:~$ nest
-- N E S T 2 beta --
Copyright 1995-2009 The NEST Initiative
Version 1.9-svn Feb 6 2010 00:33:50
This program is provided AS IS and comes with
NO WARRANTY. See the file LICENSE for details.
Problems or suggestions?
Website : https://www.nest-initiative.org
Mailing list: [email protected]
Type 'help' to get more information.
Type 'quit' or CTRL-D to quit NEST.
Command line switches
---------------------
Type
::
nest --help
to find out about NEST’s command-line parameters.
::
gewaltig@jasmin-vm:~$ nest --help
usage: nest [options] [file ..]
-h --help print usage and exit
-v --version print version information and exit.
- --batch read input from a stdin/pipe
--userargs=arg1:... put user defined arguments in statusdict::userargs
-d --debug start in debug mode (implies --verbosity=ALL)
--verbosity=ALL turn on all messages.
--verbosity=DEBUG|STATUS|INFO|WARNING|ERROR|FATAL
show messages of this priority and above.
--verbosity=QUIET turn off all messages.
SLI scripts
-----------
Scripts can be run by typing:
::
<nest_install_dir> <file>
If you are a Vim user and require support for SLI files, please refer to
our :doc:`../contribute/templates_styleguides/vim_support_sli`.
Supplying SLI scripts with parameters
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Using the ``--userargs=arg1:...`` command line switch, it is possible to
supply a SLI script with parameters from the outside of NEST. A common
use case for this are parameter sweeps, where the parameters are defined
in a bash script and multiple instances of NEST are used to test one
parameter each. A bash script for this could look like this:
::
for lambda in `seq 1 20`; do
for gamma in `seq 1 5`; do
nest --userargs=lambda=$lambda:$gamma=$gamma simulation.sli
done
done
The corresponding SLI script ``simulation.sli`` could use the supplied
parameters like this:
::
/args mark statusdict/userargs :: {(=) breakup} Map { arrayload pop int exch cvlit exch } forall >> def
args /lambda get ==
The first line first gets the array of user supplied arguments
(``userargs``) from the ``statusdict`` and breaks each element at the
“=”-symbol. It then converts the first element (lambda, gamma) to a
literal and the second argument (the number) to an integer. Using
``mark`` and ``>>``, the content of the userargs array is added to a
dictionary, which is stored under the name ``args``. The second line
just prints the content of the lamda variable.
SLI user manual
---------------
This manual gives a brief overview of the SLI programming language.
1. `First Steps <first-steps.md>`__
2. `Objects and data types <objects-and-data-types.md>`__
3. `Programming in SLI <programming-in-sli.md>`__
4. `Using files and keyboard
input <using-files-and-keyboard-input.md>`__
5. `Neural simulations <neural-simulations.md>`__
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2016 Uber Technologies, 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 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.
package zapcore
import (
"fmt"
"strings"
"sync"
"time"
"go.uber.org/zap/internal/bufferpool"
"go.uber.org/zap/internal/exit"
"go.uber.org/multierr"
)
var (
_cePool = sync.Pool{New: func() interface{} {
// Pre-allocate some space for cores.
return &CheckedEntry{
cores: make([]Core, 4),
}
}}
)
func getCheckedEntry() *CheckedEntry {
ce := _cePool.Get().(*CheckedEntry)
ce.reset()
return ce
}
func putCheckedEntry(ce *CheckedEntry) {
if ce == nil {
return
}
_cePool.Put(ce)
}
// NewEntryCaller makes an EntryCaller from the return signature of
// runtime.Caller.
func NewEntryCaller(pc uintptr, file string, line int, ok bool) EntryCaller {
if !ok {
return EntryCaller{}
}
return EntryCaller{
PC: pc,
File: file,
Line: line,
Defined: true,
}
}
// EntryCaller represents the caller of a logging function.
type EntryCaller struct {
Defined bool
PC uintptr
File string
Line int
}
// String returns the full path and line number of the caller.
func (ec EntryCaller) String() string {
return ec.FullPath()
}
// FullPath returns a /full/path/to/package/file:line description of the
// caller.
func (ec EntryCaller) FullPath() string {
if !ec.Defined {
return "undefined"
}
buf := bufferpool.Get()
buf.AppendString(ec.File)
buf.AppendByte(':')
buf.AppendInt(int64(ec.Line))
caller := buf.String()
buf.Free()
return caller
}
// TrimmedPath returns a package/file:line description of the caller,
// preserving only the leaf directory name and file name.
func (ec EntryCaller) TrimmedPath() string {
if !ec.Defined {
return "undefined"
}
// nb. To make sure we trim the path correctly on Windows too, we
// counter-intuitively need to use '/' and *not* os.PathSeparator here,
// because the path given originates from Go stdlib, specifically
// runtime.Caller() which (as of Mar/17) returns forward slashes even on
// Windows.
//
// See https://github.com/golang/go/issues/3335
// and https://github.com/golang/go/issues/18151
//
// for discussion on the issue on Go side.
//
// Find the last separator.
//
idx := strings.LastIndexByte(ec.File, '/')
if idx == -1 {
return ec.FullPath()
}
// Find the penultimate separator.
idx = strings.LastIndexByte(ec.File[:idx], '/')
if idx == -1 {
return ec.FullPath()
}
buf := bufferpool.Get()
// Keep everything after the penultimate separator.
buf.AppendString(ec.File[idx+1:])
buf.AppendByte(':')
buf.AppendInt(int64(ec.Line))
caller := buf.String()
buf.Free()
return caller
}
// An Entry represents a complete log message. The entry's structured context
// is already serialized, but the log level, time, message, and call site
// information are available for inspection and modification.
//
// Entries are pooled, so any functions that accept them MUST be careful not to
// retain references to them.
type Entry struct {
Level Level
Time time.Time
LoggerName string
Message string
Caller EntryCaller
Stack string
}
// CheckWriteAction indicates what action to take after a log entry is
// processed. Actions are ordered in increasing severity.
type CheckWriteAction uint8
const (
// WriteThenNoop indicates that nothing special needs to be done. It's the
// default behavior.
WriteThenNoop CheckWriteAction = iota
// WriteThenPanic causes a panic after Write.
WriteThenPanic
// WriteThenFatal causes a fatal os.Exit after Write.
WriteThenFatal
)
// CheckedEntry is an Entry together with a collection of Cores that have
// already agreed to log it.
//
// CheckedEntry references should be created by calling AddCore or Should on a
// nil *CheckedEntry. References are returned to a pool after Write, and MUST
// NOT be retained after calling their Write method.
type CheckedEntry struct {
Entry
ErrorOutput WriteSyncer
dirty bool // best-effort detection of pool misuse
should CheckWriteAction
cores []Core
}
func (ce *CheckedEntry) reset() {
ce.Entry = Entry{}
ce.ErrorOutput = nil
ce.dirty = false
ce.should = WriteThenNoop
for i := range ce.cores {
// don't keep references to cores
ce.cores[i] = nil
}
ce.cores = ce.cores[:0]
}
// Write writes the entry to the stored Cores, returns any errors, and returns
// the CheckedEntry reference to a pool for immediate re-use. Finally, it
// executes any required CheckWriteAction.
func (ce *CheckedEntry) Write(fields ...Field) {
if ce == nil {
return
}
if ce.dirty {
if ce.ErrorOutput != nil {
// Make a best effort to detect unsafe re-use of this CheckedEntry.
// If the entry is dirty, log an internal error; because the
// CheckedEntry is being used after it was returned to the pool,
// the message may be an amalgamation from multiple call sites.
fmt.Fprintf(ce.ErrorOutput, "%v Unsafe CheckedEntry re-use near Entry %+v.\n", time.Now(), ce.Entry)
ce.ErrorOutput.Sync()
}
return
}
ce.dirty = true
var err error
for i := range ce.cores {
err = multierr.Append(err, ce.cores[i].Write(ce.Entry, fields))
}
if ce.ErrorOutput != nil {
if err != nil {
fmt.Fprintf(ce.ErrorOutput, "%v write error: %v\n", time.Now(), err)
ce.ErrorOutput.Sync()
}
}
should, msg := ce.should, ce.Message
putCheckedEntry(ce)
switch should {
case WriteThenPanic:
panic(msg)
case WriteThenFatal:
exit.Exit()
}
}
// AddCore adds a Core that has agreed to log this CheckedEntry. It's intended to be
// used by Core.Check implementations, and is safe to call on nil CheckedEntry
// references.
func (ce *CheckedEntry) AddCore(ent Entry, core Core) *CheckedEntry {
if ce == nil {
ce = getCheckedEntry()
ce.Entry = ent
}
ce.cores = append(ce.cores, core)
return ce
}
// Should sets this CheckedEntry's CheckWriteAction, which controls whether a
// Core will panic or fatal after writing this log entry. Like AddCore, it's
// safe to call on nil CheckedEntry references.
func (ce *CheckedEntry) Should(ent Entry, should CheckWriteAction) *CheckedEntry {
if ce == nil {
ce = getCheckedEntry()
ce.Entry = ent
}
ce.should = should
return ce
}
| {
"pile_set_name": "Github"
} |
PMEMPOOLSET
# comment #1
100G w:\mountpoint0\myfile.part0
200G w:\mountpoint1\myfile.part1
# comment #2
400G w:\mountpoint2\myfile.part2
# comment #3
REPLICA
500G w:\mountpoint3\mymirror.part0
200G w:\mountpoint4\mymirror.part1
# comment #4
| {
"pile_set_name": "Github"
} |
import { ElementUIComponent } from './component'
/** Footer Component */
export declare class ElFooter extends ElementUIComponent {
/** Height of the footer */
height: string
}
| {
"pile_set_name": "Github"
} |
DEAL:2d::4
DEAL:2d::0
| {
"pile_set_name": "Github"
} |
1to2 naively converts source code files from NAN 1 to NAN 2. There will be erroneous conversions,
false positives and missed opportunities. The input files are rewritten in place. Make sure that
you have backups. You will have to manually review the changes afterwards and do some touchups.
```sh
$ tools/1to2.js
Usage: 1to2 [options] <file ...>
Options:
-h, --help output usage information
-V, --version output the version number
```
| {
"pile_set_name": "Github"
} |
<%@ include file="/html/portlet/ext/contentlet/init.jsp"%>
<%@page import="com.dotmarketing.portlets.structure.model.ContentletRelationships.ContentletRelationshipRecords"%>
<%@page import="com.dotmarketing.portlets.structure.model.ContentletRelationships"%>
<%@page import="com.dotmarketing.portlets.structure.model.Relationship"%>
<%@page import="com.dotmarketing.portlets.contentlet.model.Contentlet"%>
<%@page import="com.dotmarketing.portlets.structure.model.Structure"%>
<%@page import="com.dotmarketing.util.UtilMethods"%>
<%@page import="com.dotmarketing.util.InodeUtils"%>
<%@page import="com.dotmarketing.portlets.structure.model.Field"%>
<%@page import="com.dotmarketing.business.IdentifierFactory"%>
<%@page import="com.dotmarketing.beans.Identifier"%>
<%@page import="com.dotmarketing.util.PortletURLUtil"%>
<%@page import="com.dotmarketing.portlets.languagesmanager.business.*"%>
<%@page import="com.dotmarketing.business.APILocator"%>
<%@page import="com.dotmarketing.portlets.languagesmanager.model.Language"%>
<%@page import="com.dotmarketing.portlets.contentlet.business.ContentletAPI"%>
<%@page import="com.dotmarketing.util.Config" %>
<%@page import="com.dotmarketing.util.StringUtils" %>
<%@page import="com.dotmarketing.business.IdentifierCache"%>
<%@page import="com.dotmarketing.business.FactoryLocator"%>
<%@page import="java.util.HashMap"%>
<%
LanguageAPI langAPI = APILocator.getLanguageAPI();
List<Language> langs = langAPI.getLanguages();
List<Language> languages = (List<Language>)request.getAttribute (com.dotmarketing.util.WebKeys.LANGUAGES);
boolean canUserPublishContentlet = (request.getAttribute("canUserPublishContentlet") != null) ? ((Boolean)request.getAttribute("canUserPublishContentlet")).booleanValue() : false;
java.util.Map<String, String[]> params = new java.util.HashMap<String, String[]>();
params.put("struts_action",new String[] {"/ext/contentlet/view_contentlets_popup"});
String viewContentsPopupURL = PortletURLUtil.getActionURL(request, WindowState.MAXIMIZED.toString(), params);
DateFormat modDateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
modDateFormat.setTimeZone(timeZone);
Contentlet contentlet = (Contentlet) request.getAttribute("contentlet");
String contentTitle = (contentlet !=null && contentlet.getTitle() !=null) ? contentlet.getTitle() : LanguageUtil.get(pageContext, "modes.New-Content");
contentTitle = UtilMethods.truncatify(contentTitle, 150);
String contentletInode = String.valueOf(contentlet.getInode());
Map con = contentlet.getMap();
Language defaultLang = langAPI.getDefaultLanguage();
String languageId = String.valueOf(defaultLang.getId());
PermissionAPI conPerAPI = APILocator.getPermissionAPI();
boolean canUserWriteToContentlet = true;
if(InodeUtils.isSet(contentlet.getInode()))
canUserWriteToContentlet = conPerAPI.doesUserHavePermission(contentlet,PermissionAPI.PERMISSION_WRITE,user);
//Variable used to return after the work is done with the contentlet
String referer = "";
if (request.getParameter("referer") != null) {
referer = request.getParameter("referer");
} else {
params = new HashMap();
params.put("struts_action",new String[] {"/ext/contentlet/edit_contentlet"});
params.put("inode",new String[] { contentletInode + "" });
params.put("cmd",new String[] { Constants.EDIT });
referer = PortletURLUtil.getActionURL(request,WindowState.MAXIMIZED.toString(),params);
}
/* for managing automatic relationships coming form the add content on the relationships tab */
String relwith = request.getParameter("relwith");/*for the relationship*/
String relisparent = request.getParameter("relisparent");
String reltype = request.getParameter("reltype");
if (relwith!=null) {
%>
<%@page import="com.dotmarketing.business.PermissionAPI"%><input type="hidden" name="relwith" value="<%=relwith%>" id="relwith"/>
<input type="hidden" name="relisparent" value="<%=relisparent%>" id="relisparent"/>
<input type="hidden" name="reltype" value="<%=reltype%>" id="reltype"/>
<%
}
List<ContentletRelationships.ContentletRelationshipRecords> relationshipRecords = (List<ContentletRelationships.ContentletRelationshipRecords>)request.getAttribute("relationshipRecords");
if (relationshipRecords.size() > 0) {
List<ContentletRelationships.ContentletRelationshipRecords> sortList = new ArrayList<ContentletRelationships.ContentletRelationshipRecords>();
for (ContentletRelationshipRecords records : relationshipRecords) {
if(records.isHasParent()){
sortList.add( sortList.size(), records);
}
else{
sortList.add(0,records);
}
}
int counter=100;
int searchCounter=1;
int dialogCounter=1;
for (ContentletRelationshipRecords records : sortList) {
Relationship rel = records.getRelationship();
List<Contentlet> contentletsList = records.getRecords();
Structure targetStructure = null;
String relationType= null;
String relationName = "";
String parentInode="";
String isParent="";
String relationTypeValue = rel.getRelationTypeValue();
String relationJsName = "rel_tab_" + UtilMethods.javaScriptifyVariable(relationTypeValue) + "_" + (records.isHasParent()?"P":"C");
relationType= rel.getRelationTypeValue();
if (records.isHasParent()) {
targetStructure = rel.getChildStructure();
relationName = rel.getChildRelationName();
isParent="yes";
} else {
targetStructure = rel.getParentStructure();
relationName = rel.getParentRelationName();
isParent="no";
}
%>
<%
//if coming from an automatic relationship addind action will display relationships tab
if (request.getParameter("relend")!=null) {
%>
<script>
displayProperties('relationships');
</script>
<%
}
%>
<%
if ((rel.isChildRequired() && records.isHasParent()) || (rel.isParentRequired() && !records.isHasParent())) {
%>
<script type="text/javascript">
dojo.ready(function(){
var mainTabContainerTablistRelationships = dojo.byId("mainTabContainer_tablist_relationships");
if (mainTabContainerTablistRelationships) {
dojo.html.set(dojo.byId("mainTabContainer_tablist_relationships"), '<span class="required"></span> <%= LanguageUtil.get(pageContext, "Relationships") %>');
}
});
</script>
<%
}
%>
<div class="portlet-toolbar relationships-list">
<div class="portlet-toolbar__actions-primary">
<b><%= (sortList.size()>1 && rel.isParentRequired() && !records.isHasParent()) ? "<span class='required'></span>" :
(sortList.size()>1 && rel.isChildRequired() && records.isHasParent()) ? "<span class='required'></span>" : "" %>
<%= targetStructure.getName() %>: </b><%=("yes".equals(isParent)) ? LanguageUtil.get(pageContext, "Child"): LanguageUtil.get(pageContext, "Parent") %>
(<%= rel.getRelationTypeValue() %>)
</div>
<div class="portlet-toolbar__actions-secondary">
<div id="<%= relationJsName %>relateMenu"></div>
</div>
</div>
<table border="0" class="listingTable" style="margin-bottom:30px;">
<thead>
<tr class="beta">
<th width="20"><B><font class="beta" size="2"></font></B></th>
<%
int nFields = 3;
boolean indexed = false;
boolean hasListedFields = false;
List<Field> targetFields = targetStructure.getFields();
for (Field f : targetFields) {
if (f.isListed()) {
hasListedFields = true;
indexed = true;
nFields++;
%>
<th><B><font class="beta" size="2"><%= f.getFieldName() %> </font></B>
</th>
<%
}
}
if (!indexed) {
%>
<th><B><font class="beta" size="2"> <%= LanguageUtil.get(pageContext, "No-Searchable-Fields-Found-Showing-the-Identity-Number") %> </font></B></th>
<%
}
%>
<%
if(langs.size() > 1) {
%>
<th width="<%= langs.size() < 6 ? (langs.size() * 40) : 200 %>px;"><B><font class="beta" size="2"></font></B></th>
<%
}else{
%>
<th width="20"><B><font class="beta" size="2"></font></B></th>
<%
}
%>
</tr>
</thead>
<tbody id="<%=relationJsName%>Table">
</tbody>
</table>
<!-- Hidden relationship fields -->
<input type="hidden" name="<%= relationJsName %>Inode" id="<%= relationJsName %>Inode">
<input type="hidden" name="selected<%= relationJsName %>Inode" id="selected<%= relationJsName %>Inode">
<input type="hidden" name="<%= relationJsName %>_inodes" id="<%= relationJsName %>_inodes">
<!-- Javascripts -->
<script language="javascript">
//Initializing the relationship table data array
var hasListedFields = <%= hasListedFields %>;
var <%= relationJsName %>_Contents = new Array ();
<%String lastIdentifier = "";
boolean parent = false;
for (Contentlet cont : contentletsList) {
try{
parent = cont.getBoolProperty("dotCMSParentOnTree") ;
}
catch(Exception e){
}
if(parent && FactoryLocator.getRelationshipFactory().sameParentAndChild(rel)){
//continue;
}
/********** GIT 1057 *******/
ContentletAPI contentletAPI = APILocator.getContentletAPI();
Contentlet languageContentlet = null;
%>
var cont<%=UtilMethods.javaScriptifyVariable(cont.getInode())%>Siblings = new Array();
<%
for(Language lang : langs){
try{
languageContentlet = null;
languageContentlet = contentletAPI.findContentletByIdentifier(cont.getIdentifier(), true, lang.getId(), user, false);
}catch (Exception e) { }
//Try to find non-live version
if (languageContentlet == null) {
try{
languageContentlet = contentletAPI.findContentletByIdentifier(cont.getIdentifier(), false, lang.getId(), user, false);
}catch (Exception e1) { }
}
%>
var cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling = new Array();
<%
if((languageContentlet == null) || (!UtilMethods.isSet(languageContentlet.getInode()))){
%>
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['langCode'] = '<%=langAPI.getLanguageCodeAndCountry(lang.getId(),null)%>';
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['langName'] = '<%=lang.getLanguage() %>';
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['langId'] = '<%=lang.getId() %>';
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['inode'] = '';
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['parent'] = '<%=parent %>';
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['working'] = 'false';
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['live'] = 'false';
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['deleted'] = 'true';
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['locked'] = 'false';
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['siblingInode'] = '<%=cont.getInode()%>';
<%
}else{
%>
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['langCode'] = '<%=langAPI.getLanguageCodeAndCountry(lang.getId(),null)%>';
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['langName'] = '<%=lang.getLanguage() %>';
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['langId'] = '<%=lang.getId() %>';
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['inode'] = '<%=languageContentlet.getInode()%>';
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['parent'] = '<%=parent %>';
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['working'] = '<%=String.valueOf(languageContentlet.isWorking())%>';
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['live'] = '<%=String.valueOf(languageContentlet.isLive())%>';
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['deleted'] = '<%=String.valueOf(languageContentlet.isArchived())%>';
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['locked'] = '<%=Boolean.valueOf(languageContentlet.isLocked() && ! languageContentlet.getModUser().equals(user.getUserId()))%>';
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling['siblingInode'] = '<%=cont.getInode()%>';
<%
}
%>
cont<%=UtilMethods.javaScriptifyVariable(cont.getInode())%>Siblings[cont<%=UtilMethods.javaScriptifyVariable(cont.getInode())%>Siblings.length] = cont<%=UtilMethods.javaScriptifyVariable(cont.getInode()+lang.getId())%>Sibling;
<%
}
/********** GIT 1057 *******/
String languageCode;
String languageName;
Language language = langAPI.getLanguage(cont.getLanguageId());%>
var cont = new Array();
cont['inode'] = '<%=cont.getInode()%>';
<%languageCode = langAPI.getLanguageCodeAndCountry(cont.getLanguageId(),null);
languageName = language.getLanguage();%>
cont['langCode'] = '<%=languageCode%>';
cont['langName'] = '<%=languageName%>';
cont['parent'] = '<%=parent%>';
cont['working'] = '<%=String.valueOf(cont.isWorking())%>';
cont['live'] = '<%=String.valueOf(cont.isLive())%>';
cont['deleted'] = '<%=String.valueOf(cont.isArchived())%>';
cont['locked'] = '<%=Boolean.valueOf(cont.isLocked() && ! cont.getModUser().equals(user.getUserId()))%>';
cont['siblings'] = cont<%=UtilMethods.javaScriptifyVariable(cont.getInode())%>Siblings;
<%
for (Field f : targetFields) {
if (f.isListed()) {
String fieldName = f.getFieldName();
ContentletAPI rconAPI = APILocator.getContentletAPI();
Object fieldValueObj = rconAPI.getFieldValue(cont, f);
String fieldValue = "";
if (fieldValueObj != null) {
if (fieldValueObj instanceof java.util.Date) {
fieldValue = modDateFormat.format(fieldValueObj);
} else if (fieldValueObj instanceof java.sql.Timestamp){
java.util.Date fieldDate = new java.util.Date(((java.sql.Timestamp)fieldValueObj).getTime());
fieldValue = modDateFormat.format(fieldDate);
} else {
fieldValue = fieldValueObj.toString();
}
}
%>
cont['<%=UtilMethods.escapeSingleQuotes(fieldName)%>'] = '<%=fieldValue.replaceAll("'","\\\\'").replaceAll("\n","").replaceAll("\r","").trim()%>';
<%
}
}
if (!hasListedFields) {
Identifier contid = APILocator.getIdentifierAPI().find(cont);
%>
cont['identifier'] = '<%=contid.getInode()%>';
<%
}
%>
cont['id'] = '<%=cont.getIdentifier()%>';
<%
if(!lastIdentifier.equalsIgnoreCase(cont.getIdentifier()) )
{
%>
cont['groupStart'] = true;
<%
lastIdentifier = cont.getIdentifier();
}//end if( lastIdentifier != cont.getIdentifier() )
%>
<%= relationJsName %>_Contents[<%= relationJsName %>_Contents.length] = cont;
<%
}
%>
//Function used to render language id
function <%= relationJsName %>_lang(o) {
var contentletLangCode = '<%= langAPI.getLanguageCodeAndCountry(contentlet.getLanguageId(),null)%>';
var lang = '';
var result = '';
var anchorValue = "";
if (o != null) {
result = result + "<table width=\"100%\" class=\"relationLanguageFlag\"><tbody><tr>"
for(var sibIndex = 0; sibIndex < o['siblings'].length ; sibIndex++){
result = result + '<td class=\"relationLanguageFlag\">';
langImg = o['siblings'][sibIndex]['langCode'];
langName = o['siblings'][sibIndex]['langName'];
if(o['siblings'][sibIndex]['live'] == 'true'){
anchorValue = "";
if (o != null){
anchorValue = "<a href=\"javascript:<%= relationJsName %>editRelatedContent('" + o['siblings'][sibIndex]['inode'] + "', '"+ o['siblings'][sibIndex]['siblingInode'] +"', '"+ o['siblings'][sibIndex]['langId'] +"');\"" + ">" ;
}
result = result +' ' + anchorValue + '<img style="vertical-align: middle; border: solid 2px #33FF33; padding:2px; border-radius:5px;" src="/html/images/languages/' + langImg + '.gif" alt="'+langName+'">' + '</a>';
}else if(o['siblings'][sibIndex]['deleted'] == 'true'){
anchorValue = "";
if (o != null){
anchorValue = "<a href=\"javascript:<%= relationJsName %>editRelatedContent('" + o['siblings'][sibIndex]['inode'] + "', '"+ o['siblings'][sibIndex]['siblingInode'] +"', '"+ o['siblings'][sibIndex]['langId'] +"');\"" + ">" ;
}
result = result + ' ' + anchorValue + '<img style="vertical-align: middle; border: solid 2px #66664D; padding:2px; border-radius:5px;" src="/html/images/languages/' + langImg + '_gray.gif" alt="'+langName+'">' + '</a>';
}else{
anchorValue = "";
if (o != null){
anchorValue = "<a href=\"javascript:<%= relationJsName %>editRelatedContent('" + o['siblings'][sibIndex]['inode'] + "', '"+ o['siblings'][sibIndex]['siblingInode'] +"', '"+ o['siblings'][sibIndex]['langId'] +"');\"" + ">" ;
}
result = result + ' ' + anchorValue + '<img style="vertical-align: middle; border: solid 2px #FFCC11; padding:2px; border-radius:5px;" src="/html/images/languages/' + langImg + '.gif" alt="'+langName+'">' + '</a>';
}
result = result + "</td>";
if((sibIndex+1)%6 == 0){
result = result + "</tr><tr>";
}
}
result = result + "</tr></tbody></table>";
}
return result;
}
//Function used to render the publish/unpublish info
function <%= relationJsName %>_status(o) {
var strHTML = ' ';
if (o != null) {
live = o['live'];
deleted = o['deleted'];
working = o['working'];
var strHTML = new String();
if (live && live != "false") {
strHTML = strHTML + "<span class=\"liveIcon\"></span>";
} else if (deleted && deleted != "false") {
strHTML = strHTML + "<span class=\"archivedIcon\"></span>";
} else if (working && working != "false") {
strHTML = strHTML + "<span class=\"workingIcon\"></span>";
}
}
return strHTML;
}
//Function used to render relationship order number
var <%= relationJsName %>_current_order = 1;
var <%= relationJsName %>_identifier_current_order = 1;
function <%= relationJsName %>_order_tf() {
return <%= relationJsName %>_current_order++;
}
//Returns the given object identifier
function identifier_func (o) {
var value = "";
if (o != null)
value = "<a class=\"beta\" href=\"javascript:<%= relationJsName %>editRelatedContent('" + o['inode'] + "', '"+ o['siblingInode'] +"', '"+ o['langId'] +"');\"" + ">" + o['identifier'] + "</a>";
return value;
}
//Adding the rendering functions based on the relationship
//listed fields
<%
int fieldsCount = 3;
for (Field f : targetFields) {
if (f.isListed()) {
fieldsCount++;
String fieldName = f.getFieldName();
String varName = f.getVelocityVarName();
String functionName = relationJsName + "_" + UtilMethods.javaScriptifyVariable(fieldName) + "_func";
%>
function <%= functionName %> (o) {
var value = "";
var innerValue = "";
if (o != null){
if (o['<%=UtilMethods.escapeSingleQuotes(fieldName)%>']!=null){
innerValue = o['<%=UtilMethods.escapeSingleQuotes(fieldName)%>'];
}else{
innerValue = o[('<%=varName%>')];
}
value = "<a class=\"beta\" href=\"javascript:<%= relationJsName %>editRelatedContent('" + o['inode'] + "', '"+ o['siblingInode'] +"', '"+ o['langId'] +"');\"" + ">" + innerValue + "</a>";
}
return value;
}
<%
}
}
%>
//Removes the given inode from the relationship table
function <%= relationJsName %>_removeContentFromRelationship (identifier) {
var relationList = <%= relationJsName %>_Contents;
var found = false;
var size = relationList.length;
var firstIdentIndex = 0;
var lastIdentIndex = 0;
for (firstIdentIndex = 0; firstIdentIndex < size; firstIdentIndex++) {
var content = relationList[firstIdentIndex];
if (content['id'] == identifier) {
found = true;
break;
}
}
if( found )
{
for (lastIdentIndex = firstIdentIndex+1; lastIdentIndex < size; lastIdentIndex++) {
var content = relationList[lastIdentIndex];
if (content['id'] != identifier) {
break;
}
}
relationList.splice(firstIdentIndex, lastIdentIndex-firstIdentIndex);
}
<%= relationJsName %>_Contents = relationList;
<%= relationJsName %>_saveRelations ();
}
//Invoked to open the select contentlet popup
function <%= relationJsName %>_addRelationship(){
dijit.byId("<%= relationJsName %>Dialog").show(true);
dijit.byId("<%= relationJsName %>Dialog")._doSearchPage1();
}
//Callback received from the relate content
function callback<%= relationJsName %>(content){
//identifier refers to contentlet family to add...
setTimeout("ContentletAjax.getContentletData ('" + content.inode + "', <%= relationJsName %>_addRelationshipCallback)", 50);
}
//Invoked when a contentlet is selected to fill the contentlet data in the table
function <%= relationJsName %>_addRelationshipCallback(selectedData){
var data = new Array();
var dataToRelate = new Array();
// Eliminating existing relations
for (var indexJ = 0; indexJ < selectedData.length; indexJ++) {
var relationExists = false;
for (var indexI = 0; indexI < <%= relationJsName %>_Contents.length; indexI++) {
if(selectedData[indexJ]['id'] == <%= relationJsName %>_Contents[indexI]['id']){
relationExists = true;
}
}
if(!relationExists){
dataToRelate[dataToRelate.length] = selectedData[indexJ];
}
}
// Eliminating mulitple contentlets for same identifier
for (var indexK = 0; indexK < dataToRelate.length; indexK++) {
var doesIdentifierExists = false;
for (var indexL = 0; indexL < data.length; indexL++) {
if(dataToRelate[indexK]['id'] == data[indexL]['id'])
doesIdentifierExists = true;
}
if(!doesIdentifierExists)
data[data.length] = dataToRelate[indexK];
}
if( data == null || (data != null && data.length == 0) ) {
return;
}
var dataNoRep = new Array();
if(<%= relationJsName %>_Contents.length == 0) {
dataNoRep = data;
}
for (var i = 0; i < <%= relationJsName %>_Contents.length; i++) {
var cont = <%= relationJsName %>_Contents[i];
var identifier = "";
if (cont != null) {
identifier = cont['id'];
}
var k = 0;
for(var j = 0; j < data.length; j++ ) {
if (identifier == data[j]['id']) {
data.splice(j,1);
} else {
dataNoRep[k] = data[j];
k++;
}
}
}
for(var i=0; i < dataNoRep.length; i++) {
dataNoRep[i]['groupStart'] = true;
}
// data[0]['groupStart'] = true;
<%= relationJsName %>RelatedCons.insertNodes(false,dataNoRep);
<%= relationJsName %>_Contents = <%= relationJsName %>_Contents.concat(dataNoRep);
renumberRecolorAndReorder<%= relationJsName %>();
}
function <%= relationJsName %>_reorder () {
var newOrder = new Array();
var newContent = new Array();
var start = -1;
var lastOrder = -1;
var i;
var size = <%= relationJsName %>_Contents.length;
for (i = 0; i < size; i++) {
var content = <%= relationJsName %>_Contents[i];
if( content['groupStart'] != null ) {
if( start > -1 ) {
newOrder.push({"_start": start, "_end": i, "order": lastOrder});
}
start = i;
lastOrder = document.getElementById('<%= relationJsName %>_order_' + content['id']).value;
}
}
if( start > -1 ) {
newOrder.push({"_start": start, "_end": i, "order": lastOrder});
}
newOrder.sort(function(a,b) {
return a.order - b.order;
});
for(i =0; i < newOrder.length; i++) {
newContent = newContent.concat( <%= relationJsName %>_Contents.slice(newOrder[i]._start, newOrder[i]._end) );
}
<%= relationJsName %>_Contents = newContent;
<%= relationJsName %>_saveRelations ();
}
//Build the hidden fields required to save the relationships
function <%= relationJsName %>_saveRelations () {
var hiddenField = document.getElementById ('<%= relationJsName %>_inodes');
hiddenField.value = "<%= rel.getInode() %>,";
for (var i = 0; i < <%= relationJsName %>_Contents.length; i++) {
if (<%= relationJsName %>_Contents[i]['inode'] != null)
hiddenField.value = hiddenField.value + <%= relationJsName %>_Contents[i]['inode'] + ",";
}
}
//Add new content
function <%= relationJsName %>_addContentlet(structureInode) {
var myNode = (currentContentletInode==null || currentContentletInode=='') ? workingContentletInode : currentContentletInode;
var relationshipReturnValue = { inode: myNode, title: "<%=UtilMethods.escapeDoubleQuotes(contentTitle)%>" };
localStorage.setItem("dotcms.relationships.relationshipReturnValue", JSON.stringify(relationshipReturnValue));
var referer = "<portlet:actionURL windowState='<%= WindowState.MAXIMIZED.toString() %>'>";
referer += "<portlet:param name='struts_action' value='/ext/contentlet/edit_contentlet' />";
referer += "<portlet:param name='cmd' value='edit' />";
referer += "</portlet:actionURL>";
referer += "&inode="+'<%=contentletInode%>';
referer += "&lang=" + '<%= contentlet.getLanguageId() %>';
referer += "&relend=true";
<%if( request.getAttribute("isRelationsihpAField") != null && !(Boolean)request.getAttribute("isRelationsihpAField")){ //DOTCMS-6893 %>
referer += "&is_rel_tab=true";
<%}%>
referer += "&referer=" + '<%=java.net.URLDecoder.decode(referer, "UTF-8")%>';
var href = "<portlet:actionURL windowState='<%= WindowState.MAXIMIZED.toString() %>'>";
href += "<portlet:param name='struts_action' value='/ext/contentlet/edit_contentlet' />";
href += "<portlet:param name='cmd' value='new' />";
href += "</portlet:actionURL>";
//href += "&_content_selectedStructure=" + structureInode ;
href += "&inode" + "";
href += "&selectedStructure=" + structureInode ;
href += "&lang=" + '<%= languageId %>';
href += "&relwith=" +'<%=contentletInode%>';
href += "&relisparent=" + '<%= isParent %>';
href += "&reltype=" + '<%= relationType.toString() %>';
href += "&relname=" + '<%= relationJsName %>';
href += "&relname_inodes=" + '<%= rel.getInode()%>';
href += "&referer=" + escape(referer);
if (!confirm('<%= UtilMethods.escapeSingleQuotes(LanguageUtil.get(pageContext, "message.contentlet.lose.unsaved.changes")) %>'))
return;
window.location=href;
}
dojo.addOnLoad(
function(){
<%= relationJsName %>_saveRelations ();
}
);
// DOTCMS-6097
dojo.require("dojo.dnd.Container");
dojo.require("dojo.dnd.Manager");
dojo.require("dojo.dnd.Source");
var <%= relationJsName %>RelatedCons;
<jsp:include page="/html/portlet/ext/contentlet/field/tiny_mce_config.jsp"/>
function <%= relationJsName %>buildListing(nodeId,data){
var srcNode = document.getElementById(nodeId);
<%if(isParent.equals("no")){//DOTCMS-6878%>
<%= relationJsName %>RelatedCons = new dojo.dnd.Source(srcNode,{creator: <%= relationJsName %>CreateRow,isSource:false});
<%}else{%>
<%= relationJsName %>RelatedCons = new dojo.dnd.Source(srcNode,{creator: <%= relationJsName %>CreateRow});
<%}%>
<%= relationJsName %>RelatedCons.insertNodes(false,data);
//http://jira.dotmarketing.net/browse/DOTCMS-6465
<%= relationJsName %>RelatedCons.isDragging = false;
}
function <%= relationJsName %>CreateRow(item,hint){
var tr = document.createElement("tr");
// displays edit(pencil icon) and delete(X).
var actionTD = document.createElement("td");
actionTD.innerHTML = <%= relationJsName %>unrelateAction(item);
tr.appendChild(actionTD);
// to hold contentInode to reorder
var span = document.createElement("span");
dojo.addClass(span,"<%= relationJsName %>hiddenInodeField");
dojo.style(span,"display","none");
span.innerHTML = item['inode'];
tr.appendChild(span);
// to hold order sequence number to reorder
var order = document.createElement("input");
order.type="hidden";
order.id = "<%= relationJsName %>_order_" + item['id'];
dojo.addClass(order,"<%= relationJsName %>orderBox");
order.value = <%= relationJsName %>_order_tf();
tr.appendChild(order);
// displays each listed field
<%
for (Field f : targetFields) {
if (f.isListed()) {
String fieldName = f.getFieldName();
String functionName = relationJsName + "_" + UtilMethods.javaScriptifyVariable(fieldName) + "_func";
%>
var field<%= functionName %>TD = document.createElement("td");
var div = document.createElement("div");
div.style.width = '100%';
div.style.overflow = 'hidden';
div.innerHTML = <%= functionName %>(item);
field<%= functionName %>TD.appendChild(div);
tr.appendChild(field<%= functionName %>TD);
<%
}
}
if (!indexed) {
%> // displays content's identifier, if no listed fields exist.
var identifierTD = document.createElement("td");
identifierTD.innerHTML = identifier_func(item);
tr.appendChild(identifierTD);
<%
}
%>
<%
if(langs.size() > 1) {
%> // displays the publish/unpublish/archive status of the content and language flag, if multiple languages exists.
var langTD = document.createElement("td");
langTD.innerHTML = <%= relationJsName %>_lang(item);
tr.appendChild(langTD);
<%
}else{
%>
// displays the publish/unpublish/archive status of the content only.
var statusTD = document.createElement("td");
statusTD.innerHTML = <%= relationJsName %>_status(item);
tr.appendChild(statusTD);
<%
}
%>
return {node: tr, data: item, type: "text"};
}
function <%= relationJsName %>init(){
// Initializing related contents table.
<%= relationJsName %>buildListing('<%= relationJsName %>Table',<%= relationJsName %>_Contents);
// connectin drag and drop to reorder functionality
dojo.subscribe("/dnd/drop", function(source){
renumberRecolorAndReorder<%= relationJsName %>(source);
});
renumberRecolorAndReorder<%= relationJsName %>();
}
dojo.addOnLoad(<%= relationJsName %>init);
// to edit a related content, with proper referer
function <%= relationJsName %>editRelatedContent(inode, siblingInode, langId){
if (!confirm('<%= UtilMethods.escapeSingleQuotes(LanguageUtil.get(pageContext, "message.contentlet.lose.unsaved.changes")) %>'))
return;
var myNode = (currentContentletInode==null || currentContentletInode=='') ? workingContentletInode : currentContentletInode;
var relationshipReturnValue = { inode: myNode, title: "<%=UtilMethods.escapeDoubleQuotes(contentTitle)%>" };
localStorage.setItem("dotcms.relationships.relationshipReturnValue", JSON.stringify(relationshipReturnValue));
var referer = "<portlet:actionURL windowState='<%= WindowState.MAXIMIZED.toString() %>'>";
referer += "<portlet:param name='struts_action' value='/ext/contentlet/edit_contentlet' />";
referer += "<portlet:param name='cmd' value='edit' />";
referer += "</portlet:actionURL>";
referer += "&inode="+'<%=contentletInode%>';
referer += "&lang=" + '<%= contentlet.getLanguageId() %>';
referer += "&relend=true";
<%if( request.getAttribute("isRelationsihpAField") != null && !(Boolean)request.getAttribute("isRelationsihpAField")){ //DOTCMS-6893 %>
referer += "&is_rel_tab=true";
<%}%>
referer += "&referer=" + '<%=java.net.URLDecoder.decode(referer, "UTF-8")%>';
var href = "<portlet:actionURL windowState='<%= WindowState.MAXIMIZED.toString() %>'>";
href += "<portlet:param name='struts_action' value='/ext/contentlet/edit_contentlet' />";
href += "<portlet:param name='cmd' value='edit' />";
href += "</portlet:actionURL>";
href += "&inode="+inode;
if(inode == ''){
href += "&sibbling=" + siblingInode;
href += "&lang=" + langId;
}
href += "&referer=" + escape(referer);
document.location.href = href;
}
// displays edit icon and link to edit content
function <%= relationJsName %>editAction (o) {
var value = "";
if (o != null){
value = "<a class=\"beta\" href=\"javascript:<%= relationJsName %>editRelatedContent('" + o['inode'] + "', '"+ o['siblingInode'] +"', '"+ o['langId'] +"');\"" + "><span class=\"editIcon\"></span></a>";
}
return value;
}
// displays 'X' to unrelate content
function <%= relationJsName %>unrelateAction (o) {
var value = "";
if(<%= canUserWriteToContentlet %>){
value = "<a class=\"beta\" href=\"javascript:<%= relationJsName %>unrelateContent('<%=contentletInode%>','" + o['inode'] + "','"+ o['id'] +"');\"" + "><span class=\"deleteIcon\"></span></a>";
}else{
value = "<a class=\"beta\" href=\"javascript:alert('<%= LanguageUtil.get(pageContext, "dont-have-permissions-msg") %>');" + "><span class=\"deleteIcon\"></span></a>";
}
return value;
}
function <%= relationJsName %>unrelateContent(contentletInode,inodeToUnrelate,identifierToUnrelate){
<%= relationJsName %>RelatedCons.deleteSelectedNodes();
<%= relationJsName %>_removeContentFromRelationship (identifierToUnrelate);
renumberRecolorAndReorder<%= relationJsName %>();
}
function <%= relationJsName %>unrelateCallback (data) {
showDotCMSSystemMessage(data);
}
function renumberRecolorAndReorder<%= relationJsName %>(source){
recolor<%= relationJsName %>Rows();
eles = dojo.query(".<%= relationJsName %>orderBox");
for(i = 0;i<eles.length;i++){
eles[i].value=i+1;
}
<%= relationJsName %>_reorder();
<%= relationJsName %>setButtonState();
}
function recolor<%= relationJsName %>Rows() {
var eles = dojo.query("table#<%= relationJsName %>Table .dojoDndItem");
for(i = 0;i<eles.length;i++){
if(i % 2 ==0){
dojo.style(eles[i], "background", "#fff");
}
else{
dojo.style(eles[i], "background", "#eee");
}
}
var eles = dojo.query(".dojoDndItem .item_cell");
var bg = "#eee";
for(i = 0;i<eles.length;i++){
if(i % 8 == 0)
bg = bg == "#fff"?"#eee":"#fff";
dojo.style(eles[i], "background", bg);
}
}
// parent/child/permissions regarding relate new/existing content.
var <%= relationJsName %>canRelateNew;
var <%= relationJsName %>canRelateExisting;
function <%= relationJsName %>setButtonState(){
<%= relationJsName %>canRelateNew = true;//always true
<%= relationJsName %>canRelateExisting = true;
var prefix = '<%= relationJsName %>';
var isParentString = '<%= isParent.toLowerCase().trim() %>';
var isParent = false;
if(isParentString == "yes")
isParent = true;
var entries = eval(prefix + "_Contents").length;
if(isNewContentlet){// for both parent/child
var <%= relationJsName %>canRelateNew = false;
}
if(!isNewContentlet && !isParent){
if(entries == 0)
var <%= relationJsName %>canRelateNew = true;
else
var <%= relationJsName %>canRelateNew = false;
}
<% if (!records.isHasParent() && rel.getCardinality() == com.dotmarketing.util.WebKeys.Relationship.RELATIONSHIP_CARDINALITY.ONE_TO_MANY.ordinal()) { %>
if (<%= relationJsName %>_Contents.length > 0)
<%= relationJsName %>canRelateExisting = false;
else
<%= relationJsName %>canRelateExisting = true;
<% } %>
var canUserWriteToContentlet = <%= canUserWriteToContentlet %>;
if(!canUserWriteToContentlet){
<%= relationJsName %>canRelateExisting = false;
<%= relationJsName %>canRelateNew = false;
}
addRelateButtons<%= relationJsName %>(<%= relationJsName %>canRelateExisting,<%= relationJsName %>canRelateNew);
}
function addRelateButtons<%= relationJsName %>(canRelateExisting,canRelateNew) {
dojo.byId("<%= relationJsName %>relateMenu").innerHTML = "";
var canUserWriteToContentlet = <%=canUserWriteToContentlet%>;
if(!canUserWriteToContentlet)
return;
var menu = new dijit.Menu({
style: "display: none;"
});
var menuItem1 = new dijit.MenuItem({
label: "<%= UtilMethods.escapeSingleQuotes(LanguageUtil.get(pageContext, "Relate")) %>",
iconClass: "searchIcon",
onClick: function() {
<%= relationJsName %>_addRelationship();
}
});
if(!canRelateExisting)
menuItem1.attr('disabled','disabled');
menu.addChild(menuItem1);
var menuItem2 = new dijit.MenuItem({
label: "<%= UtilMethods.escapeSingleQuotes(LanguageUtil.get(pageContext, "Relate-New-Content")) %>",
iconClass: "plusIcon",
onClick: function() {
<%= relationJsName %>_addContentlet('<%= targetStructure.getInode() %>');
}
});
if(!canRelateNew)
menuItem2.attr('disabled','disabled');
menu.addChild(menuItem2);
var button = new dijit.form.ComboButton({
label: "<%= UtilMethods.escapeSingleQuotes(LanguageUtil.get(pageContext, "Relate")) %>",
iconClass: "searchIcon",
dropDown: menu,
onClick: function() {
<%= relationJsName %>_addRelationship();
}
});
if(!canRelateExisting)
button.attr('disabled','disabled');
dojo.byId("<%= relationJsName %>relateMenu").appendChild(button.domNode);
}
</script>
<div jsId="contentSelector" id="<%= relationJsName %>Dialog" dojoType="dotcms.dijit.form.ContentSelector"
structureInode="<%= targetStructure.getInode() %>"
relationJsName="<%= relationJsName %>"
multiple="true"
onContentSelected="callback<%= relationJsName %>"
title="<%= UtilMethods.escapeSingleQuotes(LanguageUtil.get(pageContext, "search")) %>"
counter_radio="<%= counter %>"
searchCounter="<%= searchCounter %>"
contentletLanguageId="<%=contentlet.getLanguageId() %>"
dialogCounter="<%= dialogCounter %>"
selectButtonLabel='<%= LanguageUtil.get(pageContext, "content.search.select") %>'>
</div>
<%
counter=counter+100;
searchCounter+=10000;
dialogCounter++;
}
%>
<script type="text/javascript">
dojo.require("dotcms.dijit.form.ContentSelector");
var isNewContentlet = false;
<%if(!InodeUtils.isSet(contentletInode)){%>
isNewContentlet = true;
<%}%>
<%if(UtilMethods.isSet(request.getAttribute("is_rel_tab")) && (request.getAttribute("is_rel_tab").toString().equalsIgnoreCase("true"))){%>
dojo.addOnLoad(
function(){
dijit.byId('mainTabContainer').selectChild('relationships');
}
);
<%}%>
function toggleCheckbox(id){
var chk = document.getElementById(id);
var elems = chk.getElementsByTagName ("input");
var len = elems.length;
for ( var i = 0; i < len; i++ ){
if (elems[i].checked){
dijit.byId(elems[i].id).set("checked",false);
}else{
dijit.byId(elems[i].id).set("checked",true);
}
}
}
</script>
<%
} else {
%>
<b><%= LanguageUtil.get(pageContext, "No-Relationships-Found") %></b>
<%
}
%>
| {
"pile_set_name": "Github"
} |
###############################################################################
# ilastik: interactive learning and segmentation toolkit
#
# Copyright (C) 2011-2014, the ilastik developers
# <[email protected]>
#
# 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.
#
# In addition, as a special exception, the copyright holders of
# ilastik give you permission to combine ilastik with applets,
# workflows and plugins which are not covered under the GNU
# General Public License.
#
# See the LICENSE file for details. License information is also available
# on the ilastik web site at:
# http://ilastik.org/license.html
###############################################################################
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtGui import QColor
from volumina.api import createDataSource, ColortableLayer, AlphaModulatedLayer
from volumina import colortables
from ilastik.applets.dataExport.dataExportGui import DataExportGui, DataExportLayerViewerGui
from lazyflow.operators import OpMultiArraySlicer2
from ilastik.utility.exportingOperator import ExportingGui
class ObjectClassificationDataExportGui(DataExportGui, ExportingGui):
"""
A subclass of the generic data export gui that creates custom layer viewers.
"""
def __init__(self, *args, **kwargs):
super(ObjectClassificationDataExportGui, self).__init__(*args, **kwargs)
self._exporting_operator = None
def set_exporting_operator(self, op):
self._exporting_operator = op
def get_exporting_operator(self):
return self._exporting_operator
def createLayerViewer(self, opLane):
return ObjectClassificationResultsViewer(self.parentApplet, opLane)
def get_export_dialog_title(self):
return "Export Object Information"
@property
def gui_applet(self):
return self.parentApplet
def get_table_export_settings(self):
return self._exporting_operator.get_table_export_settings()
def get_raw_shape(self):
return self._exporting_operator.get_raw_shape()
def get_feature_names(self):
return self._exporting_operator.get_feature_names()
def _initAppletDrawerUic(self):
super(ObjectClassificationDataExportGui, self)._initAppletDrawerUic()
btn = QPushButton("Configure Feature Table Export", clicked=self.configure_table_export)
self.drawer.exportSettingsGroupBox.layout().addWidget(btn)
class ObjectClassificationResultsViewer(DataExportLayerViewerGui):
_colorTable16 = colortables.default16_new
def setupLayers(self):
layers = []
opLane = self.topLevelOperatorView
selection_names = opLane.SelectionNames.value
selection = selection_names[opLane.InputSelection.value]
# This code is written to handle the specific output cases we know about.
# If those change, update this function!
assert selection in [
"Object Predictions",
"Object Probabilities",
"Blockwise Object Predictions",
"Blockwise Object Probabilities",
"Object Identities",
"Pixel Probabilities",
]
if selection in ("Object Predictions", "Blockwise Object Predictions"):
previewSlot = self.topLevelOperatorView.ImageToExport
if previewSlot.ready():
previewLayer = ColortableLayer(createDataSource(previewSlot), colorTable=self._colorTable16)
previewLayer.name = "Prediction - Preview"
previewLayer.visible = False
layers.append(previewLayer)
elif selection in ("Object Probabilities", "Blockwise Object Probabilities"):
previewLayers = self._initPredictionLayers(opLane.ImageToExport)
for layer in previewLayers:
layer.visible = False
layer.name = layer.name + "- Preview"
layers += previewLayers
elif selection == "Pixel Probabilities":
previewLayers = self._initPredictionLayers(opLane.ImageToExport)
for layer in previewLayers:
layer.visible = False
layer.name = layer.name + "- Preview"
layers += previewLayers
elif selection == "Object Identities":
previewSlot = self.topLevelOperatorView.ImageToExport
layer = self._initColortableLayer(previewSlot)
layers.append(layer)
else:
assert False, "Unknown selection."
rawSlot = self.topLevelOperatorView.RawData
if rawSlot.ready():
rawLayer = self.createStandardLayerFromSlot(rawSlot)
rawLayer.name = "Raw Data"
rawLayer.opacity = 1.0
layers.append(rawLayer)
return layers
def _initPredictionLayers(self, predictionSlot):
layers = []
opLane = self.topLevelOperatorView
# Use a slicer to provide a separate slot for each channel layer
opSlicer = OpMultiArraySlicer2(parent=opLane.viewed_operator().parent)
opSlicer.Input.connect(predictionSlot)
opSlicer.AxisFlag.setValue("c")
for channel, channelSlot in enumerate(opSlicer.Slices):
if channelSlot.ready():
drange = channelSlot.meta.drange or (0.0, 1.0)
predictsrc = createDataSource(channelSlot)
predictLayer = AlphaModulatedLayer(
predictsrc,
tintColor=QColor.fromRgba(self._colorTable16[channel + 1]),
normalize=drange,
)
predictLayer.opacity = 1.0
predictLayer.visible = True
predictLayer.name = "Probability Channel #{}".format(channel + 1)
layers.append(predictLayer)
return layers
def _initColortableLayer(self, labelSlot):
objectssrc = createDataSource(labelSlot)
objectssrc.setObjectName("LabelImage LazyflowSrc")
ct = colortables.create_default_16bit()
ct[0] = QColor(0, 0, 0, 0).rgba() # make 0 transparent
layer = ColortableLayer(objectssrc, ct)
layer.name = "Object Identities - Preview"
layer.setToolTip("Segmented objects, shown in different colors")
layer.visible = False
layer.opacity = 0.5
layer.colortableIsRandom = True
return layer
| {
"pile_set_name": "Github"
} |
# 24nov16abu
# (c) Software Lab. Alexander Burger
(de permute (Lst)
(ifn (cdr Lst)
(cons Lst)
(mapcan
'((X)
(mapcar
'((Y) (cons X Y))
(permute (delete X Lst)) ) )
Lst ) ) )
(de subsets (N Lst)
(cond
((=0 N) '(NIL))
((not Lst))
(T
(conc
(mapcar
'((X) (cons (car Lst) X))
(subsets (dec N) (cdr Lst)) )
(subsets N (cdr Lst)) ) ) ) )
(de shuffle (Lst)
(by '(NIL (rand)) sort Lst) )
(de samples (Cnt Lst)
(make
(for (N (length Lst) (n0 Cnt) (++ Lst) (dec N))
(when (>= Cnt (rand 1 N))
(link (car Lst))
(dec 'Cnt) ) ) ) )
# Genetic Algorithm
(de gen ("Pop" "Cond" "Re" "Mu" "Se")
(until ("Cond" "Pop")
(for ("P" "Pop" "P" (cdr "P"))
(set "P"
(maxi "Se" # Selection
(make
(for ("P" "Pop" "P")
(rot "P" (rand 1 (length "P")))
(link # Recombination + Mutation
("Mu" ("Re" (++ "P") (++ "P"))) ) ) ) ) ) ) )
(maxi "Se" "Pop") )
# Alpha-Beta tree search
(de game ("Flg" "Cnt" "Moves" "Move" "Cost")
(let ("Alpha" '(1000000) "Beta" -1000000)
(recur ("Flg" "Cnt" "Alpha" "Beta")
(let? "Lst" ("Moves" "Flg")
(if (=0 (dec '"Cnt"))
(loop
("Move" (caar "Lst"))
(setq "*Val" (list ("Cost" "Flg") (car "Lst")))
("Move" (cdar "Lst"))
(T (>= "Beta" (car "*Val"))
(cons "Beta" (car "Lst") (cdr "Alpha")) )
(when (> (car "Alpha") (car "*Val"))
(setq "Alpha" "*Val") )
(NIL (setq "Lst" (cdr "Lst")) "Alpha") )
(setq "Lst"
(sort
(mapcar
'(("Mov")
(prog2
("Move" (car "Mov"))
(cons ("Cost" "Flg") "Mov")
("Move" (cdr "Mov")) ) )
"Lst" ) ) )
(loop
("Move" (cadar "Lst"))
(setq "*Val"
(if (recurse (not "Flg") "Cnt" (cons (- "Beta")) (- (car "Alpha")))
(cons (- (car @)) (cdar "Lst") (cdr @))
(list (caar "Lst") (cdar "Lst")) ) )
("Move" (cddar "Lst"))
(T (>= "Beta" (car "*Val"))
(cons "Beta" (cdar "Lst") (cdr "Alpha")) )
(when (> (car "Alpha") (car "*Val"))
(setq "Alpha" "*Val") )
(NIL (setq "Lst" (cdr "Lst")) "Alpha") ) ) ) ) ) )
### Grids ###
(de grid (DX DY FX FY)
(let Grid
(make
(for X DX
(link
(make
(for Y DY
(set
(link
(if (> DX 26)
(box)
(intern (pack (char (+ X 96)) Y)) ) )
(cons (cons) (cons)) ) ) ) ) ) )
(let West (and FX (last Grid))
(for (Lst Grid Lst)
(let
(Col (++ Lst)
East (or (car Lst) (and FX (car Grid)))
South (and FY (last Col)) )
(for (L Col L)
(with (++ L)
(set (: 0 1) (++ West)) # west
(con (: 0 1) (++ East)) # east
(set (: 0 -1) South) # south
(con (: 0 -1) # north
(or (car L) (and FY (car Col))) )
(setq South This) ) )
(setq West Col) ) ) )
Grid ) )
(de west (This)
(: 0 1 1) )
(de east (This)
(: 0 1 -1) )
(de south (This)
(: 0 -1 1) )
(de north (This)
(: 0 -1 -1) )
(de disp ("Grid" "How" "Fun" "X" "Y" "DX" "DY")
(setq "Grid"
(if "X"
(mapcar
'((L) (flip (head "DY" (nth L "Y"))))
(head "DX" (nth "Grid" "X")) )
(mapcar reverse "Grid") ) )
(let (N (+ (length (cdar "Grid")) (or "Y" 1)) Sp (length N))
("border" north)
(while (caar "Grid")
(prin " " (align Sp N) " "
(and "How" (if (and (nT "How") (west (caar "Grid"))) " " '|)) )
(for L "Grid"
(prin
("Fun" (car L))
(and "How" (if (and (nT "How") (east (car L))) " " '|)) ) )
(prinl)
("border" south)
(map pop "Grid")
(dec 'N) )
(unless (> (default "X" 1) 26)
(space (inc Sp))
(for @ "Grid"
(prin " " (and "How" " ") (char (+ 96 "X")))
(T (> (inc '"X") 26)) )
(prinl) ) ) )
(de "border" (Dir)
(when "How"
(space Sp)
(prin " +")
(for L "Grid"
(prin (if (and (nT "How") (Dir (car L))) " +" "---+")) )
(prinl) ) )
| {
"pile_set_name": "Github"
} |
{
"name": "nodecat",
"version": "0.0.1",
"description": "노드버드 2차 서비스",
"main": "app.js",
"scripts": {
"start": "nodemon app"
},
"author": "Zero Cho",
"license": "ISC",
"dependencies": {
"axios": "^0.18.1",
"cookie-parser": "^1.4.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-session": "^1.17.1",
"morgan": "^1.10.0",
"nunjucks": "^3.2.1"
},
"devDependencies": {
"nodemon": "^2.0.3"
}
}
| {
"pile_set_name": "Github"
} |
use ckb_jsonrpc_types::{
CellTransaction as JsonCellTransaction, LiveCell as JsonLiveCell,
LockHashCapacity as JsonLockHashCapacity, TransactionPoint as JsonTransactionPoint,
};
use ckb_types::{
core::{BlockNumber, Capacity},
packed::{self, Byte32, CellOutput, OutPoint},
prelude::*,
};
pub struct LockHashIndex {
pub lock_hash: Byte32,
pub block_number: BlockNumber,
pub out_point: OutPoint,
}
pub struct LiveCell {
pub created_by: TransactionPoint,
pub cell_output: CellOutput,
pub output_data_len: u64,
pub cellbase: bool,
}
pub struct CellTransaction {
pub created_by: TransactionPoint,
pub consumed_by: Option<TransactionPoint>,
}
pub struct TransactionPoint {
pub block_number: BlockNumber,
pub tx_hash: Byte32,
// index of transaction outputs (create cell) or inputs (consume cell)
pub index: u32,
}
#[derive(Clone)]
pub struct LockHashCellOutput {
pub lock_hash: Byte32,
pub block_number: BlockNumber,
// Cache the `CellOutput` when `LiveCell` is deleted, it's required for fork switching.
pub cell_output: Option<CellOutput>,
}
#[derive(Debug, Clone)]
pub struct LockHashIndexState {
pub block_number: BlockNumber,
pub block_hash: Byte32,
}
#[derive(Debug, Clone)]
pub struct LockHashCapacity {
pub capacity: Capacity,
pub cells_count: u64,
pub block_number: BlockNumber,
}
impl Pack<packed::LockHashIndex> for LockHashIndex {
fn pack(&self) -> packed::LockHashIndex {
let index: u32 = self.out_point.index().unpack();
packed::LockHashIndex::new_builder()
.lock_hash(self.lock_hash.clone())
.block_number(self.block_number.pack())
.tx_hash(self.out_point.tx_hash())
.index(index.pack())
.build()
}
}
impl Pack<packed::TransactionPoint> for TransactionPoint {
fn pack(&self) -> packed::TransactionPoint {
packed::TransactionPoint::new_builder()
.block_number(self.block_number.pack())
.tx_hash(self.tx_hash.clone())
.index(self.index.pack())
.build()
}
}
impl Pack<packed::LockHashCellOutput> for LockHashCellOutput {
fn pack(&self) -> packed::LockHashCellOutput {
let cell_output_opt = packed::CellOutputOpt::new_builder()
.set(self.cell_output.clone())
.build();
packed::LockHashCellOutput::new_builder()
.lock_hash(self.lock_hash.clone())
.block_number(self.block_number.pack())
.cell_output(cell_output_opt)
.build()
}
}
impl Pack<packed::LockHashIndexState> for LockHashIndexState {
fn pack(&self) -> packed::LockHashIndexState {
packed::LockHashIndexState::new_builder()
.block_number(self.block_number.pack())
.block_hash(self.block_hash.clone())
.build()
}
}
impl LockHashIndex {
pub(crate) fn from_packed(input: packed::LockHashIndexReader<'_>) -> Self {
let lock_hash = input.lock_hash().to_entity();
let block_number = input.block_number().unpack();
let index: u32 = input.index().unpack();
let out_point = OutPoint::new_builder()
.tx_hash(input.tx_hash().to_entity())
.index(index.pack())
.build();
LockHashIndex {
lock_hash,
block_number,
out_point,
}
}
}
impl TransactionPoint {
pub(crate) fn from_packed(input: packed::TransactionPointReader<'_>) -> Self {
let block_number = input.block_number().unpack();
let tx_hash = input.tx_hash().to_entity();
let index = input.index().unpack();
TransactionPoint {
block_number,
tx_hash,
index,
}
}
}
impl LockHashCellOutput {
pub(crate) fn from_packed(input: packed::LockHashCellOutputReader<'_>) -> Self {
let lock_hash = input.lock_hash().to_entity();
let block_number = input.block_number().unpack();
let cell_output = input.cell_output().to_entity().to_opt();
LockHashCellOutput {
lock_hash,
block_number,
cell_output,
}
}
}
impl LockHashIndexState {
pub(crate) fn from_packed(input: packed::LockHashIndexStateReader<'_>) -> Self {
let block_number = input.block_number().unpack();
let block_hash = input.block_hash().to_entity();
LockHashIndexState {
block_number,
block_hash,
}
}
}
impl LockHashIndex {
pub fn new(lock_hash: Byte32, block_number: BlockNumber, tx_hash: Byte32, index: u32) -> Self {
let out_point = OutPoint::new_builder()
.tx_hash(tx_hash)
.index(index.pack())
.build();
LockHashIndex {
lock_hash,
block_number,
out_point,
}
}
}
impl From<LockHashIndex> for TransactionPoint {
fn from(lock_hash_index: LockHashIndex) -> Self {
TransactionPoint {
block_number: lock_hash_index.block_number,
tx_hash: lock_hash_index.out_point.tx_hash(),
index: lock_hash_index.out_point.index().unpack(),
}
}
}
impl From<LiveCell> for JsonLiveCell {
fn from(live_cell: LiveCell) -> JsonLiveCell {
let LiveCell {
created_by,
cell_output,
output_data_len,
cellbase,
} = live_cell;
JsonLiveCell {
created_by: created_by.into(),
cell_output: cell_output.into(),
output_data_len: output_data_len.into(),
cellbase,
}
}
}
impl From<CellTransaction> for JsonCellTransaction {
fn from(cell_transaction: CellTransaction) -> JsonCellTransaction {
let CellTransaction {
created_by,
consumed_by,
} = cell_transaction;
JsonCellTransaction {
created_by: created_by.into(),
consumed_by: consumed_by.map(Into::into),
}
}
}
impl From<TransactionPoint> for JsonTransactionPoint {
fn from(transaction_point: TransactionPoint) -> JsonTransactionPoint {
let TransactionPoint {
block_number,
tx_hash,
index,
} = transaction_point;
JsonTransactionPoint {
block_number: block_number.into(),
tx_hash: tx_hash.unpack(),
index: u64::from(index).into(),
}
}
}
impl From<LockHashCapacity> for JsonLockHashCapacity {
fn from(lock_hash_capacity: LockHashCapacity) -> JsonLockHashCapacity {
let LockHashCapacity {
capacity,
cells_count,
block_number,
} = lock_hash_capacity;
JsonLockHashCapacity {
capacity: capacity.into(),
cells_count: cells_count.into(),
block_number: block_number.into(),
}
}
}
| {
"pile_set_name": "Github"
} |
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Google_Service_CloudAsset_Policy extends Google_Collection
{
protected $collection_key = 'bindings';
protected $auditConfigsType = 'Google_Service_CloudAsset_AuditConfig';
protected $auditConfigsDataType = 'array';
protected $bindingsType = 'Google_Service_CloudAsset_Binding';
protected $bindingsDataType = 'array';
public $etag;
public $version;
/**
* @param Google_Service_CloudAsset_AuditConfig
*/
public function setAuditConfigs($auditConfigs)
{
$this->auditConfigs = $auditConfigs;
}
/**
* @return Google_Service_CloudAsset_AuditConfig
*/
public function getAuditConfigs()
{
return $this->auditConfigs;
}
/**
* @param Google_Service_CloudAsset_Binding
*/
public function setBindings($bindings)
{
$this->bindings = $bindings;
}
/**
* @return Google_Service_CloudAsset_Binding
*/
public function getBindings()
{
return $this->bindings;
}
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setVersion($version)
{
$this->version = $version;
}
public function getVersion()
{
return $this->version;
}
}
| {
"pile_set_name": "Github"
} |
/*
* Contiguous Memory Allocator
*
* Copyright (c) 2010-2011 by Samsung Electronics.
* Copyright IBM Corporation, 2013
* Copyright LG Electronics Inc., 2014
* Written by:
* Marek Szyprowski <[email protected]>
* Michal Nazarewicz <[email protected]>
* Aneesh Kumar K.V <[email protected]>
* Joonsoo Kim <[email protected]>
*
* 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 optional) any later version of the license.
*/
#define pr_fmt(fmt) "cma: " fmt
#ifdef CONFIG_CMA_DEBUG
#ifndef DEBUG
# define DEBUG
#endif
#endif
#define CREATE_TRACE_POINTS
#include <linux/memblock.h>
#include <linux/err.h>
#include <linux/mm.h>
#include <linux/mutex.h>
#include <linux/sizes.h>
#include <linux/slab.h>
#include <linux/log2.h>
#include <linux/cma.h>
#include <linux/highmem.h>
#include <linux/io.h>
#include <trace/events/cma.h>
#include "cma.h"
struct cma cma_areas[MAX_CMA_AREAS];
unsigned cma_area_count;
static DEFINE_MUTEX(cma_mutex);
phys_addr_t cma_get_base(const struct cma *cma)
{
return PFN_PHYS(cma->base_pfn);
}
unsigned long cma_get_size(const struct cma *cma)
{
return cma->count << PAGE_SHIFT;
}
const char *cma_get_name(const struct cma *cma)
{
return cma->name ? cma->name : "(undefined)";
}
static unsigned long cma_bitmap_aligned_mask(const struct cma *cma,
unsigned int align_order)
{
if (align_order <= cma->order_per_bit)
return 0;
return (1UL << (align_order - cma->order_per_bit)) - 1;
}
/*
* Find the offset of the base PFN from the specified align_order.
* The value returned is represented in order_per_bits.
*/
static unsigned long cma_bitmap_aligned_offset(const struct cma *cma,
unsigned int align_order)
{
return (cma->base_pfn & ((1UL << align_order) - 1))
>> cma->order_per_bit;
}
static unsigned long cma_bitmap_pages_to_bits(const struct cma *cma,
unsigned long pages)
{
return ALIGN(pages, 1UL << cma->order_per_bit) >> cma->order_per_bit;
}
static void cma_clear_bitmap(struct cma *cma, unsigned long pfn,
unsigned int count)
{
unsigned long bitmap_no, bitmap_count;
bitmap_no = (pfn - cma->base_pfn) >> cma->order_per_bit;
bitmap_count = cma_bitmap_pages_to_bits(cma, count);
mutex_lock(&cma->lock);
bitmap_clear(cma->bitmap, bitmap_no, bitmap_count);
mutex_unlock(&cma->lock);
}
static int __init cma_activate_area(struct cma *cma)
{
int bitmap_size = BITS_TO_LONGS(cma_bitmap_maxno(cma)) * sizeof(long);
unsigned long base_pfn = cma->base_pfn, pfn = base_pfn;
unsigned i = cma->count >> pageblock_order;
struct zone *zone;
cma->bitmap = kzalloc(bitmap_size, GFP_KERNEL);
if (!cma->bitmap)
return -ENOMEM;
WARN_ON_ONCE(!pfn_valid(pfn));
zone = page_zone(pfn_to_page(pfn));
do {
unsigned j;
base_pfn = pfn;
for (j = pageblock_nr_pages; j; --j, pfn++) {
WARN_ON_ONCE(!pfn_valid(pfn));
/*
* alloc_contig_range requires the pfn range
* specified to be in the same zone. Make this
* simple by forcing the entire CMA resv range
* to be in the same zone.
*/
if (page_zone(pfn_to_page(pfn)) != zone)
goto not_in_zone;
}
init_cma_reserved_pageblock(pfn_to_page(base_pfn));
} while (--i);
mutex_init(&cma->lock);
#ifdef CONFIG_CMA_DEBUGFS
INIT_HLIST_HEAD(&cma->mem_head);
spin_lock_init(&cma->mem_head_lock);
#endif
return 0;
not_in_zone:
pr_err("CMA area %s could not be activated\n", cma->name);
kfree(cma->bitmap);
cma->count = 0;
return -EINVAL;
}
static int __init cma_init_reserved_areas(void)
{
int i;
for (i = 0; i < cma_area_count; i++) {
int ret = cma_activate_area(&cma_areas[i]);
if (ret)
return ret;
}
return 0;
}
core_initcall(cma_init_reserved_areas);
/**
* cma_init_reserved_mem() - create custom contiguous area from reserved memory
* @base: Base address of the reserved area
* @size: Size of the reserved area (in bytes),
* @order_per_bit: Order of pages represented by one bit on bitmap.
* @res_cma: Pointer to store the created cma region.
*
* This function creates custom contiguous area from already reserved memory.
*/
int __init cma_init_reserved_mem(phys_addr_t base, phys_addr_t size,
unsigned int order_per_bit,
const char *name,
struct cma **res_cma)
{
struct cma *cma;
phys_addr_t alignment;
/* Sanity checks */
if (cma_area_count == ARRAY_SIZE(cma_areas)) {
pr_err("Not enough slots for CMA reserved regions!\n");
return -ENOSPC;
}
if (!size || !memblock_is_region_reserved(base, size))
return -EINVAL;
/* ensure minimal alignment required by mm core */
alignment = PAGE_SIZE <<
max_t(unsigned long, MAX_ORDER - 1, pageblock_order);
/* alignment should be aligned with order_per_bit */
if (!IS_ALIGNED(alignment >> PAGE_SHIFT, 1 << order_per_bit))
return -EINVAL;
if (ALIGN(base, alignment) != base || ALIGN(size, alignment) != size)
return -EINVAL;
/*
* Each reserved area must be initialised later, when more kernel
* subsystems (like slab allocator) are available.
*/
cma = &cma_areas[cma_area_count];
if (name) {
cma->name = name;
} else {
cma->name = kasprintf(GFP_KERNEL, "cma%d\n", cma_area_count);
if (!cma->name)
return -ENOMEM;
}
cma->base_pfn = PFN_DOWN(base);
cma->count = size >> PAGE_SHIFT;
cma->order_per_bit = order_per_bit;
*res_cma = cma;
cma_area_count++;
totalcma_pages += (size / PAGE_SIZE);
return 0;
}
/**
* cma_declare_contiguous() - reserve custom contiguous area
* @base: Base address of the reserved area optional, use 0 for any
* @size: Size of the reserved area (in bytes),
* @limit: End address of the reserved memory (optional, 0 for any).
* @alignment: Alignment for the CMA area, should be power of 2 or zero
* @order_per_bit: Order of pages represented by one bit on bitmap.
* @fixed: hint about where to place the reserved area
* @res_cma: Pointer to store the created cma region.
*
* This function reserves memory from early allocator. It should be
* called by arch specific code once the early allocator (memblock or bootmem)
* has been activated and all other subsystems have already allocated/reserved
* memory. This function allows to create custom reserved areas.
*
* If @fixed is true, reserve contiguous area at exactly @base. If false,
* reserve in range from @base to @limit.
*/
int __init cma_declare_contiguous(phys_addr_t base,
phys_addr_t size, phys_addr_t limit,
phys_addr_t alignment, unsigned int order_per_bit,
bool fixed, const char *name, struct cma **res_cma)
{
phys_addr_t memblock_end = memblock_end_of_DRAM();
phys_addr_t highmem_start;
int ret = 0;
/*
* We can't use __pa(high_memory) directly, since high_memory
* isn't a valid direct map VA, and DEBUG_VIRTUAL will (validly)
* complain. Find the boundary by adding one to the last valid
* address.
*/
highmem_start = __pa(high_memory - 1) + 1;
pr_debug("%s(size %pa, base %pa, limit %pa alignment %pa)\n",
__func__, &size, &base, &limit, &alignment);
if (cma_area_count == ARRAY_SIZE(cma_areas)) {
pr_err("Not enough slots for CMA reserved regions!\n");
return -ENOSPC;
}
if (!size)
return -EINVAL;
if (alignment && !is_power_of_2(alignment))
return -EINVAL;
/*
* Sanitise input arguments.
* Pages both ends in CMA area could be merged into adjacent unmovable
* migratetype page by page allocator's buddy algorithm. In the case,
* you couldn't get a contiguous memory, which is not what we want.
*/
alignment = max(alignment, (phys_addr_t)PAGE_SIZE <<
max_t(unsigned long, MAX_ORDER - 1, pageblock_order));
base = ALIGN(base, alignment);
size = ALIGN(size, alignment);
limit &= ~(alignment - 1);
if (!base)
fixed = false;
/* size should be aligned with order_per_bit */
if (!IS_ALIGNED(size >> PAGE_SHIFT, 1 << order_per_bit))
return -EINVAL;
/*
* If allocating at a fixed base the request region must not cross the
* low/high memory boundary.
*/
if (fixed && base < highmem_start && base + size > highmem_start) {
ret = -EINVAL;
pr_err("Region at %pa defined on low/high memory boundary (%pa)\n",
&base, &highmem_start);
goto err;
}
/*
* If the limit is unspecified or above the memblock end, its effective
* value will be the memblock end. Set it explicitly to simplify further
* checks.
*/
if (limit == 0 || limit > memblock_end)
limit = memblock_end;
/* Reserve memory */
if (fixed) {
if (memblock_is_region_reserved(base, size) ||
memblock_reserve(base, size) < 0) {
ret = -EBUSY;
goto err;
}
} else {
phys_addr_t addr = 0;
/*
* All pages in the reserved area must come from the same zone.
* If the requested region crosses the low/high memory boundary,
* try allocating from high memory first and fall back to low
* memory in case of failure.
*/
if (base < highmem_start && limit > highmem_start) {
addr = memblock_alloc_range(size, alignment,
highmem_start, limit,
MEMBLOCK_NONE);
limit = highmem_start;
}
if (!addr) {
addr = memblock_alloc_range(size, alignment, base,
limit,
MEMBLOCK_NONE);
if (!addr) {
ret = -ENOMEM;
goto err;
}
}
/*
* kmemleak scans/reads tracked objects for pointers to other
* objects but this address isn't mapped and accessible
*/
kmemleak_ignore_phys(addr);
base = addr;
}
ret = cma_init_reserved_mem(base, size, order_per_bit, name, res_cma);
if (ret)
goto err;
pr_info("Reserved %ld MiB at %pa\n", (unsigned long)size / SZ_1M,
&base);
return 0;
err:
pr_err("Failed to reserve %ld MiB\n", (unsigned long)size / SZ_1M);
return ret;
}
#ifdef CONFIG_CMA_DEBUG
static void cma_debug_show_areas(struct cma *cma)
{
unsigned long next_zero_bit, next_set_bit;
unsigned long start = 0;
unsigned int nr_zero, nr_total = 0;
mutex_lock(&cma->lock);
pr_info("number of available pages: ");
for (;;) {
next_zero_bit = find_next_zero_bit(cma->bitmap, cma->count, start);
if (next_zero_bit >= cma->count)
break;
next_set_bit = find_next_bit(cma->bitmap, cma->count, next_zero_bit);
nr_zero = next_set_bit - next_zero_bit;
pr_cont("%s%u@%lu", nr_total ? "+" : "", nr_zero, next_zero_bit);
nr_total += nr_zero;
start = next_zero_bit + nr_zero;
}
pr_cont("=> %u free of %lu total pages\n", nr_total, cma->count);
mutex_unlock(&cma->lock);
}
#else
static inline void cma_debug_show_areas(struct cma *cma) { }
#endif
/**
* cma_alloc() - allocate pages from contiguous area
* @cma: Contiguous memory region for which the allocation is performed.
* @count: Requested number of pages.
* @align: Requested alignment of pages (in PAGE_SIZE order).
*
* This function allocates part of contiguous memory on specific
* contiguous memory area.
*/
struct page *cma_alloc(struct cma *cma, size_t count, unsigned int align,
gfp_t gfp_mask)
{
unsigned long mask, offset;
unsigned long pfn = -1;
unsigned long start = 0;
unsigned long bitmap_maxno, bitmap_no, bitmap_count;
struct page *page = NULL;
int ret = -ENOMEM;
if (!cma || !cma->count)
return NULL;
pr_debug("%s(cma %p, count %zu, align %d)\n", __func__, (void *)cma,
count, align);
if (!count)
return NULL;
mask = cma_bitmap_aligned_mask(cma, align);
offset = cma_bitmap_aligned_offset(cma, align);
bitmap_maxno = cma_bitmap_maxno(cma);
bitmap_count = cma_bitmap_pages_to_bits(cma, count);
if (bitmap_count > bitmap_maxno)
return NULL;
for (;;) {
mutex_lock(&cma->lock);
bitmap_no = bitmap_find_next_zero_area_off(cma->bitmap,
bitmap_maxno, start, bitmap_count, mask,
offset);
if (bitmap_no >= bitmap_maxno) {
mutex_unlock(&cma->lock);
break;
}
bitmap_set(cma->bitmap, bitmap_no, bitmap_count);
/*
* It's safe to drop the lock here. We've marked this region for
* our exclusive use. If the migration fails we will take the
* lock again and unmark it.
*/
mutex_unlock(&cma->lock);
pfn = cma->base_pfn + (bitmap_no << cma->order_per_bit);
mutex_lock(&cma_mutex);
ret = alloc_contig_range(pfn, pfn + count, MIGRATE_CMA,
gfp_mask);
mutex_unlock(&cma_mutex);
if (ret == 0) {
page = pfn_to_page(pfn);
break;
}
cma_clear_bitmap(cma, pfn, count);
if (ret != -EBUSY)
break;
pr_debug("%s(): memory range at %p is busy, retrying\n",
__func__, pfn_to_page(pfn));
/* try again with a bit different memory target */
start = bitmap_no + mask + 1;
}
trace_cma_alloc(pfn, page, count, align);
if (ret && !(gfp_mask & __GFP_NOWARN)) {
pr_err("%s: alloc failed, req-size: %zu pages, ret: %d\n",
__func__, count, ret);
cma_debug_show_areas(cma);
}
pr_debug("%s(): returned %p\n", __func__, page);
return page;
}
/**
* cma_release() - release allocated pages
* @cma: Contiguous memory region for which the allocation is performed.
* @pages: Allocated pages.
* @count: Number of allocated pages.
*
* This function releases memory allocated by alloc_cma().
* It returns false when provided pages do not belong to contiguous area and
* true otherwise.
*/
bool cma_release(struct cma *cma, const struct page *pages, unsigned int count)
{
unsigned long pfn;
if (!cma || !pages)
return false;
pr_debug("%s(page %p)\n", __func__, (void *)pages);
pfn = page_to_pfn(pages);
if (pfn < cma->base_pfn || pfn >= cma->base_pfn + cma->count)
return false;
VM_BUG_ON(pfn + count > cma->base_pfn + cma->count);
free_contig_range(pfn, count);
cma_clear_bitmap(cma, pfn, count);
trace_cma_release(pfn, pages, count);
return true;
}
int cma_for_each_area(int (*it)(struct cma *cma, void *data), void *data)
{
int i;
for (i = 0; i < cma_area_count; i++) {
int ret = it(&cma_areas[i], data);
if (ret)
return ret;
}
return 0;
}
| {
"pile_set_name": "Github"
} |
//
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
/// \file hadronic/Hadr00/src/HistoManagerMessenger.cc
/// \brief Implementation of the HistoManagerMessenger class
//
//
//
//
/////////////////////////////////////////////////////////////////////////
//
// HistoManagerMessenger
//
// Created: 20.06.08 V.Ivanchenko
//
// Modified:
//
////////////////////////////////////////////////////////////////////////
//
#include "HistoManagerMessenger.hh"
#include "HistoManager.hh"
#include "G4UIdirectory.hh"
#include "G4UIcmdWithABool.hh"
#include "G4UIcmdWithAString.hh"
#include "G4UIcmdWithAnInteger.hh"
#include "G4UIcmdWith3Vector.hh"
#include "G4UIcmdWithADoubleAndUnit.hh"
#include "G4UIcmdWithoutParameter.hh"
#include "HistoManager.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
HistoManagerMessenger::HistoManagerMessenger(HistoManager * p)
:G4UImessenger(), fHisto(p)
{
fbinCmd = new G4UIcmdWithAnInteger("/testhadr/nBinsE",this);
fbinCmd->SetGuidance("Set number of bins for energy");
fbinCmd->SetParameterName("NEbins",false);
fbinCmd->AvailableForStates(G4State_PreInit,G4State_Idle);
fnOfAbsCmd = new G4UIcmdWithAnInteger("/testhadr/nBinsP",this);
fnOfAbsCmd->SetGuidance("Set number of bins for momentum");
fnOfAbsCmd->SetParameterName("NPbins",false);
fnOfAbsCmd->AvailableForStates(G4State_PreInit,G4State_Idle);
fpartCmd = new G4UIcmdWithAString("/testhadr/particle",this);
fpartCmd->SetGuidance("Set particle name");
fpartCmd->SetParameterName("Particle",false);
fpartCmd->AvailableForStates(G4State_PreInit,G4State_Idle);
fcsCmd = new G4UIcmdWithAString("/testhadr/targetElm",this);
fcsCmd->SetGuidance("Set element name");
fcsCmd->SetParameterName("Elm",false);
fcsCmd->AvailableForStates(G4State_PreInit,G4State_Idle);
fe1Cmd = new G4UIcmdWithADoubleAndUnit("/testhadr/minEnergy",this);
fe1Cmd->SetGuidance("Set min kinetic energy");
fe1Cmd->SetParameterName("eMin",false);
fe1Cmd->SetUnitCategory("Energy");
fe1Cmd->AvailableForStates(G4State_PreInit,G4State_Idle);
fe2Cmd = new G4UIcmdWithADoubleAndUnit("/testhadr/maxEnergy",this);
fe2Cmd->SetGuidance("Set max kinetic energy");
fe2Cmd->SetParameterName("eMax",false);
fe2Cmd->SetUnitCategory("Energy");
fe2Cmd->AvailableForStates(G4State_PreInit,G4State_Idle);
fp1Cmd = new G4UIcmdWithADoubleAndUnit("/testhadr/minMomentum",this);
fp1Cmd->SetGuidance("Set min momentum");
fp1Cmd->SetParameterName("pMin",false);
fp1Cmd->SetUnitCategory("Energy");
fp1Cmd->AvailableForStates(G4State_PreInit,G4State_Idle);
fp2Cmd = new G4UIcmdWithADoubleAndUnit("/testhadr/maxMomentum",this);
fp2Cmd->SetGuidance("Set max momentum");
fp2Cmd->SetParameterName("pMax",false);
fp2Cmd->SetUnitCategory("Energy");
fp2Cmd->AvailableForStates(G4State_PreInit,G4State_Idle);
fverbCmd = new G4UIcmdWithAnInteger("/testhadr/verbose",this);
fverbCmd->SetGuidance("Set verbose for ");
fverbCmd->SetParameterName("verb",false);
fverbCmd->AvailableForStates(G4State_PreInit,G4State_Idle);
fFCmd = new G4UIcmdWithAString("/testhadr/fileName",this);
fFCmd->SetGuidance("set name for the histograms file");
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
HistoManagerMessenger::~HistoManagerMessenger()
{
delete fbinCmd;
delete fnOfAbsCmd;
delete fpartCmd;
delete fcsCmd;
delete fe1Cmd;
delete fe2Cmd;
delete fp1Cmd;
delete fp2Cmd;
delete fverbCmd;
delete fFCmd;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void HistoManagerMessenger::SetNewValue(G4UIcommand* command, G4String newValue)
{
if( command == fbinCmd ) {
fHisto->SetNumberOfBinsE(fbinCmd->GetNewIntValue(newValue));
} else if( command == fnOfAbsCmd ) {
fHisto->SetNumberOfBinsP(fnOfAbsCmd->GetNewIntValue(newValue));
} else if( command == fverbCmd ) {
fHisto->SetVerbose(fverbCmd->GetNewIntValue(newValue));
} else if( command == fpartCmd ) {
fHisto->SetParticleName(newValue);
} else if( command == fcsCmd ) {
fHisto->SetElementName(newValue);
} else if( command == fe1Cmd ) {
fHisto->SetMinKinEnergy(fe1Cmd->GetNewDoubleValue(newValue));
} else if( command == fe2Cmd ) {
fHisto->SetMaxKinEnergy(fe2Cmd->GetNewDoubleValue(newValue));
} else if( command == fp1Cmd ) {
fHisto->SetMinMomentum(fp1Cmd->GetNewDoubleValue(newValue));
} else if( command == fp2Cmd ) {
fHisto->SetMaxMomentum(fp2Cmd->GetNewDoubleValue(newValue));
} else if( command == fFCmd ) {
fHisto->SetHistoName(newValue);
}
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
| {
"pile_set_name": "Github"
} |
using System.Collections.Generic;
using System.Threading.Tasks;
namespace AElf.Kernel.SmartContractExecution.Application
{
public interface IBlockchainExecutingService
{
Task<BlockExecutionResult> ExecuteBlocksAsync(IEnumerable<Block> blocks);
}
} | {
"pile_set_name": "Github"
} |
/* Generated by RuntimeBrowser.
*/
@protocol SFFeedbackListener <NSObject>
@optional
- (void)cardViewDidAppear:(SFCardViewAppearFeedback *)arg1;
- (void)cardViewDidDisappear:(SFCardViewDisappearFeedback *)arg1;
- (void)didAppendLateSections:(SFLateSectionsAppendedFeedback *)arg1;
- (void)didClearInput:(SFClearInputFeedback *)arg1;
- (void)didEndSearch:(SFEndSearchFeedback *)arg1;
- (void)didEngageCardSection:(SFCardSectionEngagementFeedback *)arg1;
- (void)didEngageResult:(SFResultEngagementFeedback *)arg1;
- (void)didEngageSection:(SFSectionEngagementFeedback *)arg1;
- (void)didEngageSuggestion:(SFSuggestionEngagementFeedback *)arg1;
- (void)didErrorOccur:(SFErrorFeedback *)arg1;
- (void)didGoToSearch:(SFDidGoToSearchFeedback *)arg1;
- (void)didGoToSite:(SFDidGoToSiteFeedback *)arg1;
- (void)didGradeLookupHintRelevancy:(SFLookupHintRelevancyFeedback *)arg1;
- (void)didGradeResultRelevancy:(SFResultGradingFeedback *)arg1;
- (void)didRankSections:(SFRankingFeedback *)arg1;
- (void)didReceiveResultsAfterTimeout:(SFResultsReceivedAfterTimeoutFeedback *)arg1;
- (void)didStartSearch:(SFStartSearchFeedback *)arg1;
- (void)reportFeedback:(SFFeedback *)arg1 queryId:(long long)arg2;
- (void)resultsDidBecomeVisible:(SFVisibleResultsFeedback *)arg1;
- (void)searchViewDidAppear:(SFSearchViewAppearFeedback *)arg1;
- (void)searchViewDidDisappear:(SFSearchViewDisappearFeedback *)arg1;
- (void)sectionHeaderDidBecomeVisible:(SFVisibleSectionHeaderFeedback *)arg1;
- (void)sendCustomFeedback:(SFCustomFeedback *)arg1;
- (void)suggestionsDidBecomeVisible:(SFVisibleSuggestionsFeedback *)arg1;
@end
| {
"pile_set_name": "Github"
} |
// RUN: %clang_cc1 -triple x86_64-apple-darwin %s -emit-llvm -o - -fmath-errno | FileCheck %s
// llvm.sqrt has undefined behavior on negative inputs, so it is
// inappropriate to translate C/C++ sqrt to this.
float sqrtf(float x);
float foo(float X) {
// CHECK: foo
// CHECK-NOT: readonly
// CHECK: call float @sqrtf
// Check that this is not marked readonly when errno is used.
return sqrtf(X);
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package com.sun.xml.internal.ws.api.server;
import com.sun.istack.internal.Nullable;
import com.sun.xml.internal.ws.api.message.Packet;
import javax.xml.ws.WebServiceContext;
/**
* {@link WebServiceContext} that exposes JAX-WS RI specific additions.
*
* <p>
* {@link WebServiceContext} instances that JAX-WS injects always
* implement this interface.
*
* <p>
* The JAX-WS RI may add methods on this interface, so do not implement
* this interface in your code, or risk {@link LinkageError}.
*
* @author Kohsuke Kawaguchi
*/
public interface WSWebServiceContext extends WebServiceContext {
/**
* Obtains the request packet that is being processed.
* @return Packet for the request
*/
@Nullable Packet getRequestPacket();
}
| {
"pile_set_name": "Github"
} |
Created on 14Sep2016 at 16:32:57
15 1 15
1 1 1 0.000001326968 0.000000000000
2 1 1 -0.000000755470 0.000000000000
3 1 1 -0.000000207635 0.000000000000
4 1 1 -0.000001020141 0.000000000000
5 1 1 0.000003147956 0.000000000000
6 1 1 0.000001184723 0.000000000000
7 1 1 -0.000001537156 0.000000000000
8 1 1 -0.000003070924 0.000000000000
9 1 1 0.000001250979 0.000000000000
10 1 1 -0.000001026318 0.000000000000
11 1 1 0.000003254980 0.000000000000
12 1 1 0.000002363750 0.000000000000
13 1 1 -0.000001182633 0.000000000000
14 1 1 -0.000003512461 0.000000000000
15 1 1 -0.000007359298 0.000000000000
1 2 1 0.002831285987 0.000000000000
2 2 1 0.005359275006 0.000000000000
3 2 1 0.002009138160 0.000000000000
4 2 1 -0.004076655610 0.000000000000
5 2 1 0.005139305826 0.000000000000
6 2 1 -0.009348604200 0.000000000000
7 2 1 -0.004146921246 0.000000000000
8 2 1 -0.003426669992 0.000000000000
9 2 1 0.013932988683 0.000000000000
10 2 1 -0.004658693032 0.000000000000
11 2 1 0.000698448188 0.000000000000
12 2 1 0.008687045423 0.000000000000
13 2 1 -0.003199806661 0.000000000000
14 2 1 -0.000567419877 0.000000000000
15 2 1 -0.001377687238 0.000000000000
1 3 1 0.000001457813 0.000000000000
2 3 1 -0.000002698986 0.000000000000
3 3 1 -0.000000063483 0.000000000000
4 3 1 -0.000001464895 0.000000000000
5 3 1 -0.000002133460 0.000000000000
6 3 1 -0.000002640137 0.000000000000
7 3 1 -0.000005412284 0.000000000000
8 3 1 -0.000000296196 0.000000000000
9 3 1 -0.000005069358 0.000000000000
10 3 1 -0.000000153998 0.000000000000
11 3 1 0.000005679928 0.000000000000
12 3 1 -0.000008507221 0.000000000000
13 3 1 0.000003352030 0.000000000000
14 3 1 -0.000000729667 0.000000000000
15 3 1 0.000009954733 0.000000000000
1 4 1 0.000013262958 0.000000000000
2 4 1 -0.000008517324 0.000000000000
3 4 1 0.000025478356 0.000000000000
4 4 1 0.000020309200 0.000000000000
5 4 1 -0.000028506063 0.000000000000
6 4 1 -0.000058454677 0.000000000000
7 4 1 -0.000036420581 0.000000000000
8 4 1 0.000008849179 0.000000000000
9 4 1 -0.000037099539 0.000000000000
10 4 1 -0.000104950176 0.000000000000
11 4 1 0.000182061024 0.000000000000
12 4 1 -0.000065901202 0.000000000000
13 4 1 0.000075009252 0.000000000000
14 4 1 -0.000442148033 0.000000000000
15 4 1 0.000150381741 0.000000000000
1 5 1 0.000037439167 0.000000000000
2 5 1 0.000074676670 0.000000000000
3 5 1 0.000015892520 0.000000000000
4 5 1 -0.000041145069 0.000000000000
5 5 1 0.000169447923 0.000000000000
6 5 1 -0.000273924847 0.000000000000
7 5 1 -0.000202719940 0.000000000000
8 5 1 -0.000073349990 0.000000000000
9 5 1 0.000424359417 0.000000000000
10 5 1 -0.000088316888 0.000000000000
11 5 1 0.000051619443 0.000000000000
12 5 1 0.000709800902 0.000000000000
13 5 1 -0.000045004997 0.000000000000
14 5 1 -0.000035316541 0.000000000000
15 5 1 -0.000106987712 0.000000000000
1 6 1 0.000005532379 0.000000000000
2 6 1 0.000003258361 0.000000000000
3 6 1 0.000005074102 0.000000000000
4 6 1 -0.000005729725 0.000000000000
5 6 1 -0.000007961385 0.000000000000
6 6 1 -0.000028459775 0.000000000000
7 6 1 0.000046787322 0.000000000000
8 6 1 -0.000005103731 0.000000000000
9 6 1 0.000045031878 0.000000000000
10 6 1 -0.000028545557 0.000000000000
11 6 1 -0.000020265081 0.000000000000
12 6 1 -0.000078208598 0.000000000000
13 6 1 -0.000040273288 0.000000000000
14 6 1 0.000026343315 0.000000000000
15 6 1 0.000042323737 0.000000000000
1 7 1 0.000025437029 0.000000000000
2 7 1 0.000040254775 0.000000000000
3 7 1 0.000032778346 0.000000000000
4 7 1 -0.000059618667 0.000000000000
5 7 1 0.000005205955 0.000000000000
6 7 1 -0.000102550336 0.000000000000
7 7 1 0.000036245612 0.000000000000
8 7 1 -0.000030609697 0.000000000000
9 7 1 0.000133745475 0.000000000000
10 7 1 -0.000115330385 0.000000000000
11 7 1 -0.000308103418 0.000000000000
12 7 1 -0.000007042516 0.000000000000
13 7 1 -0.000118749392 0.000000000000
14 7 1 0.000478315210 0.000000000000
15 7 1 0.000552912050 0.000000000000
1 8 1 0.000000876796 0.000000000000
2 8 1 0.000000080566 0.000000000000
3 8 1 0.000000164327 0.000000000000
4 8 1 0.000000720298 0.000000000000
5 8 1 -0.000000259706 0.000000000000
6 8 1 -0.000002930271 0.000000000000
7 8 1 -0.000001045858 0.000000000000
8 8 1 0.000000559845 0.000000000000
9 8 1 -0.000001331314 0.000000000000
10 8 1 -0.000009184533 0.000000000000
11 8 1 -0.000020319601 0.000000000000
12 8 1 -0.000008339900 0.000000000000
13 8 1 -0.000000211540 0.000000000000
14 8 1 0.000049421105 0.000000000000
15 8 1 -0.000001138166 0.000000000000
1 9 1 0.036473689359 0.000000000000
2 9 1 0.043438179910 0.000000000000
3 9 1 -0.049892625947 0.000000000000
4 9 1 0.070957102206 0.000000000000
5 9 1 -0.013276409303 0.000000000000
6 9 1 -0.081273615237 0.000000000000
7 9 1 0.066054476898 0.000000000000
8 9 1 0.022079783403 0.000000000000
9 9 1 0.069384475355 0.000000000000
10 9 1 0.090230026248 0.000000000000
11 9 1 0.018512939135 0.000000000000
12 9 1 -0.043762350413 0.000000000000
13 9 1 0.078732406888 0.000000000000
14 9 1 0.023445043706 0.000000000000
15 9 1 -0.021670607590 0.000000000000
1 10 1 0.000016680890 0.000000000000
2 10 1 -0.000010358082 0.000000000000
3 10 1 0.000038316676 0.000000000000
4 10 1 0.000039621327 0.000000000000
5 10 1 -0.000055730348 0.000000000000
6 10 1 -0.000113113925 0.000000000000
7 10 1 -0.000089338242 0.000000000000
8 10 1 0.000035434418 0.000000000000
9 10 1 -0.000072574866 0.000000000000
10 10 1 -0.000225773294 0.000000000000
11 10 1 -0.000137365852 0.000000000000
12 10 1 -0.000157029716 0.000000000000
13 10 1 0.000176469091 0.000000000000
14 10 1 0.000405849329 0.000000000000
15 10 1 -0.000116818224 0.000000000000
1 11 1 0.000006866897 0.000000000000
2 11 1 0.000008025438 0.000000000000
3 11 1 -0.000011072515 0.000000000000
4 11 1 0.000017757438 0.000000000000
5 11 1 -0.000003950031 0.000000000000
6 11 1 -0.000029610203 0.000000000000
7 11 1 0.000018444306 0.000000000000
8 11 1 0.000007585612 0.000000000000
9 11 1 0.000037324832 0.000000000000
10 11 1 0.000048791161 0.000000000000
11 11 1 -0.000115551557 0.000000000000
12 11 1 -0.000019119819 0.000000000000
13 11 1 0.000051638331 0.000000000000
14 11 1 -0.000243815976 0.000000000000
15 11 1 0.000189796921 0.000000000000
1 12 1 0.000194928552 0.000000000000
2 12 1 0.000252080822 0.000000000000
3 12 1 0.000390734527 0.000000000000
4 12 1 -0.000658337532 0.000000000000
5 12 1 -0.000332854514 0.000000000000
6 12 1 -0.000990230676 0.000000000000
7 12 1 0.001118806838 0.000000000000
8 12 1 -0.000055982776 0.000000000000
9 12 1 0.001027251988 0.000000000000
10 12 1 -0.001650680987 0.000000000000
11 12 1 -0.000375198718 0.000000000000
12 12 1 -0.001088833913 0.000000000000
13 12 1 -0.001936316380 0.000000000000
14 12 1 0.000860044217 0.000000000000
15 12 1 0.000539268191 0.000000000000
1 13 1 -0.000000407757 0.000000000000
2 13 1 0.000000885751 0.000000000000
3 13 1 -0.000000024427 0.000000000000
4 13 1 -0.000000035001 0.000000000000
5 13 1 0.000001061647 0.000000000000
6 13 1 -0.000001751166 0.000000000000
7 13 1 -0.000004397571 0.000000000000
8 13 1 -0.000000394866 0.000000000000
9 13 1 -0.000001900690 0.000000000000
10 13 1 -0.000000099487 0.000000000000
11 13 1 0.000002159816 0.000000000000
12 13 1 0.000001390819 0.000000000000
13 13 1 0.000000613626 0.000000000000
14 13 1 0.000000028871 0.000000000000
15 13 1 0.000001139358 0.000000000000
1 14 1 0.083820562408 0.000000000000
2 14 1 0.081575730961 0.000000000000
3 14 1 -0.116615674406 0.000000000000
4 14 1 0.138387835433 0.000000000000
5 14 1 -0.052856933816 0.000000000000
6 14 1 -0.148689071139 0.000000000000
7 14 1 0.139601122648 0.000000000000
8 14 1 0.022219471793 0.000000000000
9 14 1 0.106777561950 0.000000000000
10 14 1 0.166062897491 0.000000000000
11 14 1 -0.054918985215 0.000000000000
12 14 1 -0.086595810840 0.000000000000
13 14 1 0.141834703913 0.000000000000
14 14 1 -0.070448474417 0.000000000000
15 14 1 0.051475467994 0.000000000000
1 15 1 -0.000000997907 0.000000000000
2 15 1 0.000000117781 0.000000000000
3 15 1 -0.000000184671 0.000000000000
4 15 1 -0.000001597375 0.000000000000
5 15 1 0.000000050597 0.000000000000
6 15 1 -0.000003863799 0.000000000000
7 15 1 -0.000000896227 0.000000000000
8 15 1 -0.000000539537 0.000000000000
9 15 1 -0.000006799483 0.000000000000
10 15 1 0.000004517400 0.000000000000
11 15 1 -0.000000743562 0.000000000000
12 15 1 -0.000001606998 0.000000000000
13 15 1 -0.000005835933 0.000000000000
14 15 1 -0.000009408457 0.000000000000
15 15 1 -0.000008159165 0.000000000000
| {
"pile_set_name": "Github"
} |
// run-pass
#![allow(unused_must_use)]
#![allow(path_statements)]
// aux-build:derive-a.rs
#[macro_use]
extern crate derive_a;
#[derive(Debug, PartialEq, A, Eq, Copy, Clone)]
struct A;
fn main() {
A;
assert_eq!(A, A);
A.clone();
let a = A;
let _c = a;
let _d = a;
}
| {
"pile_set_name": "Github"
} |
# Changelog
## 3.3.4
- Fix Object.assign not working for IE <= 11 [#616](https://github.com/Bttstrp/bootstrap-switch/issues/616)
## 3.3.3
- Deprecate CoffeeScript in favour of ES6+ with Babel
- Updated and restored documentation
## 3.3.2
- Fix for Flicker on initialisation [#425](https://github.com/nostalgiaz/bootstrap-switch/issues/425), [#422](https://github.com/nostalgiaz/bootstrap-switch/issues/422)
- Prevent horizontal misalignment inside modal in page with odd width [#414](https://github.com/nostalgiaz/bootstrap-switch/issues/414)
## 3.3.1
- Revert of switchChange event triggered only on falsy skip [#411](https://github.com/nostalgiaz/bootstrap-switch/issues/411)
## 3.3.0
- Fixed setting of correct state on drag from indeterminate state [#403](https://github.com/nostalgiaz/bootstrap-switch/issues/403)
- Fixed broken state changing on hidden switch [#392, [#383](https://github.com/nostalgiaz/bootstrap-switch/issues/383)
- Missing animation on first state change triggered by side click [#390](https://github.com/nostalgiaz/bootstrap-switch/issues/390)
- SwitchChange event always triggered after change event [#389](https://github.com/nostalgiaz/bootstrap-switch/issues/389)
- Skip check for transitionend event on init [#381](https://github.com/nostalgiaz/bootstrap-switch/issues/381)
- Added stopPropagation on element mousedown [#369](https://github.com/nostalgiaz/bootstrap-switch/issues/369)
- Fixed wrong descrition in documentation [#351](https://github.com/nostalgiaz/bootstrap-switch/issues/351)
## 3.2.2
- Fixed wrong rendering of switch on initialisation if element is hidden [#376](https://github.com/nostalgiaz/bootstrap-switch/issues/376)
## 3.2.1
- Hotfix for broken initialisation logic if $.support.transition is not set [#375](https://github.com/nostalgiaz/bootstrap-switch/issues/375)
## 3.2.0
- Added option and method handleWidth to set a specific width of the side handled [#341](https://github.com/nostalgiaz/bootstrap-switch/issues/341)
- Added option and method labelWidth to set a specific width of the center label [#341](https://github.com/nostalgiaz/bootstrap-switch/issues/341)
- Fixed broken toggling of side handles when switch is wrapped in a external label [#359](https://github.com/nostalgiaz/bootstrap-switch/issues/359)
- Minor refactoring all along the source code
## 3.1.0
- Added inverse option to swap the position of the left and right elements [#207](https://github.com/nostalgiaz/bootstrap-switch/issues/207)
- Fixed misalignment on Safari [#223](https://github.com/nostalgiaz/bootstrap-switch/issues/223)
- Added options toggleAnimate method
- Enhanced documentation with new examples
## 3.0.2
- Added radioAllOff option. allow a group of radio inputs to be all off [#322](https://github.com/nostalgiaz/bootstrap-switch/issues/322)
- Made HTML options overridable by JavaScript initalization options [#319](https://github.com/nostalgiaz/bootstrap-switch/issues/319)
- .form-control does not interfere anymore with the switch appearance [#318](https://github.com/nostalgiaz/bootstrap-switch/issues/318)
- Fixed triggering of two events in case of jQuery id selector [#317](https://github.com/nostalgiaz/bootstrap-switch/issues/317)
- Fixed internal switching loop when toggling with spacebar [#316](https://github.com/nostalgiaz/bootstrap-switch/issues/316)
- Fixed switch label toggling not working with radio inputs [#312](https://github.com/nostalgiaz/bootstrap-switch/issues/312)
## 3.0.1
- Added support for intermediate state [#218](https://github.com/nostalgiaz/bootstrap-switch/issues/218)
- Added change event triggered on label click [#299](https://github.com/nostalgiaz/bootstrap-switch/issues/299)
- Added onInit and onSwitchChange event as methods
## 3.0.0
- API redesign for a more intuitive use
- Entire code source rewriting focused on cleanliness and performance
- Initialization options can be passed as JavaScript object or written as data-*
- Plugin constructor publicly available from $.fn.bootstrapSwitch.Constructor
- Plugin instance publicly available calling .data('bootstrap-switch')
- Global overridable defaults options
- Improved flexibility with baseClass and wrapperClass options
- New onInit event
- Event namespacing
- Full Bootstrap 3 support
- A lot of fixed bug, as usual
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:Runner.xcodeproj">
</FileRef>
</Workspace>
| {
"pile_set_name": "Github"
} |
/*
* xfrm6_state.c: based on xfrm4_state.c
*
* Authors:
* Mitsuru KANDA @USAGI
* Kazunori MIYAZAWA @USAGI
* Kunihiro Ishiguro <[email protected]>
* IPv6 support
* YOSHIFUJI Hideaki @USAGI
* Split up af-specific portion
*
*/
#include <net/xfrm.h>
#include <linux/pfkeyv2.h>
#include <linux/ipsec.h>
#include <linux/netfilter_ipv6.h>
#include <net/dsfield.h>
#include <net/ipv6.h>
#include <net/addrconf.h>
static void
__xfrm6_init_tempsel(struct xfrm_selector *sel, const struct flowi *fl)
{
const struct flowi6 *fl6 = &fl->u.ip6;
/* Initialize temporary selector matching only
* to current session. */
ipv6_addr_copy((struct in6_addr *)&sel->daddr, &fl6->daddr);
ipv6_addr_copy((struct in6_addr *)&sel->saddr, &fl6->saddr);
sel->dport = xfrm_flowi_dport(fl, &fl6->uli);
sel->dport_mask = htons(0xffff);
sel->sport = xfrm_flowi_sport(fl, &fl6->uli);
sel->sport_mask = htons(0xffff);
sel->family = AF_INET6;
sel->prefixlen_d = 128;
sel->prefixlen_s = 128;
sel->proto = fl6->flowi6_proto;
sel->ifindex = fl6->flowi6_oif;
}
static void
xfrm6_init_temprop(struct xfrm_state *x, const struct xfrm_tmpl *tmpl,
const xfrm_address_t *daddr, const xfrm_address_t *saddr)
{
x->id = tmpl->id;
if (ipv6_addr_any((struct in6_addr*)&x->id.daddr))
memcpy(&x->id.daddr, daddr, sizeof(x->sel.daddr));
memcpy(&x->props.saddr, &tmpl->saddr, sizeof(x->props.saddr));
if (ipv6_addr_any((struct in6_addr*)&x->props.saddr))
memcpy(&x->props.saddr, saddr, sizeof(x->props.saddr));
x->props.mode = tmpl->mode;
x->props.reqid = tmpl->reqid;
x->props.family = AF_INET6;
}
/* distribution counting sort function for xfrm_state and xfrm_tmpl */
static int
__xfrm6_sort(void **dst, void **src, int n, int (*cmp)(void *p), int maxclass)
{
int i;
int class[XFRM_MAX_DEPTH];
int count[maxclass];
memset(count, 0, sizeof(count));
for (i = 0; i < n; i++) {
int c;
class[i] = c = cmp(src[i]);
count[c]++;
}
for (i = 2; i < maxclass; i++)
count[i] += count[i - 1];
for (i = 0; i < n; i++) {
dst[count[class[i] - 1]++] = src[i];
src[i] = NULL;
}
return 0;
}
/*
* Rule for xfrm_state:
*
* rule 1: select IPsec transport except AH
* rule 2: select MIPv6 RO or inbound trigger
* rule 3: select IPsec transport AH
* rule 4: select IPsec tunnel
* rule 5: others
*/
static int __xfrm6_state_sort_cmp(void *p)
{
struct xfrm_state *v = p;
switch (v->props.mode) {
case XFRM_MODE_TRANSPORT:
if (v->id.proto != IPPROTO_AH)
return 1;
else
return 3;
#if defined(CONFIG_IPV6_MIP6) || defined(CONFIG_IPV6_MIP6_MODULE)
case XFRM_MODE_ROUTEOPTIMIZATION:
case XFRM_MODE_IN_TRIGGER:
return 2;
#endif
case XFRM_MODE_TUNNEL:
case XFRM_MODE_BEET:
return 4;
}
return 5;
}
static int
__xfrm6_state_sort(struct xfrm_state **dst, struct xfrm_state **src, int n)
{
return __xfrm6_sort((void **)dst, (void **)src, n,
__xfrm6_state_sort_cmp, 6);
}
/*
* Rule for xfrm_tmpl:
*
* rule 1: select IPsec transport
* rule 2: select MIPv6 RO or inbound trigger
* rule 3: select IPsec tunnel
* rule 4: others
*/
static int __xfrm6_tmpl_sort_cmp(void *p)
{
struct xfrm_tmpl *v = p;
switch (v->mode) {
case XFRM_MODE_TRANSPORT:
return 1;
#if defined(CONFIG_IPV6_MIP6) || defined(CONFIG_IPV6_MIP6_MODULE)
case XFRM_MODE_ROUTEOPTIMIZATION:
case XFRM_MODE_IN_TRIGGER:
return 2;
#endif
case XFRM_MODE_TUNNEL:
case XFRM_MODE_BEET:
return 3;
}
return 4;
}
static int
__xfrm6_tmpl_sort(struct xfrm_tmpl **dst, struct xfrm_tmpl **src, int n)
{
return __xfrm6_sort((void **)dst, (void **)src, n,
__xfrm6_tmpl_sort_cmp, 5);
}
int xfrm6_extract_header(struct sk_buff *skb)
{
struct ipv6hdr *iph = ipv6_hdr(skb);
XFRM_MODE_SKB_CB(skb)->ihl = sizeof(*iph);
XFRM_MODE_SKB_CB(skb)->id = 0;
XFRM_MODE_SKB_CB(skb)->frag_off = htons(IP_DF);
XFRM_MODE_SKB_CB(skb)->tos = ipv6_get_dsfield(iph);
XFRM_MODE_SKB_CB(skb)->ttl = iph->hop_limit;
XFRM_MODE_SKB_CB(skb)->optlen = 0;
memcpy(XFRM_MODE_SKB_CB(skb)->flow_lbl, iph->flow_lbl,
sizeof(XFRM_MODE_SKB_CB(skb)->flow_lbl));
return 0;
}
static struct xfrm_state_afinfo xfrm6_state_afinfo = {
.family = AF_INET6,
.proto = IPPROTO_IPV6,
.eth_proto = htons(ETH_P_IPV6),
.owner = THIS_MODULE,
.init_tempsel = __xfrm6_init_tempsel,
.init_temprop = xfrm6_init_temprop,
.tmpl_sort = __xfrm6_tmpl_sort,
.state_sort = __xfrm6_state_sort,
.output = xfrm6_output,
.output_finish = xfrm6_output_finish,
.extract_input = xfrm6_extract_input,
.extract_output = xfrm6_extract_output,
.transport_finish = xfrm6_transport_finish,
};
int __init xfrm6_state_init(void)
{
return xfrm_state_register_afinfo(&xfrm6_state_afinfo);
}
void xfrm6_state_fini(void)
{
xfrm_state_unregister_afinfo(&xfrm6_state_afinfo);
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2017-2020 ProfunKtor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.profunktor.fs2rabbit.resiliency
import cats.effect.IO
import cats.effect.concurrent.Ref
import cats.implicits._
import dev.profunktor.fs2rabbit.BaseSpec
import fs2._
import scala.concurrent.duration._
import org.scalatest.compatible.Assertion
class ResilientStreamSpec extends BaseSpec {
private val sink: Pipe[IO, Int, Unit] = _.evalMap(putStrLn)
val emptyAssertion: Assertion = true shouldBe true
it should "run a stream until it's finished" in {
val program = Stream(1, 2, 3).covary[IO].through(sink)
ResilientStream.run(program).as(emptyAssertion).unsafeToFuture()
}
it should "run a stream and recover in case of failure" in {
val errorProgram = Stream.raiseError[IO](new Exception("on purpose")).through(sink)
def p(ref: Ref[IO, Int]): Stream[IO, Unit] =
errorProgram.handleErrorWith { t =>
Stream.eval(ref.get) flatMap { n =>
if (n == 0) Stream.eval(IO.unit)
else Stream.eval(ref.update(_ - 1) *> IO.raiseError(t))
}
}
Ref.of[IO, Int](2).flatMap(r => ResilientStream.run(p(r), 1.second)).as(emptyAssertion).unsafeToFuture()
}
}
| {
"pile_set_name": "Github"
} |
<div class="col-md-8">
{{ ChangePasswordCoreForm::display() }}
{{ TwoFactorAuthDesignCore::link('affiliate') }}
</div>
| {
"pile_set_name": "Github"
} |
// fp_traits.hpp
#ifndef BOOST_MATH_FP_TRAITS_HPP
#define BOOST_MATH_FP_TRAITS_HPP
// Copyright (c) 2006 Johan Rade
// 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)
/*
To support old compilers, care has been taken to avoid partial template
specialization and meta function forwarding.
With these techniques, the code could be simplified.
*/
#if defined(__vms) && defined(__DECCXX) && !__IEEE_FLOAT
// The VAX floating point formats are used (for float and double)
# define BOOST_FPCLASSIFY_VAX_FORMAT
#endif
#include <cstring>
#include <boost/assert.hpp>
#include <boost/cstdint.hpp>
#include <boost/detail/endian.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_floating_point.hpp>
#ifdef BOOST_NO_STDC_NAMESPACE
namespace std{ using ::memcpy; }
#endif
#ifndef FP_NORMAL
#define FP_ZERO 0
#define FP_NORMAL 1
#define FP_INFINITE 2
#define FP_NAN 3
#define FP_SUBNORMAL 4
#else
#define BOOST_HAS_FPCLASSIFY
#ifndef fpclassify
# if (defined(__GLIBCPP__) || defined(__GLIBCXX__)) \
&& defined(_GLIBCXX_USE_C99_MATH) \
&& !(defined(_GLIBCXX_USE_C99_FP_MACROS_DYNAMIC) \
&& (_GLIBCXX_USE_C99_FP_MACROS_DYNAMIC != 0))
# ifdef _STLP_VENDOR_CSTD
# if _STLPORT_VERSION >= 0x520
# define BOOST_FPCLASSIFY_PREFIX ::__std_alias::
# else
# define BOOST_FPCLASSIFY_PREFIX ::_STLP_VENDOR_CSTD::
# endif
# else
# define BOOST_FPCLASSIFY_PREFIX ::std::
# endif
# else
# undef BOOST_HAS_FPCLASSIFY
# define BOOST_FPCLASSIFY_PREFIX
# endif
#elif (defined(__HP_aCC) && !defined(__hppa))
// aCC 6 appears to do "#define fpclassify fpclassify" which messes us up a bit!
# define BOOST_FPCLASSIFY_PREFIX ::
#else
# define BOOST_FPCLASSIFY_PREFIX
#endif
#ifdef __MINGW32__
# undef BOOST_HAS_FPCLASSIFY
#endif
#endif
//------------------------------------------------------------------------------
namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost {
namespace math {
namespace detail {
//------------------------------------------------------------------------------
/*
The following classes are used to tag the different methods that are used
for floating point classification
*/
struct native_tag {};
template <bool has_limits>
struct generic_tag {};
struct ieee_tag {};
struct ieee_copy_all_bits_tag : public ieee_tag {};
struct ieee_copy_leading_bits_tag : public ieee_tag {};
#ifdef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS
//
// These helper functions are used only when numeric_limits<>
// members are not compile time constants:
//
inline bool is_generic_tag_false(const generic_tag<false>*)
{
return true;
}
inline bool is_generic_tag_false(const void*)
{
return false;
}
#endif
//------------------------------------------------------------------------------
/*
Most processors support three different floating point precisions:
single precision (32 bits), double precision (64 bits)
and extended double precision (80 - 128 bits, depending on the processor)
Note that the C++ type long double can be implemented
both as double precision and extended double precision.
*/
struct unknown_precision{};
struct single_precision {};
struct double_precision {};
struct extended_double_precision {};
// native_tag version --------------------------------------------------------------
template<class T> struct fp_traits_native
{
typedef native_tag method;
};
// generic_tag version -------------------------------------------------------------
template<class T, class U> struct fp_traits_non_native
{
#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS
typedef generic_tag<std::numeric_limits<T>::is_specialized> method;
#else
typedef generic_tag<false> method;
#endif
};
// ieee_tag versions ---------------------------------------------------------------
/*
These specializations of fp_traits_non_native contain information needed
to "parse" the binary representation of a floating point number.
Typedef members:
bits -- the target type when copying the leading bytes of a floating
point number. It is a typedef for uint32_t or uint64_t.
method -- tells us whether all bytes are copied or not.
It is a typedef for ieee_copy_all_bits_tag or ieee_copy_leading_bits_tag.
Static data members:
sign, exponent, flag, significand -- bit masks that give the meaning of the
bits in the leading bytes.
Static function members:
get_bits(), set_bits() -- provide access to the leading bytes.
*/
// ieee_tag version, float (32 bits) -----------------------------------------------
#ifndef BOOST_FPCLASSIFY_VAX_FORMAT
template<> struct fp_traits_non_native<float, single_precision>
{
typedef ieee_copy_all_bits_tag method;
BOOST_STATIC_CONSTANT(uint32_t, sign = 0x80000000u);
BOOST_STATIC_CONSTANT(uint32_t, exponent = 0x7f800000);
BOOST_STATIC_CONSTANT(uint32_t, flag = 0x00000000);
BOOST_STATIC_CONSTANT(uint32_t, significand = 0x007fffff);
typedef uint32_t bits;
static void get_bits(float x, uint32_t& a) { std::memcpy(&a, &x, 4); }
static void set_bits(float& x, uint32_t a) { std::memcpy(&x, &a, 4); }
};
// ieee_tag version, double (64 bits) ----------------------------------------------
#if defined(BOOST_NO_INT64_T) || defined(BOOST_NO_INCLASS_MEMBER_INITIALIZATION) \
|| defined(__BORLANDC__) || defined(__CODEGEAR__)
template<> struct fp_traits_non_native<double, double_precision>
{
typedef ieee_copy_leading_bits_tag method;
BOOST_STATIC_CONSTANT(uint32_t, sign = 0x80000000u);
BOOST_STATIC_CONSTANT(uint32_t, exponent = 0x7ff00000);
BOOST_STATIC_CONSTANT(uint32_t, flag = 0);
BOOST_STATIC_CONSTANT(uint32_t, significand = 0x000fffff);
typedef uint32_t bits;
static void get_bits(double x, uint32_t& a)
{
std::memcpy(&a, reinterpret_cast<const unsigned char*>(&x) + offset_, 4);
}
static void set_bits(double& x, uint32_t a)
{
std::memcpy(reinterpret_cast<unsigned char*>(&x) + offset_, &a, 4);
}
private:
#if defined(BOOST_BIG_ENDIAN)
BOOST_STATIC_CONSTANT(int, offset_ = 0);
#elif defined(BOOST_LITTLE_ENDIAN)
BOOST_STATIC_CONSTANT(int, offset_ = 4);
#else
BOOST_STATIC_ASSERT(false);
#endif
};
//..............................................................................
#else
template<> struct fp_traits_non_native<double, double_precision>
{
typedef ieee_copy_all_bits_tag method;
static const uint64_t sign = ((uint64_t)0x80000000u) << 32;
static const uint64_t exponent = ((uint64_t)0x7ff00000) << 32;
static const uint64_t flag = 0;
static const uint64_t significand
= (((uint64_t)0x000fffff) << 32) + ((uint64_t)0xffffffffu);
typedef uint64_t bits;
static void get_bits(double x, uint64_t& a) { std::memcpy(&a, &x, 8); }
static void set_bits(double& x, uint64_t a) { std::memcpy(&x, &a, 8); }
};
#endif
#endif // #ifndef BOOST_FPCLASSIFY_VAX_FORMAT
// long double (64 bits) -------------------------------------------------------
#if defined(BOOST_NO_INT64_T) || defined(BOOST_NO_INCLASS_MEMBER_INITIALIZATION)\
|| defined(__BORLANDC__) || defined(__CODEGEAR__)
template<> struct fp_traits_non_native<long double, double_precision>
{
typedef ieee_copy_leading_bits_tag method;
BOOST_STATIC_CONSTANT(uint32_t, sign = 0x80000000u);
BOOST_STATIC_CONSTANT(uint32_t, exponent = 0x7ff00000);
BOOST_STATIC_CONSTANT(uint32_t, flag = 0);
BOOST_STATIC_CONSTANT(uint32_t, significand = 0x000fffff);
typedef uint32_t bits;
static void get_bits(long double x, uint32_t& a)
{
std::memcpy(&a, reinterpret_cast<const unsigned char*>(&x) + offset_, 4);
}
static void set_bits(long double& x, uint32_t a)
{
std::memcpy(reinterpret_cast<unsigned char*>(&x) + offset_, &a, 4);
}
private:
#if defined(BOOST_BIG_ENDIAN)
BOOST_STATIC_CONSTANT(int, offset_ = 0);
#elif defined(BOOST_LITTLE_ENDIAN)
BOOST_STATIC_CONSTANT(int, offset_ = 4);
#else
BOOST_STATIC_ASSERT(false);
#endif
};
//..............................................................................
#else
template<> struct fp_traits_non_native<long double, double_precision>
{
typedef ieee_copy_all_bits_tag method;
static const uint64_t sign = (uint64_t)0x80000000u << 32;
static const uint64_t exponent = (uint64_t)0x7ff00000 << 32;
static const uint64_t flag = 0;
static const uint64_t significand
= ((uint64_t)0x000fffff << 32) + (uint64_t)0xffffffffu;
typedef uint64_t bits;
static void get_bits(long double x, uint64_t& a) { std::memcpy(&a, &x, 8); }
static void set_bits(long double& x, uint64_t a) { std::memcpy(&x, &a, 8); }
};
#endif
// long double (>64 bits), x86 and x64 -----------------------------------------
#if defined(__i386) || defined(__i386__) || defined(_M_IX86) \
|| defined(__amd64) || defined(__amd64__) || defined(_M_AMD64) \
|| defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)
// Intel extended double precision format (80 bits)
template<>
struct fp_traits_non_native<long double, extended_double_precision>
{
typedef ieee_copy_leading_bits_tag method;
BOOST_STATIC_CONSTANT(uint32_t, sign = 0x80000000u);
BOOST_STATIC_CONSTANT(uint32_t, exponent = 0x7fff0000);
BOOST_STATIC_CONSTANT(uint32_t, flag = 0x00008000);
BOOST_STATIC_CONSTANT(uint32_t, significand = 0x00007fff);
typedef uint32_t bits;
static void get_bits(long double x, uint32_t& a)
{
std::memcpy(&a, reinterpret_cast<const unsigned char*>(&x) + 6, 4);
}
static void set_bits(long double& x, uint32_t a)
{
std::memcpy(reinterpret_cast<unsigned char*>(&x) + 6, &a, 4);
}
};
// long double (>64 bits), Itanium ---------------------------------------------
#elif defined(__ia64) || defined(__ia64__) || defined(_M_IA64)
// The floating point format is unknown at compile time
// No template specialization is provided.
// The generic_tag definition is used.
// The Itanium supports both
// the Intel extended double precision format (80 bits) and
// the IEEE extended double precision format with 15 exponent bits (128 bits).
#elif defined(__GNUC__) && (LDBL_MANT_DIG == 106)
//
// Define nothing here and fall though to generic_tag:
// We have GCC's "double double" in effect, and any attempt
// to handle it via bit-fiddling is pretty much doomed to fail...
//
// long double (>64 bits), PowerPC ---------------------------------------------
#elif defined(__powerpc) || defined(__powerpc__) || defined(__POWERPC__) \
|| defined(__ppc) || defined(__ppc__) || defined(__PPC__)
// PowerPC extended double precision format (128 bits)
template<>
struct fp_traits_non_native<long double, extended_double_precision>
{
typedef ieee_copy_leading_bits_tag method;
BOOST_STATIC_CONSTANT(uint32_t, sign = 0x80000000u);
BOOST_STATIC_CONSTANT(uint32_t, exponent = 0x7ff00000);
BOOST_STATIC_CONSTANT(uint32_t, flag = 0x00000000);
BOOST_STATIC_CONSTANT(uint32_t, significand = 0x000fffff);
typedef uint32_t bits;
static void get_bits(long double x, uint32_t& a)
{
std::memcpy(&a, reinterpret_cast<const unsigned char*>(&x) + offset_, 4);
}
static void set_bits(long double& x, uint32_t a)
{
std::memcpy(reinterpret_cast<unsigned char*>(&x) + offset_, &a, 4);
}
private:
#if defined(BOOST_BIG_ENDIAN)
BOOST_STATIC_CONSTANT(int, offset_ = 0);
#elif defined(BOOST_LITTLE_ENDIAN)
BOOST_STATIC_CONSTANT(int, offset_ = 12);
#else
BOOST_STATIC_ASSERT(false);
#endif
};
// long double (>64 bits), Motorola 68K ----------------------------------------
#elif defined(__m68k) || defined(__m68k__) \
|| defined(__mc68000) || defined(__mc68000__) \
// Motorola extended double precision format (96 bits)
// It is the same format as the Intel extended double precision format,
// except that 1) it is big-endian, 2) the 3rd and 4th byte are padding, and
// 3) the flag bit is not set for infinity
template<>
struct fp_traits_non_native<long double, extended_double_precision>
{
typedef ieee_copy_leading_bits_tag method;
BOOST_STATIC_CONSTANT(uint32_t, sign = 0x80000000u);
BOOST_STATIC_CONSTANT(uint32_t, exponent = 0x7fff0000);
BOOST_STATIC_CONSTANT(uint32_t, flag = 0x00008000);
BOOST_STATIC_CONSTANT(uint32_t, significand = 0x00007fff);
// copy 1st, 2nd, 5th and 6th byte. 3rd and 4th byte are padding.
typedef uint32_t bits;
static void get_bits(long double x, uint32_t& a)
{
std::memcpy(&a, &x, 2);
std::memcpy(reinterpret_cast<unsigned char*>(&a) + 2,
reinterpret_cast<const unsigned char*>(&x) + 4, 2);
}
static void set_bits(long double& x, uint32_t a)
{
std::memcpy(&x, &a, 2);
std::memcpy(reinterpret_cast<unsigned char*>(&x) + 4,
reinterpret_cast<const unsigned char*>(&a) + 2, 2);
}
};
// long double (>64 bits), All other processors --------------------------------
#else
// IEEE extended double precision format with 15 exponent bits (128 bits)
template<>
struct fp_traits_non_native<long double, extended_double_precision>
{
typedef ieee_copy_leading_bits_tag method;
BOOST_STATIC_CONSTANT(uint32_t, sign = 0x80000000u);
BOOST_STATIC_CONSTANT(uint32_t, exponent = 0x7fff0000);
BOOST_STATIC_CONSTANT(uint32_t, flag = 0x00000000);
BOOST_STATIC_CONSTANT(uint32_t, significand = 0x0000ffff);
typedef uint32_t bits;
static void get_bits(long double x, uint32_t& a)
{
std::memcpy(&a, reinterpret_cast<const unsigned char*>(&x) + offset_, 4);
}
static void set_bits(long double& x, uint32_t a)
{
std::memcpy(reinterpret_cast<unsigned char*>(&x) + offset_, &a, 4);
}
private:
#if defined(BOOST_BIG_ENDIAN)
BOOST_STATIC_CONSTANT(int, offset_ = 0);
#elif defined(BOOST_LITTLE_ENDIAN)
BOOST_STATIC_CONSTANT(int, offset_ = 12);
#else
BOOST_STATIC_ASSERT(false);
#endif
};
#endif
//------------------------------------------------------------------------------
// size_to_precision is a type switch for converting a C++ floating point type
// to the corresponding precision type.
template<int n, bool fp> struct size_to_precision
{
typedef unknown_precision type;
};
template<> struct size_to_precision<4, true>
{
typedef single_precision type;
};
template<> struct size_to_precision<8, true>
{
typedef double_precision type;
};
template<> struct size_to_precision<10, true>
{
typedef extended_double_precision type;
};
template<> struct size_to_precision<12, true>
{
typedef extended_double_precision type;
};
template<> struct size_to_precision<16, true>
{
typedef extended_double_precision type;
};
//------------------------------------------------------------------------------
//
// Figure out whether to use native classification functions based on
// whether T is a built in floating point type or not:
//
template <class T>
struct select_native
{
typedef BOOST_DEDUCED_TYPENAME size_to_precision<sizeof(T), ::mars_boost::is_floating_point<T>::value>::type precision;
typedef fp_traits_non_native<T, precision> type;
};
template<>
struct select_native<float>
{
typedef fp_traits_native<float> type;
};
template<>
struct select_native<double>
{
typedef fp_traits_native<double> type;
};
template<>
struct select_native<long double>
{
typedef fp_traits_native<long double> type;
};
//------------------------------------------------------------------------------
// fp_traits is a type switch that selects the right fp_traits_non_native
#if (defined(BOOST_MATH_USE_C99) && !(defined(__GNUC__) && (__GNUC__ < 4))) \
&& !defined(__hpux) \
&& !defined(__DECCXX)\
&& !defined(__osf__) \
&& !defined(__SGI_STL_PORT) && !defined(_STLPORT_VERSION)\
&& !defined(__FAST_MATH__)\
&& !defined(BOOST_MATH_DISABLE_STD_FPCLASSIFY)\
&& !defined(BOOST_INTEL)\
&& !defined(sun)
# define BOOST_MATH_USE_STD_FPCLASSIFY
#endif
template<class T> struct fp_traits
{
typedef BOOST_DEDUCED_TYPENAME size_to_precision<sizeof(T), ::mars_boost::is_floating_point<T>::value>::type precision;
#if defined(BOOST_MATH_USE_STD_FPCLASSIFY) && !defined(BOOST_MATH_DISABLE_STD_FPCLASSIFY)
typedef typename select_native<T>::type type;
#else
typedef fp_traits_non_native<T, precision> type;
#endif
typedef fp_traits_non_native<T, precision> sign_change_type;
};
//------------------------------------------------------------------------------
} // namespace detail
} // namespace math
} // namespace mars_boost
#endif
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.