text
stringlengths 10
99.9k
| meta
dict |
|---|---|
//
// detail/impl/service_registry.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_DETAIL_IMPL_SERVICE_REGISTRY_HPP
#define ASIO_DETAIL_IMPL_SERVICE_REGISTRY_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
template <typename Service>
Service& service_registry::use_service()
{
execution_context::service::key key;
init_key<Service>(key, 0);
factory_type factory = &service_registry::create<Service, execution_context>;
return *static_cast<Service*>(do_use_service(key, factory, &owner_));
}
template <typename Service>
Service& service_registry::use_service(io_context& owner)
{
execution_context::service::key key;
init_key<Service>(key, 0);
factory_type factory = &service_registry::create<Service, io_context>;
return *static_cast<Service*>(do_use_service(key, factory, &owner));
}
template <typename Service>
void service_registry::add_service(Service* new_service)
{
execution_context::service::key key;
init_key<Service>(key, 0);
return do_add_service(key, new_service);
}
template <typename Service>
bool service_registry::has_service() const
{
execution_context::service::key key;
init_key<Service>(key, 0);
return do_has_service(key);
}
template <typename Service>
inline void service_registry::init_key(
execution_context::service::key& key, ...)
{
init_key_from_id(key, Service::id);
}
#if !defined(ASIO_NO_TYPEID)
template <typename Service>
void service_registry::init_key(execution_context::service::key& key,
typename enable_if<
is_base_of<typename Service::key_type, Service>::value>::type*)
{
key.type_info_ = &typeid(typeid_wrapper<Service>);
key.id_ = 0;
}
template <typename Service>
void service_registry::init_key_from_id(execution_context::service::key& key,
const service_id<Service>& /*id*/)
{
key.type_info_ = &typeid(typeid_wrapper<Service>);
key.id_ = 0;
}
#endif // !defined(ASIO_NO_TYPEID)
template <typename Service, typename Owner>
execution_context::service* service_registry::create(void* owner)
{
return new Service(*static_cast<Owner*>(owner));
}
} // namespace detail
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_DETAIL_IMPL_SERVICE_REGISTRY_HPP
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright (c) 2014-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.
*/
var React = require('react');
var Router = require('react-router');
var { Map, Seq } = require('../../../../');
var defs = require('../../../lib/getTypeDefs');
var SideBar = React.createClass({
render() {
var type = defs.Immutable;
return (
<div className="sideBar">
<div className="toolBar">
<div
onClick={this.props.toggleShowInGroups}
onKeyPress={this.props.toggleShowInGroups}
>
<span className={this.props.showInGroups && 'selected'}>
Grouped
</span>
{' • '}
<span className={this.props.showInGroups || 'selected'}>
Alphabetized
</span>
</div>
<div
onClick={this.props.toggleShowInherited}
onKeyPress={this.props.toggleShowInherited}
>
<span className={this.props.showInherited && 'selected'}>
Inherited
</span>
{' • '}
<span className={this.props.showInherited || 'selected'}>
Defined
</span>
</div>
</div>
<div className="scrollContent">
<h4 className="groupTitle">API</h4>
{Seq(type.module)
.flatMap((t, name) => flattenSubmodules(Map(), t, name))
.map((t, name) => this.renderSideBarType(name, t))
.valueSeq()
.toArray()}
</div>
</div>
);
},
renderSideBarType(typeName, type) {
var isFocus = this.props.focus === typeName;
var isFunction = !type.interface && !type.module;
var call = type.call;
var functions = Seq(type.module).filter(t => !t.interface && !t.module);
var label = typeName + (isFunction ? '()' : '');
if (!isFocus) {
label = <Router.Link to={'/' + typeName}>{label}</Router.Link>;
}
var memberGroups = this.props.memberGroups;
var members =
!isFocus || isFunction ? null : (
<div className="members">
{call && (
<section>
<h4 className="groupTitle">Construction</h4>
<div>
<Router.Link to={'/' + typeName + '/' + typeName}>
{typeName + '()'}
</Router.Link>
</div>
</section>
)}
{functions.count() > 0 && (
<section>
<h4 className="groupTitle">Static Methods</h4>
{functions
.map((t, name) => (
<div key={name}>
<Router.Link to={'/' + typeName + '/' + name}>
{typeName + '.' + name + '()'}
</Router.Link>
</div>
))
.valueSeq()
.toArray()}
</section>
)}
<section>
{Seq(memberGroups)
.map(
(members, title) =>
members.length === 0
? null
: Seq([
<h4 key={title || 'Members'} className="groupTitle">
{title || 'Members'}
</h4>,
Seq(members).map(member => (
<div key={member.memberName}>
<Router.Link
to={'/' + typeName + '/' + member.memberName}
>
{member.memberName +
(member.memberDef.signatures ? '()' : '')}
</Router.Link>
</div>
)),
])
)
.flatten()
.valueSeq()
.toArray()}
</section>
</div>
);
return (
<div key={typeName}>
<h2>{label}</h2>
{members}
</div>
);
},
});
function flattenSubmodules(modules, type, name) {
modules = modules.set(name, type);
return type.module
? Seq(type.module)
.filter(t => t.interface || t.module)
.reduce(
(modules, subT, subName) =>
flattenSubmodules(modules, subT, name + '.' + subName),
modules
)
: modules;
}
module.exports = SideBar;
|
{
"pile_set_name": "Github"
}
|
/* (c) 2014 Open Source Geospatial Foundation - all rights reserved
* (c) 2001 - 2013 OpenPlans
* This code is licensed under the GPL 2.0 license, available at the root
* application directory.
*/
package org.geoserver.wcs.kvp;
import static org.vfny.geoserver.wcs.WcsException.WcsExceptionCode.InvalidParameterValue;
import org.geoserver.ows.KvpParser;
import org.vfny.geoserver.wcs.WcsException;
/**
* Not really a parser, but a validity checker instead (ensures the specified type is among the
* values foreseen by the standard and supported by GeoServer)
*
* @author Andrea Aime
*/
public class GridTypeKvpParser extends KvpParser {
public GridTypeKvpParser() {
super("GridType", String.class);
}
@Override
public Object parse(String value) throws Exception {
GridType type = null;
for (GridType currType : GridType.values()) {
if (currType.getXmlConstant().equalsIgnoreCase(value)) {
type = currType;
break;
}
}
if (type == null)
throw new WcsException(
"Could not understand grid type '" + value + "'",
InvalidParameterValue,
"GridType");
if (type == GridType.GT2dGridIn3dCrs)
throw new WcsException(
"GeoServer does not support type " + type.name(),
InvalidParameterValue,
"GridType");
return type.getXmlConstant();
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.tests.beanManager.injectionPoint;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import jakarta.enterprise.inject.Default;
import jakarta.enterprise.inject.spi.AnnotatedConstructor;
import jakarta.enterprise.inject.spi.AnnotatedField;
import jakarta.enterprise.inject.spi.AnnotatedMethod;
import jakarta.enterprise.inject.spi.AnnotatedParameter;
import jakarta.enterprise.inject.spi.AnnotatedType;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.enterprise.inject.spi.InjectionPoint;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.BeanArchive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.weld.test.util.Utils;
import org.jboss.weld.tests.util.BeanUtilities;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
public class CreateInjectionPointTest {
@Inject
private BeanManager manager;
@Deployment
public static Archive<?> getDeployment() {
return ShrinkWrap.create(BeanArchive.class, Utils.getDeploymentNameAsHash(CreateInjectionPointTest.class)).addPackage(Book.class.getPackage()).addClass(BeanUtilities.class);
}
@Test
public void testField() {
AnnotatedType<?> type = manager.createAnnotatedType(Library.class);
assertEquals(1, type.getFields().size());
AnnotatedField<?> field = type.getFields().iterator().next();
InjectionPoint ip = manager.createInjectionPoint(field);
validateParameterizedType(ip.getType(), Book.class, String.class);
BeanUtilities.verifyQualifierTypes(ip.getQualifiers(), Monograph.class, Fictional.class);
assertNull(ip.getBean());
assertEquals(field.getJavaMember(), ip.getMember());
assertNotNull(ip.getAnnotated());
assertFalse(ip.isDelegate());
assertTrue(ip.isTransient());
}
@Test
public void testConstructorParameter() {
AnnotatedType<?> type = manager.createAnnotatedType(Library.class);
assertEquals(1, type.getConstructors().size());
AnnotatedConstructor<?> constructor = type.getConstructors().iterator().next();
AnnotatedParameter<?> parameter = constructor.getParameters().get(1);
InjectionPoint ip = manager.createInjectionPoint(parameter);
validateParameterizedType(ip.getType(), Book.class, String.class);
BeanUtilities.verifyQualifierTypes(ip.getQualifiers(), Fictional.class);
assertNull(ip.getBean());
assertEquals(constructor.getJavaMember(), ip.getMember());
assertNotNull(ip.getAnnotated());
assertFalse(ip.isDelegate());
assertFalse(ip.isTransient());
}
@Test
public void testMethodParameter() {
AnnotatedType<?> type = manager.createAnnotatedType(Library.class);
assertEquals(1, type.getMethods().size());
AnnotatedMethod<?> method = type.getMethods().iterator().next();
AnnotatedParameter<?> parameter = method.getParameters().get(2);
InjectionPoint ip = manager.createInjectionPoint(parameter);
validateParameterizedType(ip.getType(), Book.class, Integer.class);
BeanUtilities.verifyQualifierTypes(ip.getQualifiers(), Default.class);
assertNull(ip.getBean());
assertEquals(method.getJavaMember(), ip.getMember());
assertNotNull(ip.getAnnotated());
assertFalse(ip.isDelegate());
assertFalse(ip.isTransient());
}
private static void validateParameterizedType(Type type, Class<?> rawType, Type... types) {
assertTrue(type instanceof ParameterizedType);
ParameterizedType parameterized = (ParameterizedType) type;
assertEquals(rawType, parameterized.getRawType());
assertTrue(Arrays.equals(types, parameterized.getActualTypeArguments()));
}
}
|
{
"pile_set_name": "Github"
}
|
/* global FileReader */
import React from 'react'
import PropTypes from 'prop-types'
import { createMessage } from '../graphql/mutations'
import { getConvo } from '../graphql/queries'
import { graphql } from 'react-apollo'
import uuid from 'uuid/v4'
import { Popover, PopoverHeader, PopoverBody } from 'reactstrap'
import { Auth } from 'aws-amplify'
import awsmobile from '../aws-exports'
const EMPTY_FILE = {
bucket: null,
region: null,
key: null,
__typename: 'S3Object'
}
const VISIBILITY = 'protected'
async function getFile(selectedFile) {
if (!selectedFile) {
return null
}
const bucket = awsmobile.aws_user_files_s3_bucket
const region = awsmobile.aws_user_files_s3_bucket_region
const { name: fileName, type: mimeType } = selectedFile
const [, , , extension] = /([^.]+)(\.(\w+))?$/.exec(fileName)
const { identityId } = await Auth.currentCredentials()
const key = `${VISIBILITY}/${identityId}/${uuid()}${extension &&
'.'}${extension}`
console.log(fileName, mimeType, extension, key)
const file = {
bucket,
key,
region,
mimeType,
localUri: selectedFile
}
return file
}
const doCreateMessage = (
mutation,
content,
file,
convoId,
userId
) => async () => {
let contentTrim = content.trim()
if (!contentTrim.length && file) {
contentTrim = ' '
}
const variables = {
input: {
id: uuid(),
content: contentTrim,
messageConversationId: convoId,
isSent: true,
chatbot: false,
...(file ? { file } : {})
}
}
mutation({
variables,
optimisticResponse: {
createMessage: {
__typename: 'Message',
...variables.input,
...(file ? { file: EMPTY_FILE } : { file: null }),
owner: userId,
isSent: false,
conversation: {
__typename: 'Conversation',
id: convoId,
name: 'n/a',
createdAt: 'n/a'
},
createdAt: new Date().toISOString()
}
},
update: (proxy, { data: { createMessage: newMsg } }) => {
const QUERY = {
query: getConvo,
variables: { id: convoId }
}
const prev = proxy.readQuery(QUERY)
// console.log('view prev', JSON.stringify(prev, null, 2))
const data = {
getConvo: {
...prev.getConvo,
messages: {
...prev.getConvo.messages,
items: [newMsg, ...prev.getConvo.messages.items]
}
}
}
// console.log('view data', JSON.stringify(data, null, 2))
proxy.writeQuery({ ...QUERY, data })
}
})
}
export default class InputBar extends React.Component {
state = { content: '', popoverOpen: false }
handleChange = e => {
this.setState({ content: e.target.value })
}
handleFileChange = e => {
const file = e.target.files[0]
console.log(file)
if (file && file.type.startsWith('image/')) {
const reader = new FileReader()
const self = this
reader.onload = function(e) {
self.setState({ popoverOpen: true, filePreviewSrc: this.result })
}
reader.readAsDataURL(file)
this.setState({ file })
}
}
handleSubmit = async e => {
console.log('submit')
e.preventDefault()
const { content, file: selectedFile } = this.state
const { conversation, userId, createMessage } = this.props
if (content.trim().length === 0 && !selectedFile) {
return
}
const file = await getFile(selectedFile)
console.log('file for s3', file)
const mutator = doCreateMessage(
createMessage,
content,
file,
conversation.id,
userId
)
this.setState({ content: '', file: undefined, popoverOpen: false }, mutator)
}
close = () => {
this.setState({ file: undefined, popoverOpen: false })
}
render() {
const { filePreviewSrc } = this.state
const disabled = !this.props.conversation ? { disabled: 'disabled' } : {}
const imgBtnClass =
'btn btn-block ' + (this.state.file ? 'btn-success' : 'btn-primary')
return (
<div className="entry">
<div className="px-3 py-2 bg-light">
<form onSubmit={this.handleSubmit} {...disabled}>
<div className="row">
<div className="col-12">
<div className="d-flex">
<div className="file-input-holder">
<input
type="file"
onChange={this.handleFileChange}
{...disabled}
/>
<label className={imgBtnClass} id="Popover1">
<i className="fas fa-camera" />
</label>
<Popover
placement="top-start"
isOpen={this.state.popoverOpen}
target="Popover1"
>
<PopoverHeader>
<span>Preview</span>
<button
type="button"
className="close"
aria-label="Close"
onClick={this.close}
>
<span aria-hidden="true">×</span>
</button>
</PopoverHeader>
<PopoverBody>
<img
alt="previw"
className="msg-image"
src={filePreviewSrc}
/>
</PopoverBody>
</Popover>
</div>
<div className="flex-grow-1 px-2">
<input
type="text"
className="form-control"
placeholder="Type a message..."
value={this.state.content}
onChange={this.handleChange}
{...disabled}
/>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
)
}
}
InputBar.propTypes = {
createMessage: PropTypes.func,
conversation: PropTypes.object,
userId: PropTypes.string
}
const InputBarWithData = graphql(createMessage, {
name: 'createMessage'
})(InputBar)
export { InputBarWithData }
|
{
"pile_set_name": "Github"
}
|
{
"include": [
"src/l10n/*"
],
"compilerOptions": {
"target": "es2015", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"outDir": "./dist", /* Redirect output structure to the directory. */
"strict": true, /* Enable all strict type-checking options. */
"types": [
"@types/node"
],
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
}
}
|
{
"pile_set_name": "Github"
}
|
directive @relation(name: String!) on FIELD_DEFINITION
directive @default(value: Int!) on FIELD_DEFINITION
type Post {
id: ID!
title: String!
publishedAt: Int!
likes: Int! @default(value: 0)
author: Author! @relation(name: "Posts")
blog: Blog @relation(name: "Posts")
}
type Author {
id: ID!
name: String!
posts: [Post!]! @relation(name: "Author")
}
type Blog {
id: ID!
name: String!
description: String,
authors: [Author!]!
posts: [Post!]! @relation(name: "Posts")
}
type Query {
authors: [Author!]!
blogs: [Blog!]!
}
|
{
"pile_set_name": "Github"
}
|
# 一对一
一对一是一种 A 只包含一个 B 实例,而 B 只包含一个 A 实例的关系。
我们以`User`和`Profile`实体为例。
用户只能拥有一个配置文件,并且一个配置文件仅由一个用户拥有。
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
@Entity()
export class Profile {
@PrimaryGeneratedColumn()
id: number;
@Column()
gender: string;
@Column()
photo: string;
}
```
```typescript
import { Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn } from "typeorm";
import { Profile } from "./Profile";
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToOne(type => Profile)
@JoinColumn()
profile: Profile;
}
```
这里我们将`@OneToOne`添加到`profile`并将目标关系类型指定为`Profile`。
我们还添加了`@JoinColumn`,这是必选项并且只能在关系的一侧设置。
你设置`@JoinColumn`的哪一方,哪一方的表将包含一个"relation id"和目标实体表的外键。
此示例将生成以下表:
```bash
+-------------+--------------+----------------------------+
| profile |
+-------------+--------------+----------------------------+
| id | int(11) | PRIMARY KEY AUTO_INCREMENT |
| gender | varchar(255) | |
| photo | varchar(255) | |
+-------------+--------------+----------------------------+
+-------------+--------------+----------------------------+
| user |
+-------------+--------------+----------------------------+
| id | int(11) | PRIMARY KEY AUTO_INCREMENT |
| name | varchar(255) | |
| profileId | int(11) | FOREIGN KEY |
+-------------+--------------+----------------------------+
```
同样,`@JoinColumn`必须仅设置在关系的一侧且必须在数据库表中具有外键的一侧。
该例子展示如何保存这样的关系:
```typescript
const profile = new Profile();
profile.gender = "male";
profile.photo = "me.jpg";
await connection.manager.save(profile);
const user = new User();
user.name = "Joe Smith";
user.profile = profile;
await connection.manager.save(user);
```
启用级联后,只需一次`save`调用即可保存此关系。
要加载带有配置文件的用户,必须在`FindOptions`中指定关系:
```typescript
const userRepository = connection.getRepository(User);
const users = await userRepository.find({ relations: ["profile"] });
```
或者使用`QueryBuilder`:
```typescript
const users = await connection
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.profile", "profile")
.getMany();
```
通过在关系上启用预先加载,你不必指定关系或手动加入,它将始终自动加载。
关系可以是单向的和双向的。
单向是仅在一侧与关系装饰器的关系。
双向是与关系两侧的装饰者的关系。
我们刚刚创建了一个单向关系。 让我们将它改为双向:
```typescript
import { Entity, PrimaryGeneratedColumn, Column, OneToOne } from "typeorm";
import { User } from "./User";
@Entity()
export class Profile {
@PrimaryGeneratedColumn()
id: number;
@Column()
gender: string;
@Column()
photo: string;
@OneToOne(type => User, user => user.profile) // 将另一面指定为第二个参数
user: User;
}
```
```typescript
import { Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn } from "typeorm";
import { Profile } from "./Profile";
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToOne(type => Profile, profile => profile.user) // 指定另一面作为第二个参数
@JoinColumn()
profile: Profile;
}
```
我们只是创建了双向关系。 注意,反向关系没有`@JoinColumn`。
`@JoinColumn`必须只在关系的一侧且拥有外键的表上。
双向关系允许你使用`QueryBuilder`从双方加入关系:
```typescript
const profiles = await connection
.getRepository(Profile)
.createQueryBuilder("profile")
.leftJoinAndSelect("profile.user", "user")
.getMany();
```
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* @coversDefaultClass \Foo\CoveredClass
*/
class NamespaceCoverageCoversClassPublicTest extends PHPUnit_Framework_TestCase
{
/**
* @covers ::publicMethod
*/
public function testSomething()
{
$o = new Foo\CoveredClass;
$o->publicMethod();
}
}
|
{
"pile_set_name": "Github"
}
|
// 练习10.24:给定一个string,使用bind和check_size在一个int的vector中
// 查找第一个大于string长度的值。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
using namespace std::placeholders;
bool check_size(const string &s, string::size_type sz)
{
return s.size() < sz;
}
int main()
{
string s = "www";
vector<int> v = {1, 2, 3, 4, 5};
auto it = find_if(v.begin(), v.end(), bind(check_size, s, _1));
if (it != v.end())
cout << *it << endl;
else
cout << "not find" << endl;
return 0;
}
|
{
"pile_set_name": "Github"
}
|
/*!
* 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.
*/
@mixin border-image($borders...) {
$webkit-borders: ();
$spec-borders: ();
@each $border in $borders {
$webkit-border: ();
$spec-border: ();
$border-type: type-of($border);
@if $border-type == string or list {
$border-str: if($border-type == list, nth($border, 1), $border);
$url-str: str-slice($border-str, 1, 3);
$gradient-type: str-slice($border-str, 1, 6);
@if $url-str == "url" {
$webkit-border: $border;
$spec-border: $border;
}
@else if $gradient-type == "linear" {
$gradients: _linear-gradient-parser("#{$border}");
$webkit-border: map-get($gradients, webkit-image);
$spec-border: map-get($gradients, spec-image);
}
@else if $gradient-type == "radial" {
$gradients: _radial-gradient-parser("#{$border}");
$webkit-border: map-get($gradients, webkit-image);
$spec-border: map-get($gradients, spec-image);
}
@else {
$webkit-border: $border;
$spec-border: $border;
}
}
@else {
$webkit-border: $border;
$spec-border: $border;
}
$webkit-borders: append($webkit-borders, $webkit-border, comma);
$spec-borders: append($spec-borders, $spec-border, comma);
}
-webkit-border-image: $webkit-borders;
border-image: $spec-borders;
border-style: solid;
}
//Examples:
// @include border-image(url("image.png"));
// @include border-image(url("image.png") 20 stretch);
// @include border-image(linear-gradient(45deg, orange, yellow));
// @include border-image(linear-gradient(45deg, orange, yellow) stretch);
// @include border-image(linear-gradient(45deg, orange, yellow) 20 30 40 50 stretch round);
// @include border-image(radial-gradient(top, cover, orange, yellow, orange));
|
{
"pile_set_name": "Github"
}
|
const foo = require('./foo.json');
const bar = require('./bar');
module.exports = {
// 同时支持 GET 和 POST
'/api/users/1': foo,
'/api/foo/bar': bar(),
// 支持标准 HTTP
'GET /api/users': { users: [1, 2] },
'DELETE /api/users': { users: [1, 2] },
// 支持自定义函数,API 参考 express4
'POST /api/users/create': (req, res) => {
res.end('OK');
},
// 支持参数
'POST /api/users/:id': (req, res) => {
const { id } = req.params;
res.send({ id });
},
};
|
{
"pile_set_name": "Github"
}
|
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin,race linux,race freebsd,race
package unix
import (
"runtime"
"unsafe"
)
const raceenabled = true
func raceAcquire(addr unsafe.Pointer) {
runtime.RaceAcquire(addr)
}
func raceReleaseMerge(addr unsafe.Pointer) {
runtime.RaceReleaseMerge(addr)
}
func raceReadRange(addr unsafe.Pointer, len int) {
runtime.RaceReadRange(addr, len)
}
func raceWriteRange(addr unsafe.Pointer, len int) {
runtime.RaceWriteRange(addr, len)
}
|
{
"pile_set_name": "Github"
}
|
using GameObject;
using Lidgren.Network;
using SS13_Shared;
using SS13_Shared.GO;
using SS13_Shared.GO.Component.Item;
namespace CGO
{
public class BasicItemComponent : Component
{
public Entity Holder;
public InventoryLocation HoldingHand;
public BasicItemComponent()
{
Family = ComponentFamily.Item;
}
public override System.Type StateType
{
get { return typeof (ItemComponentState); }
}
public override void HandleComponentState(dynamic state)
{
SetNewState(state);
}
private void SetNewState(ItemComponentState state)
{
if(state.Holder != null && (Holder == null || Holder.Uid != state.Holder))
{
Holder = Owner.EntityManager.GetEntity((int)state.Holder);
HoldingHand = state.InventoryLocation;
}
if(Holder != null && state.Holder == null)
{
Holder = null;
HoldingHand = state.InventoryLocation;
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
/*******************************************************************************
* Copyright (c) 2017, 2018 GK Software AG, and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Stephan Herrmann - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.core.tests.compiler.regression;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.tests.util.Util;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.batch.BasicModule;
import org.eclipse.jdt.internal.compiler.batch.CompilationUnit;
import org.eclipse.jdt.internal.compiler.batch.FileSystem;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.internal.compiler.env.IModule;
import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.lookup.TypeConstants;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
public class AbstractRegressionTest9 extends AbstractRegressionTest {
public AbstractRegressionTest9(String name) {
super(name);
}
protected Map<String,IModule> moduleMap = new HashMap<>(); // by name
protected Map<String,String> file2module = new HashMap<>();
@Override
protected void tearDown() throws Exception {
super.tearDown();
this.moduleMap.clear();
this.file2module.clear();
DefaultJavaRuntimeEnvironment.cleanUpDefaultJreClassLibs();
}
@Override
protected INameEnvironment getNameEnvironment(final String[] testFiles, String[] classPaths) {
this.classpaths = classPaths == null ? getDefaultClassPaths() : classPaths;
INameEnvironment[] classLibs = getClassLibs(classPaths == null);
for (INameEnvironment nameEnvironment : classLibs) {
((FileSystem) nameEnvironment).scanForModules(createParser());
}
return new InMemoryNameEnvironment9(testFiles, this.moduleMap, classLibs);
}
@Override
protected CompilationUnit[] getCompilationUnits(String[] testFiles) {
Map<String,char[]> moduleFiles= new HashMap<>(); // filename -> modulename
CompilationUnit[] compilationUnits = Util.compilationUnits(testFiles);
// scan for all module-info.java:
for (int i = 0; i < testFiles.length; i+=2) {
IModule module = extractModuleDesc(testFiles[i], testFiles[i+1], compilationUnits[i/2]);
if (module != null) {
this.moduleMap.put(String.valueOf(module.name()), module);
moduleFiles.put(testFiles[0], module.name());
}
}
// record module information in CUs:
for (int i = 0; i < compilationUnits.length; i++) {
char[] fileName = compilationUnits[i].getFileName();
String fileNameString = String.valueOf(compilationUnits[i].getFileName());
if (CharOperation.endsWith(fileName, TypeConstants.MODULE_INFO_FILE_NAME)) {
compilationUnits[i].module = moduleFiles.get(fileNameString);
} else {
String modName = this.file2module.get(fileNameString.replace(File.separator, "/"));
if (modName != null) {
compilationUnits[i].module = modName.toCharArray();
}
}
}
return compilationUnits;
}
/**
* javac cannot leverage our internal map {@code file2module}, so we better
* neatly place each file into a sub directory matching the module name.
*/
protected String expandFileNameForJavac(String fileName) {
String fileNameAsKey = fileName.replace(File.separator, "/");
if (this.file2module != null && this.file2module.containsKey(fileNameAsKey)) {
fileName = new String(this.file2module.get(fileNameAsKey))+File.separator+fileName;
}
return fileName;
}
private IModule extractModuleDesc(String fileName, String fileContent, ICompilationUnit cu) {
if (fileName.toLowerCase().endsWith(IModule.MODULE_INFO_JAVA)) {
Parser parser = createParser();
CompilationResult compilationResult = new CompilationResult(cu, 0, 1, 10);
CompilationUnitDeclaration unit = parser.parse(cu, compilationResult);
if (unit.isModuleInfo() && unit.moduleDeclaration != null) {
return new BasicModule(unit.moduleDeclaration, null);
}
}
return null;
}
private Parser createParser() {
Map<String,String> opts = new HashMap<String, String>();
opts.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_9);
return new Parser(
new ProblemReporter(getErrorHandlingPolicy(), new CompilerOptions(opts), getProblemFactory()),
false);
}
// ------------------------------------------------------
/** Use in tests to associate the CU in given files to the module of the given name. */
public void associateToModule(String moduleName, String... fileNames) {
for (String fileName : fileNames)
this.file2module.put(fileName, moduleName);
}
}
|
{
"pile_set_name": "Github"
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using Composite.C1Console.Actions;
using Composite.Data;
using Composite.Data.Types;
using Composite.Core.ResourceSystem;
using Composite.Core.Types;
using Composite.C1Console.Users;
using Composite.Data.Validation;
using Composite.C1Console.Workflow;
using Composite.C1Console.Events;
using Composite.Plugins.Security.LoginProviderPlugins.DataBasedFormLoginProvider;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Composite.Core.Logging;
using Composite.C1Console.Security;
namespace Composite.Plugins.Elements.ElementProviders.UserElementProvider
{
[AllowPersistingWorkflow(WorkflowPersistingType.Idle)]
public sealed partial class AddNewUserWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow
{
private static class BindingNames
{
public const string NewUser = "NewUser";
public const string Username = "NewUser.Username";
public const string Password = "Password";
public const string UserFormLogin = "UserFormLogin";
}
public AddNewUserWorkflow()
{
InitializeComponent();
}
private void CheckActiveLanguagesExists(object sender, ConditionalEventArgs e)
{
e.Result = DataLocalizationFacade.ActiveLocalizationCultures.Any();
}
private void IsUserValid(object sender, ConditionalEventArgs e)
{
IUser newUser = this.GetBinding<IUser>(BindingNames.NewUser);
var bindedUserFormLogin = this.GetBinding<IUserFormLogin>(BindingNames.UserFormLogin);
NormalizeUsername(newUser);
ValidationResults validationResults = ValidationFacade.Validate(newUser);
bool isValid = validationResults.IsValid;
if (isValid)
{
validationResults = ValidationFacade.Validate(bindedUserFormLogin);
isValid = validationResults.IsValid;
}
if(isValid)
{
IQueryable<IUser> usersWithTheSameName =
from user in DataFacade.GetData<IUser>()
where string.Compare(user.Username, newUser.Username, StringComparison.InvariantCultureIgnoreCase) == 0
select user;
if(usersWithTheSameName.Any())
{
ShowFieldMessage(BindingNames.Username,
LocalizationFiles.Composite_Management.UserElementProvider_UserLoginIsAlreadyUsed);
isValid = false;
}
string password = this.GetBinding<string>(BindingNames.Password);
IList<string> validationMessages;
if (!PasswordPolicyFacade.ValidatePassword(newUser, password, out validationMessages))
{
foreach (var message in validationMessages)
{
this.ShowFieldMessage(BindingNames.Password, message);
}
isValid = false;
}
}
e.Result = isValid;
}
private void MissingActiveLanguageCodeActivity_ExecuteCode(object sender, EventArgs e)
{
var flowControllerServicesContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId);
var managementConsoleMessageService = flowControllerServicesContainer.GetService<IManagementConsoleMessageService>();
managementConsoleMessageService.ShowMessage(
DialogType.Message,
LocalizationFiles.Composite_Management.UserElementProvider_MissingActiveLanguageTitle,
LocalizationFiles.Composite_Management.UserElementProvider_MissingActiveLanguageMessage);
}
private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e)
{
IUser newUser = DataFacade.BuildNew<IUser>();
newUser.Id = Guid.NewGuid();
var userFormLogin = DataFacade.BuildNew<IUserFormLogin>();
userFormLogin.PasswordHash = "";
userFormLogin.PasswordHashSalt = "";
var groupEntityToken = this.EntityToken as UserElementProviderGroupEntityToken;
if (groupEntityToken != null)
{
userFormLogin.Folder = groupEntityToken.Id;
}
CultureInfo userCulture = UserSettings.CultureInfo; // Copy admins settings
CultureInfo c1ConsoleUiLanguage = UserSettings.C1ConsoleUiLanguage; // Copy admins settings
List<KeyValuePair> regionLanguageList = StringResourceSystemFacade.GetSupportedCulturesList();
Dictionary<string, string> culturesDictionary = StringResourceSystemFacade.GetAllCultures();
this.Bindings.Add(BindingNames.NewUser, newUser);
this.Bindings.Add(BindingNames.UserFormLogin, userFormLogin);
this.Bindings.Add("AllCultures", culturesDictionary);
this.Bindings.Add("CultureName", userCulture.Name);
this.Bindings.Add("C1ConsoleUiCultures", regionLanguageList);
this.Bindings.Add("C1ConsoleUiLanguageName", c1ConsoleUiLanguage.Name);
}
private void step1CodeActivity_ExecuteCode(object sender, EventArgs e)
{
IUser newUser = this.GetBinding<IUser>(BindingNames.NewUser);
NormalizeUsername(newUser);
ValidationResults validationResults = ValidationFacade.Validate(newUser);
foreach (ValidationResult result in validationResults)
{
this.ShowFieldMessage($"{BindingNames.NewUser}.{result.Key}", result.Message);
}
IQueryable<IUser> usersWithTheSameName =
from user in DataFacade.GetData<IUser>()
where string.Compare(user.Username, newUser.Username, StringComparison.InvariantCultureIgnoreCase) == 0
select user;
if (usersWithTheSameName.Any())
{
this.ShowFieldMessage(BindingNames.Username,
LocalizationFiles.Composite_Management.AddNewUserWorkflow_UsernameDuplicateError);
}
}
private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e)
{
AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken);
IUser newUser = this.GetBinding<IUser>(BindingNames.NewUser);
var bindedUserFormLogin = this.GetBinding<IUserFormLogin>(BindingNames.UserFormLogin);
NormalizeUsername(newUser);
string password = this.GetBinding<string>(BindingNames.Password);
newUser = DataFacade.AddNew<IUser>(newUser);
UserFormLoginManager.CreateUserFormLogin(newUser.Id, password, bindedUserFormLogin.Folder);
string cultureName = this.GetBinding<string>("CultureName");
string c1ConsoleUiLanguageName = this.GetBinding<string>("C1ConsoleUiLanguageName");
UserSettings.SetUserCultureInfo(newUser.Username, CultureInfo.CreateSpecificCulture(cultureName));
UserSettings.SetUserC1ConsoleUiLanguage(newUser.Username, CultureInfo.CreateSpecificCulture(c1ConsoleUiLanguageName));
CultureInfo locale = DataLocalizationFacade.DefaultLocalizationCulture;
UserSettings.AddActiveLocaleCultureInfo(newUser.Username, locale);
UserSettings.SetCurrentActiveLocaleCultureInfo(newUser.Username, locale);
UserSettings.SetForeignLocaleCultureInfo(newUser.Username, locale);
this.CloseCurrentView();
addNewTreeRefresher.PostRefreshMesseges(newUser.GetDataEntityToken());
LoggingService.LogEntry("UserManagement",
$"New C1 Console user '{newUser.Username}' created by '{UserValidationFacade.GetUsername()}'.",
LoggingService.Category.Audit,
TraceEventType.Information);
this.ExecuteWorklow(newUser.GetDataEntityToken(), typeof(EditUserWorkflow));
}
private static void NormalizeUsername(IUser user)
{
// User names are lower-cased
user.Username = user.Username.Trim().ToLowerInvariant();
}
}
}
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
/**
* All public methods in this class are exposed to client using API.
* Always think what kind of information you are exposing.
*/
namespace Box\Mod\Example\Api;
class Client extends \Api_Abstract
{
/**
* From client API you can call any other module API
*
* This method will collect data from all APIs and merge
* into one result.
*
* Be careful not to expose sensitive data from Admin API.
*/
public function get_info($data)
{
// call custom event hook. All active modules will be notified
$this->di['events_manager']->fire(array('event'=>'onAfterClientCalledExampleModule', 'params'=>array('key'=>'value')));
// Log message
$this->di['logger']->info('Log message to log file');
$systemService = $this->di['mod_service']('System');
$clientService = $this->di['mod_service']('Client');
$type = $this->di['array_get']($data, 'type', 'info');
return array(
'data' => $data,
'version' => $systemService->getVersion(),
'profile' => $clientService->toApiArray($this->di['loggedin_client']),
'messages' => $systemService->getMessages($type)
);
}
}
|
{
"pile_set_name": "Github"
}
|
/* vm.cc
Jeremy Barnes, 22 February 2010
Copyright (c) 2010 Jeremy Barnes. All rights reserved.
Virtual memory functions.
*/
#include "vm.h"
#include "jml/arch/format.h"
#include "jml/arch/exception.h"
#include "jml/utils/guard.h"
#include "jml/utils/info.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <boost/bind.hpp>
#include <boost/crc.hpp>
#include <fstream>
using namespace std;
namespace ML {
std::string
Pagemap_Entry::
print() const
{
if (present)
return format("P%c %09lx s 2^%-5d", (swapped ? 'S' : '.'),
pfn, (int)shift);
else if (swapped)
return format(".S %02d/%06x s 2^%-5d", (int)swap_type,
(int)swap_offset, (int)shift);
else return ".. ";
}
std::string
Page_Info::
print_mapping() const
{
return Pagemap_Entry::print();
}
std::string
Page_Info::
print_flags() const
{
const char * letters = "lerudLaswRbmAShtHUPnk";
string result;
uint64_t val = 1;
for (unsigned i = 0; i < 22; ++i) {
bool f = flags & val;
val <<= 1;
if (f) result += letters[i];
else result += '.';
}
result += format(" %06llx", (long long)flags);
return result;
}
std::string
Page_Info::
print() const
{
string result = print_mapping();
if (pfn != 0 && (count != 0 || flags != 0))
result = result + format(" c:%6lld ", (long long)count)
+ print_flags();
return result;
}
std::vector<Page_Info> page_info(const void * addr, int npages)
{
int pm_fd = open("/proc/self/pagemap", O_RDONLY);
if (pm_fd == -1)
throw Exception("open pagemap; " + string(strerror(errno)));
Call_Guard close_pm_fd(boost::bind(::close, pm_fd));
// Both of these might fail as these two files require special priviledges
// to read
int pf_fd = open("/proc/kpageflags", O_RDONLY);
int pc_fd = open("/proc/kpagecount", O_RDONLY);
// These will call guard with an fd of -1 if the files weren't open, which
// won't hurt us
Call_Guard close_pf_fd(boost::bind(::close, pf_fd), pf_fd != -1);
Call_Guard close_pc_fd(boost::bind(::close, pc_fd), pc_fd != -1);
size_t page_num = (size_t)addr / 4096;
int res = lseek(pm_fd, page_num * 8, SEEK_SET);
if (res == -1)
throw Exception("page_info(): lseek: " + string(strerror(errno)));
vector<Page_Info> result;
for (unsigned i = 0; i < npages; ++i) {
Page_Info info;
int res = read(pm_fd, &info.mapping, 8);
if (res != 8)
throw Exception("read pm_fd");
if (info.present) {
if (pf_fd != -1) {
int res = lseek(pf_fd, info.pfn * 8, SEEK_SET);
if (res == -1)
throw Exception("lseek pf_fd");
res = read(pf_fd, &info.flags, 8);
if (res != 8)
throw Exception("read flags");
}
if (pc_fd != -1) {
res = lseek(pc_fd, info.pfn * 8, SEEK_SET);
if (res == -1)
throw Exception("lseek pc_fd");
res = read(pc_fd, &info.count, 8);
if (res != 8)
throw Exception("read count");
}
}
result.push_back(info);
}
return result;
}
void dump_page_info(const void * start, const void * end,
std::ostream & stream)
{
const char * p1 = (const char *)start;
const char * p2 = (const char *)end;
size_t dist = p2 - p1;
size_t pages = dist / page_size;
size_t rem = dist % page_size;
if (rem > 0) ++pages;
if (pages > 10000)
throw Exception("dump_page_info: too many pages");
vector<Page_Info> info = page_info(start, pages);
if (info.size() != pages)
throw Exception("no pages");
const char * p = page_start(p1);
for (unsigned i = 0; i < pages; ++i, p += page_size) {
stream << format("%04x %12p ", i, p)
<< info[i] << endl;
}
}
std::vector<unsigned char> page_flags(const void * addr, int npages)
{
int pm_fd = open("/proc/self/pagemap", O_RDONLY);
if (pm_fd == -1)
throw Exception("open pagemap; " + string(strerror(errno)));
Call_Guard close_pm_fd(boost::bind(::close, pm_fd));
size_t page_num = (size_t)addr / 4096;
int res = lseek(pm_fd, page_num * 8, SEEK_SET);
if (res == -1)
throw Exception("page_info(): lseek: " + string(strerror(errno)));
vector<unsigned char> result;
result.reserve(npages);
Page_Info info;
uint64_t buf[1024];
for (unsigned i = 0; i < npages; i += 1024) {
int n = min<size_t>(1024, npages - i);
int res = read(pm_fd, buf, 8 * n);
if (res != 8 * n)
throw Exception("read pm_fd");
for (unsigned j = 0; j < n; ++j) {
info.mapping = buf[j];
result.push_back(info.present);
}
}
return result;
}
void dump_maps(std::ostream & out)
{
std::ifstream stream("/proc/self/maps");
out << string(60, '=') << endl;
out << "maps" << endl;
while (stream) {
string s;
std::getline(stream, s);
out << s << endl;
}
out << string(60, '=') << endl;
out << endl << endl;
}
/*****************************************************************************/
/* PAGEMAP_READER */
/*****************************************************************************/
Pagemap_Reader::
Pagemap_Reader(const char * mem, size_t bytes,
Pagemap_Entry * entries, int fd)
: fd(fd), mem(mem), entries(entries),
delete_entries(entries == 0), close_fd(fd == -1)
{
npages = to_page_num(mem + bytes) - to_page_num(mem);
#if 0
cerr << "mem = " << (const void *)mem << endl;
cerr << "mem + bytes = " << (const void *)(mem + bytes) << endl;
cerr << "page1 = " << to_page_num(mem + bytes) << endl;
cerr << "page2 = " << to_page_num(mem) << endl;
cerr << "bytes = " << bytes << endl;
cerr << "npages = " << npages << endl;
cerr << "pagemap_reader: fd = " << fd << endl;
#endif
if (close_fd)
this->fd = open("/proc/self/pagemap", O_RDONLY);
if (this->fd == -1)
throw Exception(errno, "Pagemap_Reader()",
"open(\"proc/self/pagemap\", O_RDONLY)");
Call_Guard do_close_fd(boost::bind(close, this->fd), close_fd);
if (delete_entries)
this->entries = new Pagemap_Entry[npages];
try {
update();
} catch (...) {
if (delete_entries) delete[] entries;
throw;
}
//cerr << "pagemap_reader init " << this
// << ": entries = " << entries << " this->entries = "
// << this->entries << " delete_entries = " << delete_entries
// << " fd = " << this->fd << endl;
do_close_fd.clear();
}
Pagemap_Reader::
~Pagemap_Reader()
{
//cerr << "pagemap_reader exit " << this
// << ": entries = " << entries << " this->entries = "
// << this->entries << " delete_entries = " << delete_entries << endl;
if (delete_entries)
delete[] entries;
if (close_fd && fd != -1) {
int res = close(fd);
if (res == -1)
cerr << "~Pagemap_Reader(): close on fd: " << strerror(errno)
<< endl;
}
entries = 0;
}
size_t
Pagemap_Reader::
update(ssize_t first_page, ssize_t last_page)
{
if (last_page == -1)
last_page = npages;
if (first_page < 0 || last_page > npages || last_page < first_page)
throw Exception("Pagemap_Reader::update(): pages out of range");
// Where do we seek to in the pagemap file?
// Counts the number of modified page map entries
size_t result = 0;
size_t CHUNK = 1024; // pages at a time
// Buffer to read them into
Pagemap_Entry buf[CHUNK];
size_t base_page_num = to_page_num(mem);
//cerr << "update: first_page = " << first_page
// << " last_page = " << last_page << endl;
// Update a chunk at a time
for (size_t page = first_page; page < last_page; /* no inc */) {
size_t limit = std::min<size_t>(page + CHUNK, last_page);
size_t todo = limit - page;
//cerr << "page = " << page << " last_page = " << last_page
// << " limit = " << limit << " todo " << todo << endl;
// Where to seek in the pagemap file?
off_t seek_pos = (base_page_num + page) * sizeof(Pagemap_Entry);
//cerr << "seek_pos = " << seek_pos << " base_page_num = "
// << base_page_num << endl;
ssize_t res = pread(fd, buf,
todo * sizeof(Pagemap_Entry),
seek_pos);
if (res <= 0) {
cerr << "fd: " << fd << " filename: " << fd_to_filename(fd)
<< endl;
}
if (res == -1)
throw Exception(errno, "Pagemap_Reader::update()", "pread");
if (res <= 0)
throw Exception("Pagemap_Reader::update(): nothing read "
"from pagemap file");
//cerr << "res = " << res << endl;
res /= sizeof(Pagemap_Entry); // convert bytes to objects
//cerr << "read " << res << " objects" << endl;
for (unsigned i = 0; i < res; ++i) {
result += this->entries[page + i] != buf[i];
this->entries[page + i] = buf[i];
}
page += res;
}
return result;
}
void
Pagemap_Reader::
dump(std::ostream & stream) const
{
const char * p = mem;
for (unsigned i = 0; i < npages; ++i, p += page_size) {
boost::crc_32_type calc_crc;
uint32_t crc = 0;
if (entries[i].present && !entries[i].swapped) {
calc_crc.process_bytes(p, page_size);
crc = calc_crc.checksum();
}
stream << format("%04x %12p ", i, p)
<< entries[i];
if (entries[i].present && !entries[i].swapped)
stream << format("%08x", crc);
stream << endl;
}
}
} // namespace ML
|
{
"pile_set_name": "Github"
}
|
module Test.Internal.KernelConstants exposing (kernelConstants)
{-| This module defines the mapping of optimized field name and enum values
for kernel code in other packages the we depend on.
-}
{-| NOTE: this is duplicating constants also defined in src/Elm/Kernel/HtmlAsJson.js
so if you make any changes here, be sure to synchronize them there!
-}
kernelConstants =
{ virtualDom =
{ nodeType = "$"
, nodeTypeText = 0
, nodeTypeKeyedNode = 2
, nodeTypeNode = 1
, nodeTypeCustom = 3
, nodeTypeTagger = 4
, nodeTypeThunk = 5
, tag = "c"
, kids = "e"
, facts = "d"
, descendantsCount = "b"
, text = "a"
, refs = "l"
, node = "k"
, tagger = "j"
, model = "g"
}
, markdown =
{ options = "a"
, markdown = "b"
}
}
|
{
"pile_set_name": "Github"
}
|
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package firehose
const (
// ErrCodeConcurrentModificationException for service response error code
// "ConcurrentModificationException".
//
// Another modification has already happened. Fetch VersionId again and use
// it to update the destination.
ErrCodeConcurrentModificationException = "ConcurrentModificationException"
// ErrCodeInvalidArgumentException for service response error code
// "InvalidArgumentException".
//
// The specified input parameter has an value that is not valid.
ErrCodeInvalidArgumentException = "InvalidArgumentException"
// ErrCodeLimitExceededException for service response error code
// "LimitExceededException".
//
// You have already reached the limit for a requested resource.
ErrCodeLimitExceededException = "LimitExceededException"
// ErrCodeResourceInUseException for service response error code
// "ResourceInUseException".
//
// The resource is already in use and not available for this operation.
ErrCodeResourceInUseException = "ResourceInUseException"
// ErrCodeResourceNotFoundException for service response error code
// "ResourceNotFoundException".
//
// The specified resource could not be found.
ErrCodeResourceNotFoundException = "ResourceNotFoundException"
// ErrCodeServiceUnavailableException for service response error code
// "ServiceUnavailableException".
//
// The service is unavailable, back off and retry the operation. If you continue
// to see the exception, throughput limits for the delivery stream may have
// been exceeded. For more information about limits and how to request an increase,
// see Amazon Kinesis Firehose Limits (http://docs.aws.amazon.com/firehose/latest/dev/limits.html).
ErrCodeServiceUnavailableException = "ServiceUnavailableException"
)
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2013 Politecnico di Torino, Italy
* TORSEC group -- http://security.polito.it
*
* Author: Roberto Sassu <roberto.sassu@polito.it>
*
* 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, version 2 of the
* License.
*
* File: ima_template_lib.h
* Header for the library of supported template fields.
*/
#ifndef __LINUX_IMA_TEMPLATE_LIB_H
#define __LINUX_IMA_TEMPLATE_LIB_H
#include <linux/seq_file.h>
#include "ima.h"
#define ENFORCE_FIELDS 0x00000001
#define ENFORCE_BUFEND 0x00000002
void ima_show_template_digest(struct seq_file *m, enum ima_show_type show,
struct ima_field_data *field_data);
void ima_show_template_digest_ng(struct seq_file *m, enum ima_show_type show,
struct ima_field_data *field_data);
void ima_show_template_string(struct seq_file *m, enum ima_show_type show,
struct ima_field_data *field_data);
void ima_show_template_sig(struct seq_file *m, enum ima_show_type show,
struct ima_field_data *field_data);
int ima_parse_buf(void *bufstartp, void *bufendp, void **bufcurp,
int maxfields, struct ima_field_data *fields, int *curfields,
unsigned long *len_mask, int enforce_mask, char *bufname);
int ima_eventdigest_init(struct ima_event_data *event_data,
struct ima_field_data *field_data);
int ima_eventname_init(struct ima_event_data *event_data,
struct ima_field_data *field_data);
int ima_eventdigest_ng_init(struct ima_event_data *event_data,
struct ima_field_data *field_data);
int ima_eventname_ng_init(struct ima_event_data *event_data,
struct ima_field_data *field_data);
int ima_eventsig_init(struct ima_event_data *event_data,
struct ima_field_data *field_data);
#endif /* __LINUX_IMA_TEMPLATE_LIB_H */
|
{
"pile_set_name": "Github"
}
|
/*
* HA-JDBC: High-Availability JDBC
* Copyright (C) 2013 Paul Ferraro
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.hajdbc.sql.io;
import java.io.IOException;
import java.io.OutputStream;
import net.sf.hajdbc.Database;
import net.sf.hajdbc.invocation.InvocationStrategies;
import net.sf.hajdbc.invocation.Invoker;
/**
* Static proxy for OutputStreams
* @author Paul Ferraro
* @param <Z> connection source
* @param <D> database
* @param <P> parent type
*/
public class OutputStreamProxy<Z, D extends Database<Z>, P> extends OutputStream
{
private final OutputStreamProxyFactory<Z, D, P> factory;
public OutputStreamProxy(OutputStreamProxyFactory<Z, D, P> factory)
{
this.factory = factory;
}
@Override
public void write(final byte[] b, final int off, final int len) throws IOException
{
OutputStreamInvoker<Z, D> invoker = new OutputStreamInvoker<Z, D>()
{
@Override
public Void invoke(D database, OutputStream output) throws IOException
{
output.write(b, off, len);
return null;
}
};
InvocationStrategies.INVOKE_ON_EXISTING.invoke(this.factory, invoker);
this.factory.record(invoker);
}
@Override
public void write(final byte[] b) throws IOException
{
OutputStreamInvoker<Z, D> invoker = new OutputStreamInvoker<Z, D>()
{
@Override
public Void invoke(D database, OutputStream output) throws IOException
{
output.write(b);
return null;
}
};
InvocationStrategies.INVOKE_ON_EXISTING.invoke(this.factory, invoker);
this.factory.record(invoker);
}
@Override
public void write(final int b) throws IOException
{
OutputStreamInvoker<Z, D> invoker = new OutputStreamInvoker<Z, D>()
{
@Override
public Void invoke(D database, OutputStream output) throws IOException
{
output.write(b);
return null;
}
};
InvocationStrategies.INVOKE_ON_EXISTING.invoke(this.factory, invoker);
this.factory.record(invoker);
}
@Override
public void flush() throws IOException
{
OutputStreamInvoker<Z, D> invoker = new OutputStreamInvoker<Z, D>()
{
@Override
public Void invoke(D database, OutputStream output) throws IOException
{
output.flush();
return null;
}
};
InvocationStrategies.INVOKE_ON_EXISTING.invoke(this.factory, invoker);
this.factory.record(invoker);
}
@Override
public void close() throws IOException
{
OutputStreamInvoker<Z, D> invoker = new OutputStreamInvoker<Z, D>()
{
@Override
public Void invoke(D database, OutputStream output) throws IOException
{
output.close();
return null;
}
};
InvocationStrategies.INVOKE_ON_EXISTING.invoke(this.factory, invoker);
this.factory.remove();
}
private interface OutputStreamInvoker<Z, D extends Database<Z>> extends Invoker<Z, D, OutputStream, Void, IOException>
{
}
}
|
{
"pile_set_name": "Github"
}
|
//===-------------- lib/Support/BranchProbability.cpp -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements Branch Probability class.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/BranchProbability.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
raw_ostream &BranchProbability::print(raw_ostream &OS) const {
return OS << N << " / " << D << " = "
<< format("%g%%", ((double)N / D) * 100.0);
}
void BranchProbability::dump() const { print(dbgs()) << '\n'; }
static uint64_t scale(uint64_t Num, uint32_t N, uint32_t D) {
assert(D && "divide by 0");
// Fast path for multiplying by 1.0.
if (!Num || D == N)
return Num;
// Split Num into upper and lower parts to multiply, then recombine.
uint64_t ProductHigh = (Num >> 32) * N;
uint64_t ProductLow = (Num & UINT32_MAX) * N;
// Split into 32-bit digits.
uint32_t Upper32 = ProductHigh >> 32;
uint32_t Lower32 = ProductLow & UINT32_MAX;
uint32_t Mid32Partial = ProductHigh & UINT32_MAX;
uint32_t Mid32 = Mid32Partial + (ProductLow >> 32);
// Carry.
Upper32 += Mid32 < Mid32Partial;
// Check for overflow.
if (Upper32 >= D)
return UINT64_MAX;
uint64_t Rem = (uint64_t(Upper32) << 32) | Mid32;
uint64_t UpperQ = Rem / D;
// Check for overflow.
if (UpperQ > UINT32_MAX)
return UINT64_MAX;
Rem = ((Rem % D) << 32) | Lower32;
uint64_t LowerQ = Rem / D;
uint64_t Q = (UpperQ << 32) + LowerQ;
// Check for overflow.
return Q < LowerQ ? UINT64_MAX : Q;
}
uint64_t BranchProbability::scale(uint64_t Num) const {
return ::scale(Num, N, D);
}
uint64_t BranchProbability::scaleByInverse(uint64_t Num) const {
return ::scale(Num, D, N);
}
|
{
"pile_set_name": "Github"
}
|
//===- llvm/Analysis/DominanceFrontier.h - Dominator Frontiers --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the DominanceFrontier class, which calculate and holds the
// dominance frontier for a function.
//
// This should be considered deprecated, don't add any more uses of this data
// structure.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_ANALYSIS_DOMINANCEFRONTIER_H
#define LLVM_ANALYSIS_DOMINANCEFRONTIER_H
#include "llvm/Analysis/Dominators.h"
#include <map>
#include <set>
namespace llvm {
//===----------------------------------------------------------------------===//
/// DominanceFrontierBase - Common base class for computing forward and inverse
/// dominance frontiers for a function.
///
class DominanceFrontierBase : public FunctionPass {
public:
typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
protected:
DomSetMapType Frontiers;
std::vector<BasicBlock*> Roots;
const bool IsPostDominators;
public:
DominanceFrontierBase(char &ID, bool isPostDom)
: FunctionPass(ID), IsPostDominators(isPostDom) {}
/// getRoots - Return the root blocks of the current CFG. This may include
/// multiple blocks if we are computing post dominators. For forward
/// dominators, this will always be a single block (the entry node).
///
inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
/// isPostDominator - Returns true if analysis based of postdoms
///
bool isPostDominator() const { return IsPostDominators; }
virtual void releaseMemory() { Frontiers.clear(); }
// Accessor interface:
typedef DomSetMapType::iterator iterator;
typedef DomSetMapType::const_iterator const_iterator;
iterator begin() { return Frontiers.begin(); }
const_iterator begin() const { return Frontiers.begin(); }
iterator end() { return Frontiers.end(); }
const_iterator end() const { return Frontiers.end(); }
iterator find(BasicBlock *B) { return Frontiers.find(B); }
const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
iterator addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
assert(find(BB) == end() && "Block already in DominanceFrontier!");
return Frontiers.insert(std::make_pair(BB, frontier)).first;
}
/// removeBlock - Remove basic block BB's frontier.
void removeBlock(BasicBlock *BB) {
assert(find(BB) != end() && "Block is not in DominanceFrontier!");
for (iterator I = begin(), E = end(); I != E; ++I)
I->second.erase(BB);
Frontiers.erase(BB);
}
void addToFrontier(iterator I, BasicBlock *Node) {
assert(I != end() && "BB is not in DominanceFrontier!");
I->second.insert(Node);
}
void removeFromFrontier(iterator I, BasicBlock *Node) {
assert(I != end() && "BB is not in DominanceFrontier!");
assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
I->second.erase(Node);
}
/// compareDomSet - Return false if two domsets match. Otherwise
/// return true;
bool compareDomSet(DomSetType &DS1, const DomSetType &DS2) const {
std::set<BasicBlock *> tmpSet;
for (DomSetType::const_iterator I = DS2.begin(),
E = DS2.end(); I != E; ++I)
tmpSet.insert(*I);
for (DomSetType::const_iterator I = DS1.begin(),
E = DS1.end(); I != E; ) {
BasicBlock *Node = *I++;
if (tmpSet.erase(Node) == 0)
// Node is in DS1 but not in DS2.
return true;
}
if (!tmpSet.empty())
// There are nodes that are in DS2 but not in DS1.
return true;
// DS1 and DS2 matches.
return false;
}
/// compare - Return true if the other dominance frontier base matches
/// this dominance frontier base. Otherwise return false.
bool compare(DominanceFrontierBase &Other) const {
DomSetMapType tmpFrontiers;
for (DomSetMapType::const_iterator I = Other.begin(),
E = Other.end(); I != E; ++I)
tmpFrontiers.insert(std::make_pair(I->first, I->second));
for (DomSetMapType::iterator I = tmpFrontiers.begin(),
E = tmpFrontiers.end(); I != E; ) {
BasicBlock *Node = I->first;
const_iterator DFI = find(Node);
if (DFI == end())
return true;
if (compareDomSet(I->second, DFI->second))
return true;
++I;
tmpFrontiers.erase(Node);
}
if (!tmpFrontiers.empty())
return true;
return false;
}
/// print - Convert to human readable form
///
virtual void print(raw_ostream &OS, const Module* = 0) const;
/// dump - Dump the dominance frontier to dbgs().
void dump() const;
};
//===-------------------------------------
/// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
/// used to compute a forward dominator frontiers.
///
class DominanceFrontier : public DominanceFrontierBase {
virtual void anchor();
public:
static char ID; // Pass ID, replacement for typeid
DominanceFrontier() :
DominanceFrontierBase(ID, false) {
initializeDominanceFrontierPass(*PassRegistry::getPassRegistry());
}
BasicBlock *getRoot() const {
assert(Roots.size() == 1 && "Should always have entry node!");
return Roots[0];
}
virtual bool runOnFunction(Function &) {
Frontiers.clear();
DominatorTree &DT = getAnalysis<DominatorTree>();
Roots = DT.getRoots();
assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
calculate(DT, DT[Roots[0]]);
return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
AU.addRequired<DominatorTree>();
}
const DomSetType &calculate(const DominatorTree &DT,
const DomTreeNode *Node);
};
} // End llvm namespace
#endif
|
{
"pile_set_name": "Github"
}
|
/* Area: ffi_call
Purpose: Check structures.
Limitations: none.
PR: none.
Originator: From the original ffitest.c */
/* { dg-do run } */
#include "ffitest.h"
typedef struct
{
double d1;
double d2;
} test_structure_2;
static test_structure_2 ABI_ATTR struct2(test_structure_2 ts)
{
ts.d1--;
ts.d2--;
return ts;
}
int main (void)
{
ffi_cif cif;
ffi_type *args[MAX_ARGS];
void *values[MAX_ARGS];
test_structure_2 ts2_arg;
ffi_type ts2_type;
ffi_type *ts2_type_elements[3];
/* This is a hack to get a properly aligned result buffer */
test_structure_2 *ts2_result =
(test_structure_2 *) malloc (sizeof(test_structure_2));
ts2_type.size = 0;
ts2_type.alignment = 0;
ts2_type.type = FFI_TYPE_STRUCT;
ts2_type.elements = ts2_type_elements;
ts2_type_elements[0] = &ffi_type_double;
ts2_type_elements[1] = &ffi_type_double;
ts2_type_elements[2] = NULL;
args[0] = &ts2_type;
values[0] = &ts2_arg;
/* Initialize the cif */
CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts2_type, args) == FFI_OK);
ts2_arg.d1 = 5.55;
ts2_arg.d2 = 6.66;
printf ("%g\n", ts2_arg.d1);
printf ("%g\n", ts2_arg.d2);
ffi_call(&cif, FFI_FN(struct2), ts2_result, values);
printf ("%g\n", ts2_result->d1);
printf ("%g\n", ts2_result->d2);
CHECK(ts2_result->d1 == 5.55 - 1);
CHECK(ts2_result->d2 == 6.66 - 1);
free (ts2_result);
exit(0);
}
|
{
"pile_set_name": "Github"
}
|
package check
import (
"fmt"
"io"
"sync"
)
// -----------------------------------------------------------------------
// Output writer manages atomic output writing according to settings.
type outputWriter struct {
m sync.Mutex
writer io.Writer
wroteCallProblemLast bool
Stream bool
Verbose bool
}
func newOutputWriter(writer io.Writer, stream, verbose bool) *outputWriter {
return &outputWriter{writer: writer, Stream: stream, Verbose: verbose}
}
func (ow *outputWriter) Write(content []byte) (n int, err error) {
ow.m.Lock()
n, err = ow.writer.Write(content)
ow.m.Unlock()
return
}
func (ow *outputWriter) WriteCallStarted(label string, c *C) {
if ow.Stream {
header := renderCallHeader(label, c, "", "\n")
ow.m.Lock()
ow.writer.Write([]byte(header))
ow.m.Unlock()
}
}
func (ow *outputWriter) WriteCallProblem(label string, c *C) {
var prefix string
if !ow.Stream {
prefix = "\n-----------------------------------" +
"-----------------------------------\n"
}
header := renderCallHeader(label, c, prefix, "\n\n")
ow.m.Lock()
ow.wroteCallProblemLast = true
ow.writer.Write([]byte(header))
if !ow.Stream {
c.logb.WriteTo(ow.writer)
}
ow.m.Unlock()
}
func (ow *outputWriter) WriteCallSuccess(label string, c *C) {
if ow.Stream || (ow.Verbose && c.kind == testKd) {
// TODO Use a buffer here.
var suffix string
if c.reason != "" {
suffix = " (" + c.reason + ")"
}
if c.status() == succeededSt {
suffix += "\t" + c.timerString()
}
suffix += "\n"
if ow.Stream {
suffix += "\n"
}
header := renderCallHeader(label, c, "", suffix)
ow.m.Lock()
// Resist temptation of using line as prefix above due to race.
if !ow.Stream && ow.wroteCallProblemLast {
header = "\n-----------------------------------" +
"-----------------------------------\n" +
header
}
ow.wroteCallProblemLast = false
ow.writer.Write([]byte(header))
ow.m.Unlock()
}
}
func renderCallHeader(label string, c *C, prefix, suffix string) string {
pc := c.method.PC()
return fmt.Sprintf("%s%s: %s: %s%s", prefix, label, niceFuncPath(pc),
niceFuncName(pc), suffix)
}
|
{
"pile_set_name": "Github"
}
|
package me.saket.dank.ui.submission;
import me.saket.dank.ui.submission.events.SubmissionChangeCommentSortClicked;
import me.saket.dank.utils.DankSubmissionRequest;
interface SubmissionUi {
void showProgress();
void hideProgress();
void acceptRequest(DankSubmissionRequest lastRequest);
void showChangeSortPopup(SubmissionChangeCommentSortClicked event, DankSubmissionRequest activeRequest);
}
|
{
"pile_set_name": "Github"
}
|
/*******************************************************************************
* Copyright (c) 2013 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.jca.utils.metagen.internal;
import java.io.File;
import com.ibm.websphere.ras.annotation.Trivial;
import com.ibm.ws.jca.utils.xml.ra.RaConnector;
import com.ibm.ws.jca.utils.xml.wlp.ra.WlpRaConnector;
/**
* Used to hold RAR, ra.xml, wlp-ra.xml, and so on files for
* a generator instance.
*/
@Trivial
public class XmlFileSet {
public File rarFile;
public File raXmlFile;
public File wlpRaXmlFile;
public RaConnector parsedXml;
public WlpRaConnector parsedWlpXml;
public String rarRaXmlFilePath;
public String rarWlpRaXmlFilePath;
@Override
public String toString() {
StringBuilder sb = new StringBuilder("XmlFileSet{");
if (rarFile != null)
sb.append("rarFile='").append(rarFile.getAbsolutePath()).append("' ");
if (raXmlFile != null)
sb.append("raXmlFile='").append(raXmlFile.getAbsolutePath()).append("' ");
if (wlpRaXmlFile != null)
sb.append("wlpRaXmlFile='").append(wlpRaXmlFile.getAbsolutePath()).append("' ");
if (rarRaXmlFilePath != null)
sb.append("rarRaXmlFilePath='").append(rarRaXmlFilePath).append("' ");
if (rarWlpRaXmlFilePath != null)
sb.append("wlpRaXmlFilePath='").append(rarWlpRaXmlFilePath).append("'");
sb.append('}');
return sb.toString();
}
}
|
{
"pile_set_name": "Github"
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Control A"]
pub ctrla: CTRLA,
#[doc = "0x01 - Reference Control"]
pub refctrl: REFCTRL,
#[doc = "0x02 - Average Control"]
pub avgctrl: AVGCTRL,
#[doc = "0x03 - Sampling Time Control"]
pub sampctrl: SAMPCTRL,
#[doc = "0x04 - Control B"]
pub ctrlb: CTRLB,
_reserved5: [u8; 2usize],
#[doc = "0x08 - Window Monitor Control"]
pub winctrl: WINCTRL,
_reserved6: [u8; 3usize],
#[doc = "0x0c - Software Trigger"]
pub swtrig: SWTRIG,
_reserved7: [u8; 3usize],
#[doc = "0x10 - Input Control"]
pub inputctrl: INPUTCTRL,
#[doc = "0x14 - Event Control"]
pub evctrl: EVCTRL,
_reserved9: [u8; 1usize],
#[doc = "0x16 - Interrupt Enable Clear"]
pub intenclr: INTENCLR,
#[doc = "0x17 - Interrupt Enable Set"]
pub intenset: INTENSET,
#[doc = "0x18 - Interrupt Flag Status and Clear"]
pub intflag: INTFLAG,
#[doc = "0x19 - Status"]
pub status: STATUS,
#[doc = "0x1a - Result"]
pub result: RESULT,
#[doc = "0x1c - Window Monitor Lower Threshold"]
pub winlt: WINLT,
_reserved15: [u8; 2usize],
#[doc = "0x20 - Window Monitor Upper Threshold"]
pub winut: WINUT,
_reserved16: [u8; 2usize],
#[doc = "0x24 - Gain Correction"]
pub gaincorr: GAINCORR,
#[doc = "0x26 - Offset Correction"]
pub offsetcorr: OFFSETCORR,
#[doc = "0x28 - Calibration"]
pub calib: CALIB,
#[doc = "0x2a - Debug Control"]
pub dbgctrl: DBGCTRL,
}
#[doc = "Control A\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ctrla](ctrla) module"]
pub type CTRLA = crate::Reg<u8, _CTRLA>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CTRLA;
#[doc = "`read()` method returns [ctrla::R](ctrla::R) reader structure"]
impl crate::Readable for CTRLA {}
#[doc = "`write(|w| ..)` method takes [ctrla::W](ctrla::W) writer structure"]
impl crate::Writable for CTRLA {}
#[doc = "Control A"]
pub mod ctrla;
#[doc = "Reference Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [refctrl](refctrl) module"]
pub type REFCTRL = crate::Reg<u8, _REFCTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _REFCTRL;
#[doc = "`read()` method returns [refctrl::R](refctrl::R) reader structure"]
impl crate::Readable for REFCTRL {}
#[doc = "`write(|w| ..)` method takes [refctrl::W](refctrl::W) writer structure"]
impl crate::Writable for REFCTRL {}
#[doc = "Reference Control"]
pub mod refctrl;
#[doc = "Average Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [avgctrl](avgctrl) module"]
pub type AVGCTRL = crate::Reg<u8, _AVGCTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _AVGCTRL;
#[doc = "`read()` method returns [avgctrl::R](avgctrl::R) reader structure"]
impl crate::Readable for AVGCTRL {}
#[doc = "`write(|w| ..)` method takes [avgctrl::W](avgctrl::W) writer structure"]
impl crate::Writable for AVGCTRL {}
#[doc = "Average Control"]
pub mod avgctrl;
#[doc = "Sampling Time Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sampctrl](sampctrl) module"]
pub type SAMPCTRL = crate::Reg<u8, _SAMPCTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SAMPCTRL;
#[doc = "`read()` method returns [sampctrl::R](sampctrl::R) reader structure"]
impl crate::Readable for SAMPCTRL {}
#[doc = "`write(|w| ..)` method takes [sampctrl::W](sampctrl::W) writer structure"]
impl crate::Writable for SAMPCTRL {}
#[doc = "Sampling Time Control"]
pub mod sampctrl;
#[doc = "Control B\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ctrlb](ctrlb) module"]
pub type CTRLB = crate::Reg<u16, _CTRLB>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CTRLB;
#[doc = "`read()` method returns [ctrlb::R](ctrlb::R) reader structure"]
impl crate::Readable for CTRLB {}
#[doc = "`write(|w| ..)` method takes [ctrlb::W](ctrlb::W) writer structure"]
impl crate::Writable for CTRLB {}
#[doc = "Control B"]
pub mod ctrlb;
#[doc = "Window Monitor Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [winctrl](winctrl) module"]
pub type WINCTRL = crate::Reg<u8, _WINCTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WINCTRL;
#[doc = "`read()` method returns [winctrl::R](winctrl::R) reader structure"]
impl crate::Readable for WINCTRL {}
#[doc = "`write(|w| ..)` method takes [winctrl::W](winctrl::W) writer structure"]
impl crate::Writable for WINCTRL {}
#[doc = "Window Monitor Control"]
pub mod winctrl;
#[doc = "Software Trigger\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [swtrig](swtrig) module"]
pub type SWTRIG = crate::Reg<u8, _SWTRIG>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SWTRIG;
#[doc = "`read()` method returns [swtrig::R](swtrig::R) reader structure"]
impl crate::Readable for SWTRIG {}
#[doc = "`write(|w| ..)` method takes [swtrig::W](swtrig::W) writer structure"]
impl crate::Writable for SWTRIG {}
#[doc = "Software Trigger"]
pub mod swtrig;
#[doc = "Input Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [inputctrl](inputctrl) module"]
pub type INPUTCTRL = crate::Reg<u32, _INPUTCTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INPUTCTRL;
#[doc = "`read()` method returns [inputctrl::R](inputctrl::R) reader structure"]
impl crate::Readable for INPUTCTRL {}
#[doc = "`write(|w| ..)` method takes [inputctrl::W](inputctrl::W) writer structure"]
impl crate::Writable for INPUTCTRL {}
#[doc = "Input Control"]
pub mod inputctrl;
#[doc = "Event Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [evctrl](evctrl) module"]
pub type EVCTRL = crate::Reg<u8, _EVCTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _EVCTRL;
#[doc = "`read()` method returns [evctrl::R](evctrl::R) reader structure"]
impl crate::Readable for EVCTRL {}
#[doc = "`write(|w| ..)` method takes [evctrl::W](evctrl::W) writer structure"]
impl crate::Writable for EVCTRL {}
#[doc = "Event Control"]
pub mod evctrl;
#[doc = "Interrupt Enable Clear\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [intenclr](intenclr) module"]
pub type INTENCLR = crate::Reg<u8, _INTENCLR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTENCLR;
#[doc = "`read()` method returns [intenclr::R](intenclr::R) reader structure"]
impl crate::Readable for INTENCLR {}
#[doc = "`write(|w| ..)` method takes [intenclr::W](intenclr::W) writer structure"]
impl crate::Writable for INTENCLR {}
#[doc = "Interrupt Enable Clear"]
pub mod intenclr;
#[doc = "Interrupt Enable Set\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [intenset](intenset) module"]
pub type INTENSET = crate::Reg<u8, _INTENSET>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTENSET;
#[doc = "`read()` method returns [intenset::R](intenset::R) reader structure"]
impl crate::Readable for INTENSET {}
#[doc = "`write(|w| ..)` method takes [intenset::W](intenset::W) writer structure"]
impl crate::Writable for INTENSET {}
#[doc = "Interrupt Enable Set"]
pub mod intenset;
#[doc = "Interrupt Flag Status and Clear\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [intflag](intflag) module"]
pub type INTFLAG = crate::Reg<u8, _INTFLAG>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTFLAG;
#[doc = "`read()` method returns [intflag::R](intflag::R) reader structure"]
impl crate::Readable for INTFLAG {}
#[doc = "`write(|w| ..)` method takes [intflag::W](intflag::W) writer structure"]
impl crate::Writable for INTFLAG {}
#[doc = "Interrupt Flag Status and Clear"]
pub mod intflag;
#[doc = "Status\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [status](status) module"]
pub type STATUS = crate::Reg<u8, _STATUS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _STATUS;
#[doc = "`read()` method returns [status::R](status::R) reader structure"]
impl crate::Readable for STATUS {}
#[doc = "Status"]
pub mod status;
#[doc = "Result\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [result](result) module"]
pub type RESULT = crate::Reg<u16, _RESULT>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RESULT;
#[doc = "`read()` method returns [result::R](result::R) reader structure"]
impl crate::Readable for RESULT {}
#[doc = "Result"]
pub mod result;
#[doc = "Window Monitor Lower Threshold\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [winlt](winlt) module"]
pub type WINLT = crate::Reg<u16, _WINLT>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WINLT;
#[doc = "`read()` method returns [winlt::R](winlt::R) reader structure"]
impl crate::Readable for WINLT {}
#[doc = "`write(|w| ..)` method takes [winlt::W](winlt::W) writer structure"]
impl crate::Writable for WINLT {}
#[doc = "Window Monitor Lower Threshold"]
pub mod winlt;
#[doc = "Window Monitor Upper Threshold\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [winut](winut) module"]
pub type WINUT = crate::Reg<u16, _WINUT>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WINUT;
#[doc = "`read()` method returns [winut::R](winut::R) reader structure"]
impl crate::Readable for WINUT {}
#[doc = "`write(|w| ..)` method takes [winut::W](winut::W) writer structure"]
impl crate::Writable for WINUT {}
#[doc = "Window Monitor Upper Threshold"]
pub mod winut;
#[doc = "Gain Correction\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gaincorr](gaincorr) module"]
pub type GAINCORR = crate::Reg<u16, _GAINCORR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GAINCORR;
#[doc = "`read()` method returns [gaincorr::R](gaincorr::R) reader structure"]
impl crate::Readable for GAINCORR {}
#[doc = "`write(|w| ..)` method takes [gaincorr::W](gaincorr::W) writer structure"]
impl crate::Writable for GAINCORR {}
#[doc = "Gain Correction"]
pub mod gaincorr;
#[doc = "Offset Correction\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [offsetcorr](offsetcorr) module"]
pub type OFFSETCORR = crate::Reg<u16, _OFFSETCORR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _OFFSETCORR;
#[doc = "`read()` method returns [offsetcorr::R](offsetcorr::R) reader structure"]
impl crate::Readable for OFFSETCORR {}
#[doc = "`write(|w| ..)` method takes [offsetcorr::W](offsetcorr::W) writer structure"]
impl crate::Writable for OFFSETCORR {}
#[doc = "Offset Correction"]
pub mod offsetcorr;
#[doc = "Calibration\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [calib](calib) module"]
pub type CALIB = crate::Reg<u16, _CALIB>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CALIB;
#[doc = "`read()` method returns [calib::R](calib::R) reader structure"]
impl crate::Readable for CALIB {}
#[doc = "`write(|w| ..)` method takes [calib::W](calib::W) writer structure"]
impl crate::Writable for CALIB {}
#[doc = "Calibration"]
pub mod calib;
#[doc = "Debug Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dbgctrl](dbgctrl) module"]
pub type DBGCTRL = crate::Reg<u8, _DBGCTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DBGCTRL;
#[doc = "`read()` method returns [dbgctrl::R](dbgctrl::R) reader structure"]
impl crate::Readable for DBGCTRL {}
#[doc = "`write(|w| ..)` method takes [dbgctrl::W](dbgctrl::W) writer structure"]
impl crate::Writable for DBGCTRL {}
#[doc = "Debug Control"]
pub mod dbgctrl;
|
{
"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.
//
////////////////////////////////////////////////////////////////////////////////
{
"config": "royale",
"compilerOptions": {
"debug": false,
"targets": ["JSRoyale"],
"source-map": true,
"html-template": "src/main/resources/jewel-example-index-template.html",
"theme": "${royalelib}/themes/Jewel-Light-NoFlat-Primary-Blue-Theme/src/main/resources/defaults.css"
},
"additionalOptions": "-remove-circulars -js-output-optimization=skipAsCoercions",
"files":
[
"src/main/royale/BE0007_Selecting_options_from_a_group_of_jewel_checkbox_controls.mxml"
]
}
|
{
"pile_set_name": "Github"
}
|
/* eslint-disable func-names */
/**
* Webpack's `externals` equivalent object,
* listing dependencies that Frint packages use.
*/
import webpackRxJsExternals from './utils/webpackRxjsExternals';
export const rxjs = [webpackRxJsExternals()];
export const lodash = [
function (context, request, callback) {
if (request.startsWith('lodash/')) {
const subModule = request.split('/')[1];
return callback(null, {
root: ['_', subModule],
commonjs: request,
commonjs2: request,
amd: request,
});
}
return callback();
}
];
// full imports
export const thirdParties = [{
'lodash': {
root: '_',
commonjs: 'lodash',
commonjs2: 'lodash',
amd: 'lodash',
},
}, {
'rxjs': {
root: 'Rx',
commonjs: 'rxjs',
commonjs2: 'rxjs',
amd: 'rxjs',
},
}, {
'react': {
root: 'React',
commonjs: 'react',
commonjs2: 'react',
amd: 'react',
},
}, {
'react-dom': {
root: 'ReactDOM',
commonjs: 'react-dom',
commonjs2: 'react-dom',
amd: 'react-dom'
}
}, {
'prop-types': {
root: 'PropTypes',
commonjs: 'prop-types',
commonjs2: 'prop-types',
amd: 'prop-types',
}
}];
export const frint = [{
'frint': {
root: 'Frint',
commonjs: 'frint',
commonjs2: 'frint',
amd: 'frint'
},
}, {
'frint-store': {
root: 'FrintStore',
commonjs: 'frint-store',
commonjs2: 'frint-store',
amd: 'frint-store'
},
}, {
'frint-model': {
root: 'FrintModel',
commonjs: 'frint-model',
commonjs2: 'frint-model',
amd: 'frint-model'
},
}, {
'frint-data': {
root: 'FrintData',
commonjs: 'frint-data',
commonjs2: 'frint-data',
amd: 'frint-data'
},
}, {
'frint-react': {
root: 'FrintReact',
commonjs: 'frint-react',
commonjs2: 'frint-react',
amd: 'frint-react'
},
}, {
'frint-router': {
root: 'FrintRouter',
commonjs: 'frint-router',
commonjs2: 'frint-router',
amd: 'frint-router'
},
}, {
'frint-router-react': {
root: 'FrintRouterReact',
commonjs: 'frint-router-react',
commonjs2: 'frint-router-react',
amd: 'frint-router-react'
}
}];
export default rxjs
.concat(lodash)
.concat(thirdParties);
|
{
"pile_set_name": "Github"
}
|
import os
import sys
if sys.version_info[0] == 2:
_ENCODE = sys.getfilesystemencoding()
def path_join(*args):
bin_args = map(lambda a: a.decode(_ENCODE), args)
return os.path.join(*bin_args).encode(_ENCODE)
def str_join(s, l):
bin_args = map(lambda a: a.decode(_ENCODE), l)
b = s.decode(_ENCODE)
return b.join(bin_args).encode(_ENCODE)
logfile_open = open
else:
path_join = os.path.join
str_join = str.join
def logfile_open(*args):
return open(*args, errors='replace')
|
{
"pile_set_name": "Github"
}
|
/* Copyright 2014-2020 Go For It! developers
*
* This file is part of Go For It!.
*
* Go For It! is free software: you can redistribute it
* and/or modify it under the terms of version 3 of the
* GNU General Public License as published by the Free Software Foundation.
*
* Go For It! 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 Go For It!. If not, see http://www.gnu.org/licenses/.
*/
namespace GOFI {
public KeyBindingSettings kbsettings;
private SettingsManager settings = null;
private ActivityLog activity_log = null;
private ListManager list_manager = null;
}
errordomain GOFIParseError {
TOO_FEW_ARGS,
TOO_MANY_ARGS,
BAD_VALUE,
PARAM_NOT_UNIQUE
}
/**
* The main application class that is responsible for initiating all
* necessary steps to create a running instance of "Go For It!".
*/
class GOFI.Main : Gtk.Application {
private TaskTimer task_timer;
private MainWindow win;
private static bool print_version = false;
private static bool show_about_dialog = false;
private static bool list_lists = false;
private static string? logfile = null;
private static string[] load_list = null;
private void load_settings () {
if (settings == null) {
settings = new SettingsManager.load_from_key_file ();
}
}
private void load_list_manager () {
if (list_manager == null) {
list_manager = new ListManager ();
}
}
/**
* Used to determine if a notification should be sent.
*/
private bool break_previously_active { get; set; default = false; }
/**
* Constructor of the Application class.
*/
public Main () {
Object (application_id: GOFI.APP_ID, flags: ApplicationFlags.HANDLES_COMMAND_LINE);
}
public void new_window () {
load_settings ();
load_list_manager ();
assert (list_manager != null);
TodoListInfo? info = null;
if (load_list != null) {
info = list_manager.get_list_info (load_list[0], load_list[1]);
if (info == null) {
stdout.printf (_("Not a known list: %s"),
new ListIdentifier(
load_list[0],
load_list[1]
).to_string ()
);
load_list = null;
return;
}
load_list = null;
}
// Don't create a new window, if one already exists
if (win != null) {
if (info != null) {
win.on_list_chosen (info);
}
win.show ();
win.present ();
return;
}
task_timer = new TaskTimer ();
// Enable Notifications for the App
Notify.init (GOFI.APP_NAME);
setup_notifications ();
kbsettings = new KeyBindingSettings ();
if (info == null) {
info = get_last_list_info ();
}
win = new MainWindow (this, task_timer, info);
win.show_all ();
}
private TodoListInfo? get_last_list_info () {
var last_loaded = settings.list_last_loaded;
if (last_loaded != null) {
var list = list_manager.get_list_info (last_loaded.provider, last_loaded.id);
if (list != null) {
return list;
}
}
return null;
}
public void show_about (Gtk.Window? parent = null) {
var dialog = new AboutDialog (parent);
dialog.run ();
}
public override int command_line (ApplicationCommandLine command_line) {
hold ();
int res = _command_line (command_line);
release ();
return res;
}
/**
* Removes arguments from args. This frees the args located at pos and
* shrinks args.
*/
private static void remove_args (ref string[] args, int pos, int length) {
for (int i = 0; i < length; i++) {
args[pos+i] = null;
}
int to_move = args.length - pos - length;
int old_length = args.length;
if (to_move > 0) {
args.move (pos+length, pos, to_move);
}
args.length = old_length - length;
}
/**
* This function performs manual parsing of parameters that have multiple
* arguments. OptionContext.parse_strv isn't able to do that at this time.
*/
private void multi_arg_parse (ref string[] args) throws GOFIParseError {
int i = 0;
for (; i < args.length; i++) {
if (args[i] == "--load") {
if (i+2 < args.length && args[i+1][0] != '-' && args[i+2][0] != '-') {
if (i+3 != args.length && args[i+3][0] != '-') {
throw new GOFIParseError.TOO_MANY_ARGS(
"Too many arguments for --load: \"%s\"", args[i+3]
);
}
load_list = {args[i+1], args[i+2]};
remove_args (ref args, i ,3);
break;
} else {
throw new GOFIParseError.TOO_FEW_ARGS("Missing arguments for --load");
}
}
}
for (; i < args.length; i++) {
if (args[i] == "--load") {
throw new GOFIParseError.PARAM_NOT_UNIQUE(
"Second --load parameter encountered!" + "\n" +
"Only one list can be loaded at a time"
);
}
}
}
private int _command_line (ApplicationCommandLine command_line) {
var context = new OptionContext (null);
context.add_main_entries (entries, GOFI.EXEC_NAME);
context.add_main_entries (get_dynamic_entries (), GOFI.EXEC_NAME);
context.add_group (Gtk.get_option_group (true));
string[] args = command_line.get_arguments ();
try {
multi_arg_parse (ref args);
context.parse_strv (ref args);
} catch (Error e) {
stdout.printf (_("%s: Error: %s") + "\n", GOFI.APP_NAME, e.message);
return 0;
}
if (print_version) {
stdout.printf ("%s %s\n", GOFI.APP_NAME, GOFI.APP_VERSION);
stdout.printf ("Copyright 2014-2020 'Go For it!' Developers.\n");
} else if (show_about_dialog) {
show_about ();
} else if (list_lists) {
load_settings ();
load_list_manager ();
stdout.printf (_("Lists (List type : List ID - List name)") + ":\n");
foreach (var info in list_manager.get_list_infos ()) {
stdout.printf ("\"%s\" : \"%s\" - \"%s\"\n", info.provider_name, info.id, info.name);
}
} else {
if (logfile != null) {
// resolving ~, useful if --logfile=~/something is used
// (The user probably doesn't mean that it wants to create a
// folder called ~)
// Doing this is probably non standard, but I think that its
// better to be helpful than to confuse the user.
if (logfile.get(0) == '~' && logfile.get(1) == '/') {
logfile = Environment.get_home_dir () + logfile.offset(1);
}
activity_log = new ActivityLog (File.new_for_commandline_arg (logfile));
} else if (activity_log == null) {
activity_log = new ActivityLog (null);
}
new_window ();
}
return 0;
}
const OptionEntry[] entries = {
{ "version", 'v', 0, OptionArg.NONE, out print_version, N_("Print version info and exit"), null },
{ "about", 'a', 0, OptionArg.NONE, out show_about_dialog, N_("Show about dialog"), null },
{ "logfile", 0, 0, OptionArg.FILENAME, out logfile, N_("CSV file to log activities to."), N_("FILE") },
{ "list", 0, 0, OptionArg.NONE, out list_lists, N_("Show configured lists and exit"), null},
{ null }
};
private const string load_entry_descr = N_("Load the list specified by the list type and ID");
private string load_entry_name = "load" + " " + _("LIST-TYPE") + " " + _("LIST-ID");
private OptionEntry[] get_dynamic_entries () {
return {
OptionEntry () {
long_name = load_entry_name,
short_name = 0,
flags = 0,
arg = OptionArg.NONE,
arg_data = null,
description = load_entry_descr,
arg_description = null
},
OptionEntry () { // empty OptionEntry to null terminate list
long_name = null,
short_name = 0,
flags = 0,
arg = 0,
arg_data = null,
description = null,
arg_description = null
}
};
}
/**
* Configures the emission of notifications when tasks/breaks are over
*/
private void setup_notifications () {
task_timer.active_task_changed.connect (task_timer_activated);
task_timer.timer_almost_over.connect (display_almost_over_notification);
task_timer.task_duration_exceeded.connect (display_duration_exceeded);
}
private void task_timer_activated (TodoTask? task, bool break_active) {
if (task == null) {
return;
}
if (break_previously_active != break_active) {
Notify.Notification notification;
if (break_active) {
notification = new Notify.Notification (
_("Take a Break"),
_("Relax and stop thinking about your current task for a while")
+ " :-)",
GOFI.EXEC_NAME);
} else {
notification = new Notify.Notification (
_("The Break is Over"),
_("Your current task is") + ": " + task.description,
GOFI.EXEC_NAME);
}
notification.set_hint (
"desktop-entry", new Variant.string (GOFI.APP_SYSTEM_NAME)
);
try {
notification.show ();
} catch (GLib.Error err){
GLib.stderr.printf (
"Error in notify! (break_active notification)\n");
}
}
break_previously_active = break_active;
}
private void display_almost_over_notification (uint remaining_time) {
Notify.Notification notification = new Notify.Notification (
_("Prepare for your break"),
_("You have %s seconds left").printf (remaining_time.to_string ()),
GOFI.EXEC_NAME
);
notification.set_hint (
"desktop-entry", new Variant.string (GOFI.APP_SYSTEM_NAME)
);
try {
notification.show ();
} catch (GLib.Error err){
GLib.stderr.printf (
"Error in notify! (remaining_time notification)\n");
}
}
private void display_duration_exceeded () {
Notify.Notification notification = new Notify.Notification (
_("Task duration exceeded"),
_("Consider switching to a different task"), GOFI.EXEC_NAME);
try {
notification.show ();
} catch (GLib.Error err){
GLib.stderr.printf (
"Error in notify! (remaining_time notification)\n");
}
}
}
|
{
"pile_set_name": "Github"
}
|
{
"accountLinkingWhitelistedDomains": null,
"asin": "B01MEF6JVS",
"averageRating": 3.3,
"canDisable": true,
"capabilities": null,
"category": null,
"description": "Ever want a quick tip to make your life better? Better Life provides exactly that. Listen to short, proven tips for better living whenever you want.",
"enablement": null,
"exampleInteractions": [
"Alexa start better life",
"Alexa ask better life for a fact",
"Alexa open better life"
],
"firstReleaseDate": 1476763911.904,
"homepageLinkText": null,
"homepageLinkUrl": null,
"id": "amzn1.ask.skill.d71b7423-28d9-4c2f-9b07-23358145d567",
"imageAltText": "Better Life tips for modern living icon",
"imageUrl": "https://github.com/dale3h/alexa-skills-list/raw/master/skills/B01MEF6JVS/skill_icon",
"inAppPurchasingSupported": false,
"launchPhrase": "better life",
"name": "Better Life tips for modern living",
"numberOfReviews": 5,
"pamsPartnerId": null,
"permissions": null,
"privacyPolicyUrl": null,
"shortDescription": "Better Life - tips for modern living",
"skillTypes": null,
"stage": "live",
"termsOfUseUrl": null,
"vendorId": "M7LOAMHE7R8YH",
"vendorName": "Andy Roberts"
}
|
{
"pile_set_name": "Github"
}
|
import {
UPDATE_ORDER_BOOK,
CLEAR_ORDER_BOOK
} from "modules/orders/actions/update-order-book";
import { RESET_STATE } from "modules/app/actions/reset-state";
const DEFAULT_STATE = {};
/**
* @param {Object} orderBooks
* @param {Object} action
*/
export default function(orderBooks = DEFAULT_STATE, { type, data }) {
switch (type) {
case UPDATE_ORDER_BOOK: {
const { marketId, outcome, orderTypeLabel, orderBook } = data;
const marketOrderBook = orderBooks[marketId] || {};
const outcomeOrderBook = marketOrderBook[outcome] || {};
return {
...orderBooks,
[marketId]: {
...marketOrderBook,
[outcome]: {
...outcomeOrderBook,
[orderTypeLabel]: {
...(outcomeOrderBook[orderTypeLabel] || {}),
...orderBook
}
}
}
};
}
case CLEAR_ORDER_BOOK: {
const { marketId, outcome, orderTypeLabel } = data;
const marketOrderBook = orderBooks[marketId] || {};
const outcomeOrderBook = marketOrderBook[outcome] || {};
return {
...orderBooks,
[marketId]: {
...marketOrderBook,
[outcome]: {
...outcomeOrderBook,
[orderTypeLabel]: {}
}
}
};
}
case RESET_STATE:
return DEFAULT_STATE;
default:
return orderBooks;
}
}
|
{
"pile_set_name": "Github"
}
|
import java.util.Objects;
/**
* 学生类
*
* @author fraser
* @date 2019/12/16 9:34 PM
*/
public class Student {
private String name;
private int age;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2018, Yahoo Inc.
* Copyright 2018, the original author or authors.
* Licensed under the Apache License, Version 2.0
* See LICENSE file in project root for terms.
*/
package com.yahoo.elide.core;
import static com.yahoo.elide.core.EntityBinding.EMPTY_BINDING;
import com.yahoo.elide.Injector;
import com.yahoo.elide.annotation.ComputedAttribute;
import com.yahoo.elide.annotation.ComputedRelationship;
import com.yahoo.elide.annotation.Exclude;
import com.yahoo.elide.annotation.Include;
import com.yahoo.elide.annotation.MappedInterface;
import com.yahoo.elide.annotation.SecurityCheck;
import com.yahoo.elide.annotation.SharePermission;
import com.yahoo.elide.core.exceptions.HttpStatusException;
import com.yahoo.elide.core.exceptions.InternalServerErrorException;
import com.yahoo.elide.core.exceptions.InvalidAttributeException;
import com.yahoo.elide.functions.LifeCycleHook;
import com.yahoo.elide.security.checks.Check;
import com.yahoo.elide.security.checks.prefab.Collections.AppendOnly;
import com.yahoo.elide.security.checks.prefab.Collections.RemoveOnly;
import com.yahoo.elide.security.checks.prefab.Common;
import com.yahoo.elide.security.checks.prefab.Role;
import com.yahoo.elide.utils.ClassScanner;
import com.yahoo.elide.utils.coerce.CoerceUtil;
import com.yahoo.elide.utils.coerce.converters.Serde;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.Maps;
import org.antlr.v4.runtime.tree.ParseTree;
import org.apache.commons.lang3.StringUtils;
import lombok.extern.slf4j.Slf4j;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.persistence.AccessType;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Transient;
import javax.ws.rs.WebApplicationException;
/**
* Entity Dictionary maps JSON API Entity beans to/from Entity type names.
*
* @see Include#type
*/
@Slf4j
@SuppressWarnings("static-method")
public class EntityDictionary {
protected final ConcurrentHashMap<String, Class<?>> bindJsonApiToEntity = new ConcurrentHashMap<>();
protected final ConcurrentHashMap<Class<?>, EntityBinding> entityBindings = new ConcurrentHashMap<>();
protected final CopyOnWriteArrayList<Class<?>> bindEntityRoots = new CopyOnWriteArrayList<>();
protected final ConcurrentHashMap<Class<?>, List<Class<?>>> subclassingEntities = new ConcurrentHashMap<>();
protected final BiMap<String, Class<? extends Check>> checkNames;
protected final Injector injector;
protected final Function<Class, Serde> serdeLookup ;
public final static String REGULAR_ID_NAME = "id";
private final static ConcurrentHashMap<Class, String> SIMPLE_NAMES = new ConcurrentHashMap<>();
/**
* Instantiate a new EntityDictionary with the provided set of checks. In addition all of the checks
* in {@link com.yahoo.elide.security.checks.prefab} are mapped to {@code Prefab.CONTAINER.CHECK}
* (e.g. {@code @ReadPermission(expression="Prefab.Role.All")}
* or {@code @ReadPermission(expression="Prefab.Common.UpdateOnCreate")})
* @param checks a map that links the identifiers used in the permission expression strings
* to their implementing classes
*/
public EntityDictionary(Map<String, Class<? extends Check>> checks) {
this(checks, null);
}
/**
* Instantiate a new EntityDictionary with the provided set of checks and an injection function.
* In addition all of the checks * in {@link com.yahoo.elide.security.checks.prefab} are mapped
* to {@code Prefab.CONTAINER.CHECK} * (e.g. {@code @ReadPermission(expression="Prefab.Role.All")}
* or {@code @ReadPermission(expression="Prefab.Common.UpdateOnCreate")})
* @param checks a map that links the identifiers used in the permission expression strings
* to their implementing classes
* @param injector a function typically associated with a dependency injection framework that will
* initialize Elide models.
*/
public EntityDictionary(Map<String, Class<? extends Check>> checks, Injector injector) {
this(checks, injector, CoerceUtil::lookup);
}
public EntityDictionary(Map<String, Class<? extends Check>> checks,
Injector injector,
Function<Class, Serde> serdeLookup) {
this.serdeLookup = serdeLookup;
checkNames = Maps.synchronizedBiMap(HashBiMap.create(checks));
addPrefabCheck("Prefab.Role.All", Role.ALL.class);
addPrefabCheck("Prefab.Role.None", Role.NONE.class);
addPrefabCheck("Prefab.Collections.AppendOnly", AppendOnly.class);
addPrefabCheck("Prefab.Collections.RemoveOnly", RemoveOnly.class);
addPrefabCheck("Prefab.Common.UpdateOnCreate", Common.UpdateOnCreate.class);
this.injector = injector;
}
private void addPrefabCheck(String alias, Class<? extends Check> checkClass) {
if (checkNames.containsKey(alias) || checkNames.inverse().containsKey(checkClass)) {
return;
}
checkNames.put(alias, checkClass);
}
private static Package getParentPackage(Package pkg) {
String name = pkg.getName();
int idx = name.lastIndexOf('.');
return idx == -1 ? null : Package.getPackage(name.substring(0, idx));
}
/**
* Cache the simple name of the provided class.
* @param cls the {@code Class} object to be checked
* @return simple name
*/
public static String getSimpleName(Class<?> cls) {
return SIMPLE_NAMES.computeIfAbsent(cls, key -> cls.getSimpleName());
}
/**
* Find an arbitrary method.
*
* @param entityClass the entity class
* @param name the name
* @param paramClass the param class
* @return method method
* @throws NoSuchMethodException the no such method exception
*/
public static Method findMethod(Class<?> entityClass, String name, Class<?>... paramClass)
throws NoSuchMethodException {
Method m = entityClass.getMethod(name, paramClass);
int modifiers = m.getModifiers();
if (Modifier.isAbstract(modifiers)
|| m.isAnnotationPresent(Transient.class)
&& !m.isAnnotationPresent(ComputedAttribute.class)
&& !m.isAnnotationPresent(ComputedRelationship.class)) {
throw new NoSuchMethodException(name);
}
return m;
}
/**
* Returns an entity binding if the provided class has been bound in the dictionary.
* Otherwise the behavior depends on whether the unbound class is an Entity or not.
* If it is not an Entity, we return an EMPTY_BINDING. This preserves existing behavior for relationships
* which are entities but not bound. Otherwise, we throw an exception - which also preserves behavior
* for unbound non-entities.
* @param entityClass
* @return
*/
protected EntityBinding getEntityBinding(Class<?> entityClass) {
if (isMappedInterface(entityClass)) {
return EMPTY_BINDING;
}
//Common case of no inheritance. This lookup is a performance boost so we don't have to do reflection.
EntityBinding binding = entityBindings.get(entityClass);
if (binding != null) {
return binding;
}
Class<?> declaredClass = lookupBoundClass(entityClass);
if (declaredClass != null) {
return entityBindings.get(declaredClass);
}
//Will throw an exception if entityClass is not an entity.
lookupEntityClass(entityClass);
return EMPTY_BINDING;
}
public boolean isMappedInterface(Class<?> interfaceClass) {
return interfaceClass.isInterface() && interfaceClass.isAnnotationPresent(MappedInterface.class);
}
/**
* Returns whether or not the ID field for a given model is generated by the persistence layer.
* @param entityClass The model to lookup.
* @return True if the ID field is generated. False otherwise.
*/
public boolean isIdGenerated(Class<?> entityClass) {
return getEntityBinding(entityClass).isIdGenerated();
}
/**
* Returns the binding class for a given entity name.
*
* @param entityName entity name
* @return binding class
*/
public Class<?> getEntityClass(String entityName) {
return bindJsonApiToEntity.get(entityName);
}
/**
* Returns the Include name for a given binding class.
*
* @param entityClass the entity class
* @return binding class
* @see Include
*/
public String getJsonAliasFor(Class<?> entityClass) {
return getEntityBinding(entityClass).jsonApiType;
}
/**
* Returns the Entity name for a given binding class.
*
* @param entityClass the entity class
* @return binding class
* @see Entity
*/
public String getEntityFor(Class<?> entityClass) {
return getEntityBinding(entityClass).entityName;
}
/**
* Determine if a given (entity class, permission) pair have any permissions defined.
*
* @param resourceClass the entity class
* @param annotationClass the permission annotation
* @return {@code true} if that permission is defined anywhere within the class
*/
public boolean entityHasChecksForPermission(Class<?> resourceClass, Class<? extends Annotation> annotationClass) {
EntityBinding binding = getEntityBinding(resourceClass);
return binding.entityPermissions.hasChecksForPermission(annotationClass);
}
/**
* Gets the specified permission definition (if any) at the class level.
*
* @param resourceClass the entity to check
* @param annotationClass the permission to look for
* @return a {@code ParseTree} expressing the permissions, if one exists
* or {@code null} if the permission is not specified at a class level
*/
public ParseTree getPermissionsForClass(Class<?> resourceClass, Class<? extends Annotation> annotationClass) {
EntityBinding binding = getEntityBinding(resourceClass);
return binding.entityPermissions.getClassChecksForPermission(annotationClass);
}
/**
* Gets the specified permission definition (if any) at the class level.
*
* @param resourceClass the entity to check
* @param field the field to inspect
* @param annotationClass the permission to look for
* @return a {@code ParseTree} expressing the permissions, if one exists
* or {@code null} if the permission is not specified on that field
*/
public ParseTree getPermissionsForField(Class<?> resourceClass,
String field,
Class<? extends Annotation> annotationClass) {
EntityBinding binding = getEntityBinding(resourceClass);
return binding.entityPermissions.getFieldChecksForPermission(field, annotationClass);
}
/**
* Returns the check mapped to a particular identifier.
*
* @param checkIdentifier the name from the expression string
* @return the {@link Check} mapped to the identifier or {@code null} if the given identifer is unmapped
*/
public Class<? extends Check> getCheck(String checkIdentifier) {
return checkNames.computeIfAbsent(checkIdentifier, cls -> {
try {
return Class.forName(checkIdentifier).asSubclass(Check.class);
} catch (ClassNotFoundException | ClassCastException e) {
throw new IllegalArgumentException(
"Could not instantiate specified check '" + checkIdentifier + "'.", e);
}
});
}
/**
* Get inherited entity names for a particular entity.
*
* @param entityName Json alias name for entity
* @return List of all inherited entity type names
*/
public List<String> getSubclassingEntityNames(String entityName) {
return getSubclassingEntityNames(getEntityClass(entityName));
}
/**
* Get inherited entity names for a particular entity.
*
* @param entityClass Entity class
* @return List of all inherited entity type names
*/
public List<String> getSubclassingEntityNames(Class entityClass) {
List<Class<?>> entities = getSubclassingEntities(entityClass);
return entities.stream().map(this::getJsonAliasFor).collect(Collectors.toList());
}
/**
* Get a list of inherited entities from a particular entity.
* Namely, the list of entities inheriting from the provided class.
*
* @param entityName Json alias name for entity
* @return List of all inherited entity types
*/
public List<Class<?>> getSubclassingEntities(String entityName) {
return getSubclassingEntities(getEntityClass(entityName));
}
/**
* Get a list of inherited entities from a particular entity.
* Namely, the list of entities inheriting from the provided class.
*
* @param entityClass Entity class
* @return List of all inherited entity types
*/
public List<Class<?>> getSubclassingEntities(Class entityClass) {
return subclassingEntities.computeIfAbsent(entityClass, unused -> entityBindings
.keySet().stream()
.filter(c -> c != entityClass && entityClass.isAssignableFrom(c))
.collect(Collectors.toList()));
}
/**
* Fetch all entity names that the provided entity inherits from (i.e. all superclass entities down to,
* but excluding Object).
*
* @param entityName Json alias name for entity
* @return List of all super class entity json names
*/
public List<String> getSuperClassEntityNames(String entityName) {
return getSuperClassEntityNames(getEntityClass(entityName));
}
/**
* Fetch all entity names that the provided entity inherits from (i.e. all superclass entities down to,
* but excluding Object).
*
* @param entityClass Entity class
* @return List of all super class entity json names
*/
public List<String> getSuperClassEntityNames(Class entityClass) {
return getSuperClassEntities(entityClass).stream()
.map(this::getJsonAliasFor)
.collect(Collectors.toList());
}
/**
* Fetch all entity classes that the provided entity inherits from (i.e. all superclass entities down to,
* but excluding Object).
*
* @param entityName Json alias name for entity
* @return List of all super class entity classes
*/
public List<Class<?>> getSuperClassEntities(String entityName) {
return getSuperClassEntities(getEntityClass(entityName));
}
/**
* Fetch all entity classes that provided entity inherits from (i.e. all superclass entities down to,
* but excluding Object).
*
* @param entityClass Entity class
* @return List of all super class entity classes
*/
public List<Class<?>> getSuperClassEntities(Class entityClass) {
return getEntityBinding(entityClass).inheritedTypes.stream()
.filter(entityBindings::containsKey)
.collect(Collectors.toList());
}
/**
* Returns the friendly named mapped to this given check.
* @param checkClass The class to lookup
* @return the friendly name of the check.
*/
public String getCheckIdentifier(Class<? extends Check> checkClass) {
String identifier = checkNames.inverse().get(checkClass);
if (identifier == null) {
return checkClass.getName();
}
return identifier;
}
/**
* Returns the name of the id field.
*
* @param entityClass Entity class
* @return id field name
*/
public String getIdFieldName(Class<?> entityClass) {
return getEntityBinding(entityClass).getIdFieldName();
}
/**
* Returns whether the entire entity uses Field or Property level access.
* @param entityClass Entity Class
* @return The JPA Access Type
*/
public AccessType getAccessType(Class<?> entityClass) {
return getEntityBinding(entityClass).getAccessType();
}
/**
* Get all bindings.
*
* @return the bindings
*/
public Set<Class<?>> getBindings() {
return entityBindings.keySet();
}
/**
* Get the check mappings.
* @return a map of check mappings this dictionary knows about
*/
public Map<String, Class<? extends Check>> getCheckMappings() {
return checkNames;
}
/**
* Get the list of attribute names for an entity.
*
* @param entityClass entity name
* @return List of attribute names for entity
*/
public List<String> getAttributes(Class<?> entityClass) {
return getEntityBinding(entityClass).attributes;
}
/**
* Get the Injector for this dictionary.
*
* @return Injector instance.
*/
public Injector getInjector() {
return injector;
}
/**
* Get the list of attribute names for an entity.
*
* @param entity entity instance
* @return List of attribute names for entity
*/
public List<String> getAttributes(Object entity) {
return getAttributes(entity.getClass());
}
/**
* Get the list of relationship names for an entity.
*
* @param entityClass entity name
* @return List of relationship names for entity
*/
public List<String> getRelationships(Class<?> entityClass) {
return getEntityBinding(entityClass).relationships;
}
/**
* Get the list of relationship names for an entity.
*
* @param entity entity instance
* @return List of relationship names for entity
*/
public List<String> getRelationships(Object entity) {
return getRelationships(entity.getClass());
}
/**
* Get a list of elide-bound relationships.
*
* @param entityClass Entity class to find relationships for
* @return List of elide-bound relationship names.
*/
public List<String> getElideBoundRelationships(Class<?> entityClass) {
return getRelationships(entityClass).stream()
.filter(relationName -> getBindings().contains(getParameterizedType(entityClass, relationName)))
.collect(Collectors.toList());
}
/**
* Get a list of elide-bound relationships.
*
* @param entity Entity instance to find relationships for
* @return List of elide-bound relationship names.
*/
public List<String> getElideBoundRelationships(Object entity) {
return getElideBoundRelationships(entity.getClass());
}
/**
* Determine whether or not a method is request scopeable.
*
* @param entity Entity instance
* @param method Method on entity to check
* @return True if method accepts a RequestScope, false otherwise.
*/
public boolean isMethodRequestScopeable(Object entity, Method method) {
return isMethodRequestScopeable(entity.getClass(), method);
}
/**
* Determine whether or not a method is request scopeable.
*
* @param entityClass Entity to check
* @param method Method on entity to check
* @return True if method accepts a RequestScope, false otherwise.
*/
public boolean isMethodRequestScopeable(Class<?> entityClass, Method method) {
return getEntityBinding(entityClass).requestScopeableMethods.getOrDefault(method, false);
}
/**
* Get a list of all fields including both relationships and attributes.
*
* @param entityClass entity name
* @return List of all fields.
*/
public List<String> getAllFields(Class<?> entityClass) {
List<String> fields = new ArrayList<>();
List<String> attrs = getAttributes(entityClass);
List<String> rels = getRelationships(entityClass);
if (attrs != null) {
fields.addAll(attrs);
}
if (rels != null) {
fields.addAll(rels);
}
return fields;
}
/**
* Get a list of all fields including both relationships and attributes.
*
* @param entity entity
* @return List of all fields.
*/
public List<String> getAllFields(Object entity) {
return getAllFields(entity.getClass());
}
/**
* Get the type of relationship from a relation.
*
* @param cls Entity class
* @param relation Name of relationship field
* @return Relationship type. RelationshipType.NONE if is none found.
*/
public RelationshipType getRelationshipType(Class<?> cls, String relation) {
final ConcurrentHashMap<String, RelationshipType> types = getEntityBinding(cls).relationshipTypes;
if (types == null) {
return RelationshipType.NONE;
}
final RelationshipType type = types.get(relation);
return (type == null) ? RelationshipType.NONE : type;
}
/**
* If a relationship is bidirectional, returns the name of the peer relationship in the peer entity.
*
* @param cls the cls
* @param relation the relation
* @return relation inverse
*/
public String getRelationInverse(Class<?> cls, String relation) {
final EntityBinding clsBinding = getEntityBinding(cls);
final ConcurrentHashMap<String, String> mappings = clsBinding.relationshipToInverse;
if (mappings != null) {
final String mapping = mappings.get(relation);
if (mapping != null && !"".equals(mapping)) {
return mapping;
}
}
/*
* This could be the owning side of the relation. Let's see if the entity referenced in the relation
* has a bidirectional reference that is mapped to the given relation.
*/
final Class<?> inverseType = getParameterizedType(cls, relation);
final ConcurrentHashMap<String, String> inverseMappings =
getEntityBinding(inverseType).relationshipToInverse;
for (Map.Entry<String, String> inverseMapping : inverseMappings.entrySet()) {
String inverseRelationName = inverseMapping.getKey();
String inverseMappedBy = inverseMapping.getValue();
if (relation.equals(inverseMappedBy)
&& getParameterizedType(inverseType, inverseRelationName).equals(clsBinding.entityClass)) {
return inverseRelationName;
}
}
return "";
}
/**
* Get the type of relationship from a relation.
*
* @param entity Entity instance
* @param relation Name of relationship field
* @return Relationship type. RelationshipType.NONE if is none found.
*/
public RelationshipType getRelationshipType(Object entity, String relation) {
return getRelationshipType(entity.getClass(), relation);
}
/**
* Get a type for a field on an entity.
* <p>
* If this method is called on a bean such as the following
* <pre>
* {@code
* public class Address {
* {@literal @}Id
* private Long id
*
* private String street1;
*
* private String street2;
* }
* }
* </pre>
* then
* <pre>
* {@code
* getType(Address.class, "id") = Long.class
* getType(Address.class, "street1") = String.class
* getType(Address.class, "street2") = String.class
* }
* </pre>
* But if the ID field is not "id" and there is no such non-ID field called "id", i.e.
* <pre>
* {@code
* public class Address {
* {@literal @}Id
* private Long surrogateKey
*
* private String street1;
*
* private String street2;
* }
* }
* </pre>
* then
* <pre>
* {@code
* getType(Address.class, "id") = Long.class
* getType(Address.class, "surrogateKey") = Long.class
* getType(Address.class, "street1") = String.class
* getType(Address.class, "street2") = String.class
* }
* </pre>
* JSON-API spec does not allow "id" as non-ID field name. If, therefore, there is a non-ID field called "id",
* calling this method has undefined behavior
*
* @param entityClass Entity class
* @param identifier Identifier/Field to lookup type
* @return Type of entity
*/
public Class<?> getType(Class<?> entityClass, String identifier) {
if (identifier.equals(REGULAR_ID_NAME)) {
return getEntityBinding(entityClass).getIdType();
}
ConcurrentHashMap<String, Class<?>> fieldTypes = getEntityBinding(entityClass).fieldsToTypes;
return fieldTypes == null ? null : fieldTypes.get(identifier);
}
/**
* Get a type for a field on an entity.
*
* @param entity Entity instance
* @param identifier Field to lookup type
* @return Type of entity
*/
public Class<?> getType(Object entity, String identifier) {
return getType(entity.getClass(), identifier);
}
/**
* Retrieve the parameterized type for the given field.
*
* @param entityClass the entity class
* @param identifier the identifier
* @return Entity type for field otherwise null.
*/
public Class<?> getParameterizedType(Class<?> entityClass, String identifier) {
return getParameterizedType(entityClass, identifier, 0);
}
/**
* Retrieve the parameterized type for the given field.
*
* @param entityClass the entity class
* @param identifier the identifier/field name
* @param paramIndex the index of the parameterization
* @return Entity type for field otherwise null.
*/
public Class<?> getParameterizedType(Class<?> entityClass, String identifier, int paramIndex) {
ConcurrentHashMap<String, AccessibleObject> fieldOrMethods = getEntityBinding(entityClass).fieldsToValues;
if (fieldOrMethods == null) {
return null;
}
AccessibleObject fieldOrMethod = fieldOrMethods.get(identifier);
if (fieldOrMethod == null) {
return null;
}
return EntityBinding.getFieldType(entityClass, fieldOrMethod, Optional.of(paramIndex));
}
/**
* Retrieve the parameterized type for the given field.
*
* @param entity Entity instance
* @param identifier Field to lookup
* @return Entity type for field otherwise null.
*/
public Class<?> getParameterizedType(Object entity, String identifier) {
return getParameterizedType(entity.getClass(), identifier);
}
/**
* Retrieve the parameterized type for the given field.
*
* @param entity Entity instance
* @param identifier Field to lookup
* @param paramIndex the index of the parameterization
* @return Entity type for field otherwise null.
*/
public Class<?> getParameterizedType(Object entity, String identifier, int paramIndex) {
return getParameterizedType(entity.getClass(), identifier, paramIndex);
}
/**
* Get the true field/method name from an alias.
*
* @param entityClass Entity name
* @param alias Alias to convert
* @return Real field/method name as a string. null if not found.
*/
public String getNameFromAlias(Class<?> entityClass, String alias) {
ConcurrentHashMap<String, String> map = getEntityBinding(entityClass).aliasesToFields;
if (map != null) {
return map.get(alias);
}
return null;
}
/**
* Get the true field/method name from an alias.
*
* @param entity Entity instance
* @param alias Alias to convert
* @return Real field/method name as a string. null if not found.
*/
public String getNameFromAlias(Object entity, String alias) {
return getNameFromAlias(entity.getClass(), alias);
}
/**
* Initialize an entity.
*
* @param <T> the type parameter
* @param entity Entity to initialize
*/
public <T> void initializeEntity(T entity) {
if (entity != null) {
@SuppressWarnings("unchecked")
Initializer<T> initializer = getEntityBinding(entity.getClass()).getInitializer();
if (initializer != null) {
initializer.initialize(entity);
} else if (injector != null) {
injector.inject(entity);
}
}
}
/**
* Bind a particular initializer to a class.
*
* @param <T> the type parameter
* @param initializer Initializer to use for class
* @param cls Class to bind initialization
*/
public <T> void bindInitializer(Initializer<T> initializer, Class<T> cls) {
bindIfUnbound(cls);
getEntityBinding(cls).setInitializer(initializer);
}
/**
* Returns whether or not an entity is shareable.
*
* @param entityClass the entity type to check for the shareable permissions
* @return true if entityClass is shareable. False otherwise.
*/
public boolean isShareable(Class<?> entityClass) {
return getAnnotation(entityClass, SharePermission.class) != null
&& getAnnotation(entityClass, SharePermission.class).sharable();
}
/**
* Add given Entity bean to dictionary.
*
* @param cls Entity bean class
*/
public void bindEntity(Class<?> cls) {
Class<?> declaredClass = lookupIncludeClass(cls);
if (declaredClass == null) {
log.trace("Missing include or excluded class {}", cls.getName());
return;
}
if (isClassBound(declaredClass)) {
//Ignore duplicate bindings.
return;
}
Include include = (Include) getFirstAnnotation(declaredClass, Arrays.asList(Include.class));
Entity entity = (Entity) getFirstAnnotation(declaredClass, Arrays.asList(Entity.class));
String name;
if (entity == null || "".equals(entity.name())) {
name = StringUtils.uncapitalize(cls.getSimpleName());
} else {
name = entity.name();
}
String type;
if ("".equals(include.type())) {
type = name;
} else {
type = include.type();
}
bindJsonApiToEntity.put(type, declaredClass);
entityBindings.put(declaredClass, new EntityBinding(this, declaredClass, type, name));
if (include.rootLevel()) {
bindEntityRoots.add(declaredClass);
}
}
/**
* Return annotation from class, parents or package.
*
* @param record the record
* @param annotationClass the annotation class
* @param <A> genericClass
* @return the annotation
*/
public <A extends Annotation> A getAnnotation(PersistentResource record, Class<A> annotationClass) {
return getAnnotation(record.getResourceClass(), annotationClass);
}
/**
* Return annotation from class, parents or package.
*
* @param recordClass the record class
* @param annotationClass the annotation class
* @param <A> genericClass
* @return the annotation
*/
public <A extends Annotation> A getAnnotation(Class<?> recordClass, Class<A> annotationClass) {
return getEntityBinding(recordClass).getAnnotation(annotationClass);
}
/**
* Return annotation from class for provided method.
* @param recordClass the record class
* @param method the method
* @param annotationClass the annotation class
* @param <A> genericClass
* @return the annotation
*/
public <A extends Annotation> A getMethodAnnotation(Class<?> recordClass, String method, Class<A> annotationClass) {
return getEntityBinding(recordClass).getMethodAnnotation(annotationClass, method);
}
public <A extends Annotation> Collection<LifeCycleHook> getTriggers(Class<?> cls,
Class<A> annotationClass,
String fieldName) {
return getEntityBinding(cls).getTriggers(annotationClass, fieldName);
}
public <A extends Annotation> Collection<LifeCycleHook> getTriggers(Class<?> cls,
Class<A> annotationClass) {
return getEntityBinding(cls).getTriggers(annotationClass);
}
/**
* Return a single annotation from field or accessor method.
*
* @param entityClass the entity class
* @param annotationClass given annotation type
* @param identifier the identifier
* @param <A> genericClass
* @return annotation found
*/
public <A extends Annotation> A getAttributeOrRelationAnnotation(Class<?> entityClass,
Class<A> annotationClass,
String identifier) {
AccessibleObject fieldOrMethod = getEntityBinding(entityClass).fieldsToValues.get(identifier);
if (fieldOrMethod == null) {
return null;
}
return fieldOrMethod.getAnnotation(annotationClass);
}
/**
* Return multiple annotations from field or accessor method.
*
* @param <A> the type parameter
* @param entityClass the entity class
* @param annotationClass given annotation type
* @param identifier the identifier
* @return annotation found or null if none found
*/
public <A extends Annotation> A[] getAttributeOrRelationAnnotations(Class<?> entityClass,
Class<A> annotationClass,
String identifier) {
AccessibleObject fieldOrMethod = getEntityBinding(entityClass).fieldsToValues.get(identifier);
if (fieldOrMethod == null) {
return null;
}
return fieldOrMethod.getAnnotationsByType(annotationClass);
}
/**
* Return first matching annotation from class, parents or package.
*
* @param entityClass Entity class type
* @param annotationClassList List of sought annotations
* @return annotation found
*/
public static Annotation getFirstAnnotation(Class<?> entityClass,
List<Class<? extends Annotation>> annotationClassList) {
Annotation annotation = null;
for (Class<?> cls = entityClass; annotation == null && cls != null; cls = cls.getSuperclass()) {
for (Class<? extends Annotation> annotationClass : annotationClassList) {
annotation = cls.getDeclaredAnnotation(annotationClass);
if (annotation != null) {
break;
}
}
}
// no class annotation, try packages
for (Package pkg = entityClass.getPackage(); annotation == null && pkg != null; pkg = getParentPackage(pkg)) {
for (Class<? extends Annotation> annotationClass : annotationClassList) {
annotation = pkg.getDeclaredAnnotation(annotationClass);
if (annotation != null) {
break;
}
}
}
return annotation;
}
/**
* Is root.
*
* @param entityClass the entity class
* @return the boolean
*/
public boolean isRoot(Class<?> entityClass) {
return bindEntityRoots.contains(entityClass);
}
/**
* Gets id.
*
* @param value the value
* @return the id
*/
public String getId(Object value) {
if (value == null) {
return null;
}
try {
AccessibleObject idField = null;
Class<?> valueClass = value.getClass();
for (; idField == null && valueClass != null; valueClass = valueClass.getSuperclass()) {
try {
idField = getEntityBinding(valueClass).getIdField();
} catch (NullPointerException e) {
log.warn("Class: {} ID Field: {}", valueClass.getSimpleName(), idField);
}
}
Class<?> idClass;
Object idValue;
if (idField instanceof Field) {
idValue = ((Field) idField).get(value);
idClass = ((Field) idField).getType();
} else if (idField instanceof Method) {
idValue = ((Method) idField).invoke(value, (Object[]) null);
idClass = ((Method) idField).getReturnType();
} else {
return null;
}
Serde serde = serdeLookup.apply(idClass);
if (serde != null) {
return String.valueOf(serde.serialize(idValue));
}
return String.valueOf(idValue);
} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
return null;
}
}
/**
* Returns type of id field.
*
* @param entityClass the entity class
* @return ID type
*/
public Class<?> getIdType(Class<?> entityClass) {
return getEntityBinding(entityClass).getIdType();
}
/**
* Returns annotations applied to the ID field.
*
* @param value the value
* @return Collection of Annotations
*/
public Collection<Annotation> getIdAnnotations(Object value) {
if (value == null) {
return null;
}
AccessibleObject idField = getEntityBinding(value.getClass()).getIdField();
if (idField != null) {
return Arrays.asList(idField.getDeclaredAnnotations());
}
return Collections.emptyList();
}
/**
* Follow for this class or super-class for Entity annotation.
*
* @param objClass provided class
* @return class with Entity annotation
*/
public Class<?> lookupEntityClass(Class<?> objClass) {
Class<?> declaringClass = lookupAnnotationDeclarationClass(objClass, Entity.class);
if (declaringClass != null) {
return declaringClass;
}
throw new IllegalArgumentException("Unbound Entity " + objClass);
}
/**
* Follow for this class or super-class for Include annotation.
*
* @param objClass provided class
* @return class with Include annotation or
*/
public Class<?> lookupIncludeClass(Class<?> objClass) {
Annotation first = getFirstAnnotation(objClass, Arrays.asList(Exclude.class, Include.class));
if (first instanceof Include) {
return objClass;
}
return null;
}
/**
* Search a class hierarchy to find the first instance of a declared annotation.
* @param objClass The class to start searching.
* @param annotationClass The annotation to search for.
* @return The class which declares the annotation or null.
*/
public Class<?> lookupAnnotationDeclarationClass(Class<?> objClass, Class<? extends Annotation> annotationClass) {
for (Class<?> cls = objClass; cls != null; cls = cls.getSuperclass()) {
if (cls.getDeclaredAnnotation(annotationClass) != null) {
return cls;
}
}
return null;
}
/**
* Return bound entity or null.
*
* @param objClass provided class
* @return Bound class.
*/
public Class<?> lookupBoundClass(Class<?> objClass) {
//Common case - we can avoid reflection by checking the map ...
EntityBinding binding = entityBindings.getOrDefault(objClass, EMPTY_BINDING);
if (binding != EMPTY_BINDING) {
return binding.entityClass;
}
Class<?> declaredClass = lookupIncludeClass(objClass);
if (declaredClass == null) {
return null;
}
binding = entityBindings.getOrDefault(declaredClass, EMPTY_BINDING);
if (binding != EMPTY_BINDING) {
return binding.entityClass;
}
try {
//Special Case for ORM proxied objects. If the class is a proxy,
//and it is unbound, try the superclass.
return lookupEntityClass(declaredClass.getSuperclass());
} catch (IllegalArgumentException e) {
return null;
}
}
/**
* Return if the class has been bound or not. Only safe to call while binding an entity (does not consider
* ORM proxy objects).
*
* @param objClass provided class
* @return true if the class is already bound.
*/
private boolean isClassBound(Class<?> objClass) {
return (entityBindings.getOrDefault(objClass, EMPTY_BINDING) != EMPTY_BINDING);
}
/**
* Retrieve the accessible object for a field from a target object.
*
* @param target the object to get
* @param fieldName the field name to get or invoke equivalent get method
* @return the value
*/
public AccessibleObject getAccessibleObject(Object target, String fieldName) {
return getAccessibleObject(target.getClass(), fieldName);
}
public boolean isComputed(Class<?> entityClass, String fieldName) {
AccessibleObject fieldOrMethod = getAccessibleObject(entityClass, fieldName);
if (fieldOrMethod == null) {
return false;
}
return (fieldOrMethod.isAnnotationPresent(ComputedAttribute.class)
|| fieldOrMethod.isAnnotationPresent(ComputedRelationship.class));
}
/**
* Retrieve the accessible object for a field.
*
* @param targetClass the object to get
* @param fieldName the field name to get or invoke equivalent get method
* @return the value
*/
public AccessibleObject getAccessibleObject(Class<?> targetClass, String fieldName) {
return getEntityBinding(targetClass).fieldsToValues.get(fieldName);
}
/**
* Retrieve fields from an object containing a particular type.
*
* @param targetClass Class to search for fields
* @param targetType Type of fields to find
* @return Set containing field names
*/
public Set<String> getFieldsOfType(Class<?> targetClass, Class<?> targetType) {
HashSet<String> fields = new HashSet<>();
for (String field : getAllFields(targetClass)) {
if (getParameterizedType(targetClass, field).equals(targetType)) {
fields.add(field);
}
}
return fields;
}
public boolean isRelation(Class<?> entityClass, String relationName) {
return getEntityBinding(entityClass).relationships.contains(relationName);
}
public boolean isAttribute(Class<?> entityClass, String attributeName) {
return getEntityBinding(entityClass).attributes.contains(attributeName);
}
/**
* Scan for security checks and automatically bind them to the dictionary.
*/
public void scanForSecurityChecks() {
// Logic is based on https://github.com/illyasviel/elide-spring-boot/blob/master
// /elide-spring-boot-autoconfigure/src/main/java/org/illyasviel/elide
// /spring/boot/autoconfigure/ElideAutoConfiguration.java
for (Class<?> cls : ClassScanner.getAnnotatedClasses(SecurityCheck.class)) {
if (Check.class.isAssignableFrom(cls)) {
SecurityCheck securityCheckMeta = cls.getAnnotation(SecurityCheck.class);
log.debug("Register Elide Check [{}] with expression [{}]",
cls.getCanonicalName(), securityCheckMeta.value());
checkNames.put(securityCheckMeta.value(), cls.asSubclass(Check.class));
} else {
throw new IllegalStateException("Class annotated with SecurityCheck is not a Check");
}
}
}
/**
* Binds a lifecycle hook to a particular field or method in an entity. The hook will be called a
* single time per request per field READ, CREATE, or UPDATE.
* @param entityClass The entity that triggers the lifecycle hook.
* @param annotationClass (OnReadPostCommit, OnUpdatePreSecurity, etc)
* @param fieldOrMethodName The name of the field or method
* @param callback The callback function to invoke.
*/
public void bindTrigger(Class<?> entityClass,
Class<? extends Annotation> annotationClass,
String fieldOrMethodName,
LifeCycleHook callback) {
bindIfUnbound(entityClass);
getEntityBinding(entityClass).bindTrigger(annotationClass, fieldOrMethodName, callback);
}
/**
* Binds a lifecycle hook to a particular entity class. The hook will either be called:
* - A single time single time per request per class READ, CREATE, UPDATE, or DELETE.
* - Multiple times per request per field READ, CREATE, or UPDATE.
*
* The behavior is determined by the value of the {@code allowMultipleInvocations} flag.
* @param entityClass The entity that triggers the lifecycle hook.
* @param annotationClass (OnReadPostCommit, OnUpdatePreSecurity, etc)
* @param callback The callback function to invoke.
* @param allowMultipleInvocations Should the same life cycle hook be invoked multiple times for multiple
* CRUD actions on the same model.
*/
public void bindTrigger(Class<?> entityClass,
Class<? extends Annotation> annotationClass,
LifeCycleHook callback,
boolean allowMultipleInvocations) {
bindIfUnbound(entityClass);
if (allowMultipleInvocations) {
getEntityBinding(entityClass).bindTrigger(annotationClass, callback);
} else {
getEntityBinding(entityClass).bindTrigger(annotationClass, PersistentResource.CLASS_NO_FIELD, callback);
}
}
/**
* Binds a lifecycle hook to a particular entity class. The hook will be called a single time per request
* per class READ, CREATE, UPDATE, or DELETE.
* @param entityClass The entity that triggers the lifecycle hook.
* @param annotationClass (OnReadPostCommit, OnUpdatePreSecurity, etc)
* @param callback The callback function to invoke.
*/
public void bindTrigger(Class<?> entityClass,
Class<? extends Annotation> annotationClass,
LifeCycleHook callback) {
bindTrigger(entityClass, annotationClass, callback, false);
}
/**
* Returns true if the relationship cascades deletes and false otherwise.
* @param targetClass The class which owns the relationship.
* @param fieldName The relationship
* @return true or false
*/
public boolean cascadeDeletes(Class<?> targetClass, String fieldName) {
CascadeType [] cascadeTypes =
getEntityBinding(targetClass).relationshipToCascadeTypes.getOrDefault(fieldName, new CascadeType[0]);
for (CascadeType cascadeType : cascadeTypes) {
if (cascadeType == CascadeType.ALL || cascadeType == CascadeType.REMOVE) {
return true;
}
}
return false;
}
/**
* Walks the entity graph and performs a transform function on each element.
* @param entities The roots of the entity graph.
* @param transform The function to transform each entity class into a result.
* @param <T> The result type.
* @return The collection of results.
*/
public <T> List<T> walkEntityGraph(Set<Class<?>> entities, Function<Class<?>, T> transform) {
ArrayList<T> results = new ArrayList<>();
Queue<Class<?>> toVisit = new ArrayDeque<>(entities);
Set<Class<?>> visited = new HashSet<>();
while (! toVisit.isEmpty()) {
Class<?> clazz = toVisit.remove();
results.add(transform.apply(clazz));
visited.add(clazz);
for (String relationship : getElideBoundRelationships(clazz)) {
Class<?> relationshipClass = getParameterizedType(clazz, relationship);
if (lookupBoundClass(relationshipClass) == null) {
/* The relationship hasn't been bound */
continue;
}
if (!visited.contains(relationshipClass)) {
toVisit.add(relationshipClass);
}
}
}
return results;
}
/**
* Returns whether or not a class is already bound.
* @param cls
* @return true if the class is bound. False otherwise.
*/
public boolean hasBinding(Class<?> cls) {
return bindJsonApiToEntity.contains(cls);
}
/**
* Invoke the get[fieldName] method on the target object OR get the field with the corresponding name.
* @param target the object to get
* @param fieldName the field name to get or invoke equivalent get method
* @return the value
*/
public Object getValue(Object target, String fieldName, RequestScope scope) {
AccessibleObject accessor = getAccessibleObject(target, fieldName);
try {
if (accessor instanceof Method) {
// Pass RequestScope into @Computed fields if requested
if (isMethodRequestScopeable(target, (Method) accessor)) {
return ((Method) accessor).invoke(target, scope);
}
return ((Method) accessor).invoke(target);
}
if (accessor instanceof Field) {
return ((Field) accessor).get(target);
}
} catch (IllegalAccessException e) {
throw new InvalidAttributeException(fieldName, getJsonAliasFor(target.getClass()), e);
} catch (InvocationTargetException e) {
throw handleInvocationTargetException(e);
}
throw new InvalidAttributeException(fieldName, getJsonAliasFor(target.getClass()));
}
/**
* Invoke the set[fieldName] method on the target object OR set the field with the corresponding name.
* @param fieldName the field name to set or invoke equivalent set method
* @param value the value to set
*/
public void setValue(Object target, String fieldName, Object value) {
Class<?> targetClass = target.getClass();
String targetType = getJsonAliasFor(targetClass);
String fieldAlias = fieldName;
try {
Class<?> fieldClass = getType(targetClass, fieldName);
String realName = getNameFromAlias(target, fieldName);
fieldAlias = (realName != null) ? realName : fieldName;
String setMethod = "set" + StringUtils.capitalize(fieldAlias);
Method method = EntityDictionary.findMethod(targetClass, setMethod, fieldClass);
method.invoke(target, coerce(target, value, fieldAlias, fieldClass));
} catch (IllegalAccessException e) {
throw new InvalidAttributeException(fieldAlias, targetType, e);
} catch (InvocationTargetException e) {
throw handleInvocationTargetException(e);
} catch (IllegalArgumentException | NoSuchMethodException noMethod) {
AccessibleObject accessor = getAccessibleObject(target, fieldAlias);
if (accessor != null && accessor instanceof Field) {
Field field = (Field) accessor;
try {
field.set(target, coerce(target, value, fieldAlias, field.getType()));
} catch (IllegalAccessException noField) {
throw new InvalidAttributeException(fieldAlias, targetType, noField);
}
} else {
throw new InvalidAttributeException(fieldAlias, targetType);
}
}
}
/**
* Handle an invocation target exception.
*
* @param e Exception the exception encountered while reflecting on an object's field
* @return Equivalent runtime exception
*/
private static RuntimeException handleInvocationTargetException(InvocationTargetException e) {
Throwable exception = e.getTargetException();
if (exception instanceof HttpStatusException || exception instanceof WebApplicationException) {
return (RuntimeException) exception;
}
log.error("Caught an unexpected exception (rethrowing as internal server error)", e);
return new InternalServerErrorException("Unexpected exception caught", e);
}
/**
* Coerce provided value into expected class type.
*
* @param value provided value
* @param fieldName the field name
* @param fieldClass expected class type
* @return coerced value
*/
public Object coerce(Object target, Object value, String fieldName, Class<?> fieldClass) {
if (fieldClass != null && Collection.class.isAssignableFrom(fieldClass) && value instanceof Collection) {
return coerceCollection(target, (Collection) value, fieldName, fieldClass);
}
if (fieldClass != null && Map.class.isAssignableFrom(fieldClass) && value instanceof Map) {
return coerceMap(target, (Map<?, ?>) value, fieldName);
}
return CoerceUtil.coerce(value, fieldClass);
}
private Collection coerceCollection(Object target, Collection<?> values, String fieldName, Class<?> fieldClass) {
Class<?> providedType = getParameterizedType(target, fieldName);
// check if collection is of and contains the correct types
if (fieldClass.isAssignableFrom(values.getClass())) {
boolean valid = true;
for (Object member : values) {
if (member != null && !providedType.isAssignableFrom(member.getClass())) {
valid = false;
break;
}
}
if (valid) {
return values;
}
}
ArrayList<Object> list = new ArrayList<>(values.size());
for (Object member : values) {
list.add(CoerceUtil.coerce(member, providedType));
}
if (Set.class.isAssignableFrom(fieldClass)) {
return new LinkedHashSet<>(list);
}
return list;
}
private Map coerceMap(Object target, Map<?, ?> values, String fieldName) {
Class<?> keyType = getParameterizedType(target, fieldName, 0);
Class<?> valueType = getParameterizedType(target, fieldName, 1);
// Verify the existing Map
if (isValidParameterizedMap(values, keyType, valueType)) {
return values;
}
LinkedHashMap<Object, Object> result = new LinkedHashMap<>(values.size());
for (Map.Entry<?, ?> entry : values.entrySet()) {
result.put(CoerceUtil.coerce(entry.getKey(), keyType), CoerceUtil.coerce(entry.getValue(), valueType));
}
return result;
}
private boolean isValidParameterizedMap(Map<?, ?> values, Class<?> keyType, Class<?> valueType) {
for (Map.Entry<?, ?> entry : values.entrySet()) {
Object key = entry.getKey();
Object value = entry.getValue();
if ((key != null && !keyType.isAssignableFrom(key.getClass()))
|| (value != null && !valueType.isAssignableFrom(value.getClass()))) {
return false;
}
}
return true;
}
/**
* Binds the entity class if not yet bound.
* @param entityClass the class to bind.
*/
private void bindIfUnbound(Class<?> entityClass) {
if (! isClassBound(entityClass)) {
bindEntity(entityClass);
}
}
}
|
{
"pile_set_name": "Github"
}
|
import * as Lint from "tslint";
import * as ts from "typescript";
import { failure } from "../util";
// Same functionality as https://github.com/palantir/tslint/pull/1654, but simpler implementation.
// Remove when that PR is in.
export class Rule extends Lint.Rules.AbstractRule {
static metadata: Lint.IRuleMetadata = {
ruleName: "no-useless-files",
description: "Forbids files with no content.",
optionsDescription: "Not configurable.",
options: null,
type: "functionality",
typescriptOnly: false,
};
static FAILURE_STRING = failure(
Rule.metadata.ruleName,
"File has no content.");
apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
const { statements, referencedFiles, typeReferenceDirectives } = sourceFile;
if (statements.length + referencedFiles.length + typeReferenceDirectives.length !== 0) {
return [];
}
return [new Lint.RuleFailure(sourceFile, 0, 1, Rule.FAILURE_STRING, this.ruleName)];
}
}
|
{
"pile_set_name": "Github"
}
|
//////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
#ifndef _Rtt_CoronaViewRuntimeDelegate_H__
#define _Rtt_CoronaViewRuntimeDelegate_H__
#include "Rtt_RuntimeDelegatePlayer.h"
// ----------------------------------------------------------------------------
@class CoronaView;
@protocol CoronaRuntime;
namespace Rtt
{
// ----------------------------------------------------------------------------
class CoronaViewRuntimeDelegate : public RuntimeDelegatePlayer
{
public:
CoronaViewRuntimeDelegate( CoronaView *owner );
virtual ~CoronaViewRuntimeDelegate();
public:
virtual void DidInitLuaLibraries( const Runtime& sender ) const;
virtual bool HasDependencies( const Runtime& sender ) const;
virtual void InitializeConfig( const Runtime& sender, lua_State *L ) const;
virtual void DidLoadConfig( const Runtime& sender, lua_State *L ) const;
protected:
virtual id< CoronaRuntime > GetPluginContext() const;
private:
CoronaView *fOwner; // Weak ref
};
// ----------------------------------------------------------------------------
} // namespace Rtt
// ----------------------------------------------------------------------------
#endif // _Rtt_CoronaViewRuntimeDelegate_H__
|
{
"pile_set_name": "Github"
}
|
package nucleus.example.util.adapters;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import java.util.Collections;
import java.util.List;
import static java.util.Arrays.asList;
public abstract class BaseRecyclerViewAdapter extends RecyclerView.Adapter<BaseViewHolder> {
private final List<ViewHolderType> types;
public BaseRecyclerViewAdapter(ViewHolderType... types) {
this.types = Collections.unmodifiableList(asList(types));
}
protected abstract List<?> getItems();
@Override
public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return types.get(viewType).create(parent);
}
@Override
public void onBindViewHolder(BaseViewHolder holder, int position) {
holder.bind(getItems().get(position));
}
@Override
public int getItemViewType(int position) {
Object item = getItems().get(position);
for (int t = 0, size = types.size(); t < size; t++) {
if (types.get(t).isOfItem(item))
return t;
}
throw new IllegalStateException("No view holder is registered for item: " + item + " at position: " + position);
}
@Override
public int getItemCount() {
return getItems().size();
}
}
|
{
"pile_set_name": "Github"
}
|
/**
* SyntaxHighlighter
* http://alexgorbatchev.com/SyntaxHighlighter
*
* SyntaxHighlighter is donationware. If you are using it, please donate.
* http://alexgorbatchev.com/SyntaxHighlighter/donate.html
*
* @version
* 3.0.83 (July 02 2010)
*
* @copyright
* Copyright (C) 2004-2010 Alex Gorbatchev.
*
* @license
* Dual licensed under the MIT and GPL licenses.
*/
.syntaxhighlighter {
background-color: black !important;
}
.syntaxhighlighter .line.alt1 {
background-color: black !important;
}
.syntaxhighlighter .line.alt2 {
background-color: black !important;
}
.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
background-color: #2a3133 !important;
}
.syntaxhighlighter .line.highlighted.number {
color: white !important;
}
.syntaxhighlighter table caption {
color: #d3d3d3 !important;
}
.syntaxhighlighter .gutter {
color: #d3d3d3 !important;
}
.syntaxhighlighter .gutter .line {
border-right: 3px solid #990000 !important;
}
.syntaxhighlighter .gutter .line.highlighted {
background-color: #990000 !important;
color: black !important;
}
.syntaxhighlighter.printing .line .content {
border: none !important;
}
.syntaxhighlighter.collapsed {
overflow: visible !important;
}
.syntaxhighlighter.collapsed .toolbar {
color: #ebdb8d !important;
background: black !important;
border: 1px solid #990000 !important;
}
.syntaxhighlighter.collapsed .toolbar a {
color: #ebdb8d !important;
}
.syntaxhighlighter.collapsed .toolbar a:hover {
color: #ff7d27 !important;
}
.syntaxhighlighter .toolbar {
color: white !important;
background: #990000 !important;
border: none !important;
}
.syntaxhighlighter .toolbar a {
color: white !important;
}
.syntaxhighlighter .toolbar a:hover {
color: #9ccff4 !important;
}
.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
color: #d3d3d3 !important;
}
.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
color: #ff7d27 !important;
}
.syntaxhighlighter .string, .syntaxhighlighter .string a {
color: #ff9e7b !important;
}
.syntaxhighlighter .keyword {
color: aqua !important;
}
.syntaxhighlighter .preprocessor {
color: #aec4de !important;
}
.syntaxhighlighter .variable {
color: #ffaa3e !important;
}
.syntaxhighlighter .value {
color: #009900 !important;
}
.syntaxhighlighter .functions {
color: #81cef9 !important;
}
.syntaxhighlighter .constants {
color: #ff9e7b !important;
}
.syntaxhighlighter .script {
font-weight: bold !important;
color: aqua !important;
background-color: none !important;
}
.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
color: #ebdb8d !important;
}
.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
color: #ff7d27 !important;
}
.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
color: #aec4de !important;
}
|
{
"pile_set_name": "Github"
}
|
/* The PyObject_ memory family: high-level object memory interfaces.
See pymem.h for the low-level PyMem_ family.
*/
#ifndef Py_OBJIMPL_H
#define Py_OBJIMPL_H
#include "pymem.h"
#ifdef __cplusplus
extern "C" {
#endif
/* BEWARE:
Each interface exports both functions and macros. Extension modules should
use the functions, to ensure binary compatibility across Python versions.
Because the Python implementation is free to change internal details, and
the macros may (or may not) expose details for speed, if you do use the
macros you must recompile your extensions with each Python release.
Never mix calls to PyObject_ memory functions with calls to the platform
malloc/realloc/ calloc/free, or with calls to PyMem_.
*/
/*
Functions and macros for modules that implement new object types.
- PyObject_New(type, typeobj) allocates memory for a new object of the given
type, and initializes part of it. 'type' must be the C structure type used
to represent the object, and 'typeobj' the address of the corresponding
type object. Reference count and type pointer are filled in; the rest of
the bytes of the object are *undefined*! The resulting expression type is
'type *'. The size of the object is determined by the tp_basicsize field
of the type object.
- PyObject_NewVar(type, typeobj, n) is similar but allocates a variable-size
object with room for n items. In addition to the refcount and type pointer
fields, this also fills in the ob_size field.
- PyObject_Del(op) releases the memory allocated for an object. It does not
run a destructor -- it only frees the memory. PyObject_Free is identical.
- PyObject_Init(op, typeobj) and PyObject_InitVar(op, typeobj, n) don't
allocate memory. Instead of a 'type' parameter, they take a pointer to a
new object (allocated by an arbitrary allocator), and initialize its object
header fields.
Note that objects created with PyObject_{New, NewVar} are allocated using the
specialized Python allocator (implemented in obmalloc.c), if WITH_PYMALLOC is
enabled. In addition, a special debugging allocator is used if PYMALLOC_DEBUG
is also #defined.
In case a specific form of memory management is needed (for example, if you
must use the platform malloc heap(s), or shared memory, or C++ local storage or
operator new), you must first allocate the object with your custom allocator,
then pass its pointer to PyObject_{Init, InitVar} for filling in its Python-
specific fields: reference count, type pointer, possibly others. You should
be aware that Python no control over these objects because they don't
cooperate with the Python memory manager. Such objects may not be eligible
for automatic garbage collection and you have to make sure that they are
released accordingly whenever their destructor gets called (cf. the specific
form of memory management you're using).
Unless you have specific memory management requirements, use
PyObject_{New, NewVar, Del}.
*/
/*
* Raw object memory interface
* ===========================
*/
/* Functions to call the same malloc/realloc/free as used by Python's
object allocator. If WITH_PYMALLOC is enabled, these may differ from
the platform malloc/realloc/free. The Python object allocator is
designed for fast, cache-conscious allocation of many "small" objects,
and with low hidden memory overhead.
PyObject_Malloc(0) returns a unique non-NULL pointer if possible.
PyObject_Realloc(NULL, n) acts like PyObject_Malloc(n).
PyObject_Realloc(p != NULL, 0) does not return NULL, or free the memory
at p.
Returned pointers must be checked for NULL explicitly; no action is
performed on failure other than to return NULL (no warning it printed, no
exception is set, etc).
For allocating objects, use PyObject_{New, NewVar} instead whenever
possible. The PyObject_{Malloc, Realloc, Free} family is exposed
so that you can exploit Python's small-block allocator for non-object
uses. If you must use these routines to allocate object memory, make sure
the object gets initialized via PyObject_{Init, InitVar} after obtaining
the raw memory.
*/
PyAPI_FUNC(void *) PyObject_Malloc(size_t);
PyAPI_FUNC(void *) PyObject_Realloc(void *, size_t);
PyAPI_FUNC(void) PyObject_Free(void *);
/* Macros */
#ifdef WITH_PYMALLOC
#ifdef PYMALLOC_DEBUG /* WITH_PYMALLOC && PYMALLOC_DEBUG */
PyAPI_FUNC(void *) _PyObject_DebugMalloc(size_t nbytes);
PyAPI_FUNC(void *) _PyObject_DebugRealloc(void *p, size_t nbytes);
PyAPI_FUNC(void) _PyObject_DebugFree(void *p);
PyAPI_FUNC(void) _PyObject_DebugDumpAddress(const void *p);
PyAPI_FUNC(void) _PyObject_DebugCheckAddress(const void *p);
PyAPI_FUNC(void) _PyObject_DebugMallocStats(void);
PyAPI_FUNC(void *) _PyObject_DebugMallocApi(char api, size_t nbytes);
PyAPI_FUNC(void *) _PyObject_DebugReallocApi(char api, void *p, size_t nbytes);
PyAPI_FUNC(void) _PyObject_DebugFreeApi(char api, void *p);
PyAPI_FUNC(void) _PyObject_DebugCheckAddressApi(char api, const void *p);
PyAPI_FUNC(void *) _PyMem_DebugMalloc(size_t nbytes);
PyAPI_FUNC(void *) _PyMem_DebugRealloc(void *p, size_t nbytes);
PyAPI_FUNC(void) _PyMem_DebugFree(void *p);
#define PyObject_MALLOC _PyObject_DebugMalloc
#define PyObject_Malloc _PyObject_DebugMalloc
#define PyObject_REALLOC _PyObject_DebugRealloc
#define PyObject_Realloc _PyObject_DebugRealloc
#define PyObject_FREE _PyObject_DebugFree
#define PyObject_Free _PyObject_DebugFree
#else /* WITH_PYMALLOC && ! PYMALLOC_DEBUG */
#define PyObject_MALLOC PyObject_Malloc
#define PyObject_REALLOC PyObject_Realloc
#define PyObject_FREE PyObject_Free
#endif
#else /* ! WITH_PYMALLOC */
#define PyObject_MALLOC PyMem_MALLOC
#define PyObject_REALLOC PyMem_REALLOC
#define PyObject_FREE PyMem_FREE
#endif /* WITH_PYMALLOC */
#define PyObject_Del PyObject_Free
#define PyObject_DEL PyObject_FREE
/* for source compatibility with 2.2 */
#define _PyObject_Del PyObject_Free
/*
* Generic object allocator interface
* ==================================
*/
/* Functions */
PyAPI_FUNC(PyObject *) PyObject_Init(PyObject *, PyTypeObject *);
PyAPI_FUNC(PyVarObject *) PyObject_InitVar(PyVarObject *,
PyTypeObject *, Py_ssize_t);
PyAPI_FUNC(PyObject *) _PyObject_New(PyTypeObject *);
PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t);
#define PyObject_New(type, typeobj) \
( (type *) _PyObject_New(typeobj) )
#define PyObject_NewVar(type, typeobj, n) \
( (type *) _PyObject_NewVar((typeobj), (n)) )
/* Macros trading binary compatibility for speed. See also pymem.h.
Note that these macros expect non-NULL object pointers.*/
#define PyObject_INIT(op, typeobj) \
( Py_TYPE(op) = (typeobj), _Py_NewReference((PyObject *)(op)), (op) )
#define PyObject_INIT_VAR(op, typeobj, size) \
( Py_SIZE(op) = (size), PyObject_INIT((op), (typeobj)) )
#define _PyObject_SIZE(typeobj) ( (typeobj)->tp_basicsize )
/* _PyObject_VAR_SIZE returns the number of bytes (as size_t) allocated for a
vrbl-size object with nitems items, exclusive of gc overhead (if any). The
value is rounded up to the closest multiple of sizeof(void *), in order to
ensure that pointer fields at the end of the object are correctly aligned
for the platform (this is of special importance for subclasses of, e.g.,
str or long, so that pointers can be stored after the embedded data).
Note that there's no memory wastage in doing this, as malloc has to
return (at worst) pointer-aligned memory anyway.
*/
#if ((SIZEOF_VOID_P - 1) & SIZEOF_VOID_P) != 0
# error "_PyObject_VAR_SIZE requires SIZEOF_VOID_P be a power of 2"
#endif
#define _PyObject_VAR_SIZE(typeobj, nitems) \
(size_t) \
( ( (typeobj)->tp_basicsize + \
(nitems)*(typeobj)->tp_itemsize + \
(SIZEOF_VOID_P - 1) \
) & ~(SIZEOF_VOID_P - 1) \
)
#define PyObject_NEW(type, typeobj) \
( (type *) PyObject_Init( \
(PyObject *) PyObject_MALLOC( _PyObject_SIZE(typeobj) ), (typeobj)) )
#define PyObject_NEW_VAR(type, typeobj, n) \
( (type *) PyObject_InitVar( \
(PyVarObject *) PyObject_MALLOC(_PyObject_VAR_SIZE((typeobj),(n)) ),\
(typeobj), (n)) )
/* This example code implements an object constructor with a custom
allocator, where PyObject_New is inlined, and shows the important
distinction between two steps (at least):
1) the actual allocation of the object storage;
2) the initialization of the Python specific fields
in this storage with PyObject_{Init, InitVar}.
PyObject *
YourObject_New(...)
{
PyObject *op;
op = (PyObject *) Your_Allocator(_PyObject_SIZE(YourTypeStruct));
if (op == NULL)
return PyErr_NoMemory();
PyObject_Init(op, &YourTypeStruct);
op->ob_field = value;
...
return op;
}
Note that in C++, the use of the new operator usually implies that
the 1st step is performed automatically for you, so in a C++ class
constructor you would start directly with PyObject_Init/InitVar
*/
/*
* Garbage Collection Support
* ==========================
*/
/* C equivalent of gc.collect(). */
PyAPI_FUNC(Py_ssize_t) PyGC_Collect(void);
/* Test if a type has a GC head */
#define PyType_IS_GC(t) PyType_HasFeature((t), Py_TPFLAGS_HAVE_GC)
/* Test if an object has a GC head */
#define PyObject_IS_GC(o) (PyType_IS_GC(Py_TYPE(o)) && \
(Py_TYPE(o)->tp_is_gc == NULL || Py_TYPE(o)->tp_is_gc(o)))
PyAPI_FUNC(PyVarObject *) _PyObject_GC_Resize(PyVarObject *, Py_ssize_t);
#define PyObject_GC_Resize(type, op, n) \
( (type *) _PyObject_GC_Resize((PyVarObject *)(op), (n)) )
/* for source compatibility with 2.2 */
#define _PyObject_GC_Del PyObject_GC_Del
/* GC information is stored BEFORE the object structure. */
typedef union _gc_head {
struct {
union _gc_head *gc_next;
union _gc_head *gc_prev;
Py_ssize_t gc_refs;
} gc;
long double dummy; /* force worst-case alignment */
} PyGC_Head;
extern PyGC_Head *_PyGC_generation0;
#define _Py_AS_GC(o) ((PyGC_Head *)(o)-1)
#define _PyGC_REFS_UNTRACKED (-2)
#define _PyGC_REFS_REACHABLE (-3)
#define _PyGC_REFS_TENTATIVELY_UNREACHABLE (-4)
/* Tell the GC to track this object. NB: While the object is tracked the
* collector it must be safe to call the ob_traverse method. */
#define _PyObject_GC_TRACK(o) do { \
PyGC_Head *g = _Py_AS_GC(o); \
if (g->gc.gc_refs != _PyGC_REFS_UNTRACKED) \
Py_FatalError("GC object already tracked"); \
g->gc.gc_refs = _PyGC_REFS_REACHABLE; \
g->gc.gc_next = _PyGC_generation0; \
g->gc.gc_prev = _PyGC_generation0->gc.gc_prev; \
g->gc.gc_prev->gc.gc_next = g; \
_PyGC_generation0->gc.gc_prev = g; \
} while (0);
/* Tell the GC to stop tracking this object.
* gc_next doesn't need to be set to NULL, but doing so is a good
* way to provoke memory errors if calling code is confused.
*/
#define _PyObject_GC_UNTRACK(o) do { \
PyGC_Head *g = _Py_AS_GC(o); \
assert(g->gc.gc_refs != _PyGC_REFS_UNTRACKED); \
g->gc.gc_refs = _PyGC_REFS_UNTRACKED; \
g->gc.gc_prev->gc.gc_next = g->gc.gc_next; \
g->gc.gc_next->gc.gc_prev = g->gc.gc_prev; \
g->gc.gc_next = NULL; \
} while (0);
/* True if the object is currently tracked by the GC. */
#define _PyObject_GC_IS_TRACKED(o) \
((_Py_AS_GC(o))->gc.gc_refs != _PyGC_REFS_UNTRACKED)
/* True if the object may be tracked by the GC in the future, or already is.
This can be useful to implement some optimizations. */
#define _PyObject_GC_MAY_BE_TRACKED(obj) \
(PyObject_IS_GC(obj) && \
(!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj)))
PyAPI_FUNC(PyObject *) _PyObject_GC_Malloc(size_t);
PyAPI_FUNC(PyObject *) _PyObject_GC_New(PyTypeObject *);
PyAPI_FUNC(PyVarObject *) _PyObject_GC_NewVar(PyTypeObject *, Py_ssize_t);
PyAPI_FUNC(void) PyObject_GC_Track(void *);
PyAPI_FUNC(void) PyObject_GC_UnTrack(void *);
PyAPI_FUNC(void) PyObject_GC_Del(void *);
#define PyObject_GC_New(type, typeobj) \
( (type *) _PyObject_GC_New(typeobj) )
#define PyObject_GC_NewVar(type, typeobj, n) \
( (type *) _PyObject_GC_NewVar((typeobj), (n)) )
/* Utility macro to help write tp_traverse functions.
* To use this macro, the tp_traverse function must name its arguments
* "visit" and "arg". This is intended to keep tp_traverse functions
* looking as much alike as possible.
*/
#define Py_VISIT(op) \
do { \
if (op) { \
int vret = visit((PyObject *)(op), arg); \
if (vret) \
return vret; \
} \
} while (0)
/* This is here for the sake of backwards compatibility. Extensions that
* use the old GC API will still compile but the objects will not be
* tracked by the GC. */
#define PyGC_HEAD_SIZE 0
#define PyObject_GC_Init(op)
#define PyObject_GC_Fini(op)
#define PyObject_AS_GC(op) (op)
#define PyObject_FROM_GC(op) (op)
/* Test if a type supports weak references */
#define PyType_SUPPORTS_WEAKREFS(t) \
(PyType_HasFeature((t), Py_TPFLAGS_HAVE_WEAKREFS) \
&& ((t)->tp_weaklistoffset > 0))
#define PyObject_GET_WEAKREFS_LISTPTR(o) \
((PyObject **) (((char *) (o)) + Py_TYPE(o)->tp_weaklistoffset))
#ifdef __cplusplus
}
#endif
#endif /* !Py_OBJIMPL_H */
|
{
"pile_set_name": "Github"
}
|
#pylint: disable=missing-docstring
#* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgpl-2.1.html
import vtk
import mooseutils
from .ExodusReader import ExodusReader
from .. import utils
from .. import base
from .. import filters
class ExodusSource(base.ChiggerSource):
"""
Object for visualizing 3D volumes from an ExodusReader object.
See ExodusReader for details regarding the ExodusII file support provided.
Inputs:
reader[ExodusReader]: The reader object containing the ExodusII file desired to be open.
**kwargs: see ChiggerSource
"""
FILTER_TYPES = [filters.ContourFilter, filters.ClipperFilterBase, filters.GeometryFilter,
filters.TransformFilter, filters.TubeFilter, filters.RotationalExtrusionFilter]
@staticmethod
def getOptions():
opt = base.ChiggerSource.getOptions()
# Variable
opt.add('variable', "The nodal or elemental variable to render.", vtype=str)
opt.add('component', -1, "The vector variable component to render (-1 plots the "
" magnitude).", vtype=int, allow=[-1, 0, 1, 2])
# Subdomains/sidesets/nodesets
opt.add('nodeset', None, "A list of nodeset ids or names to display, use [] to display all "
"nodesets.", vtype=list)
opt.add('boundary', None, "A list of boundary ids (sideset) ids or names to display, use "
"[] to display all sidesets", vtype=list)
opt.add('block', [], "A list of subdomain (block) ids or names to display, use [] to "
"dislpay all blocks.", vtype=list)
opt.add('representation', 'surface', "View volume representation.",
allow=['surface', 'wireframe', 'points'])
opt.add('range', "The range of data to display on the volume and colorbar; range takes "
"precedence of min/max.", vtype=list)
opt.add('min', "The minimum range.", vtype=float)
opt.add('max', "The maximum range.", vtype=float)
# Colormap
opt += base.ColorMap.getOptions()
return opt
def __init__(self, reader, **kwargs):
super(ExodusSource, self).__init__(**kwargs)
if not isinstance(reader, ExodusReader):
raise mooseutils.MooseException('The supplied reader must be a '
'"chigger.readers.ExodusReader", but a "{}" was '
'provided.'.format(type(reader).__name__))
self.__reader = reader
self.__current_variable = None
self._colormap = base.ColorMap()
self.__extract_indices = []
self.__vtkextractblock = vtk.vtkExtractBlock()
self.__vtkextractblock.SetInputConnection(self.__reader.getVTKReader().GetOutputPort())
self._required_filters = [filters.GeometryFilter()]
def getExodusReader(self):
"""
Return the ExodusReader object.
"""
return self.__reader
def getCurrentVariableInformation(self):
"""
Return the chigger ExodusReader object.
"""
return self.__current_variable
def getVTKSource(self):
"""
Returns the vtkExtractBlock object used for pulling subdomain/sideset/nodeset data from the
reader. (override)
Returns:
vtk.vtkExtractBlock (see ChiggerFilterSourceBase)
"""
return self.__vtkextractblock
def getBounds(self):
"""
Return the extents of the active data objects.
"""
self.checkUpdateState()
bnds = []
for i in range(self.__vtkextractblock.GetOutput().GetNumberOfBlocks()):
current = self.__vtkextractblock.GetOutput().GetBlock(i)
if isinstance(current, vtk.vtkUnstructuredGrid):
bnds.append(current.GetBounds())
elif isinstance(current, vtk.vtkMultiBlockDataSet):
for j in range(current.GetNumberOfBlocks()):
bnds.append(current.GetBlock(j).GetBounds())
return utils.get_bounds_min_max(*bnds)
def getRange(self, local=False):
"""
Return range of the active variable and blocks.
"""
self.checkUpdateState()
if self.__current_variable is None:
return (None, None)
elif not local:
return self.__getRange()
else:
return self.__getLocalRange()
def __getRange(self):
"""
Private version of range for the update method.
"""
component = self.getOption('component')
pairs = []
for i in range(self.__vtkextractblock.GetOutput().GetNumberOfBlocks()):
current = self.__vtkextractblock.GetOutput().GetBlock(i)
if isinstance(current, vtk.vtkUnstructuredGrid):
array = self.__getActiveArray(current)
if array:
pairs.append(array.GetRange(component))
elif isinstance(current, vtk.vtkMultiBlockDataSet):
for j in range(current.GetNumberOfBlocks()):
array = self.__getActiveArray(current.GetBlock(j))
if array:
pairs.append(array.GetRange(component))
return utils.get_min_max(*pairs)
def __getLocalRange(self):
"""
Determine the range of visible items.
"""
component = self.getOption('component')
self.getVTKMapper().Update() # required to have up-to-date ranges
data = self.getVTKMapper().GetInput()
out = self.__getActiveArray(data)
if out is not None:
return out.GetRange(component)
else:
return [None, None]
def __getActiveArray(self, data):
"""
Return the vtkArray for the current variable.
Inputs:
data[vtkUnstructuredGrid]: The VTK data object to extract array from.
see __GetRange and __GetBounds
"""
name = self.__current_variable.name
if self.__current_variable.object_type == ExodusReader.ELEMENTAL:
for a in range(data.GetCellData().GetNumberOfArrays()):
if data.GetCellData().GetArrayName(a) == name:
return data.GetCellData().GetAbstractArray(a)
elif self.__current_variable.object_type == ExodusReader.NODAL:
for a in range(data.GetPointData().GetNumberOfArrays()):
if data.GetPointData().GetArrayName(a) == name:
return data.GetPointData().GetAbstractArray(a)
else:
raise mooseutils.MooseException('Unable to get the range for the '
'variable "{}"'.format(self.__current_variable.name))
def needsUpdate(self):
"""
Indicates if this object needs its update method called. (override)
This adds checking of the contained reader, if the reader needs updating then so does this
class.
"""
needs_update = super(ExodusSource, self).needsUpdate()
mooseutils.mooseDebug('ExodusSource.needsUpdate() = {}'.format(needs_update))
return needs_update or self.__reader.needsUpdate()
def update(self, **kwargs):
"""
Updates this object based on the reader and specified options.
Inputs:
see ChiggerSource
"""
# Update the options, but do not call update from base class. See comment at end of this
# method.
self.setOptions(**kwargs)
# Update the reader, if needed
if self.__reader.needsUpdate():
self.__reader.update()
# Enable all blocks (subdomains) if nothing is enabled
block_info = self.__reader.getBlockInformation()
for item in ['block', 'boundary', 'nodeset']:
if self.isOptionValid(item) and self.getOption(item) == []:
self.setOption(item, [item.name for item in \
block_info[getattr(ExodusReader, item.upper())].values()])
self.setNeedsUpdate(False) # this function does not need to update again
def get_indices(option, vtk_type):
"""
Helper to populate vtkExtractBlock object from the selected blocks/sidesets/nodesets
"""
indices = []
if self.isOptionValid(option):
blocks = self.getOption(option)
for vtkid, item in block_info[vtk_type].items():
for name in blocks:
if (item.name == str(name)) or (str(name) == vtkid):
indices.append(item.multiblock_index)
return indices
extract_indices = get_indices('block', ExodusReader.BLOCK)
extract_indices += get_indices('boundary', ExodusReader.SIDESET)
extract_indices += get_indices('nodeset', ExodusReader.NODESET)
if self.__extract_indices != extract_indices:
self.__vtkextractblock.RemoveAllIndices()
for index in extract_indices:
self.__vtkextractblock.AddIndex(index)
self.__extract_indices = extract_indices
self.__vtkextractblock.Update()
# Define the coloring to utilize for the object
self.__updateVariable()
# Representation
if self.isOptionValid('representation'):
func = 'SetRepresentationTo{}'.format(self.getOption('representation').title())
attr = getattr(self._vtkactor.GetProperty(), func)
attr()
# Without this the results can be less than ideal
# (https://blog.kitware.com/what-is-interpolatescalarsbeforemapping-in-vtk/)
self._vtkmapper.InterpolateScalarsBeforeMappingOn()
# Call the base class method, this is done last because the reader and block extracting
# needs to be in place before the filters can be applied
super(ExodusSource, self).update()
def __updateVariable(self):
"""
Method to update the active variable to display on the object. (private)
"""
def get_available_variables():
"""
Returns a sting listing the available nodal and elemental variable names.
"""
nvars = self.__reader.getVariableInformation(var_types=[ExodusReader.NODAL]).keys()
evars = self.__reader.getVariableInformation(var_types=[ExodusReader.ELEMENTAL]).keys()
msg = ["Nodal:"]
msg += [" " + var for var in nvars]
msg += ["\nElemental:"]
msg += [" " + var for var in evars]
return ''.join(msg)
# Define the active variable name
available = self.__reader.getVariableInformation(var_types=[ExodusReader.NODAL,
ExodusReader.ELEMENTAL])
# Case when no variable exists
if not available:
return
default = available[list(available.keys())[0]]
if not self.isOptionValid('variable'):
varinfo = default
else:
var_name = self.getOption('variable')
if var_name not in available:
msg = "The variable '{}' provided does not exist, using '{}', available " \
"variables include:\n{}"
mooseutils.mooseError(msg.format(var_name, default.name, get_available_variables()))
varinfo = default
else:
varinfo = available[var_name]
# Update vtkMapper to the correct data mode
if varinfo.object_type == ExodusReader.ELEMENTAL:
self._vtkmapper.SetScalarModeToUseCellFieldData()
elif varinfo.object_type == ExodusReader.NODAL:
self._vtkmapper.SetScalarModeToUsePointFieldData()
else:
raise mooseutils.MooseException('Unknown variable type, not sure how you made it here.')
self.__current_variable = varinfo
# Colormap
if not self.isOptionValid('color'):
self._colormap.setOptions(cmap=self.getOption('cmap'),
cmap_reverse=self.getOption('cmap_reverse'),
cmap_num_colors=self.getOption('cmap_num_colors'))
self._vtkmapper.SelectColorArray(varinfo.name)
self._vtkmapper.SetLookupTable(self._colormap())
self._vtkmapper.UseLookupTableScalarRangeOff()
# Component
component = -1 # Default component to utilize if not valid
if self.isOptionValid('component'):
component = self.getOption('component')
if component == -1:
self._vtkmapper.GetLookupTable().SetVectorModeToMagnitude()
else:
if component > varinfo.num_components:
msg = 'Invalid component number ({}), the variable "{}" has {} components.'
mooseutils.mooseError(msg.format(component, varinfo.name, varinfo.num_components))
self._vtkmapper.GetLookupTable().SetVectorModeToComponent()
self._vtkmapper.GetLookupTable().SetVectorComponent(component)
# Range
if (self.isOptionValid('min') or self.isOptionValid('max')) and self.isOptionValid('range'):
mooseutils.mooseError('Both a "min" and/or "max" options has been set along with the '
'"range" option, the "range" is being utilized, the others are '
'ignored.')
# Range
rng = list(self.__getRange()) # Use range from all sources as the default
if self.isOptionValid('range'):
rng = self.getOption('range')
else:
if self.isOptionValid('min'):
rng[0] = self.getOption('min')
if self.isOptionValid('max'):
rng[1] = self.getOption('max')
if rng[0] > rng[1]:
mooseutils.mooseDebug("Minimum range greater than maximum:", rng[0], ">", rng[1],
", the range/min/max settings are being ignored.")
rng = list(self.__getRange())
self.getVTKMapper().SetScalarRange(rng)
# Handle Elemental variables that are not everywhere on the domain
varname = self.__current_variable.name
block = self.getOption('block')
if (self.__current_variable.object_type == ExodusReader.ELEMENTAL) and (block is not None):
for i in range(self.__vtkextractblock.GetOutput().GetNumberOfBlocks()):
if not hasattr(self.__vtkextractblock.GetOutput().GetBlock(i), 'GetNumberOfBlocks'):
continue
for j in range(self.__vtkextractblock.GetOutput().GetBlock(i).GetNumberOfBlocks()):
blk = self.__vtkextractblock.GetOutput().GetBlock(i).GetBlock(j)
if not blk.GetCellData().HasArray(varname):
data = vtk.vtkDoubleArray()
data.SetName(varname)
data.SetNumberOfTuples(blk.GetCellData().GetArray(0).GetNumberOfTuples())
data.FillComponent(0, vtk.vtkMath.Nan())
blk.GetCellData().AddArray(data)
|
{
"pile_set_name": "Github"
}
|
(function() {var implementors = {};
implementors['collections'] = [];
if (window.register_implementors) {
window.register_implementors(implementors);
} else {
window.pending_implementors = implementors;
}
})()
|
{
"pile_set_name": "Github"
}
|
/*******************************************************************************
* Copyright (c) 2013-2015 Sierra Wireless and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v20.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.html.
*
* Contributors:
* Sierra Wireless - initial API and implementation
*******************************************************************************/
package org.eclipse.leshan.server.demo.servlet.json;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.leshan.core.node.LwM2mMultipleResource;
import org.eclipse.leshan.core.node.LwM2mNode;
import org.eclipse.leshan.core.node.LwM2mObject;
import org.eclipse.leshan.core.node.LwM2mObjectInstance;
import org.eclipse.leshan.core.node.LwM2mResource;
import org.eclipse.leshan.core.node.LwM2mSingleResource;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
public class LwM2mNodeDeserializer implements JsonDeserializer<LwM2mNode> {
@Override
public LwM2mNode deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
if (json == null) {
return null;
}
LwM2mNode node;
if (json.isJsonObject()) {
JsonObject object = (JsonObject) json;
Integer id = null;
if (object.has("id")) {
id = object.get("id").getAsInt();
}
if (object.has("instances")) {
if (id == null) {
throw new JsonParseException("Missing id");
}
JsonArray array = object.get("instances").getAsJsonArray();
LwM2mObjectInstance[] instances = new LwM2mObjectInstance[array.size()];
for (int i = 0; i < array.size(); i++) {
instances[i] = context.deserialize(array.get(i), LwM2mNode.class);
}
node = new LwM2mObject(id, instances);
} else if (object.has("resources")) {
JsonArray array = object.get("resources").getAsJsonArray();
LwM2mResource[] resources = new LwM2mResource[array.size()];
for (int i = 0; i < array.size(); i++) {
resources[i] = context.deserialize(array.get(i), LwM2mNode.class);
}
if (id == null) {
node = new LwM2mObjectInstance(Arrays.asList(resources));
} else {
node = new LwM2mObjectInstance(id, resources);
}
} else if (object.has("value")) {
if (id == null) {
throw new JsonParseException("Missing id");
}
// single value resource
JsonPrimitive val = object.get("value").getAsJsonPrimitive();
org.eclipse.leshan.core.model.ResourceModel.Type expectedType = getTypeFor(val);
node = LwM2mSingleResource.newResource(id, deserializeValue(val, expectedType), expectedType);
} else if (object.has("values")) {
if (id == null) {
throw new JsonParseException("Missing id");
}
// multi-instances resource
Map<Integer, Object> values = new HashMap<>();
org.eclipse.leshan.core.model.ResourceModel.Type expectedType = null;
for (Entry<String, JsonElement> entry : object.get("values").getAsJsonObject().entrySet()) {
JsonPrimitive pval = entry.getValue().getAsJsonPrimitive();
expectedType = getTypeFor(pval);
values.put(Integer.valueOf(entry.getKey()), deserializeValue(pval, expectedType));
}
// use string by default;
if (expectedType == null)
expectedType = org.eclipse.leshan.core.model.ResourceModel.Type.STRING;
node = LwM2mMultipleResource.newResource(id, values, expectedType);
} else {
throw new JsonParseException("Invalid node element");
}
} else {
throw new JsonParseException("Invalid node element");
}
return node;
}
private org.eclipse.leshan.core.model.ResourceModel.Type getTypeFor(JsonPrimitive val) {
if (val.isBoolean())
return org.eclipse.leshan.core.model.ResourceModel.Type.BOOLEAN;
if (val.isString())
return org.eclipse.leshan.core.model.ResourceModel.Type.STRING;
if (val.isNumber()) {
if (val.getAsDouble() == val.getAsLong()) {
return org.eclipse.leshan.core.model.ResourceModel.Type.INTEGER;
} else {
return org.eclipse.leshan.core.model.ResourceModel.Type.FLOAT;
}
}
// use string as default value
return org.eclipse.leshan.core.model.ResourceModel.Type.STRING;
}
private Object deserializeValue(JsonPrimitive val, org.eclipse.leshan.core.model.ResourceModel.Type expectedType) {
switch (expectedType) {
case BOOLEAN:
return val.getAsBoolean();
case STRING:
return val.getAsString();
case INTEGER:
return val.getAsLong();
case FLOAT:
return val.getAsDouble();
case TIME:
case OPAQUE:
default:
// TODO we need to better handle this.
return val.getAsString();
}
}
}
|
{
"pile_set_name": "Github"
}
|
//! [Problem 70](https://projecteuler.net/problem=70) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use integer::Integer;
use prime::PrimeSet;
use std::f64;
fn compute(limit: u64) -> u64 {
// n = \Pi_{k=1}^d p_k
// n / phi(n) = 1 / \Pi_{k=1}^d (1 - 1/p_k)
// => p^k / phi(p^k) = p / phi(p)
// p is greater then n / phi(p) is less
//
// phi(p) = p - 1 (if p is prime) => phi(p) is not permutation of p
// phi(p1 * p2) = (p1 - 1) * (p2 - 1)
let ps = PrimeSet::new();
let mut min_n = 0;
let mut min_n_phi = f64::INFINITY;
for p1 in &ps {
if p1 * p1 > limit {
break;
}
for p2 in &ps {
if p2 < p1 {
continue;
}
let n = p1 * p2;
if n > limit {
break;
}
let phi = (p1 - 1) * (p2 - 1);
let ds1 = n.into_digit_histogram();
let ds2 = phi.into_digit_histogram();
if ds1 != ds2 {
continue;
}
let n_phi = (n as f64) / (phi as f64);
if n_phi < min_n_phi {
min_n_phi = n_phi;
min_n = n;
}
}
}
min_n
}
fn solve() -> String {
compute(10000000).to_string()
}
common::problem!("8319823", solve);
|
{
"pile_set_name": "Github"
}
|
<?php
namespace Kahlan\Plugin;
use InvalidArgumentException;
use Kahlan\Suite;
use Kahlan\Analysis\Inspector;
use Kahlan\Plugin\Stub\Method;
class Stub
{
/**
* Registered stubbed instance/class methods.
*
* @var array
*/
protected static $_registered = [];
/**
* The stub reference.
*
* @var mixed
*/
protected $_reference = null;
/**
* Method chain.
*
* @var Method[]
*/
protected $_chain = [];
/**
* Stubbed methods.
*
* @var Method[]
*/
protected $_methods = [];
/**
* Generic stubs.
*
* @var Method[]
*/
protected $_stubs = [];
/**
* Stub index counter.
*
* @var integer
*/
protected $_needToBePatched = false;
/**
* The Constructor.
*
* @param mixed $reference An instance or a fully-namespaced class name.
*/
public function __construct($reference)
{
$reference = $this->_reference($reference);
$isString = is_string($reference);
if ($isString) {
if (!class_exists($reference)) {
throw new InvalidArgumentException("Can't Stub the unexisting class `{$reference}`.");
}
$reference = ltrim($reference, '\\');
$reflection = Inspector::inspect($reference);
} else {
$reflection = Inspector::inspect(get_class($reference));
}
if (!$reflection->isInternal()) {
$this->_reference = $reference;
return;
}
if (!$isString) {
throw new InvalidArgumentException("Can't Stub built-in PHP instances, create a test double using `Double::instance()`.");
}
$this->_needToBePatched = true;
return $this->_reference = $reference;
}
/**
* Return the actual reference which must be used.
*
* @param mixed $reference An instance or a fully-namespaced class name.
* @param mixed The reference or the monkey patched one if exist.
*/
protected function _reference($reference)
{
if (!is_string($reference)) {
return $reference;
}
$pos = strrpos($reference, '\\');
if ($pos !== false) {
$namespace = substr($reference, 0, $pos);
$basename = substr($reference, $pos + 1);
} else {
$namespace = null;
$basename = $reference;
}
$substitute = null;
$reference = Monkey::patched($namespace, $basename, false, $substitute);
return $substitute ?: $reference;
}
/**
* Getd/Setd stubs for methods or get stubbed methods array.
*
* @param array $name An array of method names.
* @return Method[] Return the array of stubbed methods.
*/
public function methods($name = [])
{
if (!func_num_args()) {
return $this->_methods;
}
foreach ($name as $method => $returns) {
if (is_callable($returns)) {
$this->method($method, $returns);
} elseif (is_array($returns)) {
$stub = $this->method($method);
call_user_func_array([$stub, 'andReturn'], $returns);
} else {
$error = "Stubbed method definition for `{$method}` must be a closure or an array of returned value(s).";
throw new InvalidArgumentException($error);
}
}
}
/**
* Stubs a method.
*
* @param string $path Method name or array of stubs where key are method names and
* values the stubs.
* @param string $closure The stub implementation.
* @return Method[] The created array of method instances.
* @return Method The stubbed method instance.
*/
public function method($path, $closure = null)
{
if ($this->_needToBePatched) {
$layer = Double::classname();
Monkey::patch($this->_reference, $layer);
$this->_needToBePatched = false;
$this->_reference = $layer;
}
$reference = $this->_reference;
if (!$path) {
throw new InvalidArgumentException("Method name can't be empty.");
}
$names = is_array($path) ? $path : [$path];
$this->_chain = [];
$total = count($names);
foreach ($names as $index => $name) {
if (preg_match('/^::.*/', $name)) {
$reference = is_object($reference) ? get_class($reference) : $reference;
}
$hash = Suite::hash($reference);
if (!isset(static::$_registered[$hash])) {
static::$_registered[$hash] = new static($reference);
}
$instance = static::$_registered[$hash];
if (is_object($reference)) {
Suite::register(get_class($reference));
} else {
Suite::register($reference);
}
if (!isset($instance->_methods[$name])) {
$instance->_methods[$name] = [];
$instance->_stubs[$name] = Double::instance();
}
$method = new Method([
'parent' => $this,
'reference' => $reference,
'name' => $name
]);
$this->_chain[$name] = $method;
array_unshift($instance->_methods[$name], $method);
if ($index < $total - 1) {
$reference = $instance->_stubs[$name];
$method->andReturn($instance->_stubs[$name]);
}
}
$method = end($this->_chain);
if ($closure) {
$method->andRun($closure);
}
return $method;
}
/**
* Set arguments requirement indexed by method name.
*
* @param mixed ... <0,n> Argument(s).
* @return self
*/
public function where($requirements = [])
{
foreach ($requirements as $name => $args) {
if (!isset($this->_chain[$name])) {
throw new InvalidArgumentException("Unexisting `{$name}` as method as part of the chain definition.");
}
if (!is_array($args)) {
throw new InvalidArgumentException("Argument requirements must be an arrays for `{$name}` method.");
}
call_user_func_array([$this->_chain[$name], 'with'], $args);
}
return $this;
}
/**
* Stubs class methods.
*
* @param object|string $reference An instance or a fully-namespaced class name.
* @return self The Stub instance.
*/
public static function on($reference)
{
$hash = Suite::hash($reference);
if (isset(static::$_registered[$hash])) {
return static::$_registered[$hash];
}
return static::$_registered[$hash] = new static($reference);
}
/**
* Finds a stub.
*
* @param mixed $references An instance or a fully namespaced class name.
* or an array of that.
* @param string $method The method name.
* @param array $args The required arguments.
* @return object|null Return the subbed method or `null` if not founded.
*/
public static function find($references, $method = null, $args = null)
{
$references = (array) $references;
$stub = null;
foreach ($references as $reference) {
$hash = Suite::hash($reference);
if (!isset(static::$_registered[$hash])) {
continue;
}
$stubs = static::$_registered[$hash]->methods();
if (!isset($stubs[$method])) {
continue;
}
foreach ($stubs[$method] as $stub) {
$call['name'] = $method;
$call['args'] = $args;
if ($stub->match($call)) {
return $stub;
}
}
}
return false;
}
/**
* Checks if a stub has been registered for a hash
*
* @param mixed $hash An instance hash or a fully namespaced class name.
* @return boolean|array
*/
public static function registered($hash = null)
{
if (!func_num_args()) {
return array_keys(static::$_registered);
}
return isset(static::$_registered[$hash]);
}
/**
* Clears the registered references.
*
* @param string $reference An instance or a fully namespaced class name or `null` to clear all.
*/
public static function reset($reference = null)
{
if ($reference === null) {
static::$_registered = [];
Suite::reset();
return;
}
unset(static::$_registered[Suite::hash($reference)]);
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "syzygy/integration_tests/integration_tests_dll.h"
#include <windows.h> // NOLINT
#include <stdint.h>
#include "syzygy/integration_tests/asan_check_tests.h"
#include "syzygy/integration_tests/asan_interceptors_tests.h"
#include "syzygy/integration_tests/asan_page_protection_tests.h"
#ifndef __clang__
#include "syzygy/integration_tests/bb_entry_tests.h"
#include "syzygy/integration_tests/behavior_tests.h"
#include "syzygy/integration_tests/coverage_tests.h"
#include "syzygy/integration_tests/profile_tests.h"
#endif // __clang__
#include "syzygy/integration_tests/deferred_free_tests.h"
BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved) {
return TRUE;
}
unsigned int CALLBACK EndToEndTest(testing::EndToEndTestId test) {
switch (test) {
#define DECLARE_END_TO_END_SWITCH_TABLE(enum_name, function_to_call) \
case testing::enum_name: { \
return function_to_call(); \
}
END_TO_END_TEST_ID_TABLE(DECLARE_END_TO_END_SWITCH_TABLE)
#undef DECLARE_END_TO_END_SWITCH_TABLE
default:
return 0;
}
}
|
{
"pile_set_name": "Github"
}
|
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"## Word 2 Vec"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import pandas as pd\n",
"\n",
"filename=\"C:/Users/Madhu/Desktop/\"\n",
"data = pd.read_csv(filename+'sentences.csv')"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style>\n",
" .dataframe thead tr:only-child th {\n",
" text-align: right;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: left;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>SentenceId</th>\n",
" <th>EpisodeId</th>\n",
" <th>Season</th>\n",
" <th>Episode</th>\n",
" <th>Sentence</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>Pilot</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>2</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>Scene One</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>3</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>[Title: The Year 2030]</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>4</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>Narrator: Kids, I'm going to tell you an incre...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>5</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>Son: Are we being punished for something?</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" SentenceId EpisodeId Season Episode \\\n",
"0 1 1 1 1 \n",
"1 2 1 1 1 \n",
"2 3 1 1 1 \n",
"3 4 1 1 1 \n",
"4 5 1 1 1 \n",
"\n",
" Sentence \n",
"0 Pilot \n",
"1 Scene One \n",
"2 [Title: The Year 2030] \n",
"3 Narrator: Kids, I'm going to tell you an incre... \n",
"4 Son: Are we being punished for something? "
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"data.head()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"df= data.loc[data['Season']==1]\n",
"df=df.fillna(\"(\")"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"df['Character']=\"\"\n",
"for sen,id in zip(df[\"Sentence\"],df[\"SentenceId\"]):\n",
" \n",
" if \"[\" is sen[0] or \"(\" is sen[0] or \"Scene\" in sen[0:5] or \":\" not in sen:\n",
" df = df.drop(df[df['Sentence']==sen].index)\n",
" \n",
" else:\n",
" value=\"\"\n",
" for c in sen:\n",
" if c==\":\":\n",
" df.set_value(id-1, 'Sentence', sen[len(value)+1:])\n",
" break\n",
" \n",
" else:\n",
" value+=c\n",
" \n",
" \n",
" if \"(\" in value:\n",
" index=value.index(\"(\")\n",
" value=value[:index-1]\n",
" \n",
" value=value.lower() \n",
" #df.loc[df['Sentence'] == sen,'Character']=sen #setting the values\n",
" df.set_value(id-1, 'Character', value)\n",
"\n",
"#re arrange the order \n",
"df = df[['SentenceId','EpisodeId','Season','Episode','Character','Sentence']]"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style>\n",
" .dataframe thead tr:only-child th {\n",
" text-align: right;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: left;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>SentenceId</th>\n",
" <th>EpisodeId</th>\n",
" <th>Season</th>\n",
" <th>Episode</th>\n",
" <th>Character</th>\n",
" <th>Sentence</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>4</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>narrator</td>\n",
" <td>Kids, I'm going to tell you an incredible sto...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>5</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>son</td>\n",
" <td>Are we being punished for something?</td>\n",
" </tr>\n",
" <tr>\n",
" <th>5</th>\n",
" <td>6</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>narrator</td>\n",
" <td>No</td>\n",
" </tr>\n",
" <tr>\n",
" <th>6</th>\n",
" <td>7</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>daughter</td>\n",
" <td>Yeah, is this going to take a while?</td>\n",
" </tr>\n",
" <tr>\n",
" <th>7</th>\n",
" <td>8</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>narrator</td>\n",
" <td>Yes. (Kids are annoyed) Twenty-five years ago...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" SentenceId EpisodeId Season Episode Character \\\n",
"3 4 1 1 1 narrator \n",
"4 5 1 1 1 son \n",
"5 6 1 1 1 narrator \n",
"6 7 1 1 1 daughter \n",
"7 8 1 1 1 narrator \n",
"\n",
" Sentence \n",
"3 Kids, I'm going to tell you an incredible sto... \n",
"4 Are we being punished for something? \n",
"5 No \n",
"6 Yeah, is this going to take a while? \n",
"7 Yes. (Kids are annoyed) Twenty-five years ago... "
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df[:5]"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAY4AAAEqCAYAAAACibeEAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3Xu8VVW5//HPFxBBUbxwMdgCXsFbEOGlMtPsgmbhJTWi\nkxfKXxaleSlPVh4xj2WevBZqeUHzgGiWnMIUEdTygoAIlqJIKCQIooKGSsDz+2OODYvNvk3de821\n4Pt+vdZrzTnmWGs9a6291zPHmGOOqYjAzMysudoUHYCZmVUXJw4zM8vFicPMzHJx4jAzs1ycOMzM\nLBcnDjMzy8WJw1qdpMGS5hYdR6WS9IKkjzSy/TFJXylnTC1NUgdJIakmrd8s6XvNfGzVv/9NjRPH\nJk7SWyW3tZLeLlkfVnR85SSpn6TVRcdRV0TsFhGPAkj6qaTfFB1TUyQtlnTwe318RJwcEZe2ZExW\nPu2KDsBaV0R0ql2WNB/4WkTcX1xE74+kdhFRyI9/ka9tVknc4tjMSeoo6ZeSFklaKOnnkrZI2wZL\nmivpQkmvSZon6fhGnquLpFvS3ujrkm6vs/0HkpZK+mdpa0fSMZKekrRC0ouSflCyrZ+k1ZK+LmkB\nMEFSO0m/k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pe8muL3Mt2QCPbwB/LjakJs2UNJ7szPHSnaCK\n3nlz4rA/StoOuJRsRApkXVYVKyJGFx2DVaTvk42wOp3sYP59VPjfMrAD2c5a6SjGipy5oZRHVW3m\nJHUk+0f7ONkf7MPAqIh4p9DAGiFpD7LpJfZmwwP6uxYWlNlmxC0OG012DYCr0vpQshFKJxQWUdNu\nIrse9uVkB/VPYf3YfdvMVOt13WHdyYvD2XhUY8VdlKyUE4f1jYj+JeuTJT1VWDTN0zEiJqUDoS8C\n/yXpYbJkYpuf2uu630Q2InBBgbHkdSvwLPBZspNwhwEVf20cz1VlT6ZrAgAg6UDgrwXG0xzvSGoD\nPC9phKRjyK5gaJuhiFiUFrcBrgN+SzZdyjtVMKx494j4Edk1OEYDnwP2KzimJvkYx2aqpFm/BdAX\neCmt9wb+HhH7FhheoyTtT7ZXth1wEdmcRJdGxOOFBmYVQdIHgRPJJgtcWMnX75Y0NSIOkPQQ2eWn\nFwNTK/14nbuqNl9HFR3A+xBkTfzerJ+j6tdAxfZlW1ktIfsBXkblt0SvT2e4/5Bs2pFOwI+KDalp\nbnFY1ZE0BzgXmA2srS2vgm4Ja0WSTidraXQF7gRuj4i/FxtV4yRtSdYy6sP6naCo1Cl/arnFYdVo\naZXM2mrl1Rs4MyJmFh1IDncDy8nOoXq3iboVwy0OqzqSDicbNjyJCr9OulljJD1dyccTG+IWh1Wj\nU4B+ZE372q6qij/b1qwej0jaLyJmFx1IHm5xWNWRNDsiKn7IollT0nVPdgf+QdZ6rvjrnoBbHFad\nHpO0d6Uf+DRrhmq87olbHFZ9JD0D7EaV7aWZbSqcOKzqSOpdX7mH45qVhxOHmZnl4rmqzMwsFycO\nMzPLxYnDzMxyceIwM7NcnDjMzCyX/w8lKRLmlCG05gAAAABJRU5ErkJggg==\n",
"text/plain": [
"<matplotlib.figure.Figure at 0x20303168da0>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# for labeling in plotting\n",
"def autolabel(rects):\n",
" for rect in rects:\n",
" height = rect.get_height()\n",
" ax.text(rect.get_x() + rect.get_width()/2., 1.02*height,\n",
" '%d' % int(height),\n",
" ha='center', va='bottom')\n",
"\n",
"topchar=df.Character.value_counts()[:7]\n",
"labels=np.array(topchar.keys())\n",
"values=np.array(topchar)\n",
"ind=np.arange(len(labels))\n",
"\n",
"fig,ax=plt.subplots()\n",
"rects=ax.bar(ind,values,color='g')\n",
"ax.set_xticklabels(labels,rotation='vertical')\n",
"ax.set_xticks(ind)\n",
"ax.set_ylabel(\"Count\")\n",
"ax.set_title(\"Top characters with most dialogs\")\n",
"autolabel(rects)\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"#pre processing the text \n",
"import re\n",
"def normalize_text(text):\n",
"\n",
" text=text.lower()\n",
" text = re.sub('((www\\.[^\\s]+)|(https?://[^\\s]+)|(pic\\.twitter\\.com/[^\\s]+))','', text)\n",
" text = re.sub('@[^\\s]+','', text)\n",
" text = re.sub('#([^\\s]+)', '', text)\n",
" text = re.sub('[:;>?<=*+()&,\\-#!$%\\{˜|\\}\\[^_\\\\@\\]1234567890’‘]',' ', text)\n",
" text = re.sub('[\\d]','', text)\n",
" text = text.replace(\".\", '')\n",
" text = text.replace(\"'\", '')\n",
" text = text.replace(\"`\", '')\n",
" text = text.replace(\"'s\", '')\n",
" text = text.replace(\"/\", ' ')\n",
" text = text.replace(\"\\\"\", ' ')\n",
" text = text.replace(\"\\\\\", '')\n",
" re.sub(' +', ' ', text)\n",
" text=text.replace('\\n', ' ').replace('\\r', ' ').replace('\\t', ' ')\n",
" #normalize some utf8 encoding\n",
" text = text.replace(\"\\x9d\",'').replace(\"\\x8c\",'')\n",
" text = text.replace(\"\\xa0\",'')\n",
" text = text.replace(\"\\x9d\\x92\", '').replace(\"\\x9a\\xaa\\xf0\\x9f\\x94\\xb5\", '').replace(\"\\xf0\\x9f\\x91\\x8d\\x87\\xba\\xf0\\x9f\\x87\\xb8\", '').replace(\"\\x9f\",'').replace(\"\\x91\\x8d\",'')\n",
" text = text.replace(\"\\xf0\\x9f\\x87\\xba\\xf0\\x9f\\x87\\xb8\",'').replace(\"\\xf0\",'').replace('\\xf0x9f','').replace(\"\\x9f\\x91\\x8d\",'').replace(\"\\x87\\xba\\x87\\xb8\",'')\n",
" text = text.replace(\"\\xe2\\x80\\x94\",'').replace(\"\\x9d\\xa4\",'').replace(\"\\x96\\x91\",'').replace(\"\\xe1\\x91\\xac\\xc9\\x8c\\xce\\x90\\xc8\\xbb\\xef\\xbb\\x89\\xd4\\xbc\\xef\\xbb\\x89\\xc5\\xa0\\xc5\\xa0\\xc2\\xb8\",'')\n",
" text = text.replace(\"\\xe2\\x80\\x99s\", \"\").replace(\"\\xe2\\x80\\x98\", '').replace(\"\\xe2\\x80\\x99\", '').replace(\"\\xe2\\x80\\x9c\", \"\").replace(\"\\xe2\\x80\\x9d\", \"\")\n",
" text = text.replace(\"\\xe2\\x82\\xac\", \"\").replace(\"\\xc2\\xa3\", \"\").replace(\"\\xc2\\xa0\", \"\").replace(\"\\xc2\\xab\", \"\").replace(\"\\xf0\\x9f\\x94\\xb4\", \"\").replace(\"\\xf0\\x9f\\x87\\xba\\xf0\\x9f\\x87\\xb8\\xf0\\x9f\", \"\")\n",
" text = re.sub(r\"\\b[a-z]\\b\", \"\", text)\n",
" text=re.sub( '\\s+', ' ', text).strip()\n",
" \n",
" text=re.sub(r'\\.+', \".\", text)\n",
" text=re.sub(r'\\.\\.+', ' ', text).replace('.', '')\n",
" # Replace multiple dots with space\n",
" text = re.sub('\\.\\.+', ' ', text) \n",
" # Remove single dots\n",
" text = re.sub('\\.', '', text)\n",
" text = re.sub(r'\\.{2,}', ' ', text)\n",
" text = re.sub(r'\\.{1}', '', text)\n",
" \n",
" return text"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"sentences=df[\"Sentence\"].tolist()\n",
"normalized_sentences=[]\n",
"for sentence in sentences:\n",
" norm_sent=normalize_text(sentence)\n",
" normalized_sentences.append(norm_sent)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Word count [('you', 2061), ('the', 1585), ('to', 1537), ('and', 1027), ('it', 839)]\n"
]
}
],
"source": [
"import collections\n",
"# sentences to words and count\n",
"words=\" \".join(normalized_sentences).split() \n",
"count= collections.Counter(words).most_common() \n",
"print (\"Word count\", count[:5])"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Build dictionaries\n",
"unique_words = [i[0] for i in count]\n",
"dic = {w: i for i, w in enumerate(unique_words)} #dic, word -> id cats:0 dogs:1 ......\n",
"voc_size = len(dic)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"5057"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"voc_size"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Sample data [198, 8, 42, 2, 125, 0, 77, 839, 185, 1] ['kids', 'im', 'going', 'to', 'tell', 'you', 'an', 'incredible', 'story', 'the']\n"
]
}
],
"source": [
"# Make indexed word data\n",
"data = [dic[word] for word in words] #count rank for every word in words\n",
"print('Sample data', data[:10], words[:10])"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Context pairs rank ids [[[198, 42], 8], [[8, 2], 42], [[42, 125], 2], [[2, 0], 125], [[125, 77], 0]]\n",
"\n",
"Context pairs words [[['kids', 'going'], 'im'], [['im', 'to'], 'going'], [['going', 'tell'], 'to'], [['to', 'you'], 'tell'], [['tell', 'an'], 'you']]\n"
]
}
],
"source": [
"# Let's make a training data for window size 1 for simplicity\n",
"\n",
"cbow_pairs = []\n",
"for i in range(1, len(data)-1) :\n",
" cbow_pairs.append([[data[i-1], data[i+1]], data[i]]);\n",
" \n",
"print('Context pairs rank ids', cbow_pairs[:5])\n",
"print()\n",
"\n",
"cbow_pairs_words = []\n",
"for i in range(1, len(words)-1) :\n",
" cbow_pairs_words.append([[words[i-1], words[i+1]], words[i]]);\n",
"print('Context pairs words', cbow_pairs_words[:5])"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"skip-gram pairs [[8, 198], [8, 42], [42, 8], [42, 2], [2, 42]]\n",
"\n",
"skip-gram pairs words [['im', 'kids'], ['im', 'going'], ['going', 'im'], ['going', 'to'], ['to', 'going']]\n"
]
}
],
"source": [
"# Let's make skip-gram pairs\n",
"# (quick, the), (quick, brown), (brown, quick), (brown, fox), ...\n",
"skip_gram_pairs=[]\n",
"\n",
"for c in cbow_pairs:\n",
" skip_gram_pairs.append([c[1],c[0][0]])\n",
" skip_gram_pairs.append([c[1],c[0][1]])\n",
"print('skip-gram pairs', skip_gram_pairs[:5])\n",
"print()\n",
"skip_gram_pairs_words=[]\n",
"for c in cbow_pairs_words:\n",
" skip_gram_pairs_words.append([c[1],c[0][0]])\n",
" skip_gram_pairs_words.append([c[1],c[0][1]])\n",
"print('skip-gram pairs words', skip_gram_pairs_words[:5])"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Batches (x, y) ([51, 15, 281], [[1347], [11], [106]])\n"
]
}
],
"source": [
"def get_batch(size):\n",
" assert size<len(skip_gram_pairs)\n",
" X=[]\n",
" Y=[]\n",
" rdm = np.random.choice(range(len(skip_gram_pairs)),size,replace=False)\n",
" \n",
" for r in rdm:\n",
" X.append(skip_gram_pairs[r][0])\n",
" Y.append([skip_gram_pairs[r][1]])\n",
" return X , Y\n",
"\n",
"# generate_batch test\n",
"print ('Batches (x, y)', get_batch(3))"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#tensor flow code\n",
"import tensorflow as tf\n",
"\n",
"batch_size = 20\n",
"embedding_size = 2\n",
"num_sampled = 15 # Number of negative examples to sample.\n",
"\n",
"X= tf.placeholder(tf.int32,shape=[batch_size]) #inputs\n",
"Y= tf.placeholder(tf.int32,shape=[batch_size,1]) #labels\n",
"\n",
"with tf.device(\"/cpu:0\"):\n",
" # Look up embeddings for inputs.\n",
" embeddings = tf.Variable(tf.random_uniform([voc_size,embedding_size],-1.0,1.0))\n",
" embed = tf.nn.embedding_lookup(embeddings, X) # lookup table\n",
" \n",
"# Construct the variables for the NCE loss\n",
"nce_weights = tf.Variable(tf.random_uniform([voc_size, embedding_size],-1.0, 1.0))\n",
"nce_biases = tf.Variable(tf.zeros([voc_size]))\n",
"\n",
"# Compute the average NCE loss for the batch.\n",
"# This does the magic:\n",
"# tf.nn.nce_loss(weights, biases, inputs, labels, num_sampled, num_classes ...)\n",
"# It automatically draws negative samples when we evaluate the loss.\n",
"loss = tf.reduce_mean(tf.nn.nce_loss(nce_weights, nce_biases, Y, embed, num_sampled, voc_size))\n",
"# Use the adam optimizer\n",
"optimizer = tf.train.AdamOptimizer(1e-1).minimize(loss)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Loss at 0 67.6239\n",
"Loss at 1000 27.5269\n",
"Loss at 2000 11.6259\n",
"Loss at 3000 8.19029\n",
"Loss at 4000 4.84377\n",
"Loss at 5000 5.21787\n",
"Loss at 6000 5.9497\n",
"Loss at 7000 5.17859\n",
"Loss at 8000 7.05449\n",
"Loss at 9000 4.89466\n"
]
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAX8AAAD8CAYAAACfF6SlAAAABHNCSVQICAgIfAhkiAAAA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DHmxmrKcf\njAf+IyLfqeqxUNTPgn+Iqersrt4XkYeBOcBfNcA8W1U94fnbJCJluH8Cx8x//BC0QT1w42XLY4AT\noath3+ru+we5jbjuA0GI6T4AXbeBiDSKyChVbRCRUUBTgG14+0GtiFQAmUBIgr8N+4SRiNwDrAbm\nqWpbgHWSRGSw9zXwN9wXyOJCMG0A7AcmiMg4ERkILAZCOtMhmsV7HwhSvPeB7cDDntcPA1f9GhKR\noSKS4Hk9HJgJHAxVBSz4h9dmYDDun/HfiEgJgIjcICI7PeuMBPaKyLfAPuBDVf0oMtXtE922geeC\n8D+B3cAh4F1VrYlUhUNJROaLSD0wA/hQRHZ7yh3TB4Jpg3juAx7PA3eJyBHgLs8yIjJVRF7zrDMR\nqPL0g3LgeVUNWfC3O3yNMcaB7MzfGGMcyIK/McY4kAV/Y4xxIAv+xhjjQBb8jTHGgSz4G2OMA1nw\nN8YYB7Lgb4wxDvR/Z5RXJU0Q9egAAAAASUVORK5CYII=\n",
"text/plain": [
"<matplotlib.figure.Figure at 0x2030ac33da0>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"epochs=10000\n",
"with tf.Session() as sess:\n",
" sess.run(tf.global_variables_initializer())\n",
" \n",
" for epoch in range(epochs):\n",
" \n",
" batch_inputs, batch_labels = get_batch(batch_size)\n",
" _,loss_val=sess.run([optimizer,loss],feed_dict = {X : batch_inputs, Y : batch_labels })\n",
" \n",
" if epoch % 1000 == 0:\n",
" print(\"Loss at \", epoch, loss_val) # Report the loss\n",
" \n",
" # Final embeddings are ready for you to use. Need to normalize for practical use\n",
" trained_embeddings = embeddings.eval()\n",
" \n",
"\n",
"import matplotlib.pyplot as plt\n",
"# Show word2vec if dim is 2\n",
"if trained_embeddings.shape[1] == 2:\n",
" labels = unique_words[:50] # Show top 10 words\n",
" for i, label in enumerate(labels):\n",
" x, y = trained_embeddings[i,:]\n",
" plt.scatter(x, y)\n",
" plt.annotate(label, xy=(x, y), xytext=(5, 2),\n",
" textcoords='offset points', ha='right', va='bottom')\n",
" #plt.savefig(\"word2vec.png\")\n",
" plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAX8AAAD8CAYAAACfF6SlAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3XlcV1X++PHXEdkEBRVNXAo1V1YBd0GNDKfcl9Sx1HHU\nmUoz++qU42io1VhZ2jL9HJ1Em9HRcRe10USdcE0QREVco1Q0NYMEAVnO7w/gkygICJ8FPu/n48ED\nPodz733f68f353LuWZTWGiGEENalhrkDEEIIYXqS/IUQwgpJ8hdCCCskyV8IIayQJH8hhLBCkvyF\nEMIKSfIXQggrJMlfCCGskCR/IYSwQjXNHUBJ3NzctIeHh7nDEEKIKiUmJuam1rpBafUsNvl7eHgQ\nHR1t7jBEBTg7O5OWllbm+itWrCA6OprPPvuMsLAwnJ2dmT59uhEjFKL6UUp9X5Z60uwjKiQnJ8fc\nIQghHoEkfyuVlJRE27ZtmTBhAl5eXowePZrdu3fTvXt3WrVqxbfffsu3335Lt27d6NChA926dePM\nmTNA/h368OHD6d+/P8888wxXr14lODgYPz8/vLy8iIqKMhxn1qxZ+Pr60qVLF3788UcAIiIi6Ny5\nMx06dODpp582lAshTEeSvxU7f/48U6dOJT4+nsTERFavXs3+/ftZuHAh7777Lm3btuWbb74hNjaW\nefPm8ec//9mw7aFDh1i5ciV79uxh9erVhIaGEhcXx/Hjx/Hz8wMgPT2dLl26cPz4cYKDg1m2bBkA\nPXr04PDhw8TGxjJy5Ejef/99s5y/ENbMYtv8hfE1b94cb29vADw9PQkJCUEphbe3N0lJSaSmpjJ2\n7FjOnTuHUors7GzDtn369KFevXoAdOzYkfHjx5Odnc2gQYMMyd/Ozo5+/foBEBAQwNdffw3A5cuX\nGTFiBFevXuXu3bs0b97clKcthEDu/K2avb294ecaNWoYXteoUYOc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VqrcvSLGBR\nKuFaqGLKqlwXtbJchzKwmvdEabsopqzKvSfg4deiHLt5vOB90QLYo5Q6obW+UNpGkvyNQGv99MN+\nr5QaC/QDQnQJfW211skF368rpTaR/6dulfuPXgnX4jLQ7J7XTYHkyovQNEq7DmXch1W8J8qgWrwn\n4OHXQin1o1LKXWt9VSnlDlwvYR+F74uLSql9QAeg1OQvzT4mppTqC7wBDNBa3ymhjpNSqnbhz8Az\n5D8Iq1bKci2Ao0ArpVRzpZQdMBIoc4+G6sJa3hNlZC3via3A2IKfxwIP/FWklKqrlLIv+NkN6A4k\nlGXnkvxN7zOgNvl/tscppZYAKKUaK6V2FNR5DNivlDoOfAts11r/1zzhGlWp16LggfBkYCdwGviP\n1vqUuQI2BqXUYKXUZaArsF0ptbOg3OreE2W5FtbwniiwAOijlDoH9Cl4jVIqUCn1j4I67YDogvfF\nXmCB1rpMyV9G+AohhBWSO38hhLBCkvyFEMIKSfIXQggrJMlfCCGskCR/IYSwQpL8hRDCCknyF0II\nKyTJXwghrND/B9TATECCnMIPAAAAAElFTkSuQmCC\n",
"text/plain": [
"<matplotlib.figure.Figure at 0x2030b56e198>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import matplotlib.pyplot as plt\n",
"# Show word2vec if dim is 2\n",
"if trained_embeddings.shape[1] == 2:\n",
" labels = unique_words[30:60] # Show top 10 words\n",
" for i, label in enumerate(labels):\n",
" x, y = trained_embeddings[i,:]\n",
" plt.scatter(x, y)\n",
" plt.annotate(label, xy=(x, y), xytext=(5, 2),\n",
" textcoords='offset points', ha='right', va='bottom')\n",
" #plt.savefig(\"word2vec.png\")\n",
" plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|
{
"pile_set_name": "Github"
}
|
///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
/// Auto-generated by Stone, do not modify.
///
#import <Foundation/Foundation.h>
#import "DBSerializableProtocol.h"
@class DBFILEPROPERTIESPropertyGroup;
@class DBFILESCommitInfo;
@class DBFILESWriteMode;
NS_ASSUME_NONNULL_BEGIN
#pragma mark - API Object
///
/// The `CommitInfo` struct.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBFILESCommitInfo : NSObject <DBSerializable, NSCopying>
#pragma mark - Instance fields
/// Path in the user's Dropbox to save the file.
@property (nonatomic, readonly, copy) NSString *path;
/// Selects what to do if the file already exists.
@property (nonatomic, readonly) DBFILESWriteMode *mode;
/// If there's a conflict, as determined by mode, have the Dropbox server try to
/// autorename the file to avoid conflict.
@property (nonatomic, readonly) NSNumber *autorename;
/// The value to store as the clientModified timestamp. Dropbox automatically
/// records the time at which the file was written to the Dropbox servers. It
/// can also record an additional timestamp, provided by Dropbox desktop
/// clients, mobile clients, and API apps of when the file was actually created
/// or modified.
@property (nonatomic, readonly, nullable) NSDate *clientModified;
/// Normally, users are made aware of any file modifications in their Dropbox
/// account via notifications in the client software. If true, this tells the
/// clients that this modification shouldn't result in a user notification.
@property (nonatomic, readonly) NSNumber *mute;
/// List of custom properties to add to file.
@property (nonatomic, readonly, nullable) NSArray<DBFILEPROPERTIESPropertyGroup *> *propertyGroups;
/// Be more strict about how each WriteMode detects conflict. For example,
/// always return a conflict error when mode = `update` in `DBFILESWriteMode`
/// and the given "rev" doesn't match the existing file's "rev", even if the
/// existing file has been deleted.
@property (nonatomic, readonly) NSNumber *strictConflict;
#pragma mark - Constructors
///
/// Full constructor for the struct (exposes all instance variables).
///
/// @param path Path in the user's Dropbox to save the file.
/// @param mode Selects what to do if the file already exists.
/// @param autorename If there's a conflict, as determined by mode, have the
/// Dropbox server try to autorename the file to avoid conflict.
/// @param clientModified The value to store as the clientModified timestamp.
/// Dropbox automatically records the time at which the file was written to the
/// Dropbox servers. It can also record an additional timestamp, provided by
/// Dropbox desktop clients, mobile clients, and API apps of when the file was
/// actually created or modified.
/// @param mute Normally, users are made aware of any file modifications in
/// their Dropbox account via notifications in the client software. If true,
/// this tells the clients that this modification shouldn't result in a user
/// notification.
/// @param propertyGroups List of custom properties to add to file.
/// @param strictConflict Be more strict about how each WriteMode detects
/// conflict. For example, always return a conflict error when mode = `update`
/// in `DBFILESWriteMode` and the given "rev" doesn't match the existing file's
/// "rev", even if the existing file has been deleted.
///
/// @return An initialized instance.
///
- (instancetype)initWithPath:(NSString *)path
mode:(nullable DBFILESWriteMode *)mode
autorename:(nullable NSNumber *)autorename
clientModified:(nullable NSDate *)clientModified
mute:(nullable NSNumber *)mute
propertyGroups:(nullable NSArray<DBFILEPROPERTIESPropertyGroup *> *)propertyGroups
strictConflict:(nullable NSNumber *)strictConflict;
///
/// Convenience constructor (exposes only non-nullable instance variables with
/// no default value).
///
/// @param path Path in the user's Dropbox to save the file.
///
/// @return An initialized instance.
///
- (instancetype)initWithPath:(NSString *)path;
- (instancetype)init NS_UNAVAILABLE;
@end
#pragma mark - Serializer Object
///
/// The serialization class for the `CommitInfo` struct.
///
@interface DBFILESCommitInfoSerializer : NSObject
///
/// Serializes `DBFILESCommitInfo` instances.
///
/// @param instance An instance of the `DBFILESCommitInfo` API object.
///
/// @return A json-compatible dictionary representation of the
/// `DBFILESCommitInfo` API object.
///
+ (nullable NSDictionary<NSString *, id> *)serialize:(DBFILESCommitInfo *)instance;
///
/// Deserializes `DBFILESCommitInfo` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBFILESCommitInfo` API object.
///
/// @return An instantiation of the `DBFILESCommitInfo` object.
///
+ (DBFILESCommitInfo *)deserialize:(NSDictionary<NSString *, id> *)dict;
@end
NS_ASSUME_NONNULL_END
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright © 2019 同程艺龙 (zhihui.li@ly.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
package com.ly.train.flower.registry;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.ly.train.flower.common.core.config.FlowConfig;
import com.ly.train.flower.common.logging.Logger;
import com.ly.train.flower.common.logging.LoggerFactory;
import com.ly.train.flower.common.util.StringUtil;
import com.ly.train.flower.common.util.URL;
import com.ly.train.flower.common.util.concurrent.NamedThreadFactory;
import com.ly.train.flower.registry.config.ServiceInfo;
/**
* @author leeyazhou
*
*/
public abstract class AbstractRegistry implements Registry {
protected final Logger logger = LoggerFactory.getLogger(getClass());
protected final ConcurrentMap<String, ServiceInfo> serviceInfoCache = new ConcurrentHashMap<>();
protected final ConcurrentMap<String, FlowConfig> flowConfigCache = new ConcurrentHashMap<>();
private static final ScheduledExecutorService executorService =
Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("flower-registry"));
protected final String infoRoot = "flower:info";
protected final String configRoot = "flower:config";
protected final URL url;
public AbstractRegistry(URL url) {
this.url = url;
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
doRegisterServiceInfos();
List<ServiceInfo> tt = doGetProvider(null);
if (tt != null && !tt.isEmpty()) {
for (ServiceInfo info : tt) {
serviceInfoCache.put(info.getServiceMeta().getServiceClassName(), info);
}
}
List<FlowConfig> t2 = doGetFlowConfig(null);
if (t2 != null && !t2.isEmpty()) {
for (FlowConfig info : t2) {
if (StringUtil.isNotBlank(info.getFlowName())) {
flowConfigCache.put(info.getFlowName(), info);
}
}
}
} catch (Exception e) {
logger.error("", e);
}
}
}, 5L, 3L, TimeUnit.SECONDS);
}
@Override
public boolean register(ServiceInfo serviceInfo) {
serviceInfoCache.putIfAbsent(serviceInfo.getServiceMeta().getServiceClassName(), serviceInfo);
return doRegister(serviceInfo);
}
@Override
public List<ServiceInfo> getProvider(ServiceInfo serviceInfo) {
List<ServiceInfo> ret = doGetProvider(serviceInfo);
if (ret != null) {
for (ServiceInfo i : ret) {
serviceInfoCache.put(i.getServiceMeta().getServiceClassName(), i);
}
}
return new ArrayList<ServiceInfo>(serviceInfoCache.values());
}
private void doRegisterServiceInfos() {
for (Map.Entry<String, ServiceInfo> entry : serviceInfoCache.entrySet()) {
doRegister(entry.getValue());
}
}
@Override
public URL getUrl() {
return url;
}
@Override
public boolean registerFlowConfig(FlowConfig flowConfig) {
flowConfigCache.put(flowConfig.getFlowName(), flowConfig);
return doRegisterFlowConfig(flowConfig);
}
@Override
public List<FlowConfig> getFlowConfig(FlowConfig flowConfig) {
List<FlowConfig> ret = doGetFlowConfig(flowConfig);
if (ret != null) {
for (FlowConfig i : ret) {
if (StringUtil.isNotBlank(i.getFlowName())) {
flowConfigCache.put(i.getFlowName(), i);
}
}
}
return new ArrayList<FlowConfig>(flowConfigCache.values());
}
public abstract boolean doRegister(ServiceInfo serviceInfo);
public abstract List<ServiceInfo> doGetProvider(ServiceInfo serviceInfo);
public abstract boolean doRegisterFlowConfig(FlowConfig flowConfig);
public abstract List<FlowConfig> doGetFlowConfig(FlowConfig flowConfig);
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !gccgo
#include "textflag.h"
TEXT ·use(SB),NOSPLIT,$0
RET
|
{
"pile_set_name": "Github"
}
|
(function(compodoc) {
var MAX_RESULTS = 15,
MAX_DESCRIPTION_SIZE = 500,
usePushState = (typeof history.pushState !== 'undefined'),
// DOM Elements
$body = $('body'),
$searchResults,
$searchInput,
$searchList,
$searchTitle,
$searchResultsCount,
$searchQuery,
$mainContainer,
$xsMenu;
// Throttle search
function throttle(fn, wait) {
var timeout;
return function() {
var ctx = this, args = arguments;
if (!timeout) {
timeout = setTimeout(function() {
timeout = undefined;
fn.apply(ctx, args);
}, wait);
}
};
}
function displayResults(res) {
var noResults = res.count == 0;
var groups = {};
$searchResults.toggleClass('no-results', noResults);
// Clear old results
$searchList.empty();
// Display title for research
$searchResultsCount.text(res.count);
$searchQuery.text(res.query);
// Group result by context
res.results.forEach(function(res) {
var context = res.title.split(' - ')[0];
if (typeof groups[context] === 'undefined') {
groups[context] = {
results: [res]
}
} else {
groups[context].results.push(res)
}
});
var sortedGroups = Object.keys(groups).sort();
for (var i = 0; i < sortedGroups.length; i++) {
var property = sortedGroups[i];
var $li = $('<li>', {
'class': 'search-results-group'
});
var finalPropertyLabel = '';
var propertyLabels = property.split('-');
if (propertyLabels.length === 2 && propertyLabels[0] !== 'miscellaneous' && propertyLabels[0] !== 'additional') {
finalPropertyLabel = propertyLabels[0].charAt(0).toUpperCase() + propertyLabels[0].substring(1) + ' - ' + propertyLabels[1].charAt(0).toUpperCase() + propertyLabels[1].substring(1) + ' (' + groups[property].results.length + ')';
} else if (propertyLabels[0] === 'additional') {
finalPropertyLabel = 'Additional pages' + ' (' + groups[property].results.length + ')'
} else {
finalPropertyLabel = propertyLabels[0].charAt(0).toUpperCase() + propertyLabels[0].substring(1) + ' (' + groups[property].results.length + ')'
}
var $groupTitle = $('<h3>', {
'text': finalPropertyLabel
});
$groupTitle.appendTo($li);
var $ulResults = $('<ul>', {
'class': 'search-results-list'
})
groups[property].results.forEach(function(res) {
var link = '';
var $liResult = $('<li>', {
'class': 'search-results-item'
});
switch (COMPODOC_CURRENT_PAGE_DEPTH) {
case 0:
link = './';
break;
case 1:
case 2:
case 3:
case 4:
case 5:
link = '../'.repeat(COMPODOC_CURRENT_PAGE_DEPTH);
break;
};
var finalResLabel = res.title.split(' - ')[1].charAt(0).toUpperCase() + res.title.split(' - ')[1].substring(1);
var $link = $('<a>', {
'href': link + res.url,
'text': finalResLabel
});
$link.appendTo($liResult);
$liResult.appendTo($ulResults);
});
$ulResults.appendTo($li);
$li.appendTo($searchList);
}
}
function launchSearch(q) {
$body.addClass('with-search');
if ($xsMenu.css('display') === 'block') {
$mainContainer.css('height', 'calc(100% - 100px)');
$mainContainer.css('margin-top', '100px');
}
throttle(compodoc.search.query(q, 0, MAX_RESULTS)
.then(function(results) {
displayResults(results);
}), 1000);
}
function closeSearch() {
$body.removeClass('with-search');
if ($xsMenu.css('display') === 'block') {
$mainContainer.css('height', 'calc(100% - 50px)');
$mainContainer.css('margin-top', '50px');
}
}
function bindMenuButton() {
document.getElementById('btn-menu').addEventListener('click', function() {
if ($xsMenu.css('display') === 'none') {
$body.removeClass('with-search');
$mainContainer.css('height', 'calc(100% - 50px)');
$mainContainer.css('margin-top', '50px');
}
$.each($searchInputs, function(index, item){
var item = $(item);
item.val('');
});
});
}
function bindSearch() {
// Bind DOM
$searchInputs = $('#book-search-input input');
$searchResults = $('.search-results');
$searchList = $searchResults.find('.search-results-list');
$searchTitle = $searchResults.find('.search-results-title');
$searchResultsCount = $searchTitle.find('.search-results-count');
$searchQuery = $searchTitle.find('.search-query');
$mainContainer = $('.container-fluid');
$xsMenu = $('.xs-menu');
// Launch query based on input content
function handleUpdate(item) {
var q = item.val();
if (q.length == 0) {
closeSearch();
window.location.href = window.location.href.replace(window.location.search, '');
} else {
launchSearch(q);
}
}
// Detect true content change in search input
var propertyChangeUnbound = false;
$.each($searchInputs, function(index, item){
var item = $(item);
// HTML5 (IE9 & others)
item.on('input', function(e) {
// Unbind propertychange event for IE9+
if (!propertyChangeUnbound) {
$(this).unbind('propertychange');
propertyChangeUnbound = true;
}
handleUpdate($(this));
});
// Workaround for IE < 9
item.on('propertychange', function(e) {
if (e.originalEvent.propertyName == 'value') {
handleUpdate($(this));
}
});
// Push to history on blur
item.on('blur', function(e) {
// Update history state
if (usePushState) {
var uri = updateQueryString('q', $(this).val());
if ($(this).val() !== '') {
history.pushState({ path: uri }, null, uri);
}
}
});
});
}
function launchSearchFromQueryString() {
var q = getParameterByName('q');
if (q && q.length > 0) {
// Update search inputs
$.each($searchInputs, function(index, item){
var item = $(item);
item.val(q)
});
// Launch search
launchSearch(q);
}
}
compodoc.addEventListener(compodoc.EVENTS.SEARCH_READY, function(event) {
bindSearch();
bindMenuButton();
launchSearchFromQueryString();
});
function getParameterByName(name) {
var url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)', 'i'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
function updateQueryString(key, value) {
value = encodeURIComponent(value);
var url = window.location.href;
var re = new RegExp('([?&])' + key + '=.*?(&|#|$)(.*)', 'gi'),
hash;
if (re.test(url)) {
if (typeof value !== 'undefined' && value !== null)
return url.replace(re, '$1' + key + '=' + value + '$2$3');
else {
hash = url.split('#');
url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
if (typeof hash[1] !== 'undefined' && hash[1] !== null)
url += '#' + hash[1];
return url;
}
}
else {
if (typeof value !== 'undefined' && value !== null) {
var separator = url.indexOf('?') !== -1 ? '&' : '?';
hash = url.split('#');
url = hash[0] + separator + key + '=' + value;
if (typeof hash[1] !== 'undefined' && hash[1] !== null)
url += '#' + hash[1];
return url;
}
else
return url;
}
}
})(compodoc);
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#ifdef AWS_MULTI_FRAMEWORK
#import <AWSRuntime/AmazonServiceRequest.h>
#else
#import "../AmazonServiceRequest.h"
#endif
#import "SNSRequest.h"
#import "SNSListSubscriptionsRequest.h"
/**
* List Subscriptions Request Marshaller
*/
@interface SNSListSubscriptionsRequestMarshaller:NSObject {
}
+(AmazonServiceRequest *)createRequest:(SNSListSubscriptionsRequest *)listSubscriptionsRequest;
@end
|
{
"pile_set_name": "Github"
}
|
import { Search } from '@destinyitemmanager/dim-api-types';
import { saveSearch, searchDeleted, searchUsed } from 'app/dim-api/basic-actions';
import { recentSearchesSelector } from 'app/dim-api/selectors';
import { Loading } from 'app/dim-ui/Loading';
import Sheet from 'app/dim-ui/Sheet';
import UserGuideLink from 'app/dim-ui/UserGuideLink';
import { t } from 'app/i18next-t';
import { isPhonePortraitSelector } from 'app/shell/selectors';
import { RootState, ThunkDispatchProp } from 'app/store/types';
import clsx from 'clsx';
import { useCombobox } from 'downshift';
import _ from 'lodash';
import React, {
Suspense,
useCallback,
useEffect,
useImperativeHandle,
useLayoutEffect,
useMemo,
useRef,
useState,
} from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import {
AppIcon,
closeIcon,
disabledIcon,
faClock,
helpIcon,
moveDownIcon,
moveUpIcon,
searchIcon,
starIcon,
starOutlineIcon,
unTrackedIcon,
} from '../shell/icons';
import createAutocompleter, { SearchItem, SearchItemType } from './autocomplete';
import HighlightedText from './HighlightedText';
import { canonicalizeQuery, parseQuery } from './query-parser';
import { searchConfigSelector } from './search-config';
import './search-filter.scss';
import styles from './SearchBar.m.scss';
const searchItemIcons: { [key in SearchItemType]: string } = {
[SearchItemType.Recent]: faClock,
[SearchItemType.Saved]: starIcon,
[SearchItemType.Suggested]: unTrackedIcon, // TODO: choose a real icon
[SearchItemType.Autocomplete]: searchIcon, // TODO: choose a real icon
[SearchItemType.Help]: helpIcon,
};
interface ProvidedProps {
/** Placeholder text when nothing has been typed */
placeholder: string;
/** Is this the main search bar in the header? It behaves somewhat differently. */
mainSearchBar?: boolean;
/** Whether to autofocus this on mount */
autoFocus?: boolean;
/** A fake property that can be used to force the "live" query to be replaced with the one from props */
searchQueryVersion?: number;
/** The search query to fill in the input. This is used only initially, or when searchQueryVersion changes */
searchQuery?: string;
/** Children are used as optional extra action buttons only when there is a query. */
children?: React.ReactChild;
/** Fired whenever the query changes (already debounced) */
onQueryChanged(query: string): void;
/** Fired whenever the query has been cleared */
onClear?(): void;
}
interface StoreProps {
recentSearches: Search[];
isPhonePortrait: boolean;
autocompleter: (query: string, caretIndex: number, recentSearches: Search[]) => SearchItem[];
}
type Props = ProvidedProps & StoreProps & ThunkDispatchProp;
const autoCompleterSelector = createSelector(searchConfigSelector, createAutocompleter);
function mapStateToProps() {
let prevSearchQueryVersion: number | undefined;
let prevSearchQuery: string | undefined;
return (
state: RootState,
{ searchQuery, searchQueryVersion }: ProvidedProps
): StoreProps & { searchQuery?: string } => {
// This is a hack that prevents `searchQuery` from changing if `searchQueryVersion`
// doesn't change, so we don't trigger an update.
let manipulatedSearchQuery = prevSearchQuery;
if (searchQueryVersion != prevSearchQueryVersion) {
manipulatedSearchQuery = searchQuery;
prevSearchQuery = searchQuery;
prevSearchQueryVersion = searchQueryVersion;
}
return {
recentSearches: recentSearchesSelector(state),
isPhonePortrait: isPhonePortraitSelector(state),
autocompleter: autoCompleterSelector(state),
searchQuery: manipulatedSearchQuery,
};
};
}
const LazyFilterHelp = React.lazy(
() => import(/* webpackChunkName: "filter-help" */ './FilterHelp')
);
// TODO: break filter autocomplete into its own object/helpers... with tests
/** An interface for interacting with the search filter through a ref */
export interface SearchFilterRef {
/** Switch focus to the filter field */
focusFilterInput(): void;
/** Clear the filter field */
clearFilter(): void;
}
/**
* A reusable, autocompleting item search input. This is an uncontrolled input that
* announces its query has changed only after some delay. This is the new version of the component
* that offers a browser-style autocompleting search bar with history.
*
* TODO: Should this be the main search bar only, or should it also work for item picker, etc?
*/
function SearchBar(
{
searchQueryVersion,
searchQuery,
mainSearchBar,
placeholder,
children,
autoFocus,
onQueryChanged,
onClear,
dispatch,
autocompleter,
recentSearches,
isPhonePortrait,
}: Props,
ref: React.Ref<SearchFilterRef>
) {
const [liveQuery, setLiveQuery] = useState('');
const [filterHelpOpen, setFilterHelpOpen] = useState(false);
const inputElement = useRef<HTMLInputElement>(null);
// eslint-disable-next-line react-hooks/exhaustive-deps
const debouncedUpdateQuery = useCallback(
_.debounce((query: string) => {
onQueryChanged(query);
}, 500),
[onQueryChanged]
);
const lastBlurQuery = useRef<string>();
const onBlur = () => {
if (liveQuery && liveQuery !== lastBlurQuery.current) {
// save this to the recent searches only on blur
// we use the ref to only fire if the query changed since the last blur
dispatch(searchUsed(liveQuery));
lastBlurQuery.current = liveQuery;
}
};
// Is the current search saved?
const canonical = liveQuery ? canonicalizeQuery(parseQuery(liveQuery)) : '';
const saved = canonical ? recentSearches.find((s) => s.query === canonical)?.saved : false;
const toggleSaved = () => {
// TODO: keep track of the last search, if you search for something more narrow immediately after then replace?
dispatch(saveSearch({ query: liveQuery, saved: !saved }));
};
const items = useMemo(
() =>
autocompleter(
liveQuery,
inputElement.current?.selectionStart || liveQuery.length,
recentSearches
),
[autocompleter, liveQuery, recentSearches]
);
// useCombobox from Downshift manages the state of the dropdown
const {
isOpen,
getToggleButtonProps,
getMenuProps,
getInputProps,
getLabelProps,
getComboboxProps,
highlightedIndex,
getItemProps,
setInputValue,
reset,
openMenu,
closeMenu,
} = useCombobox<SearchItem>({
items,
initialIsOpen: isPhonePortrait && mainSearchBar,
defaultHighlightedIndex: liveQuery ? 0 : -1,
itemToString: (i) => i?.query || '',
onSelectedItemChange: ({ selectedItem }) => {
if (selectedItem) {
// Handle selecting the special "help" item
if (selectedItem.type === SearchItemType.Help) {
setFilterHelpOpen(true);
closeMenu();
}
}
},
onInputValueChange: ({ inputValue }) => {
setLiveQuery(inputValue || '');
debouncedUpdateQuery(inputValue || '');
},
});
const onFocus = () => {
if (!liveQuery && !isOpen && !autoFocus) {
openMenu();
}
};
const clearFilter = useCallback(() => {
debouncedUpdateQuery('');
reset();
onClear?.();
}, [onClear, reset, debouncedUpdateQuery]);
// Reset live query when search version changes
useEffect(() => {
if (searchQuery !== undefined && (searchQueryVersion || 0) > 0) {
setInputValue(searchQuery);
}
// This should only happen when the query version changes
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchQueryVersion]);
const deleteSearch = useCallback(
(e: React.MouseEvent, item: SearchItem) => {
e.stopPropagation();
dispatch(searchDeleted(item.query));
},
[dispatch]
);
// Add some methods for refs to use
useImperativeHandle(
ref,
() => ({
focusFilterInput: () => {
inputElement.current?.focus();
},
clearFilter,
}),
[clearFilter]
);
// Setting this ref's value allows us to set the cursor position to a specific index on the next render
const selectionRef = useRef<number>();
useLayoutEffect(() => {
if (selectionRef.current !== undefined && inputElement.current) {
inputElement.current.setSelectionRange(selectionRef.current, selectionRef.current);
selectionRef.current = undefined;
}
});
// Implement tab completion on the tab key. If the highlighted item is an autocomplete suggestion,
// accept it. Otherwise, we scan from the beginning to find the first autocomplete suggestion and
// accept that. If there's nothing to accept, the tab key does its normal thing, which is to switch
// focus. The tabAutocompleteItem is computed as part of render so we can offer keyboard help.
const tabAutocompleteItem =
highlightedIndex > 0 && items[highlightedIndex]?.type === SearchItemType.Autocomplete
? items[highlightedIndex]
: items.find((s) => s.type === SearchItemType.Autocomplete && s.query !== liveQuery);
const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Tab' && !e.altKey && tabAutocompleteItem) {
e.preventDefault();
setInputValue(tabAutocompleteItem.query);
if (tabAutocompleteItem.highlightRange) {
selectionRef.current = tabAutocompleteItem.highlightRange[1];
}
} else if (e.key === 'Home' || e.key === 'End') {
// Disable the use of Home/End to select items in the menu
// https://github.com/downshift-js/downshift/issues/1162
(e.nativeEvent as any).preventDownshiftDefault = true;
} else if (
(e.key === 'Delete' || e.key === 'Backspace') &&
e.shiftKey &&
highlightedIndex >= 0 &&
items[highlightedIndex]?.query &&
items[highlightedIndex]?.type === SearchItemType.Recent
) {
e.preventDefault();
dispatch(searchDeleted(items[highlightedIndex].query));
}
};
return (
<div
className={clsx('search-filter', styles.searchBar, { [styles.open]: isOpen })}
role="search"
enterkeyhint="search"
{...getComboboxProps()}
>
<AppIcon icon={searchIcon} className="search-bar-icon" {...getLabelProps()} />
<input
{...getInputProps({
onBlur,
onFocus,
onKeyDown,
ref: inputElement,
className: 'filter-input',
autoComplete: 'off',
autoCorrect: 'off',
autoCapitalize: 'off',
spellCheck: false,
autoFocus,
placeholder,
type: 'text',
name: 'filter',
})}
/>
{liveQuery.length > 0 && children}
{liveQuery.length > 0 && (
<button
type="button"
className={clsx('filter-bar-button', styles.saveSearchButton)}
onClick={toggleSaved}
title={t('Header.SaveSearch')}
>
<AppIcon icon={saved ? starIcon : starOutlineIcon} />
</button>
)}
{(liveQuery.length > 0 || (isPhonePortrait && mainSearchBar)) && (
<button
type="button"
className="filter-bar-button"
onClick={clearFilter}
title={t('Header.Clear')}
>
<AppIcon icon={disabledIcon} />
</button>
)}
<button
type="button"
className={clsx('filter-bar-button', styles.openButton)}
{...getToggleButtonProps()}
aria-label="toggle menu"
>
<AppIcon icon={isOpen ? moveUpIcon : moveDownIcon} />
</button>
{filterHelpOpen &&
ReactDOM.createPortal(
<Sheet
onClose={() => setFilterHelpOpen(false)}
header={
<>
<h1>{t('Header.Filters')}</h1>
<UserGuideLink topic="Item_Search" />
</>
}
sheetClassName="filterHelp"
freezeInitialHeight={true}
>
<Suspense fallback={<Loading message={t('Loading.FilterHelp')} />}>
<LazyFilterHelp />
</Suspense>
</Sheet>,
document.body
)}
<ul {...getMenuProps()} className={styles.menu}>
{isOpen &&
items.map((item, index) => (
<li
className={clsx(styles.menuItem, {
[styles.highlightedItem]: highlightedIndex === index,
})}
key={`${item.type}${item.query}`}
{...getItemProps({ item, index })}
>
<Row
highlighted={highlightedIndex === index}
item={item}
isPhonePortrait={isPhonePortrait}
isTabAutocompleteItem={item === tabAutocompleteItem}
onClick={deleteSearch}
/>
</li>
))}
</ul>
</div>
);
}
export default connect<StoreProps>(mapStateToProps, null, null, { forwardRef: true })(
React.forwardRef(SearchBar)
);
const Row = React.memo(
({
highlighted,
item,
isPhonePortrait,
isTabAutocompleteItem,
onClick,
}: {
highlighted: boolean;
item: SearchItem;
isPhonePortrait: boolean;
isTabAutocompleteItem: boolean;
onClick(e: React.MouseEvent, item: SearchItem);
}) => (
<>
<AppIcon className={styles.menuItemIcon} icon={searchItemIcons[item.type]} />
<span className={styles.menuItemQuery}>
{item.type === SearchItemType.Help ? (
t('Header.FilterHelpMenuItem')
) : item.highlightRange ? (
<HighlightedText
text={item.query}
startIndex={item.highlightRange[0]}
endIndex={item.highlightRange[1]}
className={styles.textHighlight}
/>
) : (
item.query
)}
</span>
<span className={styles.menuItemHelp} />
{!isPhonePortrait && isTabAutocompleteItem && (
<span className={styles.keyHelp}>{t('Hotkey.Tab')}</span>
)}
{!isPhonePortrait && highlighted && (
<span className={styles.keyHelp}>{t('Hotkey.Enter')}</span>
)}
{(item.type === SearchItemType.Recent || item.type === SearchItemType.Saved) && (
<button
type="button"
className={styles.deleteIcon}
onClick={(e) => onClick(e, item)}
title={t('Header.DeleteSearch')}
>
<AppIcon icon={closeIcon} />
</button>
)}
</>
)
);
|
{
"pile_set_name": "Github"
}
|
import { EntryPoint, EntryPointComponent, EnvironmentProviderOptions, IEnvironmentProvider } from './EntryPointTypes';
export type EntryPointContainerProps<
TEntryPointParams,
TPreloadedQueries,
TPreloadedEntryPoints,
TRuntimeProps,
TExtraProps
> = Readonly<
Readonly<{
entryPoint: EntryPoint<
TEntryPointParams,
EntryPointComponent<TPreloadedQueries, TPreloadedEntryPoints, TRuntimeProps, TExtraProps>
>;
entryPointParams: TEntryPointParams;
environmentProvider?: IEnvironmentProvider<EnvironmentProviderOptions>;
props: TRuntimeProps;
}>
>;
export function LazyLoadEntryPointContainer<
TEntryPointParams extends {},
TPreloadedQueries extends {},
TPreloadedEntryPoints extends {},
TRuntimeProps extends {},
TExtraProps
>({
entryPoint,
entryPointParams,
props,
environmentProvider,
}: EntryPointContainerProps<
// tslint:disable-next-line no-unnecessary-generics
TEntryPointParams,
// tslint:disable-next-line no-unnecessary-generics
TPreloadedQueries,
// tslint:disable-next-line no-unnecessary-generics
TPreloadedEntryPoints,
// tslint:disable-next-line no-unnecessary-generics
TRuntimeProps,
// tslint:disable-next-line no-unnecessary-generics
TExtraProps
>): JSX.Element;
|
{
"pile_set_name": "Github"
}
|
import itertools
import numpy
import six
from chainer.backends import cuda
from chainer.utils.conv import get_conv_outsize
from chainer.utils import conv_nd_kernel
def as_tuple(x, n):
if hasattr(x, '__getitem__'):
assert len(x) == n
return tuple(x)
return (x,) * n
def im2col_nd_cpu(img, ksize, stride, pad, pval=0, cover_all=False, dilate=1):
n, c = img.shape[0:2] # (n, c, d_1, d_2, ..., d_N)
dims = img.shape[2:]
ndim = len(dims)
dilate = as_tuple(dilate, ndim)
assert ndim == len(ksize) == len(stride) == len(pad)
outs = tuple(get_conv_outsize(d, k, s, p, cover_all, di)
for (d, k, s, p, di)
in zip(dims, ksize, stride, pad, dilate))
assert all(out > 0 for out in outs), 'Output sizes should be positive.'
# Pad around image.
pad_width = ((0, 0), (0, 0)) + tuple(
(p, p + s - 1) for (s, p) in zip(stride, pad))
img = numpy.pad(img, pad_width, mode='constant', constant_values=(pval,))
# Make patch array with which we will compute correlation with filter.
# shape: (n, c, k_1, k_2, ..., k_N, out_1, out_2, ..., out_N)
shape = (n, c) + ksize + outs
col = numpy.ndarray(shape, dtype=img.dtype)
# Fill the patch array.
colon = slice(None)
for kxs in itertools.product(*[six.moves.range(k) for k in ksize]):
# col[:, :, kx_1, kx_2, ..., kx_N, :, :, ..., :]
col_index = (colon, colon) + kxs + (colon,) * ndim
# img[:, :, kx_1:kx_lim_1:s_1, ..., kx_N:kx_lim_N:s_N]
kx_dilate = tuple(kx * di for (kx, di) in zip(kxs, dilate))
kx_lims = tuple(kx_di + s * out
for (kx_di, s, out) in zip(kx_dilate, stride, outs))
img_index = (colon, colon) + tuple(
slice(kx_di, kx_lim, s)
for (kx_di, kx_lim, s) in zip(kx_dilate, kx_lims, stride))
col[col_index] = img[img_index]
return col
def im2col_nd_gpu(img, ksize, stride, pad, cover_all=False, dilate=1):
n, c = img.shape[0:2] # (n, c, d_1, d_2, ..., d_N)
dims = img.shape[2:]
ndim = len(dims)
dilate = as_tuple(dilate, ndim)
assert ndim == len(ksize) == len(stride) == len(pad)
outs = tuple(get_conv_outsize(d, k, s, p, cover_all, di)
for (d, k, s, p, di)
in zip(dims, ksize, stride, pad, dilate))
assert all(out > 0 for out in outs), 'Output sizes should be positive.'
# col_shape: (n, c, k_1, k_2, ..., k_N, out_1, out_2, ..., out_N)
shape = (n, c) + ksize + outs
col = cuda.cupy.empty(shape, dtype=img.dtype)
in_params, out_params, operation, name = \
conv_nd_kernel.Im2colNDKernel.generate(ndim)
cuda.elementwise(in_params, out_params, operation, name)(
img.reduced_view(),
*(dims + outs + ksize + stride + pad + dilate + (col,)))
return col
def im2col_nd(img, ksize, stride, pad, cover_all=False, dilate=1):
fn = im2col_nd_gpu if isinstance(img, cuda.ndarray) else im2col_nd_cpu
return fn(img, ksize, stride, pad, cover_all=cover_all, dilate=dilate)
def col2im_nd_cpu(col, stride, pad, dims, dilate=1):
n, c = col.shape[:2] # (n, c, kx_1, ..., kx_N, out_1, ..., out_N)
mid = (len(col.shape) - 2) // 2 + 2
ksize = col.shape[2:mid]
outs = col.shape[mid:]
colon = slice(None)
ndim = len(outs)
dilate = as_tuple(dilate, ndim)
assert len(ksize) == len(stride) == len(pad) == len(dims) == ndim
# Image with padded size.
img_shape = (n, c) + tuple(d + 2 * p + s - 1
for (d, p, s) in zip(dims, pad, stride))
img = numpy.zeros(img_shape, dtype=col.dtype)
for kxs in itertools.product(*[six.moves.range(k) for k in ksize]):
# (:, :, kx_1:kx_lim_1:s_1, ..., kx_N:kx_lim_N:s_N)
kx_dilate = tuple(kx * di for (kx, di) in zip(kxs, dilate))
kx_lims = tuple(kx_di + s * out
for (kx_di, s, out) in zip(kx_dilate, stride, outs))
img_index = (colon, colon) + tuple(
slice(kx_di, kx_lim, s)
for (kx_di, kx_lim, s) in zip(kx_dilate, kx_lims, stride))
# (:, :, kx_1, kx_2, ..., kx_N, :, :, ..., :)
col_index = (colon, colon) + kxs + (colon,) * len(outs)
img[img_index] += col[col_index]
# (:, :, p_1:d_1 + p_1, p_2:d_2 + p_2, ..., p_N:d_N + p_N]
img_index = (colon, colon) + tuple(
slice(p, d + p) for (p, d) in zip(pad, dims))
return img[img_index]
def col2im_nd_gpu(col, stride, pad, dims, dilate=1):
n, c = col.shape[:2] # (n, c, k_1, ..., k_N, out_1, ..., out_N)
mid = (len(col.shape) - 2) // 2 + 2
ksize = col.shape[2:mid]
outs = col.shape[mid:]
ndim = len(dims)
dilate = as_tuple(dilate, ndim)
assert len(outs) == len(ksize) == len(stride) == len(pad) == ndim
img_shape = (n, c) + dims # (n, c, d_1, d_2, ..., d_N)
img = cuda.cupy.empty(img_shape, dtype=col.dtype)
in_params, out_params, operation, name = \
conv_nd_kernel.Col2imNDKernel.generate(ndim)
cuda.elementwise(in_params, out_params, operation, name)(
col.reduced_view(),
*(dims + outs + ksize + stride + pad + dilate + (img,)))
return img
def col2im_nd(col, stride, pad, dims, dilate=1):
fn = col2im_nd_gpu if isinstance(col, cuda.ndarray) else col2im_nd_cpu
return fn(col, stride, pad, dims, dilate)
|
{
"pile_set_name": "Github"
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.codegen.calls
import org.apache.flink.api.common.typeinfo.TypeInformation
import org.apache.flink.table.codegen.CodeGenUtils._
import org.apache.flink.table.codegen.{CodeGenerator, GeneratedExpression}
import org.apache.flink.table.typeutils.TypeCheckUtils
trait CallGenerator {
def generate(
codeGenerator: CodeGenerator,
operands: Seq[GeneratedExpression])
: GeneratedExpression
}
object CallGenerator {
/**
* Generates a call with a single result statement.
*/
def generateCallIfArgsNotNull(
nullCheck: Boolean,
returnType: TypeInformation[_],
operands: Seq[GeneratedExpression])
(call: (Seq[String]) => String)
: GeneratedExpression = {
generateCallWithStmtIfArgsNotNull(nullCheck, returnType, operands) {
(terms) => (None, call(terms))
}
}
/**
* Generates a call with auxiliary statements and result expression.
*/
def generateCallWithStmtIfArgsNotNull(
nullCheck: Boolean,
returnType: TypeInformation[_],
operands: Seq[GeneratedExpression])
(call: (Seq[String]) => (Option[String], String))
: GeneratedExpression = {
val resultTerm = newName("result")
val nullTerm = newName("isNull")
val resultTypeTerm = primitiveTypeTermForTypeInfo(returnType)
val defaultValue = primitiveDefaultValue(returnType)
val (auxiliaryStmt, result) = call(operands.map(_.resultTerm))
val nullTermCode = if (
nullCheck &&
isReference(returnType) &&
!TypeCheckUtils.isTemporal(returnType)) {
s"""
|$nullTerm = ($resultTerm == null);
""".stripMargin
} else {
""
}
val resultCode = if (nullCheck && operands.nonEmpty) {
s"""
|${operands.map(_.code).mkString("\n")}
|boolean $nullTerm = ${operands.map(_.nullTerm).mkString(" || ")};
|$resultTypeTerm $resultTerm = $defaultValue;
|if (!$nullTerm) {
| ${auxiliaryStmt.getOrElse("")}
| $resultTerm = $result;
| $nullTermCode
|}
|""".stripMargin
} else if (nullCheck && operands.isEmpty) {
s"""
|${operands.map(_.code).mkString("\n")}
|boolean $nullTerm = false;
|${auxiliaryStmt.getOrElse("")}
|$resultTypeTerm $resultTerm = $result;
|$nullTermCode
|""".stripMargin
} else{
s"""
|boolean $nullTerm = false;
|${operands.map(_.code).mkString("\n")}
|${auxiliaryStmt.getOrElse("")}
|$resultTypeTerm $resultTerm = $result;
|""".stripMargin
}
GeneratedExpression(resultTerm, nullTerm, resultCode, returnType)
}
}
|
{
"pile_set_name": "Github"
}
|
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`NewTabLink handles children 1`] = `
<StyledLinkBase
className="insights-link"
href="test"
target="_blank"
>
link text
</StyledLinkBase>
`;
exports[`NewTabLink renders content with custom className 1`] = `
<StyledLinkBase
className="insights-link custom-class"
href="test"
target="_blank"
/>
`;
exports[`NewTabLink renders content without custom className 1`] = `
<StyledLinkBase
className="insights-link"
href="test"
target="_blank"
/>
`;
|
{
"pile_set_name": "Github"
}
|
import DS from "ember-data";
import cardColor from "../utils/card-color";
export default DS.Model.extend({
name: DS.attr('string'),
icon: DS.attr('string'),
policy: DS.attr('number'),
ports: DS.attr(),
type: DS.attr('string'),
cardColor: function() {
return cardColor();
}.property(),
displayPorts: function() {
var portsStrings = [];
this.get('ports').forEach(function(i) {
portsStrings.push(i[1]+" ("+i[0]+")");
});
return portsStrings.join(", ");
}.property('ports'),
policyDisplayIcon: function() {
var policy = this.get('policy');
if (policy === 0) {
return "minus circle";
} else if (policy === 1) {
return "home";
} else if (policy === 2) {
return "check circle";
} else {
return "";
}
}.property('policy'),
policyDisplayText: function() {
var policy = this.get('policy');
if (policy === 0) {
return "Deny All Connections";
} else if (policy === 1) {
return "Local Networks Only";
} else if (policy === 2) {
return "Allow All Connections";
} else {
return "Unknown Policy";
}
}.property('policy'),
policyDisplayClass: function() {
var policy = this.get('policy');
if (policy === 0) {
return "text red";
} else if (policy === 2) {
return "text green";
} else {
return "text black";
}
}.property('policy'),
notWideOpen: function() {
return this.get('policy') !== 2;
}.property('policy'),
notLocal: function() {
return this.get('policy') !== 1;
}.property('policy'),
notDenied: function() {
return this.get('policy') !== 0;
}.property('policy'),
canDeny: function() {
return this.get('type') !== "arkos";
}.property('type'),
isCustomPolicy: function() {
return this.get('type') === "custom";
}.property('type'),
isReady: DS.attr('boolean', {defaultValue: false})
});
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* 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 external.com.android.dx.rop.code;
import external.com.android.dx.rop.type.StdTypeList;
import external.com.android.dx.rop.type.Type;
import external.com.android.dx.rop.type.TypeList;
import external.com.android.dx.util.ToHuman;
/**
* A register-based instruction. An instruction is the combination of
* an opcode (which specifies operation and source/result types), a
* list of actual sources and result registers/values, and additional
* information.
*/
public abstract class Insn implements ToHuman {
/** {@code non-null;} opcode */
private final Rop opcode;
/** {@code non-null;} source position */
private final SourcePosition position;
/** {@code null-ok;} spec for the result of this instruction, if any */
private final RegisterSpec result;
/** {@code non-null;} specs for all the sources of this instruction */
private final RegisterSpecList sources;
/**
* Constructs an instance.
*
* @param opcode {@code non-null;} the opcode
* @param position {@code non-null;} source position
* @param result {@code null-ok;} spec for the result, if any
* @param sources {@code non-null;} specs for all the sources
*/
public Insn(Rop opcode, SourcePosition position, RegisterSpec result,
RegisterSpecList sources) {
if (opcode == null) {
throw new NullPointerException("opcode == null");
}
if (position == null) {
throw new NullPointerException("position == null");
}
if (sources == null) {
throw new NullPointerException("sources == null");
}
this.opcode = opcode;
this.position = position;
this.result = result;
this.sources = sources;
}
/**
* {@inheritDoc}
*
* Instances of this class compare by identity. That is,
* {@code x.equals(y)} is only true if {@code x == y}.
*/
@Override
public final boolean equals(Object other) {
return (this == other);
}
/**
* {@inheritDoc}
*
* This implementation returns the identity hashcode of this
* instance. This is proper, since instances of this class compare
* by identity (see {@link #equals}).
*/
@Override
public final int hashCode() {
return System.identityHashCode(this);
}
/** {@inheritDoc} */
@Override
public String toString() {
return toStringWithInline(getInlineString());
}
/**
* Gets a human-oriented (and slightly lossy) string for this instance.
*
* @return {@code non-null;} the human string form
*/
@Override
public String toHuman() {
return toHumanWithInline(getInlineString());
}
/**
* Gets an "inline" string portion for toHuman(), if available. This
* is the portion that appears after the Rop opcode
*
* @return {@code null-ok;} if non-null, the inline text for toHuman()
*/
public String getInlineString() {
return null;
}
/**
* Gets the opcode.
*
* @return {@code non-null;} the opcode
*/
public final Rop getOpcode() {
return opcode;
}
/**
* Gets the source position.
*
* @return {@code non-null;} the source position
*/
public final SourcePosition getPosition() {
return position;
}
/**
* Gets the result spec, if any. A return value of {@code null}
* means this instruction returns nothing.
*
* @return {@code null-ok;} the result spec, if any
*/
public final RegisterSpec getResult() {
return result;
}
/**
* Gets the spec of a local variable assignment that occurs at this
* instruction, or null if no local variable assignment occurs. This
* may be the result register, or for {@code mark-local} insns
* it may be the source.
*
* @return {@code null-ok;} a named register spec or null
*/
public final RegisterSpec getLocalAssignment() {
RegisterSpec assignment;
if (opcode.getOpcode() == RegOps.MARK_LOCAL) {
assignment = sources.get(0);
} else {
assignment = result;
}
if (assignment == null) {
return null;
}
LocalItem localItem = assignment.getLocalItem();
if (localItem == null) {
return null;
}
return assignment;
}
/**
* Gets the source specs.
*
* @return {@code non-null;} the source specs
*/
public final RegisterSpecList getSources() {
return sources;
}
/**
* Gets whether this instruction can possibly throw an exception. This
* is just a convenient wrapper for {@code getOpcode().canThrow()}.
*
* @return {@code true} iff this instruction can possibly throw
*/
public final boolean canThrow() {
return opcode.canThrow();
}
/**
* Gets the list of possibly-caught exceptions. This returns {@link
* StdTypeList#EMPTY} if this instruction has no handlers,
* which can be <i>either</i> if this instruction can't possibly
* throw or if it merely doesn't handle any of its possible
* exceptions. To determine whether this instruction can throw,
* use {@link #canThrow}.
*
* @return {@code non-null;} the catches list
*/
public abstract TypeList getCatches();
/**
* Calls the appropriate method on the given visitor, depending on the
* class of this instance. Subclasses must override this.
*
* @param visitor {@code non-null;} the visitor to call on
*/
public abstract void accept(Visitor visitor);
/**
* Returns an instance that is just like this one, except that it
* has a catch list with the given item appended to the end. This
* method throws an exception if this instance can't possibly
* throw. To determine whether this instruction can throw, use
* {@link #canThrow}.
*
* @param type {@code non-null;} type to append to the catch list
* @return {@code non-null;} an appropriately-constructed instance
*/
public abstract Insn withAddedCatch(Type type);
/**
* Returns an instance that is just like this one, except that all
* register references have been offset by the given delta.
*
* @param delta the amount to offset register references by
* @return {@code non-null;} an appropriately-constructed instance
*/
public abstract Insn withRegisterOffset(int delta);
/**
* Returns an instance that is just like this one, except that, if
* possible, the insn is converted into a version in which a source
* (if it is a constant) is represented directly rather than as a
* register reference. {@code this} is returned in cases where the
* translation is not possible.
*
* @return {@code non-null;} an appropriately-constructed instance
*/
public Insn withSourceLiteral() {
return this;
}
/**
* Returns an exact copy of this Insn
*
* @return {@code non-null;} an appropriately-constructed instance
*/
public Insn copy() {
return withRegisterOffset(0);
}
/**
* Compares, handling nulls safely
*
* @param a first object
* @param b second object
* @return true if they're equal or both null.
*/
private static boolean equalsHandleNulls (Object a, Object b) {
return (a == b) || ((a != null) && a.equals(b));
}
/**
* Compares Insn contents, since {@code Insn.equals()} is defined
* to be an identity compare. Insn's are {@code contentEquals()}
* if they have the same opcode, registers, source position, and other
* metadata.
*
* @return true in the case described above
*/
public boolean contentEquals(Insn b) {
return opcode == b.getOpcode()
&& position.equals(b.getPosition())
&& (getClass() == b.getClass())
&& equalsHandleNulls(result, b.getResult())
&& equalsHandleNulls(sources, b.getSources())
&& StdTypeList.equalContents(getCatches(), b.getCatches());
}
/**
* Returns an instance that is just like this one, except
* with new result and source registers.
*
* @param result {@code null-ok;} new result register
* @param sources {@code non-null;} new sources registers
* @return {@code non-null;} an appropriately-constructed instance
*/
public abstract Insn withNewRegisters(RegisterSpec result,
RegisterSpecList sources);
/**
* Returns the string form of this instance, with the given bit added in
* the standard location for an inline argument.
*
* @param extra {@code null-ok;} the inline argument string
* @return {@code non-null;} the string form
*/
protected final String toStringWithInline(String extra) {
StringBuilder sb = new StringBuilder(80);
sb.append("Insn{");
sb.append(position);
sb.append(' ');
sb.append(opcode);
if (extra != null) {
sb.append(' ');
sb.append(extra);
}
sb.append(" :: ");
if (result != null) {
sb.append(result);
sb.append(" <- ");
}
sb.append(sources);
sb.append('}');
return sb.toString();
}
/**
* Returns the human string form of this instance, with the given
* bit added in the standard location for an inline argument.
*
* @param extra {@code null-ok;} the inline argument string
* @return {@code non-null;} the human string form
*/
protected final String toHumanWithInline(String extra) {
StringBuilder sb = new StringBuilder(80);
sb.append(position);
sb.append(": ");
sb.append(opcode.getNickname());
if (extra != null) {
sb.append("(");
sb.append(extra);
sb.append(")");
}
if (result == null) {
sb.append(" .");
} else {
sb.append(" ");
sb.append(result.toHuman());
}
sb.append(" <-");
int sz = sources.size();
if (sz == 0) {
sb.append(" .");
} else {
for (int i = 0; i < sz; i++) {
sb.append(" ");
sb.append(sources.get(i).toHuman());
}
}
return sb.toString();
}
/**
* Visitor interface for this (outer) class.
*/
public static interface Visitor {
/**
* Visits a {@link PlainInsn}.
*
* @param insn {@code non-null;} the instruction to visit
*/
public void visitPlainInsn(PlainInsn insn);
/**
* Visits a {@link PlainCstInsn}.
*
* @param insn {@code non-null;} the instruction to visit
*/
public void visitPlainCstInsn(PlainCstInsn insn);
/**
* Visits a {@link SwitchInsn}.
*
* @param insn {@code non-null;} the instruction to visit
*/
public void visitSwitchInsn(SwitchInsn insn);
/**
* Visits a {@link ThrowingCstInsn}.
*
* @param insn {@code non-null;} the instruction to visit
*/
public void visitThrowingCstInsn(ThrowingCstInsn insn);
/**
* Visits a {@link ThrowingInsn}.
*
* @param insn {@code non-null;} the instruction to visit
*/
public void visitThrowingInsn(ThrowingInsn insn);
/**
* Visits a {@link FillArrayDataInsn}.
*
* @param insn {@code non-null;} the instruction to visit
*/
public void visitFillArrayDataInsn(FillArrayDataInsn insn);
/**
* Visits a {@link InvokePolymorphicInsn}.
*
* @param insn {@code non-null;} the instruction to visit
*/
public void visitInvokePolymorphicInsn(InvokePolymorphicInsn insn);
}
/**
* Base implementation of {@link Visitor}, which has empty method
* bodies for all methods.
*/
public static class BaseVisitor implements Visitor {
/** {@inheritDoc} */
@Override
public void visitPlainInsn(PlainInsn insn) {
// This space intentionally left blank.
}
/** {@inheritDoc} */
@Override
public void visitPlainCstInsn(PlainCstInsn insn) {
// This space intentionally left blank.
}
/** {@inheritDoc} */
@Override
public void visitSwitchInsn(SwitchInsn insn) {
// This space intentionally left blank.
}
/** {@inheritDoc} */
@Override
public void visitThrowingCstInsn(ThrowingCstInsn insn) {
// This space intentionally left blank.
}
/** {@inheritDoc} */
@Override
public void visitThrowingInsn(ThrowingInsn insn) {
// This space intentionally left blank.
}
/** {@inheritDoc} */
@Override
public void visitFillArrayDataInsn(FillArrayDataInsn insn) {
// This space intentionally left blank.
}
/** {@inheritDoc} */
@Override
public void visitInvokePolymorphicInsn(InvokePolymorphicInsn insn) {
// This space intentionally left blank.
}
}
}
|
{
"pile_set_name": "Github"
}
|
{
"name": "objc-codegenutils",
"full_name": "objc-codegenutils",
"oldname": null,
"aliases": [
],
"versioned_formulae": [
],
"desc": "Three small tools to help work with XCode",
"license": "Apache-2.0",
"homepage": "https://github.com/square/objc-codegenutils",
"versions": {
"stable": "1.0",
"head": "HEAD",
"bottle": true
},
"urls": {
"stable": {
"url": "https://github.com/square/objc-codegenutils/archive/v1.0.tar.gz",
"tag": null,
"revision": null
}
},
"revision": 0,
"version_scheme": 0,
"bottle": {
"stable": {
"rebuild": 0,
"cellar": ":any_skip_relocation",
"prefix": "/home/linuxbrew/.linuxbrew",
"root_url": "https://linuxbrew.bintray.com/bottles",
"files": {
"catalina": {
"url": "https://linuxbrew.bintray.com/bottles/objc-codegenutils-1.0.catalina.bottle.tar.gz",
"sha256": "24745ae53d47e15598835ee0538c3f121c48b31b21902b1fd3fab0a8c9886543"
},
"mojave": {
"url": "https://linuxbrew.bintray.com/bottles/objc-codegenutils-1.0.mojave.bottle.tar.gz",
"sha256": "7a10354a20ef417eeb521c983f4714be063b68e6d74bec7ddf6f72b99d3cbfbe"
},
"high_sierra": {
"url": "https://linuxbrew.bintray.com/bottles/objc-codegenutils-1.0.high_sierra.bottle.tar.gz",
"sha256": "118c03e858a60fa17c71fbc84fb5a8b9c5f778a0c68531e3df576e1d85d9c91a"
},
"sierra": {
"url": "https://linuxbrew.bintray.com/bottles/objc-codegenutils-1.0.sierra.bottle.tar.gz",
"sha256": "d7b3d3d26970add3af78b0820f3ef8b5e0290f1b2114f5bf06acddcd8d6bdb34"
},
"el_capitan": {
"url": "https://linuxbrew.bintray.com/bottles/objc-codegenutils-1.0.el_capitan.bottle.tar.gz",
"sha256": "d7b945db595b07ee5677902586e01002ba555affdcae366f1fcbe919a6013772"
},
"mavericks": {
"url": "https://linuxbrew.bintray.com/bottles/objc-codegenutils-1.0.mavericks.bottle.tar.gz",
"sha256": "46d389e6ec12462dfbdd97822ce7c6e8156bbe9fac7a3baf04c20cb1991d9f75"
}
}
}
},
"keg_only": false,
"bottle_disabled": false,
"options": [
],
"build_dependencies": [
],
"dependencies": [
],
"recommended_dependencies": [
],
"optional_dependencies": [
],
"uses_from_macos": [
],
"requirements": [
],
"conflicts_with": [
],
"caveats": null,
"installed": [
],
"linked_keg": null,
"pinned": false,
"outdated": false,
"deprecated": false,
"disabled": false
}
|
{
"pile_set_name": "Github"
}
|
// Copyright Aleksey Gurtovoy 2000-2004
//
// 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)
//
// Preprocessed version of "boost/mpl/or.hpp" header
// -- DO NOT modify by hand!
namespace boost { namespace mpl {
namespace aux {
template< bool C_, typename T1, typename T2, typename T3, typename T4 >
struct or_impl
: true_
{
};
template< typename T1, typename T2, typename T3, typename T4 >
struct or_impl< false,T1,T2,T3,T4 >
: or_impl<
BOOST_MPL_AUX_NESTED_TYPE_WKND(T1)::value
, T2, T3, T4
, false_
>
{
};
template<>
struct or_impl<
false
, false_, false_, false_, false_
>
: false_
{
};
} // namespace aux
template<
typename BOOST_MPL_AUX_NA_PARAM(T1)
, typename BOOST_MPL_AUX_NA_PARAM(T2)
, typename T3 = false_, typename T4 = false_, typename T5 = false_
>
struct or_
: aux::or_impl<
BOOST_MPL_AUX_NESTED_TYPE_WKND(T1)::value
, T2, T3, T4, T5
>
{
BOOST_MPL_AUX_LAMBDA_SUPPORT(
5
, or_
, ( T1, T2, T3, T4, T5)
)
};
BOOST_MPL_AUX_NA_SPEC2(
2
, 5
, or_
)
}}
|
{
"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.rocketmq.example.ordermessage;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
public class Consumer {
public static void main(String[] args) throws MQClientException {
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("please_rename_unique_group_name_3");
consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
consumer.subscribe("TopicTest", "TagA || TagC || TagD");
consumer.registerMessageListener(new MessageListenerOrderly() {
AtomicLong consumeTimes = new AtomicLong(0);
@Override
public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
context.setAutoCommit(true);
System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs);
this.consumeTimes.incrementAndGet();
if ((this.consumeTimes.get() % 2) == 0) {
return ConsumeOrderlyStatus.SUCCESS;
} else if ((this.consumeTimes.get() % 3) == 0) {
return ConsumeOrderlyStatus.ROLLBACK;
} else if ((this.consumeTimes.get() % 4) == 0) {
return ConsumeOrderlyStatus.COMMIT;
} else if ((this.consumeTimes.get() % 5) == 0) {
context.setSuspendCurrentQueueTimeMillis(3000);
return ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT;
}
return ConsumeOrderlyStatus.SUCCESS;
}
});
consumer.start();
System.out.printf("Consumer Started.%n");
}
}
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright 2010-2015 Mike van Riel<mike@phpdoc.org>
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link http://phpdoc.org
*/
namespace phpDocumentor\Reflection\Types;
use ArrayIterator;
use IteratorAggregate;
use phpDocumentor\Reflection\Type;
/**
* Value Object representing a Compound Type.
*
* A Compound Type is not so much a special keyword or object reference but is a series of Types that are separated
* using an OR operator (`|`). This combination of types signifies that whatever is associated with this compound type
* may contain a value with any of the given types.
*/
final class Compound implements Type, IteratorAggregate
{
/** @var Type[] */
private $types;
/**
* Initializes a compound type (i.e. `string|int`) and tests if the provided types all implement the Type interface.
*
* @param Type[] $types
* @throws \InvalidArgumentException when types are not all instance of Type
*/
public function __construct(array $types)
{
foreach ($types as $type) {
if (!$type instanceof Type) {
throw new \InvalidArgumentException('A compound type can only have other types as elements');
}
}
$this->types = $types;
}
/**
* Returns the type at the given index.
*
* @param integer $index
*
* @return Type|null
*/
public function get($index)
{
if (!$this->has($index)) {
return null;
}
return $this->types[$index];
}
/**
* Tests if this compound type has a type with the given index.
*
* @param integer $index
*
* @return bool
*/
public function has($index)
{
return isset($this->types[$index]);
}
/**
* Returns a rendered output of the Type as it would be used in a DocBlock.
*
* @return string
*/
public function __toString()
{
return implode('|', $this->types);
}
/**
* {@inheritdoc}
*/
public function getIterator()
{
return new ArrayIterator($this->types);
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build gccgo
// +build !aix
#include <errno.h>
#include <stdint.h>
#include <unistd.h>
#define _STRINGIFY2_(x) #x
#define _STRINGIFY_(x) _STRINGIFY2_(x)
#define GOSYM_PREFIX _STRINGIFY_(__USER_LABEL_PREFIX__)
// Call syscall from C code because the gccgo support for calling from
// Go to C does not support varargs functions.
struct ret {
uintptr_t r;
uintptr_t err;
};
struct ret
gccgoRealSyscall(uintptr_t trap, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t a4, uintptr_t a5, uintptr_t a6, uintptr_t a7, uintptr_t a8, uintptr_t a9)
{
struct ret r;
errno = 0;
r.r = syscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9);
r.err = errno;
return r;
}
uintptr_t
gccgoRealSyscallNoError(uintptr_t trap, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t a4, uintptr_t a5, uintptr_t a6, uintptr_t a7, uintptr_t a8, uintptr_t a9)
{
return syscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9);
}
|
{
"pile_set_name": "Github"
}
|
//
// Umbrella.swift
// RainyRefresh
//
// Created by Anton Dolzhenko on 16.11.16.
// Copyright © 2016 Onix Systems. All rights reserved.
//
import UIKit
enum UmbrellaState {
case closed
case opened
var value: CGFloat {
return (self == .opened) ? 0.0 : 1.0
}
}
final class UmbrellaView:UIView {
var lineWidth:CGFloat = 1.0
var strokeColor: UIColor = .white
private(set) var state = UmbrellaState.closed
private var animationValue: CGFloat {
set {
if let layer = layer as? UmbrellaLayer {
layer.animationValue = newValue
}
}
get {
if let layer = layer as? UmbrellaLayer {
return layer.animationValue
}
return 0.0
}
}
override class var layerClass : AnyClass {
return UmbrellaLayer.self
}
override init(frame: CGRect) {
super.init(frame: frame)
if let layer = layer as? UmbrellaLayer {
layer.contentsScale = UIScreen.main.scale
layer.lineWidth = lineWidth
layer.strokeColor = strokeColor
}
animationValue = 1
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Methods
func setButtonState(state: UmbrellaState, animated: Bool) {
if self.state == state {
return
}
self.state = state
let toValue: CGFloat = state.value
if animated {
UIView.animate(withDuration: 0.25, animations: {
self.animationValue = toValue
})
} else {
animationValue = toValue
}
}
}
final class UmbrellaLayer:CALayer {
@NSManaged var animationValue: CGFloat
var lineWidth:CGFloat = 1.0
var strokeColor:UIColor = .white
private var APoint:CGPoint!
private var aPoint:CGPoint!
private var a1Point:CGPoint!
private var BPoint:CGPoint!
private var bPoint:CGPoint!
private var b1Point:CGPoint!
private var CPoint:CGPoint!
private var cPoint:CGPoint!
private var DPoint:CGPoint!
private var dPoint:CGPoint!
private var d1Point:CGPoint!
private var EPoint:CGPoint!
private var ePoint:CGPoint!
private var e1Point:CGPoint!
private var FPoint:CGPoint!
fileprivate class func isCustomAnimKey(_ key: String) -> Bool {
return key == "animationValue"
}
override class func needsDisplay(forKey key: String) -> Bool {
if self.isCustomAnimKey(key) {
return true
}
return super.needsDisplay(forKey: key)
}
override func action(forKey event: String) -> CAAction? {
if UmbrellaLayer.isCustomAnimKey(event) {
if let animation = super.action(forKey: "backgroundColor") as? CABasicAnimation {
animation.keyPath = event
if let pLayer = presentation() {
animation.fromValue = pLayer.animationValue
}
animation.toValue = nil
return animation
}
setNeedsDisplay()
return nil
}
return super.action(forKey: event)
}
func update() {
let midX = bounds.midX
let midY = bounds.midY
let width = bounds.width
let height = bounds.height
APoint = CGPoint(x: (midX-width*0.4133)+(width*0.3633*animationValue), y: (midY+0.055*height)+(height*0.0683*animationValue))
aPoint = CGPoint(x: (midX-width*0.385)+(width*0.3366*animationValue), y: (midY-height*0.3716)-(height*0.0016*animationValue))
a1Point = CGPoint(x: (midX-width*0.3033)+(width*0.265*animationValue), y: (midY-height*0.1166)+(height*0.07*animationValue))
BPoint = CGPoint(x: (midX-width*0.2033)+(width*0.1783*animationValue), y: (midY+height*0.0433)+(height*0.0783*animationValue))
bPoint = CGPoint(x: (midX-width*0.2233)+(width*0.1957*animationValue), y: (midY-height*0.295)+(height*0.0129*animationValue))
b1Point = CGPoint(x: (midX-width*0.0892)+(width*0.0792*animationValue), y: (midY-height*0.105)+(height*0.105*animationValue))
CPoint = CGPoint(x: midX, y: (midY+height*0.0433)+(height*0.0783*animationValue))
DPoint = CGPoint(x: (midX+width*0.2033)-(width*0.1783*animationValue), y: (midY+height*0.0433)+(height*0.0783*animationValue))
dPoint = CGPoint(x: (midX+width*0.2175)-(width*0.1908*animationValue), y: (midY-height*0.295)+(height*0.0129*animationValue))
d1Point = CGPoint(x: (midX+width*0.0894)-(width*0.0778*animationValue), y:(midY-height*0.105)+(height*0.105*animationValue))
EPoint = CGPoint(x: (midX+width*0.4133)-(width*0.3633*animationValue), y: (midY+height*0.0566)+(height*0.0666*animationValue))
ePoint = CGPoint(x: (midX+width*0.385)-(width*0.3366*animationValue), y: (midY-height*0.375)+(height*0.0016*animationValue))
e1Point = CGPoint(x: (midX+width*0.3116)-(width*0.2733*animationValue), y: (midY-height*0.1091)+(height*0.0625*animationValue))
FPoint = CGPoint(x: midX, y: (midY-height*0.3683)-(0.0016*animationValue))
}
override func draw(in ctx: CGContext) {
super.draw(in: ctx)
ctx.setStrokeColor(strokeColor.cgColor)
ctx.setLineWidth(lineWidth)
update()
//// Draw a handle
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: bounds.midX, y: bounds.midY+bounds.height*0.4266))
bezierPath.addLine(to: CGPoint(x: bounds.midX, y: bounds.midY-bounds.height*0.415))
let arrayOfDots:[(CGPoint,CGPoint,CGPoint,CGPoint)] = [(APoint,FPoint,aPoint,FPoint),
(FPoint,EPoint,FPoint,ePoint),
(BPoint,FPoint,bPoint,FPoint),
(APoint,BPoint,a1Point,BPoint),
(BPoint,CPoint,b1Point,CPoint),
(DPoint,CPoint,d1Point,CPoint),
(FPoint,DPoint,FPoint,dPoint),
(DPoint,EPoint,DPoint,e1Point)]
arrayOfDots.forEach { (a,b,c,d) in
bezierPath.move(to: a)
bezierPath.addCurve(to: b, controlPoint1: c, controlPoint2: d)
}
ctx.addPath(bezierPath.cgPath)
ctx.setLineCap(.round)
ctx.strokePath()
}
}
|
{
"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.servicecomb.service.center.client.model;
public class GetSchemaResponse {
private String schema;
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
}
|
{
"pile_set_name": "Github"
}
|
<!--
doc/src/sgml/ref/security_label.sgml
PostgreSQL documentation
-->
<refentry id="SQL-SECURITY-LABEL">
<refmeta>
<refentrytitle>SECURITY LABEL</refentrytitle>
<manvolnum>7</manvolnum>
<refmiscinfo>SQL - Language Statements</refmiscinfo>
</refmeta>
<refnamediv>
<refname>SECURITY LABEL</refname>
<refpurpose>define or change a security label applied to an object</refpurpose>
</refnamediv>
<indexterm zone="sql-security-label">
<primary>SECURITY LABEL</primary>
</indexterm>
<refsynopsisdiv>
<synopsis>
SECURITY LABEL [ FOR <replaceable class="PARAMETER">provider</replaceable> ] ON
{
TABLE <replaceable class="PARAMETER">object_name</replaceable> |
COLUMN <replaceable class="PARAMETER">table_name</replaceable>.<replaceable class="PARAMETER">column_name</replaceable> |
AGGREGATE <replaceable class="PARAMETER">agg_name</replaceable> (<replaceable class="PARAMETER">agg_type</replaceable> [, ...] ) |
DATABASE <replaceable class="PARAMETER">object_name</replaceable> |
DOMAIN <replaceable class="PARAMETER">object_name</replaceable> |
FOREIGN TABLE <replaceable class="PARAMETER">object_name</replaceable>
FUNCTION <replaceable class="PARAMETER">function_name</replaceable> ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] ) |
LARGE OBJECT <replaceable class="PARAMETER">large_object_oid</replaceable> |
[ PROCEDURAL ] LANGUAGE <replaceable class="PARAMETER">object_name</replaceable> |
ROLE <replaceable class="PARAMETER">object_name</replaceable> |
SCHEMA <replaceable class="PARAMETER">object_name</replaceable> |
SEQUENCE <replaceable class="PARAMETER">object_name</replaceable> |
TABLESPACE <replaceable class="PARAMETER">object_name</replaceable> |
TYPE <replaceable class="PARAMETER">object_name</replaceable> |
VIEW <replaceable class="PARAMETER">object_name</replaceable>
} IS '<replaceable class="PARAMETER">label</replaceable>'
</synopsis>
</refsynopsisdiv>
<refsect1>
<title>Description</title>
<para>
<command>SECURITY LABEL</command> applies a security label to a database
object. An arbitrary number of security labels, one per label provider, can
be associated with a given database object. Label providers are loadable
modules which register themselves by using the function
<function>register_label_provider</>.
</para>
<note>
<para>
<function>register_label_provider</> is not an SQL function; it can
only be called from C code loaded into the backend.
</para>
</note>
<para>
The label provider determines whether a given label is valid and whether
it is permissible to assign that label to a given object. The meaning of a
given label is likewise at the discretion of the label provider.
<productname>PostgreSQL</> places no restrictions on whether or how a
label provider must interpret security labels; it merely provides a
mechanism for storing them. In practice, this facility is intended to allow
integration with label-based mandatory access control (MAC) systems such as
<productname>SE-Linux</>. Such systems make all access control decisions
based on object labels, rather than traditional discretionary access control
(DAC) concepts such as users and groups.
</para>
</refsect1>
<refsect1>
<title>Parameters</title>
<variablelist>
<varlistentry>
<term><replaceable class="parameter">object_name</replaceable></term>
<term><replaceable class="parameter">table_name.column_name</replaceable></term>
<term><replaceable class="parameter">agg_name</replaceable></term>
<term><replaceable class="parameter">function_name</replaceable></term>
<listitem>
<para>
The name of the object to be labeled. Names of tables,
aggregates, domains, foreign tables, functions, sequences, types, and
views can be schema-qualified.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><replaceable class="parameter">provider</replaceable></term>
<listitem>
<para>
The name of the provider with which this label is to be associated. The
named provider must be loaded and must consent to the proposed labeling
operation. If exactly one provider is loaded, the provider name may be
omitted for brevity.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><replaceable class="parameter">arg_type</replaceable></term>
<listitem>
<para>
An input data type on which the aggregate function operates.
To reference a zero-argument aggregate function, write <literal>*</>
in place of the list of input data types.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><replaceable class="parameter">argmode</replaceable></term>
<listitem>
<para>
The mode of a function argument: <literal>IN</>, <literal>OUT</>,
<literal>INOUT</>, or <literal>VARIADIC</>.
If omitted, the default is <literal>IN</>.
Note that <command>SECURITY LABEL ON FUNCTION</command> does not actually
pay any attention to <literal>OUT</> arguments, since only the input
arguments are needed to determine the function's identity.
So it is sufficient to list the <literal>IN</>, <literal>INOUT</>,
and <literal>VARIADIC</> arguments.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><replaceable class="parameter">argname</replaceable></term>
<listitem>
<para>
The name of a function argument.
Note that <command>SECURITY LABEL ON FUNCTION</command> does not actually
pay any attention to argument names, since only the argument data
types are needed to determine the function's identity.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><replaceable class="parameter">argtype</replaceable></term>
<listitem>
<para>
The data type(s) of the function's arguments (optionally
schema-qualified), if any.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><replaceable class="parameter">large_object_oid</replaceable></term>
<listitem>
<para>
The OID of the large object.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><literal>PROCEDURAL</literal></term>
<listitem>
<para>
This is a noise word.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><replaceable class="parameter">label</replaceable></term>
<listitem>
<para>
The new security label, written as a string literal; or <literal>NULL</>
to drop the security label.
</para>
</listitem>
</varlistentry>
</variablelist>
</refsect1>
<refsect1>
<title>Examples</title>
<para>
The following example shows how the security label of a table might
be changed.
<programlisting>
SECURITY LABEL FOR selinux ON TABLE mytable IS 'system_u:object_r:sepgsql_table_t:s0';
</programlisting></para>
</refsect1>
<refsect1>
<title>Compatibility</title>
<para>
There is no <command>SECURITY LABEL</command> command in the SQL standard.
</para>
</refsect1>
<refsect1>
<title>See Also</title>
<simplelist type="inline">
<member><xref linkend="sepgsql"></member>
<member><xref linkend="dummy-seclabel"></member>
</simplelist>
</refsect1>
</refentry>
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* li₃: the most RAD framework for PHP (http://li3.me)
*
* Copyright 2009, Union of RAD. All rights reserved. This source
* code is distributed under the terms of the BSD 3-Clause License.
* The full license text can be found in the LICENSE.txt file.
*/
namespace lithium\data;
use lithium\core\Libraries;
/**
* The `Connections` class manages a list of named configurations that connect to external
* resources. Connections are usually comprised of a type (i.e. `'database'` or `'http'`), a
* reference to an adapter class (i.e. `'MySql'` or `'CouchDb'`), and authentication credentials.
*
* While connections can be added and removed dynamically during the course of your application
* (using `Connections::add()`), it is most typical to define all connections at once, in
* `config/bootstrap/connections.php`.
*
* The `Connections` class handles adapter classes efficiently by only loading adapter classes and
* creating instances when they are requested (using `Connections::get()`).
*
* Adapters are usually subclasses of `lithium\data\Source`.
*
* @see lithium\data\Source
*/
class Connections extends \lithium\core\Adaptable {
/**
* A Collection of the configurations you add through Connections::add().
*
* @var `lithium\util\Collection`
*/
protected static $_configurations = [];
/**
* Libraries::locate() compatible path to adapters for this class.
*
* @var string Dot-delimited path.
*/
protected static $_adapters = 'data.source';
/**
* Add connection configurations to your app in `config/bootstrap/connections.php`
*
* For example:
* ```
* Connections::add('default', [
* 'type' => 'database',
* 'adapter' => 'MySql',
* 'host' => 'localhost',
* 'login' => 'root',
* 'password' => '',
* 'database' => 'my_blog'
* ]);
* ```
*
* or
*
* ```
* Connections::add('couch', [
* 'type' => 'http',
* 'adapter' => 'CouchDb',
* 'host' => '127.0.0.1',
* 'port' => 5984
* ]);
* ```
*
* or
*
* ```
* Connections::add('mongo', [
* 'type' => 'MongoDb',
* 'database' => 'my_app'
* ]);
* ```
*
* @see lithium\data\Model::$_meta
* @param string $name The name by which this connection is referenced. Use this name to
* retrieve the connection again using `Connections::get()`, or to bind a model to it
* using `Model::$_meta['connection']`.
* @param array $config Contains all additional configuration information used by the
* connection, including the name of the adapter class where applicable (i.e. `MySql`),
* and typcially the server host/socket to connect to, the name of the database or
* other entity to use. Each adapter has its own specific configuration settings for
* handling things like connection persistence, data encoding, etc. See the
* individual adapter or data source class for more information on what configuration
* settings it supports. Basic / required options supported are:
* - `'type'` _string_: The type of data source that defines this connection; typically a
* class or namespace name. Relational database data sources, use `'database'`, while
* CouchDB and other HTTP-related data sources use `'http'`, etc. For classes which
* directly extend `lithium\data\Source`, and do not use an adapter, simply use the
* name of the class, i.e. `'MongoDb'`.
* - `'adapter'` _string_: For `type`s such as `'database'` which are adapter-driven,
* provides the name of the adapter associated with this configuration.
* @return array Returns the final post-processed connection information, as stored in the
* internal configuration array used by `Connections`.
*/
public static function add($name, array $config = []) {
$defaults = [
'type' => null,
'adapter' => null
];
return static::$_configurations[$name] = $config + $defaults;
}
/**
* Removing a configuration.
*
* @param string $name The name by which this connection is referenced.
*/
public static function remove($name) {
unset(static::$_configurations[$name]);
}
/**
* Read the configuration or access the connections you have set up.
*
* Usage:
* ```
* // Gets the names of all available configurations
* $configurations = Connections::get();
*
* // Gets the configuration array for the connection named 'db'
* $config = Connections::get('db', ['config' => true]);
*
* // Gets the instance of the connection object, configured with the settings defined for
* // this object in Connections::add()
* $dbConnection = Connections::get('db');
*
* // Gets the connection object, but only if it has already been built.
* // Otherwise returns null.
* $dbConnection = Connections::get('db', ['autoCreate' => false]);
* ```
*
* @param string $name The name of the connection to get, as defined in the first parameter of
* `add()`, when the connection was initially created.
* @param array $options Options to use when returning the connection:
* - `'autoCreate'`: If `false`, the connection object is only returned if it has
* already been instantiated by a previous call.
* - `'config'`: If `true`, returns an array representing the connection's internal
* configuration, instead of the connection itself.
* @return mixed A configured instance of the connection, or an array of the configuration used.
*/
public static function get($name = null, array $options = []) {
static $mockAdapter;
$defaults = ['config' => false, 'autoCreate' => true];
$options += $defaults;
if ($name === false) {
if (!$mockAdapter) {
$class = Libraries::locate('data.source', 'Mock');
$mockAdapter = new $class();
}
return $mockAdapter;
}
if (!$name) {
return array_keys(static::$_configurations);
}
if (!isset(static::$_configurations[$name])) {
return null;
}
if ($options['config']) {
return static::_config($name);
}
$settings = static::$_configurations[$name];
if (!isset($settings[0]['object']) && !$options['autoCreate']) {
return null;
}
return static::adapter($name);
}
/**
* Constructs a data source or adapter object instance from a configuration array.
*
* @param array $config
* @param array $paths
* @return object
*/
protected static function _class($config, $paths = []) {
if (!$config['adapter']) {
$config['adapter'] = $config['type'];
} else {
$paths = array_merge(["adapter.data.source.{$config['type']}"], (array) $paths);
}
return parent::_class($config, $paths);
}
}
?>
|
{
"pile_set_name": "Github"
}
|
// (C) Copyright Dave Abrahams, Steve Cleary, Beman Dawes, Howard
// Hinnant & John Maddock 2000.
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
//
// See http://www.boost.org/libs/type_traits for most recent version including documentation.
#ifndef BOOST_TT_REMOVE_CONST_HPP_INCLUDED
#define BOOST_TT_REMOVE_CONST_HPP_INCLUDED
#include <boost/config.hpp>
#include <cstddef>
#include <boost/detail/workaround.hpp>
namespace boost {
// convert a type T to a non-cv-qualified type - remove_const<T>
template <class T> struct remove_const{ typedef T type; };
template <class T> struct remove_const<T const>{ typedef T type; };
#if !defined(BOOST_NO_ARRAY_TYPE_SPECIALIZATIONS)
template <class T, std::size_t N> struct remove_const<T const[N]>{ typedef T type[N]; };
#if !BOOST_WORKAROUND(__BORLANDC__, < 0x600) && !defined(__IBMCPP__) && !BOOST_WORKAROUND(__DMC__, BOOST_TESTED_AT(0x840))
template <class T> struct remove_const<T const[]>{ typedef T type[]; };
#endif
#endif
} // namespace boost
#endif // BOOST_TT_REMOVE_CONST_HPP_INCLUDED
|
{
"pile_set_name": "Github"
}
|
/*
* Based on nios2-generic.c:
* (C) Copyright 2005, Psyent Corporation <www.psyent.com>
* Scott McNutt <smcnutt@psyent.com>
* (C) Copyright 2010, Thomas Chou <thomas@wytron.com.tw>
*
* SPDX-License-Identifier: GPL-2.0+
*/
#include <common.h>
#include <netdev.h>
int board_early_init_f(void)
{
return 0;
}
int checkboard(void)
{
printf("BOARD: %s\n", CONFIG_BOARD_NAME);
return 0;
}
phys_size_t initdram(int board_type)
{
return 0;
}
#ifdef CONFIG_CMD_NET
int board_eth_init(bd_t *bis)
{
int rc = 0;
#ifdef CONFIG_ETHOC
rc += ethoc_initialize(0, CONFIG_SYS_ETHOC_BASE);
#endif
return rc;
}
#endif
|
{
"pile_set_name": "Github"
}
|
import { equal } from 'assert';
import curry from '../curry';
import reduce from '../reduce';
import compose from '../compose';
test('#curry', () => {
const f = (a, b) => a + b;
equal(curry(f)(1)(2), 3);
const g = (a, b, c) => a + b + c;
equal(
curry(g)(1)(2, 3),
6
);
equal(
curry(g)(1, 2)(3),
6
);
const curry3 = compose(curry, curry);
equal(
curry3(g)(1)(2)(3),
6
);
const h = (a, b, c, d) => a + b + c + d;
const curry4 = reduce(compose, [curry, curry, curry]);
equal(
curry4(h)(1)(2)(3)(4),
10
);
});
|
{
"pile_set_name": "Github"
}
|
package org.eclipse.ceylon.compiler.java.test.annotations;
@.org.eclipse.ceylon.compiler.java.metadata.Ceylon(
major = 8,
minor = 1)
@.org.eclipse.ceylon.compiler.java.metadata.Attribute
@.org.eclipse.ceylon.compiler.java.metadata.Name("attr1")
final class attr1_ {
private attr1_() {
}
private static final long $object$;
@.org.eclipse.ceylon.compiler.java.metadata.Ignore
private static volatile boolean $init$$object$ = false;
private static final .java.lang.Throwable $initException$;
static {
try {
$object$ = 1L;
.org.eclipse.ceylon.compiler.java.test.annotations.attr1_.$init$$object$ = true;
$initException$ = null;
} catch (.java.lang.Throwable x) {
$initException$ = x;
$object$ = 0L;
.org.eclipse.ceylon.compiler.java.test.annotations.attr1_.$init$$object$ = false;
}
}
public static long get_() {
if (.org.eclipse.ceylon.compiler.java.test.annotations.attr1_.$init$$object$) {
return .org.eclipse.ceylon.compiler.java.test.annotations.attr1_.$object$;
} else {
if ($initException$ != null) .org.eclipse.ceylon.compiler.java.Util.rethrow($initException$);
throw new .ceylon.language.InitializationError("Cyclic initialization trying to read the value of \'attr1\' before it was set");
}
}
}
@.org.eclipse.ceylon.compiler.java.metadata.Ceylon(
major = 8,
minor = 1)
@.org.eclipse.ceylon.compiler.java.metadata.Attribute
@.org.eclipse.ceylon.compiler.java.metadata.Name("attr2")
final class attr2_ {
private attr2_() {
}
private static long $object$;
@.org.eclipse.ceylon.compiler.java.metadata.Ignore
private static volatile boolean $init$$object$ = false;
private static final .java.lang.Throwable $initException$;
static {
try {
.org.eclipse.ceylon.compiler.java.test.annotations.attr2_.$object$ = 1L;
.org.eclipse.ceylon.compiler.java.test.annotations.attr2_.$init$$object$ = true;
$initException$ = null;
} catch (.java.lang.Throwable x) {
$initException$ = x;
.org.eclipse.ceylon.compiler.java.test.annotations.attr2_.$object$ = 0L;
.org.eclipse.ceylon.compiler.java.test.annotations.attr2_.$init$$object$ = false;
}
}
@.ceylon.language.VariableAnnotation$annotation$
public static long get_() {
if (.org.eclipse.ceylon.compiler.java.test.annotations.attr2_.$init$$object$) {
return .org.eclipse.ceylon.compiler.java.test.annotations.attr2_.$object$;
} else {
if ($initException$ != null) .org.eclipse.ceylon.compiler.java.Util.rethrow($initException$);
throw new .ceylon.language.InitializationError("Cyclic initialization trying to read the value of \'attr2\' before it was set");
}
}
public static void set_(@.org.eclipse.ceylon.compiler.java.metadata.Name("attr2")
final long attr2) {
if ($initException$ != null) .org.eclipse.ceylon.compiler.java.Util.rethrow($initException$);
.org.eclipse.ceylon.compiler.java.test.annotations.attr2_.$object$ = attr2;
}
}
@.org.eclipse.ceylon.compiler.java.metadata.Ceylon(
major = 8,
minor = 1)
@.org.eclipse.ceylon.compiler.java.metadata.Attribute
@.org.eclipse.ceylon.compiler.java.metadata.Name("attr3")
final class attr3_ {
private attr3_() {
}
@.org.eclipse.ceylon.compiler.java.metadata.Transient
public static long get_() {
return 1L;
}
}
@.org.eclipse.ceylon.compiler.java.metadata.Ceylon(
major = 8,
minor = 1)
@.org.eclipse.ceylon.compiler.java.metadata.Attribute
@.org.eclipse.ceylon.compiler.java.metadata.Name("attr4")
final class attr4_ {
private attr4_() {
}
@.org.eclipse.ceylon.compiler.java.metadata.Transient
public static long get_() {
return 1L;
}
public static void set_(@.org.eclipse.ceylon.compiler.java.metadata.Name("attr4")
final long attr4) {
}
}
|
{
"pile_set_name": "Github"
}
|
// RUN: llvm-tblgen -gen-disassembler -I %p/../../include %s | FileCheck %s
// Check that we don't generate invalid code of the form "( && Cond2)" when
// emitting AssemblerPredicate conditions. In the example below, the invalid
// code would be: "return ( && (Bits & arch::AssemblerCondition2));".
include "llvm/Target/Target.td"
def archInstrInfo : InstrInfo { }
def arch : Target {
let InstructionSet = archInstrInfo;
}
def Pred1 : Predicate<"Condition1">;
def Pred2 : Predicate<"Condition2">,
AssemblerPredicate<"AssemblerCondition2">;
def foo : Instruction {
let Size = 2;
let OutOperandList = (outs);
let InOperandList = (ins);
field bits<16> Inst;
let Inst = 0xAAAA;
let AsmString = "foo";
field bits<16> SoftFail = 0;
// This is the important bit:
let Predicates = [Pred1, Pred2];
}
// CHECK: return (Bits[arch::AssemblerCondition2]);
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\commerce\migrations;
use Craft;
use craft\commerce\fields\Products;
use craft\db\Migration;
use craft\db\Query;
use craft\helpers\Json;
/**
* m180319_130001_fieldSettings migration.
*/
class m180319_130001_fieldSettings extends Migration
{
/**
* @inheritdoc
*/
public function safeUp()
{
$fields = (new Query())
->select(['id', 'type', 'translationMethod', 'settings'])
->from(['{{%fields}}'])
->where([
'type' => [
Products::class,
]
])
->all($this->db);
foreach ($fields as $field) {
$settings = Json::decodeIfJson($field['settings']);
if (!is_array($settings)) {
echo 'Field ' . $field['id'] . ' (' . $field['type'] . ') settings were invalid JSON: ' . $field['settings'] . "\n";
$settings = [];
}
$localized = ($field['translationMethod'] === 'site');
// Exception: Cannot use a scalar value as an array
$settings['localizeRelations'] = $localized;
// targetLocale => targetSiteId
if (!empty($settings['targetLocale'])) {
$site = Craft::$app->getSites()->getSiteByHandle($settings['targetLocale']);
if ($site) {
$settings['targetSiteId'] = $site->id;
} else {
$settings['targetSiteId'] = Craft::$app->getSites()->getPrimarySite()->id;
}
}
unset($settings['targetLocale']);
$this->update(
'{{%fields}}',
[
'translationMethod' => 'none',
'settings' => Json::encode($settings),
],
['id' => $field['id']],
[],
false);
}
return true;
}
/**
* @inheritdoc
*/
public function safeDown()
{
echo "m180319_130001_fieldSettings cannot be reverted.\n";
return false;
}
}
|
{
"pile_set_name": "Github"
}
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03
// <filesystem>
// class path
// path& replace_filename()
#include "filesystem_include.h"
#include <type_traits>
#include <cassert>
#include "test_macros.h"
#include "test_iterators.h"
#include "count_new.h"
#include "filesystem_test_helper.h"
#include "assert_checkpoint.h"
#include "verbose_assert.h"
struct ReplaceFilenameTestcase {
const char* value;
const char* expect;
const char* filename;
};
const ReplaceFilenameTestcase TestCases[] =
{
{"/foo", "/bar", "bar"}
, {"/foo", "/", ""}
, {"foo", "bar", "bar"}
, {"/", "/bar", "bar"}
, {"\\", "bar", "bar"}
, {"///", "///bar", "bar"}
, {"\\\\", "bar", "bar"}
, {"\\/\\", "\\/bar", "bar"}
, {".", "bar", "bar"}
, {"..", "bar", "bar"}
, {"/foo\\baz/bong/", "/foo\\baz/bong/bar", "bar"}
, {"/foo\\baz/bong", "/foo\\baz/bar", "bar"}
};
int main(int, char**)
{
using namespace fs;
for (auto const & TC : TestCases) {
path p(TC.value);
ASSERT_EQ(p, TC.value);
path& Ref = (p.replace_filename(TC.filename));
ASSERT_EQ(p, TC.expect)
<< DISPLAY(TC.value)
<< DISPLAY(TC.filename);
assert(&Ref == &p);
// Tests Effects "as-if": remove_filename() append(filename)
{
path p2(TC.value);
path replace(TC.filename);
p2.remove_filename();
p2 /= replace;
ASSERT_EQ(p, p2);
}
}
return 0;
}
|
{
"pile_set_name": "Github"
}
|
package bolt
import (
"errors"
"fmt"
"hash/fnv"
"log"
"os"
"runtime"
"runtime/debug"
"strings"
"sync"
"time"
"unsafe"
)
// The largest step that can be taken when remapping the mmap.
const maxMmapStep = 1 << 30 // 1GB
// The data file format version.
const version = 2
// Represents a marker value to indicate that a file is a Bolt DB.
const magic uint32 = 0xED0CDAED
// IgnoreNoSync specifies whether the NoSync field of a DB is ignored when
// syncing changes to a file. This is required as some operating systems,
// such as OpenBSD, do not have a unified buffer cache (UBC) and writes
// must be synchronized using the msync(2) syscall.
const IgnoreNoSync = runtime.GOOS == "openbsd"
// Default values if not set in a DB instance.
const (
DefaultMaxBatchSize int = 1000
DefaultMaxBatchDelay = 10 * time.Millisecond
DefaultAllocSize = 16 * 1024 * 1024
)
// default page size for db is set to the OS page size.
var defaultPageSize = os.Getpagesize()
// DB represents a collection of buckets persisted to a file on disk.
// All data access is performed through transactions which can be obtained through the DB.
// All the functions on DB will return a ErrDatabaseNotOpen if accessed before Open() is called.
type DB struct {
// When enabled, the database will perform a Check() after every commit.
// A panic is issued if the database is in an inconsistent state. This
// flag has a large performance impact so it should only be used for
// debugging purposes.
StrictMode bool
// Setting the NoSync flag will cause the database to skip fsync()
// calls after each commit. This can be useful when bulk loading data
// into a database and you can restart the bulk load in the event of
// a system failure or database corruption. Do not set this flag for
// normal use.
//
// If the package global IgnoreNoSync constant is true, this value is
// ignored. See the comment on that constant for more details.
//
// THIS IS UNSAFE. PLEASE USE WITH CAUTION.
NoSync bool
// When true, skips the truncate call when growing the database.
// Setting this to true is only safe on non-ext3/ext4 systems.
// Skipping truncation avoids preallocation of hard drive space and
// bypasses a truncate() and fsync() syscall on remapping.
//
// https://github.com/boltdb/bolt/issues/284
NoGrowSync bool
// If you want to read the entire database fast, you can set MmapFlag to
// syscall.MAP_POPULATE on Linux 2.6.23+ for sequential read-ahead.
MmapFlags int
// MaxBatchSize is the maximum size of a batch. Default value is
// copied from DefaultMaxBatchSize in Open.
//
// If <=0, disables batching.
//
// Do not change concurrently with calls to Batch.
MaxBatchSize int
// MaxBatchDelay is the maximum delay before a batch starts.
// Default value is copied from DefaultMaxBatchDelay in Open.
//
// If <=0, effectively disables batching.
//
// Do not change concurrently with calls to Batch.
MaxBatchDelay time.Duration
// AllocSize is the amount of space allocated when the database
// needs to create new pages. This is done to amortize the cost
// of truncate() and fsync() when growing the data file.
AllocSize int
path string
file *os.File
lockfile *os.File // windows only
dataref []byte // mmap'ed readonly, write throws SEGV
data *[maxMapSize]byte
datasz int
filesz int // current on disk file size
meta0 *meta
meta1 *meta
pageSize int
opened bool
rwtx *Tx
txs []*Tx
freelist *freelist
stats Stats
pagePool sync.Pool
batchMu sync.Mutex
batch *batch
rwlock sync.Mutex // Allows only one writer at a time.
metalock sync.Mutex // Protects meta page access.
mmaplock sync.RWMutex // Protects mmap access during remapping.
statlock sync.RWMutex // Protects stats access.
ops struct {
writeAt func(b []byte, off int64) (n int, err error)
}
// Read only mode.
// When true, Update() and Begin(true) return ErrDatabaseReadOnly immediately.
readOnly bool
}
// Path returns the path to currently open database file.
func (db *DB) Path() string {
return db.path
}
// GoString returns the Go string representation of the database.
func (db *DB) GoString() string {
return fmt.Sprintf("bolt.DB{path:%q}", db.path)
}
// String returns the string representation of the database.
func (db *DB) String() string {
return fmt.Sprintf("DB<%q>", db.path)
}
// Open creates and opens a database at the given path.
// If the file does not exist then it will be created automatically.
// Passing in nil options will cause Bolt to open the database with the default options.
func Open(path string, mode os.FileMode, options *Options) (*DB, error) {
var db = &DB{opened: true}
// Set default options if no options are provided.
if options == nil {
options = DefaultOptions
}
db.NoGrowSync = options.NoGrowSync
db.MmapFlags = options.MmapFlags
// Set default values for later DB operations.
db.MaxBatchSize = DefaultMaxBatchSize
db.MaxBatchDelay = DefaultMaxBatchDelay
db.AllocSize = DefaultAllocSize
flag := os.O_RDWR
if options.ReadOnly {
flag = os.O_RDONLY
db.readOnly = true
}
// Open data file and separate sync handler for metadata writes.
db.path = path
var err error
if db.file, err = os.OpenFile(db.path, flag|os.O_CREATE, mode); err != nil {
_ = db.close()
return nil, err
}
// Lock file so that other processes using Bolt in read-write mode cannot
// use the database at the same time. This would cause corruption since
// the two processes would write meta pages and free pages separately.
// The database file is locked exclusively (only one process can grab the lock)
// if !options.ReadOnly.
// The database file is locked using the shared lock (more than one process may
// hold a lock at the same time) otherwise (options.ReadOnly is set).
if err := flock(db, mode, !db.readOnly, options.Timeout); err != nil {
_ = db.close()
return nil, err
}
// Default values for test hooks
db.ops.writeAt = db.file.WriteAt
// Initialize the database if it doesn't exist.
if info, err := db.file.Stat(); err != nil {
return nil, err
} else if info.Size() == 0 {
// Initialize new files with meta pages.
if err := db.init(); err != nil {
return nil, err
}
} else {
// Read the first meta page to determine the page size.
var buf [0x1000]byte
if _, err := db.file.ReadAt(buf[:], 0); err == nil {
m := db.pageInBuffer(buf[:], 0).meta()
if err := m.validate(); err != nil {
// If we can't read the page size, we can assume it's the same
// as the OS -- since that's how the page size was chosen in the
// first place.
//
// If the first page is invalid and this OS uses a different
// page size than what the database was created with then we
// are out of luck and cannot access the database.
db.pageSize = os.Getpagesize()
} else {
db.pageSize = int(m.pageSize)
}
}
}
// Initialize page pool.
db.pagePool = sync.Pool{
New: func() interface{} {
return make([]byte, db.pageSize)
},
}
// Memory map the data file.
if err := db.mmap(options.InitialMmapSize); err != nil {
_ = db.close()
return nil, err
}
// Read in the freelist.
db.freelist = newFreelist()
db.freelist.read(db.page(db.meta().freelist))
// Mark the database as opened and return.
return db, nil
}
// mmap opens the underlying memory-mapped file and initializes the meta references.
// minsz is the minimum size that the new mmap can be.
func (db *DB) mmap(minsz int) error {
db.mmaplock.Lock()
defer db.mmaplock.Unlock()
info, err := db.file.Stat()
if err != nil {
return fmt.Errorf("mmap stat error: %s", err)
} else if int(info.Size()) < db.pageSize*2 {
return fmt.Errorf("file size too small")
}
// Ensure the size is at least the minimum size.
var size = int(info.Size())
if size < minsz {
size = minsz
}
size, err = db.mmapSize(size)
if err != nil {
return err
}
// Dereference all mmap references before unmapping.
if db.rwtx != nil {
db.rwtx.root.dereference()
}
// Unmap existing data before continuing.
if err := db.munmap(); err != nil {
return err
}
// Memory-map the data file as a byte slice.
if err := mmap(db, size); err != nil {
return err
}
// Save references to the meta pages.
db.meta0 = db.page(0).meta()
db.meta1 = db.page(1).meta()
// Validate the meta pages. We only return an error if both meta pages fail
// validation, since meta0 failing validation means that it wasn't saved
// properly -- but we can recover using meta1. And vice-versa.
err0 := db.meta0.validate()
err1 := db.meta1.validate()
if err0 != nil && err1 != nil {
return err0
}
return nil
}
// munmap unmaps the data file from memory.
func (db *DB) munmap() error {
if err := munmap(db); err != nil {
return fmt.Errorf("unmap error: " + err.Error())
}
return nil
}
// mmapSize determines the appropriate size for the mmap given the current size
// of the database. The minimum size is 32KB and doubles until it reaches 1GB.
// Returns an error if the new mmap size is greater than the max allowed.
func (db *DB) mmapSize(size int) (int, error) {
// Double the size from 32KB until 1GB.
for i := uint(15); i <= 30; i++ {
if size <= 1<<i {
return 1 << i, nil
}
}
// Verify the requested size is not above the maximum allowed.
if size > maxMapSize {
return 0, fmt.Errorf("mmap too large")
}
// If larger than 1GB then grow by 1GB at a time.
sz := int64(size)
if remainder := sz % int64(maxMmapStep); remainder > 0 {
sz += int64(maxMmapStep) - remainder
}
// Ensure that the mmap size is a multiple of the page size.
// This should always be true since we're incrementing in MBs.
pageSize := int64(db.pageSize)
if (sz % pageSize) != 0 {
sz = ((sz / pageSize) + 1) * pageSize
}
// If we've exceeded the max size then only grow up to the max size.
if sz > maxMapSize {
sz = maxMapSize
}
return int(sz), nil
}
// init creates a new database file and initializes its meta pages.
func (db *DB) init() error {
// Set the page size to the OS page size.
db.pageSize = os.Getpagesize()
// Create two meta pages on a buffer.
buf := make([]byte, db.pageSize*4)
for i := 0; i < 2; i++ {
p := db.pageInBuffer(buf[:], pgid(i))
p.id = pgid(i)
p.flags = metaPageFlag
// Initialize the meta page.
m := p.meta()
m.magic = magic
m.version = version
m.pageSize = uint32(db.pageSize)
m.freelist = 2
m.root = bucket{root: 3}
m.pgid = 4
m.txid = txid(i)
m.checksum = m.sum64()
}
// Write an empty freelist at page 3.
p := db.pageInBuffer(buf[:], pgid(2))
p.id = pgid(2)
p.flags = freelistPageFlag
p.count = 0
// Write an empty leaf page at page 4.
p = db.pageInBuffer(buf[:], pgid(3))
p.id = pgid(3)
p.flags = leafPageFlag
p.count = 0
// Write the buffer to our data file.
if _, err := db.ops.writeAt(buf, 0); err != nil {
return err
}
if err := fdatasync(db); err != nil {
return err
}
return nil
}
// Close releases all database resources.
// All transactions must be closed before closing the database.
func (db *DB) Close() error {
db.rwlock.Lock()
defer db.rwlock.Unlock()
db.metalock.Lock()
defer db.metalock.Unlock()
db.mmaplock.RLock()
defer db.mmaplock.RUnlock()
return db.close()
}
func (db *DB) close() error {
if !db.opened {
return nil
}
db.opened = false
db.freelist = nil
// Clear ops.
db.ops.writeAt = nil
// Close the mmap.
if err := db.munmap(); err != nil {
return err
}
// Close file handles.
if db.file != nil {
// No need to unlock read-only file.
if !db.readOnly {
// Unlock the file.
if err := funlock(db); err != nil {
log.Printf("bolt.Close(): funlock error: %s", err)
}
}
// Close the file descriptor.
if err := db.file.Close(); err != nil {
return fmt.Errorf("db file close: %s", err)
}
db.file = nil
}
db.path = ""
return nil
}
// Begin starts a new transaction.
// Multiple read-only transactions can be used concurrently but only one
// write transaction can be used at a time. Starting multiple write transactions
// will cause the calls to block and be serialized until the current write
// transaction finishes.
//
// Transactions should not be dependent on one another. Opening a read
// transaction and a write transaction in the same goroutine can cause the
// writer to deadlock because the database periodically needs to re-mmap itself
// as it grows and it cannot do that while a read transaction is open.
//
// If a long running read transaction (for example, a snapshot transaction) is
// needed, you might want to set DB.InitialMmapSize to a large enough value
// to avoid potential blocking of write transaction.
//
// IMPORTANT: You must close read-only transactions after you are finished or
// else the database will not reclaim old pages.
func (db *DB) Begin(writable bool) (*Tx, error) {
if writable {
return db.beginRWTx()
}
return db.beginTx()
}
func (db *DB) beginTx() (*Tx, error) {
// Lock the meta pages while we initialize the transaction. We obtain
// the meta lock before the mmap lock because that's the order that the
// write transaction will obtain them.
db.metalock.Lock()
// Obtain a read-only lock on the mmap. When the mmap is remapped it will
// obtain a write lock so all transactions must finish before it can be
// remapped.
db.mmaplock.RLock()
// Exit if the database is not open yet.
if !db.opened {
db.mmaplock.RUnlock()
db.metalock.Unlock()
return nil, ErrDatabaseNotOpen
}
// Create a transaction associated with the database.
t := &Tx{}
t.init(db)
// Keep track of transaction until it closes.
db.txs = append(db.txs, t)
n := len(db.txs)
// Unlock the meta pages.
db.metalock.Unlock()
// Update the transaction stats.
db.statlock.Lock()
db.stats.TxN++
db.stats.OpenTxN = n
db.statlock.Unlock()
return t, nil
}
func (db *DB) beginRWTx() (*Tx, error) {
// If the database was opened with Options.ReadOnly, return an error.
if db.readOnly {
return nil, ErrDatabaseReadOnly
}
// Obtain writer lock. This is released by the transaction when it closes.
// This enforces only one writer transaction at a time.
db.rwlock.Lock()
// Once we have the writer lock then we can lock the meta pages so that
// we can set up the transaction.
db.metalock.Lock()
defer db.metalock.Unlock()
// Exit if the database is not open yet.
if !db.opened {
db.rwlock.Unlock()
return nil, ErrDatabaseNotOpen
}
// Create a transaction associated with the database.
t := &Tx{writable: true}
t.init(db)
db.rwtx = t
// Free any pages associated with closed read-only transactions.
var minid txid = 0xFFFFFFFFFFFFFFFF
for _, t := range db.txs {
if t.meta.txid < minid {
minid = t.meta.txid
}
}
if minid > 0 {
db.freelist.release(minid - 1)
}
return t, nil
}
// removeTx removes a transaction from the database.
func (db *DB) removeTx(tx *Tx) {
// Release the read lock on the mmap.
db.mmaplock.RUnlock()
// Use the meta lock to restrict access to the DB object.
db.metalock.Lock()
// Remove the transaction.
for i, t := range db.txs {
if t == tx {
last := len(db.txs) - 1
db.txs[i] = db.txs[last]
db.txs[last] = nil
db.txs = db.txs[:last]
break
}
}
n := len(db.txs)
// Unlock the meta pages.
db.metalock.Unlock()
// Merge statistics.
db.statlock.Lock()
db.stats.OpenTxN = n
db.stats.TxStats.add(&tx.stats)
db.statlock.Unlock()
}
// Update executes a function within the context of a read-write managed transaction.
// If no error is returned from the function then the transaction is committed.
// If an error is returned then the entire transaction is rolled back.
// Any error that is returned from the function or returned from the commit is
// returned from the Update() method.
//
// Attempting to manually commit or rollback within the function will cause a panic.
func (db *DB) Update(fn func(*Tx) error) error {
t, err := db.Begin(true)
if err != nil {
return err
}
// Make sure the transaction rolls back in the event of a panic.
defer func() {
if t.db != nil {
t.rollback()
}
}()
// Mark as a managed tx so that the inner function cannot manually commit.
t.managed = true
// If an error is returned from the function then rollback and return error.
err = fn(t)
t.managed = false
if err != nil {
_ = t.Rollback()
return err
}
return t.Commit()
}
// View executes a function within the context of a managed read-only transaction.
// Any error that is returned from the function is returned from the View() method.
//
// Attempting to manually rollback within the function will cause a panic.
func (db *DB) View(fn func(*Tx) error) error {
t, err := db.Begin(false)
if err != nil {
return err
}
// Make sure the transaction rolls back in the event of a panic.
defer func() {
if t.db != nil {
t.rollback()
}
}()
// Mark as a managed tx so that the inner function cannot manually rollback.
t.managed = true
// If an error is returned from the function then pass it through.
err = fn(t)
t.managed = false
if err != nil {
_ = t.Rollback()
return err
}
if err := t.Rollback(); err != nil {
return err
}
return nil
}
// Batch calls fn as part of a batch. It behaves similar to Update,
// except:
//
// 1. concurrent Batch calls can be combined into a single Bolt
// transaction.
//
// 2. the function passed to Batch may be called multiple times,
// regardless of whether it returns error or not.
//
// This means that Batch function side effects must be idempotent and
// take permanent effect only after a successful return is seen in
// caller.
//
// The maximum batch size and delay can be adjusted with DB.MaxBatchSize
// and DB.MaxBatchDelay, respectively.
//
// Batch is only useful when there are multiple goroutines calling it.
func (db *DB) Batch(fn func(*Tx) error) error {
errCh := make(chan error, 1)
db.batchMu.Lock()
if (db.batch == nil) || (db.batch != nil && len(db.batch.calls) >= db.MaxBatchSize) {
// There is no existing batch, or the existing batch is full; start a new one.
db.batch = &batch{
db: db,
}
db.batch.timer = time.AfterFunc(db.MaxBatchDelay, db.batch.trigger)
}
db.batch.calls = append(db.batch.calls, call{fn: fn, err: errCh})
if len(db.batch.calls) >= db.MaxBatchSize {
// wake up batch, it's ready to run
go db.batch.trigger()
}
db.batchMu.Unlock()
err := <-errCh
if err == trySolo {
err = db.Update(fn)
}
return err
}
type call struct {
fn func(*Tx) error
err chan<- error
}
type batch struct {
db *DB
timer *time.Timer
start sync.Once
calls []call
}
// trigger runs the batch if it hasn't already been run.
func (b *batch) trigger() {
b.start.Do(b.run)
}
// run performs the transactions in the batch and communicates results
// back to DB.Batch.
func (b *batch) run() {
b.db.batchMu.Lock()
b.timer.Stop()
// Make sure no new work is added to this batch, but don't break
// other batches.
if b.db.batch == b {
b.db.batch = nil
}
b.db.batchMu.Unlock()
retry:
for len(b.calls) > 0 {
var failIdx = -1
err := b.db.Update(func(tx *Tx) error {
for i, c := range b.calls {
if err := safelyCall(c.fn, tx); err != nil {
failIdx = i
return err
}
}
return nil
})
if failIdx >= 0 {
// take the failing transaction out of the batch. it's
// safe to shorten b.calls here because db.batch no longer
// points to us, and we hold the mutex anyway.
c := b.calls[failIdx]
b.calls[failIdx], b.calls = b.calls[len(b.calls)-1], b.calls[:len(b.calls)-1]
// tell the submitter re-run it solo, continue with the rest of the batch
c.err <- trySolo
continue retry
}
// pass success, or bolt internal errors, to all callers
for _, c := range b.calls {
if c.err != nil {
c.err <- err
}
}
break retry
}
}
// trySolo is a special sentinel error value used for signaling that a
// transaction function should be re-run. It should never be seen by
// callers.
var trySolo = errors.New("batch function returned an error and should be re-run solo")
type panicked struct {
reason interface{}
}
func (p panicked) Error() string {
if err, ok := p.reason.(error); ok {
return err.Error()
}
return fmt.Sprintf("panic: %v", p.reason)
}
func safelyCall(fn func(*Tx) error, tx *Tx) (err error) {
defer func() {
if p := recover(); p != nil {
err = panicked{p}
}
}()
return fn(tx)
}
// Sync executes fdatasync() against the database file handle.
//
// This is not necessary under normal operation, however, if you use NoSync
// then it allows you to force the database file to sync against the disk.
func (db *DB) Sync() error { return fdatasync(db) }
// Stats retrieves ongoing performance stats for the database.
// This is only updated when a transaction closes.
func (db *DB) Stats() Stats {
db.statlock.RLock()
defer db.statlock.RUnlock()
return db.stats
}
// This is for internal access to the raw data bytes from the C cursor, use
// carefully, or not at all.
func (db *DB) Info() *Info {
return &Info{uintptr(unsafe.Pointer(&db.data[0])), db.pageSize}
}
// page retrieves a page reference from the mmap based on the current page size.
func (db *DB) page(id pgid) *page {
pos := id * pgid(db.pageSize)
return (*page)(unsafe.Pointer(&db.data[pos]))
}
// pageInBuffer retrieves a page reference from a given byte array based on the current page size.
func (db *DB) pageInBuffer(b []byte, id pgid) *page {
return (*page)(unsafe.Pointer(&b[id*pgid(db.pageSize)]))
}
// meta retrieves the current meta page reference.
func (db *DB) meta() *meta {
// We have to return the meta with the highest txid which doesn't fail
// validation. Otherwise, we can cause errors when in fact the database is
// in a consistent state. metaA is the one with the higher txid.
metaA := db.meta0
metaB := db.meta1
if db.meta1.txid > db.meta0.txid {
metaA = db.meta1
metaB = db.meta0
}
// Use higher meta page if valid. Otherwise fallback to previous, if valid.
if err := metaA.validate(); err == nil {
return metaA
} else if err := metaB.validate(); err == nil {
return metaB
}
// This should never be reached, because both meta1 and meta0 were validated
// on mmap() and we do fsync() on every write.
panic("bolt.DB.meta(): invalid meta pages")
}
// allocate returns a contiguous block of memory starting at a given page.
func (db *DB) allocate(count int) (*page, error) {
// Allocate a temporary buffer for the page.
var buf []byte
if count == 1 {
buf = db.pagePool.Get().([]byte)
} else {
buf = make([]byte, count*db.pageSize)
}
p := (*page)(unsafe.Pointer(&buf[0]))
p.overflow = uint32(count - 1)
// Use pages from the freelist if they are available.
if p.id = db.freelist.allocate(count); p.id != 0 {
return p, nil
}
// Resize mmap() if we're at the end.
p.id = db.rwtx.meta.pgid
var minsz = int((p.id+pgid(count))+1) * db.pageSize
if minsz >= db.datasz {
if err := db.mmap(minsz); err != nil {
return nil, fmt.Errorf("mmap allocate error: %s", err)
}
}
// Move the page id high water mark.
db.rwtx.meta.pgid += pgid(count)
return p, nil
}
// grow grows the size of the database to the given sz.
func (db *DB) grow(sz int) error {
// Ignore if the new size is less than available file size.
if sz <= db.filesz {
return nil
}
// If the data is smaller than the alloc size then only allocate what's needed.
// Once it goes over the allocation size then allocate in chunks.
if db.datasz < db.AllocSize {
sz = db.datasz
} else {
sz += db.AllocSize
}
// Truncate and fsync to ensure file size metadata is flushed.
// https://github.com/boltdb/bolt/issues/284
if !db.NoGrowSync && !db.readOnly {
if runtime.GOOS != "windows" {
if err := db.file.Truncate(int64(sz)); err != nil {
return fmt.Errorf("file resize error: %s", err)
}
}
if err := db.file.Sync(); err != nil {
return fmt.Errorf("file sync error: %s", err)
}
}
db.filesz = sz
return nil
}
func (db *DB) IsReadOnly() bool {
return db.readOnly
}
// Options represents the options that can be set when opening a database.
type Options struct {
// Timeout is the amount of time to wait to obtain a file lock.
// When set to zero it will wait indefinitely. This option is only
// available on Darwin and Linux.
Timeout time.Duration
// Sets the DB.NoGrowSync flag before memory mapping the file.
NoGrowSync bool
// Open database in read-only mode. Uses flock(..., LOCK_SH |LOCK_NB) to
// grab a shared lock (UNIX).
ReadOnly bool
// Sets the DB.MmapFlags flag before memory mapping the file.
MmapFlags int
// InitialMmapSize is the initial mmap size of the database
// in bytes. Read transactions won't block write transaction
// if the InitialMmapSize is large enough to hold database mmap
// size. (See DB.Begin for more information)
//
// If <=0, the initial map size is 0.
// If initialMmapSize is smaller than the previous database size,
// it takes no effect.
InitialMmapSize int
}
// DefaultOptions represent the options used if nil options are passed into Open().
// No timeout is used which will cause Bolt to wait indefinitely for a lock.
var DefaultOptions = &Options{
Timeout: 0,
NoGrowSync: false,
}
// Stats represents statistics about the database.
type Stats struct {
// Freelist stats
FreePageN int // total number of free pages on the freelist
PendingPageN int // total number of pending pages on the freelist
FreeAlloc int // total bytes allocated in free pages
FreelistInuse int // total bytes used by the freelist
// Transaction stats
TxN int // total number of started read transactions
OpenTxN int // number of currently open read transactions
TxStats TxStats // global, ongoing stats.
}
// Sub calculates and returns the difference between two sets of database stats.
// This is useful when obtaining stats at two different points and time and
// you need the performance counters that occurred within that time span.
func (s *Stats) Sub(other *Stats) Stats {
if other == nil {
return *s
}
var diff Stats
diff.FreePageN = s.FreePageN
diff.PendingPageN = s.PendingPageN
diff.FreeAlloc = s.FreeAlloc
diff.FreelistInuse = s.FreelistInuse
diff.TxN = s.TxN - other.TxN
diff.TxStats = s.TxStats.Sub(&other.TxStats)
return diff
}
func (s *Stats) add(other *Stats) {
s.TxStats.add(&other.TxStats)
}
type Info struct {
Data uintptr
PageSize int
}
type meta struct {
magic uint32
version uint32
pageSize uint32
flags uint32
root bucket
freelist pgid
pgid pgid
txid txid
checksum uint64
}
// validate checks the marker bytes and version of the meta page to ensure it matches this binary.
func (m *meta) validate() error {
if m.magic != magic {
return ErrInvalid
} else if m.version != version {
return ErrVersionMismatch
} else if m.checksum != 0 && m.checksum != m.sum64() {
return ErrChecksum
}
return nil
}
// copy copies one meta object to another.
func (m *meta) copy(dest *meta) {
*dest = *m
}
// write writes the meta onto a page.
func (m *meta) write(p *page) {
if m.root.root >= m.pgid {
panic(fmt.Sprintf("root bucket pgid (%d) above high water mark (%d)", m.root.root, m.pgid))
} else if m.freelist >= m.pgid {
panic(fmt.Sprintf("freelist pgid (%d) above high water mark (%d)", m.freelist, m.pgid))
}
// Page id is either going to be 0 or 1 which we can determine by the transaction ID.
p.id = pgid(m.txid % 2)
p.flags |= metaPageFlag
// Calculate the checksum.
m.checksum = m.sum64()
m.copy(p.meta())
}
// generates the checksum for the meta.
func (m *meta) sum64() uint64 {
var h = fnv.New64a()
_, _ = h.Write((*[unsafe.Offsetof(meta{}.checksum)]byte)(unsafe.Pointer(m))[:])
return h.Sum64()
}
// _assert will panic with a given formatted message if the given condition is false.
func _assert(condition bool, msg string, v ...interface{}) {
if !condition {
panic(fmt.Sprintf("assertion failed: "+msg, v...))
}
}
func warn(v ...interface{}) { fmt.Fprintln(os.Stderr, v...) }
func warnf(msg string, v ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\n", v...) }
func printstack() {
stack := strings.Join(strings.Split(string(debug.Stack()), "\n")[2:], "\n")
fmt.Fprintln(os.Stderr, stack)
}
|
{
"pile_set_name": "Github"
}
|
---
title: Companion -
---
//[detekt-api](../../../index.md)/[io.gitlab.arturbosch.detekt.api.internal](../../index.md)/[YamlConfig](../index.md)/[Companion](index.md)
# Companion
[jvm] object [Companion](index.md)
## Functions
| Name| Summary|
|---|---|
| [equals](index.md#kotlin/Any/equals/#kotlin.Any?/PointingToDeclaration/)| [jvm] <br>Content <br>open operator override fun [equals](index.md#kotlin/Any/equals/#kotlin.Any?/PointingToDeclaration/)(other: [Any](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html)?): [Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html) <br><br><br>
| [hashCode](index.md#kotlin/Any/hashCode/#/PointingToDeclaration/)| [jvm] <br>Content <br>open override fun [hashCode](index.md#kotlin/Any/hashCode/#/PointingToDeclaration/)(): [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html) <br><br><br>
| [load](load.md)| [jvm] <br>Brief description <br><br><br><br><br>Constructs a [YamlConfig](../index.md) from any [Reader](https://docs.oracle.com/javase/8/docs/api/java/io/Reader.html).<br><br><br><br>Note the reader will be consumed and closed.<br><br><br><br> <br>Content <br>fun [load](load.md)(reader: [Reader](https://docs.oracle.com/javase/8/docs/api/java/io/Reader.html)): [Config](../../../io.gitlab.arturbosch.detekt.api/-config/index.md) <br><br><br>[jvm] <br>Brief description <br><br><br>Factory method to load a yaml configuration. Given path must exist and point to a readable file.<br><br> <br>Content <br>fun [load](load.md)(path: [Path](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html)): [Config](../../../io.gitlab.arturbosch.detekt.api/-config/index.md) <br><br><br>
| [loadResource](load-resource.md)| [jvm] <br>Brief description <br><br><br>Factory method to load a yaml configuration from a URL.<br><br> <br>Content <br>fun [loadResource](load-resource.md)(url: [URL](https://docs.oracle.com/javase/8/docs/api/java/net/URL.html)): [Config](../../../io.gitlab.arturbosch.detekt.api/-config/index.md) <br><br><br>
| [toString](index.md#kotlin/Any/toString/#/PointingToDeclaration/)| [jvm] <br>Content <br>open override fun [toString](index.md#kotlin/Any/toString/#/PointingToDeclaration/)(): [String](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html) <br><br><br>
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho;
import static com.facebook.litho.LifecycleStep.getSteps;
import static org.assertj.core.api.Java6Assertions.assertThat;
import com.facebook.litho.testing.LithoViewRule;
import com.facebook.litho.testing.testrunner.LithoTestRunner;
import com.facebook.litho.widget.LayoutSpecTriggerTester;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(LithoTestRunner.class)
public class LayoutSpecTriggerTest {
public final @Rule LithoViewRule mLithoViewRule = new LithoViewRule();
@Test
public void layoutSpec_setRootAndTriggerEvent_eventIsTriggered() {
final ComponentContext componentContext = mLithoViewRule.getContext();
final AtomicReference<Object> triggerObjectRef = new AtomicReference<>();
final Handle triggerHandle = new Handle();
final List<LifecycleStep.StepInfo> info = new ArrayList<>();
final Component component =
LayoutSpecTriggerTester.create(componentContext)
.steps(info)
.triggerObjectRef(triggerObjectRef)
.handle(triggerHandle)
.build();
mLithoViewRule.setRoot(component);
mLithoViewRule.attachToWindow().measure().layout();
final Object bazObject = new Object();
// We need to use a ComponentContext with a ComponentTree on it
LayoutSpecTriggerTester.triggerTestEvent(
mLithoViewRule.getComponentTree().getContext(), triggerHandle, bazObject);
assertThat(getSteps(info))
.describedAs("Should call @OnTrigger method")
.containsExactly(LifecycleStep.ON_TRIGGER);
assertThat(triggerObjectRef.get())
.describedAs("Event object is correctly passed")
.isEqualTo(bazObject);
}
}
|
{
"pile_set_name": "Github"
}
|
#ifndef TRISYCL_SYCL_DETAIL_LINEAR_ID_HPP
#define TRISYCL_SYCL_DETAIL_LINEAR_ID_HPP
/** \file Compute linearized array access
Ronan at Keryell point FR
This file is distributed under the University of Illinois Open Source
License. See LICENSE.TXT for details.
*/
#include <cstddef>
namespace trisycl::detail {
/** \addtogroup helpers Some helpers for the implementation
@{
*/
/** Compute a linearized array access used in the OpenCL 2 world
Typically for the get_global_linear_id() and get_local_linear_id()
functions.
*/
template <typename Range, typename Id>
size_t constexpr inline linear_id(Range range, Id id, Id offset = {}) {
auto dims = std::distance(std::begin(range), std::end(range));
size_t linear_id = 0;
/* A good compiler should unroll this and do partial evaluation to
remove the first multiplication by 0 of this Horner evaluation and
remove the 0 offset evaluation */
for (int i = dims - 1; i >= 0; --i)
linear_id = linear_id*range[i] + id[i] - offset[i];
return linear_id;
}
/// @} End the helpers Doxygen group
}
/*
# Some Emacs stuff:
### Local Variables:
### ispell-local-dictionary: "american"
### eval: (flyspell-prog-mode)
### End:
*/
#endif // TRISYCL_SYCL_DETAIL_LINEAR_ID_HPP
|
{
"pile_set_name": "Github"
}
|
var baseAt = require('../internal/baseAt'),
baseFlatten = require('../internal/baseFlatten'),
restParam = require('../function/restParam');
/**
* Creates an array of elements corresponding to the given keys, or indexes,
* of `collection`. Keys may be specified as individual arguments or as arrays
* of keys.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {...(number|number[]|string|string[])} [props] The property names
* or indexes of elements to pick, specified individually or in arrays.
* @returns {Array} Returns the new array of picked elements.
* @example
*
* _.at(['a', 'b', 'c'], [0, 2]);
* // => ['a', 'c']
*
* _.at(['barney', 'fred', 'pebbles'], 0, 2);
* // => ['barney', 'pebbles']
*/
var at = restParam(function(collection, props) {
return baseAt(collection, baseFlatten(props));
});
module.exports = at;
|
{
"pile_set_name": "Github"
}
|
/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package labels
import (
"fmt"
"sort"
"strings"
)
// Labels allows you to present labels independently from their storage.
type Labels interface {
// Has returns whether the provided label exists.
Has(label string) (exists bool)
// Get returns the value for the provided label.
Get(label string) (value string)
}
// Set is a map of label:value. It implements Labels.
type Set map[string]string
// String returns all labels listed as a human readable string.
// Conveniently, exactly the format that ParseSelector takes.
func (ls Set) String() string {
selector := make([]string, 0, len(ls))
for key, value := range ls {
selector = append(selector, key+"="+value)
}
// Sort for determinism.
sort.StringSlice(selector).Sort()
return strings.Join(selector, ",")
}
// Has returns whether the provided label exists in the map.
func (ls Set) Has(label string) bool {
_, exists := ls[label]
return exists
}
// Get returns the value in the map for the provided label.
func (ls Set) Get(label string) string {
return ls[label]
}
// AsSelector converts labels into a selectors.
func (ls Set) AsSelector() Selector {
return SelectorFromSet(ls)
}
// AsSelectorPreValidated converts labels into a selector, but
// assumes that labels are already validated and thus don't
// preform any validation.
// According to our measurements this is significantly faster
// in codepaths that matter at high scale.
func (ls Set) AsSelectorPreValidated() Selector {
return SelectorFromValidatedSet(ls)
}
// FormatLabels convert label map into plain string
func FormatLabels(labelMap map[string]string) string {
l := Set(labelMap).String()
if l == "" {
l = "<none>"
}
return l
}
// Conflicts takes 2 maps and returns true if there a key match between
// the maps but the value doesn't match, and returns false in other cases
func Conflicts(labels1, labels2 Set) bool {
small := labels1
big := labels2
if len(labels2) < len(labels1) {
small = labels2
big = labels1
}
for k, v := range small {
if val, match := big[k]; match {
if val != v {
return true
}
}
}
return false
}
// Merge combines given maps, and does not check for any conflicts
// between the maps. In case of conflicts, second map (labels2) wins
func Merge(labels1, labels2 Set) Set {
mergedMap := Set{}
for k, v := range labels1 {
mergedMap[k] = v
}
for k, v := range labels2 {
mergedMap[k] = v
}
return mergedMap
}
// Equals returns true if the given maps are equal
func Equals(labels1, labels2 Set) bool {
if len(labels1) != len(labels2) {
return false
}
for k, v := range labels1 {
value, ok := labels2[k]
if !ok {
return false
}
if value != v {
return false
}
}
return true
}
// AreLabelsInWhiteList verifies if the provided label list
// is in the provided whitelist and returns true, otherwise false.
func AreLabelsInWhiteList(labels, whitelist Set) bool {
if len(whitelist) == 0 {
return true
}
for k, v := range labels {
value, ok := whitelist[k]
if !ok {
return false
}
if value != v {
return false
}
}
return true
}
// ConvertSelectorToLabelsMap converts selector string to labels map
// and validates keys and values
func ConvertSelectorToLabelsMap(selector string) (Set, error) {
labelsMap := Set{}
if len(selector) == 0 {
return labelsMap, nil
}
labels := strings.Split(selector, ",")
for _, label := range labels {
l := strings.Split(label, "=")
if len(l) != 2 {
return labelsMap, fmt.Errorf("invalid selector: %s", l)
}
key := strings.TrimSpace(l[0])
if err := validateLabelKey(key); err != nil {
return labelsMap, err
}
value := strings.TrimSpace(l[1])
if err := validateLabelValue(key, value); err != nil {
return labelsMap, err
}
labelsMap[key] = value
}
return labelsMap, nil
}
|
{
"pile_set_name": "Github"
}
|
<template>
<div class="movie-list-cell">
<h4>{{ $t('movie.history') }}<a href="">{{ $t('common.browseMore.seemore') }}</a></h4>
<i-row>
<i-col :xs="12" :sm="12" :md="8" :lg="6" v-for="movie in movies" :key="movie.id">
<div class="list">
<movie-list-item :movie="movie"></movie-list-item>
</div>
</i-col>
</i-row>
</div>
</template>
<script type="text/ecmascript-6">
import MovieListItem from '@/components/views/Movie/MovieListItem';
export default {
name: 'movie-list-cell',
props: {
movies: {
Type: Array
}
},
components: {
'movie-list-item': MovieListItem
}
};
</script>
<style lang="stylus" type="text/stylus" rel="stylesheet/stylus">
@import "../../../common/stylus/theme.styl";
.movie-list-cell
border 1px solid $default-border-color
padding 10px
h4
font-size 26px
line-height 30px
padding 10px 20px 10px 10px
a
font-size 16px
float right
.list
padding 10px
a
.info
height 30%
padding 8px
@media only screen and (max-width: 768px)
height 20%
@media screen and (min-width: 768px)
height 20%
@media screen and (min-width: 992px)
height 30%
@media screen and (min-width: 1200px)
height 30%
.title
margin-bottom 5px
@media only screen and (max-width: 768px)
font-size 16px
line-height 18px
@media screen and (min-width: 768px)
font-size 18px
line-height 21px
@media screen and (min-width: 992px)
font-size 18px
line-height 21px
@media screen and (min-width: 1200px)
font-size 17px
line-height 20px
.desc
@media only screen and (max-width: 768px)
font-size 12px
line-height 14px
@media screen and (min-width: 768px)
font-size 14px
line-height 17px
@media screen and (min-width: 992px)
font-size 14px
line-height 17px
@media screen and (min-width: 1200px)
font-size 13px
line-height 15px
&:hover
.info
@media only screen and (max-width: 768px)
height 22%
@media screen and (min-width: 768px)
height 22%
@media screen and (min-width: 992px)
height 35%
@media screen and (min-width: 1200px)
height 35%
</style>
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2020, ARM Limited and Contributors. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef PLATFORM_DEF_H
#define PLATFORM_DEF_H
#include <lib/utils_def.h>
#include <sgi_base_platform_def.h>
#define PLAT_ARM_CLUSTER_COUNT U(4)
#define CSS_SGI_MAX_CPUS_PER_CLUSTER U(1)
#define CSS_SGI_MAX_PE_PER_CPU U(1)
#define PLAT_CSS_MHU_BASE UL(0x45400000)
#define PLAT_MHUV2_BASE PLAT_CSS_MHU_BASE
#define CSS_SYSTEM_PWR_DMN_LVL ARM_PWR_LVL2
#define PLAT_MAX_PWR_LVL ARM_PWR_LVL1
/* Virtual address used by dynamic mem_protect for chunk_base */
#define PLAT_ARM_MEM_PROTEC_VA_FRAME UL(0xC0000000)
/* Physical and virtual address space limits for MMU in AARCH64 mode */
#define PLAT_PHY_ADDR_SPACE_SIZE CSS_SGI_REMOTE_CHIP_MEM_OFFSET( \
CSS_SGI_CHIP_COUNT)
#define PLAT_VIRT_ADDR_SPACE_SIZE CSS_SGI_REMOTE_CHIP_MEM_OFFSET( \
CSS_SGI_CHIP_COUNT)
/* GIC related constants */
#define PLAT_ARM_GICD_BASE UL(0x30000000)
#define PLAT_ARM_GICC_BASE UL(0x2C000000)
#define PLAT_ARM_GICR_BASE UL(0x30140000)
#endif /* PLATFORM_DEF_H */
|
{
"pile_set_name": "Github"
}
|
/*
* RelativeMeanAbsoluteDeviationMT.java
* Copyright (C) 2017 University of Porto, Portugal
* @author J. Duarte, J. Gama
*
* 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 moa.classifiers.rules.multilabel.errormeasurers;
import com.yahoo.labs.samoa.instances.Prediction;
/**
* Relative Mean Absolute Deviation for multitarget and with fading factor
*/
public class RelativeMeanAbsoluteDeviationMT extends AbstractMultiTargetErrorMeasurer {
/**
*
*/
protected double weightSeen;
protected double [] sumError;
protected double [] sumY;
protected double [] sumErrorToTargetMean;
private static final long serialVersionUID = 1L;
protected boolean hasStarted;
protected int numLearnedOutputs;
@Override
public void addPrediction(Prediction prediction, Prediction trueClass, double weight) {
int numOutputs=prediction.numOutputAttributes();
if (!hasStarted){
sumError=new double[numOutputs];
sumY=new double[numOutputs];
sumErrorToTargetMean=new double[numOutputs];
hasStarted=true;
for(int i=0; i<numOutputs;i++)
if(prediction.hasVotesForAttribute(i))
++numLearnedOutputs;
hasStarted=true;
}
weightSeen=weight+fadingErrorFactor*weightSeen;
for(int i=0; i<numOutputs;i++){
if(prediction.hasVotesForAttribute(i)){
sumError[i]=Math.abs(prediction.getVote(i, 0)-trueClass.getVote(i, 0))*weight+fadingErrorFactor*sumError[i];
sumY[i]=trueClass.getVote(i, 0)*weight+fadingErrorFactor*sumY[i];
double errorOutputTM=Math.abs(prediction.getVote(i, 0)-sumY[i]/weightSeen); //error to target mean
sumErrorToTargetMean[i]=errorOutputTM*weight+fadingErrorFactor*sumErrorToTargetMean[i];
}
}
}
@Override
public double getCurrentError() {
if(weightSeen==0)
return Double.MAX_VALUE;
else
{
double sum=0;
int numOutputs=sumError.length;
for (int i=0; i<numOutputs; i++)
sum+=getCurrentError(i);
return sum/numLearnedOutputs;
}
}
@Override
public double getCurrentError(int index) {
return sumError[index]/sumErrorToTargetMean[index];
}
@Override
public double[] getCurrentErrors() {
double [] errors=null;
if(sumError!=null){
errors=new double[sumError.length];
for (int i=0;i<sumError.length; i++)
errors[i]=getCurrentError(i);
}
return errors;
}
}
|
{
"pile_set_name": "Github"
}
|
#ifndef BOOST_ARCHIVE_DETAIL_POLYMORPHIC_OARCHIVE_ROUTE_HPP
#define BOOST_ARCHIVE_DETAIL_POLYMORPHIC_OARCHIVE_ROUTE_HPP
// MS compatible compilers support #pragma once
#if defined(_MSC_VER)
# pragma once
#endif
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// polymorphic_oarchive_route.hpp
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for updates, documentation, and revision history.
#include <string>
#include <ostream>
#include <cstddef> // size_t
#include <boost/config.hpp>
#if defined(BOOST_NO_STDC_NAMESPACE)
namespace std{
using ::size_t;
} // namespace std
#endif
#include <boost/cstdint.hpp>
#include <boost/integer_traits.hpp>
#include <boost/archive/polymorphic_oarchive.hpp>
#include <boost/archive/detail/abi_prefix.hpp> // must be the last header
namespace boost {
namespace serialization {
class extended_type_info;
} // namespace serialization
namespace archive {
namespace detail{
class BOOST_ARCHIVE_DECL(BOOST_PP_EMPTY()) basic_oserializer;
class BOOST_ARCHIVE_DECL(BOOST_PP_EMPTY()) basic_pointer_oserializer;
#ifdef BOOST_MSVC
# pragma warning(push)
# pragma warning(disable : 4511 4512)
#endif
template<class ArchiveImplementation>
class polymorphic_oarchive_route :
public polymorphic_oarchive,
// note: gcc dynamic cross cast fails if the the derivation below is
// not public. I think this is a mistake.
public /*protected*/ ArchiveImplementation
{
private:
// these are used by the serialization library.
virtual void save_object(
const void *x,
const detail::basic_oserializer & bos
){
ArchiveImplementation::save_object(x, bos);
}
virtual void save_pointer(
const void * t,
const detail::basic_pointer_oserializer * bpos_ptr
){
ArchiveImplementation::save_pointer(t, bpos_ptr);
}
virtual void save_null_pointer(){
ArchiveImplementation::save_null_pointer();
}
// primitive types the only ones permitted by polymorphic archives
virtual void save(const bool t){
ArchiveImplementation::save(t);
}
virtual void save(const char t){
ArchiveImplementation::save(t);
}
virtual void save(const signed char t){
ArchiveImplementation::save(t);
}
virtual void save(const unsigned char t){
ArchiveImplementation::save(t);
}
#ifndef BOOST_NO_CWCHAR
#ifndef BOOST_NO_INTRINSIC_WCHAR_T
virtual void save(const wchar_t t){
ArchiveImplementation::save(t);
}
#endif
#endif
virtual void save(const short t){
ArchiveImplementation::save(t);
}
virtual void save(const unsigned short t){
ArchiveImplementation::save(t);
}
virtual void save(const int t){
ArchiveImplementation::save(t);
}
virtual void save(const unsigned int t){
ArchiveImplementation::save(t);
}
virtual void save(const long t){
ArchiveImplementation::save(t);
}
virtual void save(const unsigned long t){
ArchiveImplementation::save(t);
}
#if defined(BOOST_HAS_LONG_LONG)
virtual void save(const boost::long_long_type t){
ArchiveImplementation::save(t);
}
virtual void save(const boost::ulong_long_type t){
ArchiveImplementation::save(t);
}
#elif defined(BOOST_HAS_MS_INT64)
virtual void save(const boost::int64_t t){
ArchiveImplementation::save(t);
}
virtual void save(const boost::uint64_t t){
ArchiveImplementation::save(t);
}
#endif
virtual void save(const float t){
ArchiveImplementation::save(t);
}
virtual void save(const double t){
ArchiveImplementation::save(t);
}
virtual void save(const std::string & t){
ArchiveImplementation::save(t);
}
#ifndef BOOST_NO_STD_WSTRING
virtual void save(const std::wstring & t){
ArchiveImplementation::save(t);
}
#endif
virtual library_version_type get_library_version() const{
return ArchiveImplementation::get_library_version();
}
virtual unsigned int get_flags() const {
return ArchiveImplementation::get_flags();
}
virtual void save_binary(const void * t, std::size_t size){
ArchiveImplementation::save_binary(t, size);
}
// used for xml and other tagged formats default does nothing
virtual void save_start(const char * name){
ArchiveImplementation::save_start(name);
}
virtual void save_end(const char * name){
ArchiveImplementation::save_end(name);
}
virtual void end_preamble(){
ArchiveImplementation::end_preamble();
}
virtual void register_basic_serializer(const detail::basic_oserializer & bos){
ArchiveImplementation::register_basic_serializer(bos);
}
public:
// this can't be inheriteded because they appear in mulitple
// parents
typedef mpl::bool_<false> is_loading;
typedef mpl::bool_<true> is_saving;
// the << operator
template<class T>
polymorphic_oarchive & operator<<(T & t){
return polymorphic_oarchive::operator<<(t);
}
// the & operator
template<class T>
polymorphic_oarchive & operator&(T & t){
return polymorphic_oarchive::operator&(t);
}
// register type function
template<class T>
const basic_pointer_oserializer *
register_type(T * t = NULL){
return ArchiveImplementation::register_type(t);
}
// all current archives take a stream as constructor argument
template <class _Elem, class _Tr>
polymorphic_oarchive_route(
std::basic_ostream<_Elem, _Tr> & os,
unsigned int flags = 0
) :
ArchiveImplementation(os, flags)
{}
virtual ~polymorphic_oarchive_route(){};
};
} // namespace detail
} // namespace archive
} // namespace boost
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
#include <boost/archive/detail/abi_suffix.hpp> // pops abi_suffix.hpp pragmas
#endif // BOOST_ARCHIVE_DETAIL_POLYMORPHIC_OARCHIVE_DISPATCH_HPP
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS 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.
*
* QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.model
import android.content.ContentUris
import android.net.Uri
import android.provider.Telephony.*
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.Index
import io.realm.annotations.PrimaryKey
open class Message : RealmObject() {
enum class AttachmentType { TEXT, IMAGE, VIDEO, AUDIO, SLIDESHOW, NOT_LOADED }
@PrimaryKey var id: Long = 0
@Index var threadId: Long = 0
// The MMS-SMS content provider returns messages where duplicate ids can exist. This is because
// SMS and MMS are stored in separate tables. We can't use these ids as our realm message id
// since it's our primary key for the single message object, so we'll store the original id in
// case we need to access the original message item in the content provider
var contentId: Long = 0
var address: String = ""
var boxId: Int = 0
var type: String = ""
var date: Long = 0
var dateSent: Long = 0
var seen: Boolean = false
var read: Boolean = false
var locked: Boolean = false
var subId: Int = -1
// SMS only
var body: String = ""
var errorCode: Int = 0
var deliveryStatus: Int = Sms.STATUS_NONE
// MMS only
var attachmentTypeString: String = AttachmentType.NOT_LOADED.toString()
var attachmentType: AttachmentType
get() = AttachmentType.valueOf(attachmentTypeString)
set(value) {
attachmentTypeString = value.toString()
}
var mmsDeliveryStatusString: String = ""
var readReportString: String = ""
var errorType: Int = 0
var messageSize: Int = 0
var messageType: Int = 0
var mmsStatus: Int = 0
var subject: String = ""
var textContentType: String = ""
var parts: RealmList<MmsPart> = RealmList()
fun getUri(): Uri {
val baseUri = if (isMms()) Mms.CONTENT_URI else Sms.CONTENT_URI
return ContentUris.withAppendedId(baseUri, contentId)
}
fun isMms(): Boolean = type == "mms"
fun isSms(): Boolean = type == "sms"
fun isMe(): Boolean {
val isIncomingMms = isMms() && (boxId == Mms.MESSAGE_BOX_INBOX || boxId == Mms.MESSAGE_BOX_ALL)
val isIncomingSms = isSms() && (boxId == Sms.MESSAGE_TYPE_INBOX || boxId == Sms.MESSAGE_TYPE_ALL)
return !(isIncomingMms || isIncomingSms)
}
fun isOutgoingMessage(): Boolean {
val isOutgoingMms = isMms() && boxId == Mms.MESSAGE_BOX_OUTBOX
val isOutgoingSms = isSms() && (boxId == Sms.MESSAGE_TYPE_FAILED
|| boxId == Sms.MESSAGE_TYPE_OUTBOX
|| boxId == Sms.MESSAGE_TYPE_QUEUED)
return isOutgoingMms || isOutgoingSms
}
/**
* Returns the text that should be copied to the clipboard
*/
fun getText(): String {
return when {
isSms() -> body
else -> parts
.filter { it.type == "text/plain" }
.mapNotNull { it.text }
.joinToString("\n") { text -> text }
}
}
/**
* Returns the text that should be displayed when a preview of the message
* needs to be displayed, such as in the conversation view or in a notification
*/
fun getSummary(): String = when {
isSms() -> body
else -> {
val sb = StringBuilder()
// Add subject
getCleansedSubject().takeIf { it.isNotEmpty() }?.run(sb::appendln)
// Add parts
parts.mapNotNull { it.getSummary() }.forEach { summary -> sb.appendln(summary) }
sb.toString().trim()
}
}
/**
* Cleanses the subject in case it's useless, so that the UI doesn't have to show it
*/
fun getCleansedSubject(): String {
val uselessSubjects = listOf("no subject", "NoSubject", "<not present>")
return if (uselessSubjects.contains(subject)) "" else subject
}
fun isSending(): Boolean {
return !isFailedMessage() && isOutgoingMessage()
}
fun isDelivered(): Boolean {
val isDeliveredMms = false // TODO
val isDeliveredSms = deliveryStatus == Sms.STATUS_COMPLETE
return isDeliveredMms || isDeliveredSms
}
fun isFailedMessage(): Boolean {
val isFailedMms = isMms() && (errorType >= MmsSms.ERR_TYPE_GENERIC_PERMANENT || boxId == Mms.MESSAGE_BOX_FAILED)
val isFailedSms = isSms() && boxId == Sms.MESSAGE_TYPE_FAILED
return isFailedMms || isFailedSms
}
fun compareSender(other: Message): Boolean = when {
isMe() && other.isMe() -> subId == other.subId
!isMe() && !other.isMe() -> subId == other.subId && address == other.address
else -> false
}
}
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.