prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>ip_transport.py<|end_file_name|><|fim▁begin|>"""
Abstract base for a specific IP transports (TCP or UDP).
* It starts and stops a socket
* It handles callbacks for incoming frame service types
"""
from __future__ import annotations
from abc import ABC, abstractmethod
import asyncio
import logging
from typing import Callable, cast
from xknx.exceptions import CommunicationError
from xknx.knxip import HPAI, KNXIPFrame, KNXIPServiceType<|fim▁hole|>
class KNXIPTransport(ABC):
"""Abstract base class for KNX/IP transports."""
callbacks: list[KNXIPTransport.Callback]
local_hpai: HPAI
remote_addr: tuple[str, int]
transport: asyncio.BaseTransport | None
class Callback:
"""Callback class for handling callbacks for different 'KNX service types' of received packets."""
def __init__(
self,
callback: TransportCallbackType,
service_types: list[KNXIPServiceType] | None = None,
):
"""Initialize Callback class."""
self.callback = callback
self.service_types = service_types or []
def has_service(self, service_type: KNXIPServiceType) -> bool:
"""Test if callback is listening for given service type."""
return not self.service_types or service_type in self.service_types
def register_callback(
self,
callback: TransportCallbackType,
service_types: list[KNXIPServiceType] | None = None,
) -> KNXIPTransport.Callback:
"""Register callback."""
if service_types is None:
service_types = []
callb = KNXIPTransport.Callback(callback, service_types)
self.callbacks.append(callb)
return callb
def unregister_callback(self, callb: KNXIPTransport.Callback) -> None:
"""Unregister callback."""
self.callbacks.remove(callb)
def handle_knxipframe(self, knxipframe: KNXIPFrame, source: HPAI) -> None:
"""Handle KNXIP Frame and call all callbacks matching the service type ident."""
handled = False
for callback in self.callbacks:
if callback.has_service(knxipframe.header.service_type_ident):
callback.callback(knxipframe, source, self)
handled = True
if not handled:
knx_logger.debug(
"Unhandled: %s from: %s",
knxipframe.header.service_type_ident,
source,
)
@abstractmethod
async def connect(self) -> None:
"""Connect transport."""
@abstractmethod
def send(self, knxipframe: KNXIPFrame, addr: tuple[str, int] | None = None) -> None:
"""Send KNXIPFrame via transport."""
def getsockname(self) -> tuple[str, int]:
"""Return socket IP and port."""
if self.transport is None:
raise CommunicationError(
"No transport defined. Socket information not resolveable"
)
return cast(tuple[str, int], self.transport.get_extra_info("sockname"))
def getremote(self) -> str | None:
"""Return peername."""
return (
self.transport.get_extra_info("peername")
if self.transport is not None
else None
)
def stop(self) -> None:
"""Stop socket."""
if self.transport is not None:
self.transport.close()<|fim▁end|> |
TransportCallbackType = Callable[[KNXIPFrame, HPAI, "KNXIPTransport"], None]
knx_logger = logging.getLogger("xknx.knx") |
<|file_name|>caching.rs<|end_file_name|><|fim▁begin|>/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use abomonation_derive::Abomonation;
use anyhow::{anyhow, Context, Error, Result};
use async_trait::async_trait;
use bytes::Bytes;<|fim▁hole|> get_or_fill, CacheDisposition, CacheTtl, CachelibHandler, EntityStore, KeyedEntityStore,
MemcacheEntity, MemcacheHandler,
};
use context::CoreContext;
use fbinit::FacebookInit;
use fbthrift::compact_protocol;
use memcache::{KeyGen, MemcacheClient};
use mononoke_types::{ChangesetId, Globalrev, RepositoryId};
use std::collections::{HashMap, HashSet};
use bonsai_globalrev_mapping_thrift as thrift;
use super::{BonsaiGlobalrevMapping, BonsaiGlobalrevMappingEntry, BonsaisOrGlobalrevs};
#[derive(Abomonation, Clone, Debug, Eq, Hash, PartialEq)]
pub struct BonsaiGlobalrevMappingCacheEntry {
pub repo_id: RepositoryId,
pub bcs_id: ChangesetId,
pub globalrev: Globalrev,
}
impl BonsaiGlobalrevMappingCacheEntry {
fn into_entry(self, repo_id: RepositoryId) -> Result<BonsaiGlobalrevMappingEntry> {
if self.repo_id == repo_id {
Ok(BonsaiGlobalrevMappingEntry {
bcs_id: self.bcs_id,
globalrev: self.globalrev,
})
} else {
Err(anyhow!(
"Cache returned invalid entry: repo {} returned for query to repo {}",
self.repo_id,
repo_id
))
}
}
fn from_entry(
entry: BonsaiGlobalrevMappingEntry,
repo_id: RepositoryId,
) -> BonsaiGlobalrevMappingCacheEntry {
BonsaiGlobalrevMappingCacheEntry {
repo_id,
bcs_id: entry.bcs_id,
globalrev: entry.globalrev,
}
}
}
#[derive(Clone)]
pub struct CachingBonsaiGlobalrevMapping<T> {
cachelib: CachelibHandler<BonsaiGlobalrevMappingCacheEntry>,
memcache: MemcacheHandler,
keygen: KeyGen,
inner: T,
}
impl<T> CachingBonsaiGlobalrevMapping<T> {
pub fn new(fb: FacebookInit, inner: T, cachelib: VolatileLruCachePool) -> Self {
Self {
inner,
cachelib: cachelib.into(),
memcache: MemcacheClient::new(fb)
.expect("Memcache initialization failed")
.into(),
keygen: Self::create_key_gen(),
}
}
pub fn new_test(inner: T) -> Self {
Self {
inner,
cachelib: CachelibHandler::create_mock(),
memcache: MemcacheHandler::create_mock(),
keygen: Self::create_key_gen(),
}
}
fn create_key_gen() -> KeyGen {
let key_prefix = "scm.mononoke.bonsai_globalrev_mapping";
KeyGen::new(
key_prefix,
thrift::MC_CODEVER as u32,
thrift::MC_SITEVER as u32,
)
}
pub fn cachelib(&self) -> &CachelibHandler<BonsaiGlobalrevMappingCacheEntry> {
&self.cachelib
}
}
#[async_trait]
impl<T> BonsaiGlobalrevMapping for CachingBonsaiGlobalrevMapping<T>
where
T: BonsaiGlobalrevMapping + Clone + Sync + Send + 'static,
{
fn repo_id(&self) -> RepositoryId {
self.inner.repo_id()
}
async fn bulk_import(
&self,
ctx: &CoreContext,
entries: &[BonsaiGlobalrevMappingEntry],
) -> Result<(), Error> {
self.inner.bulk_import(ctx, entries).await
}
async fn get(
&self,
ctx: &CoreContext,
objects: BonsaisOrGlobalrevs,
) -> Result<Vec<BonsaiGlobalrevMappingEntry>, Error> {
let cache_request = (ctx, self);
let repo_id = self.repo_id();
let res = match objects {
BonsaisOrGlobalrevs::Bonsai(cs_ids) => {
get_or_fill(cache_request, cs_ids.into_iter().collect())
.await
.with_context(|| "Error fetching globalrevs via cache")?
.into_iter()
.map(|(_, val)| val.into_entry(repo_id))
.collect::<Result<_>>()?
}
BonsaisOrGlobalrevs::Globalrev(globalrevs) => {
get_or_fill(cache_request, globalrevs.into_iter().collect())
.await
.with_context(|| "Error fetching bonsais via cache")?
.into_iter()
.map(|(_, val)| val.into_entry(repo_id))
.collect::<Result<_>>()?
}
};
Ok(res)
}
async fn get_closest_globalrev(
&self,
ctx: &CoreContext,
globalrev: Globalrev,
) -> Result<Option<Globalrev>, Error> {
self.inner.get_closest_globalrev(ctx, globalrev).await
}
async fn get_max(&self, ctx: &CoreContext) -> Result<Option<Globalrev>, Error> {
self.inner.get_max(ctx).await
}
}
impl MemcacheEntity for BonsaiGlobalrevMappingCacheEntry {
fn serialize(&self) -> Bytes {
let entry = thrift::BonsaiGlobalrevMappingEntry {
repo_id: self.repo_id.id(),
bcs_id: self.bcs_id.into_thrift(),
globalrev: self
.globalrev
.id()
.try_into()
.expect("Globalrevs must fit within a i64"),
};
compact_protocol::serialize(&entry)
}
fn deserialize(bytes: Bytes) -> Result<Self, ()> {
let thrift::BonsaiGlobalrevMappingEntry {
repo_id,
bcs_id,
globalrev,
} = compact_protocol::deserialize(bytes).map_err(|_| ())?;
let repo_id = RepositoryId::new(repo_id);
let bcs_id = ChangesetId::from_thrift(bcs_id).map_err(|_| ())?;
let globalrev = Globalrev::new(globalrev.try_into().map_err(|_| ())?);
Ok(BonsaiGlobalrevMappingCacheEntry {
repo_id,
bcs_id,
globalrev,
})
}
}
type CacheRequest<'a, T> = (&'a CoreContext, &'a CachingBonsaiGlobalrevMapping<T>);
impl<T> EntityStore<BonsaiGlobalrevMappingCacheEntry> for CacheRequest<'_, T> {
fn cachelib(&self) -> &CachelibHandler<BonsaiGlobalrevMappingCacheEntry> {
let (_, mapping) = self;
&mapping.cachelib
}
fn keygen(&self) -> &KeyGen {
let (_, mapping) = self;
&mapping.keygen
}
fn memcache(&self) -> &MemcacheHandler {
let (_, mapping) = self;
&mapping.memcache
}
fn cache_determinator(&self, _: &BonsaiGlobalrevMappingCacheEntry) -> CacheDisposition {
CacheDisposition::Cache(CacheTtl::NoTtl)
}
caching_ext::impl_singleton_stats!("bonsai_globalrev_mapping");
}
#[async_trait]
impl<T> KeyedEntityStore<ChangesetId, BonsaiGlobalrevMappingCacheEntry> for CacheRequest<'_, T>
where
T: BonsaiGlobalrevMapping + Send + Sync + Clone + 'static,
{
fn get_cache_key(&self, key: &ChangesetId) -> String {
let (_, mapping) = self;
format!("{}.bonsai.{}", mapping.repo_id(), key)
}
async fn get_from_db(
&self,
keys: HashSet<ChangesetId>,
) -> Result<HashMap<ChangesetId, BonsaiGlobalrevMappingCacheEntry>, Error> {
let (ctx, mapping) = self;
let repo_id = mapping.repo_id();
let res = mapping
.inner
.get(ctx, BonsaisOrGlobalrevs::Bonsai(keys.into_iter().collect()))
.await
.with_context(|| "Error fetching globalrevs from bonsais from SQL")?;
Result::<_, Error>::Ok(
res.into_iter()
.map(|e| {
(
e.bcs_id,
BonsaiGlobalrevMappingCacheEntry::from_entry(e, repo_id),
)
})
.collect(),
)
}
}
#[async_trait]
impl<T> KeyedEntityStore<Globalrev, BonsaiGlobalrevMappingCacheEntry> for CacheRequest<'_, T>
where
T: BonsaiGlobalrevMapping + Send + Sync + Clone + 'static,
{
fn get_cache_key(&self, key: &Globalrev) -> String {
let (_, mapping) = self;
format!("{}.globalrev.{}", mapping.repo_id(), key.id())
}
async fn get_from_db(
&self,
keys: HashSet<Globalrev>,
) -> Result<HashMap<Globalrev, BonsaiGlobalrevMappingCacheEntry>, Error> {
let (ctx, mapping) = self;
let repo_id = mapping.repo_id();
let res = mapping
.inner
.get(
ctx,
BonsaisOrGlobalrevs::Globalrev(keys.into_iter().collect()),
)
.await
.with_context(|| "Error fetching bonsais from globalrevs from SQL")?;
Result::<_, Error>::Ok(
res.into_iter()
.map(|e| {
(
e.globalrev,
BonsaiGlobalrevMappingCacheEntry::from_entry(e, repo_id),
)
})
.collect(),
)
}
}<|fim▁end|> | use cachelib::VolatileLruCachePool;
use caching_ext::{ |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>#[inline]
fn reverse_str(s: &str) -> String<|fim▁hole|>
fn rotate_right(s: &str, d: usize) -> String
{
let s1 = reverse_str(&s[..d]);
let s2 = reverse_str(&s[d..]);
reverse_str(&(s1 + &s2))
}
fn main() {
let s = "Hello, world!";
println!("{} -> {} ; {}", &s, reverse_str(&s), rotate_right(&s, 4));
}<|fim▁end|> | {
s.chars().rev().collect::<String>()
} |
<|file_name|>initialization_test.go<|end_file_name|><|fim▁begin|>package vnc
import (
"io"
"testing"
)
func TestClientInit(t *testing.T) {
tests := []struct {
exclusive bool
shared uint8
}{
{true, 0},
{false, 1},
}
mockConn := &MockConn{}
conn := NewClientConn(mockConn, &ClientConfig{})
for _, tt := range tests {
mockConn.Reset()
// Send client initialization.
conn.config.Exclusive = tt.exclusive
if err := conn.clientInit(); err != nil {
t.Fatalf("unexpected error; %s", err)
}
// Validate server reception.
var shared uint8
if err := conn.receive(&shared); err != nil {
t.Errorf("error receiving client init; %s", err)
continue
}
if got, want := shared, tt.shared; got != want {
t.Errorf("incorrect shared-flag: got = %d, want = %d", got, want)
continue
}
// Ensure nothing extra was sent by client.
var buf []byte
if err := conn.receiveN(&buf, 1024); err != io.EOF {
t.Errorf("expected EOF; %s", err)
continue
}
}
}
func TestServerInit(t *testing.T) {
const (
none = iota
fbw
fbh
pf
dn
)
tests := []struct {
eof int
fbWidth, fbHeight uint16
pixelFormat PixelFormat
desktopName string
}{
// Valid protocol.
{dn, 100, 200, NewPixelFormat(16), "foo"},
// Invalid protocol (missing fields).
{eof: none},
{eof: fbw, fbWidth: 1},
{eof: fbh, fbWidth: 2, fbHeight: 1},
{eof: pf, fbWidth: 3, fbHeight: 2, pixelFormat: NewPixelFormat(16)},
}
mockConn := &MockConn{}
conn := NewClientConn(mockConn, &ClientConfig{})
for i, tt := range tests {
mockConn.Reset()
if tt.eof >= fbw {
if err := conn.send(tt.fbWidth); err != nil {
t.Fatal(err)<|fim▁hole|> if tt.eof >= fbh {
if err := conn.send(tt.fbHeight); err != nil {
t.Fatal(err)
}
}
if tt.eof >= pf {
pfBytes, err := tt.pixelFormat.Marshal()
if err != nil {
t.Fatal(err)
}
if err := conn.send(pfBytes); err != nil {
t.Fatal(err)
}
}
if tt.eof >= dn {
if err := conn.send(uint32(len(tt.desktopName))); err != nil {
t.Fatal(err)
}
if err := conn.send([]byte(tt.desktopName)); err != nil {
t.Fatal(err)
}
}
// Validate server message handling.
err := conn.serverInit()
if tt.eof < dn && err == nil {
t.Fatalf("%v: expected error", i)
}
if tt.eof < dn {
// The protocol was incomplete; no point in checking values.
continue
}
if err != nil {
t.Fatalf("%v: unexpected error %v", i, err)
}
if conn.fbWidth != tt.fbWidth {
t.Errorf("FramebufferWidth: got = %v, want = %v", conn.fbWidth, tt.fbWidth)
}
if conn.fbHeight != tt.fbHeight {
t.Errorf("FramebufferHeight: got = %v, want = %v", conn.fbHeight, tt.fbHeight)
}
if !equalPixelFormat(conn.pixelFormat, tt.pixelFormat) {
t.Errorf("PixelFormat: got = %v, want = %v", conn.pixelFormat, tt.pixelFormat)
}
if conn.DesktopName() != tt.desktopName {
t.Errorf("DesktopName: got = %v, want = %v", conn.DesktopName(), tt.desktopName)
}
}
}<|fim▁end|> | }
} |
<|file_name|>test_tree_loader.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# reference_node_loader.py: unit tests for
# vyconf.tree.referencetree.ReferenceTreeLoader
# Copyright (C) 2014 VyOS Development Group <[email protected]>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software<|fim▁hole|>
from vyconf.tree import referencetree as reftree
from vyconf.tests.integration.reference_tree import base
class MockType(object):
@staticmethod
def get_format_string(constraint):
return "fgsfds"
class TestVytreeReferenceLoader(base.ReferenceTreeTestCase):
def setUp(self):
super(TestVytreeReferenceLoader, self).setUp()
self.reference_tree = reftree.ReferenceNode('root')
# For testing interface that expands other node
self.reference_tree.insert_child(['quux'])
loader = self.get_loader(
"interface_definition_valid.xml",
{"mock": MockType},
'schemas/interface_definition.rng')
loader.load(self.reference_tree)
def test_get_child(self):
child = self.reference_tree.get_child(['quux', 'foo', 'bar'])
self.assertIsInstance(child, reftree.ReferenceNode)
def test_should_not_be_tag_node(self):
child = self.reference_tree.get_child(['quux', 'foo'])
self.assertFalse(child.is_tag())
def test_should_be_tag_node(self):
child = self.reference_tree.get_child(['quux', 'foo', 'bar'])
self.assertTrue(child.is_tag())
def test_should_be_leaf_node(self):
child = self.reference_tree.get_child(['quux', 'foo', 'bar', 'baz'])
self.assertTrue(child.is_leaf())
# Try loading an invalid definition
def test_invalid_interface_definition(self):
with testtools.ExpectedException(reftree.ReferenceTreeLoaderError):
self.get_loader(
'interface_definition_invalid.xml',
{"mock": MockType},
'schemas/interface_definition.rng')
def test_duplicate_node(self):
with testtools.ExpectedException(reftree.ReferenceTreeLoaderError):
l = self.get_loader(
'interface_definition_duplicate.xml',
{"mock": MockType},
'schemas/interface_definition.rng')
t = reftree.ReferenceNode("root")
l.load(t)
l.load(t)<|fim▁end|> | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA
import testtools |
<|file_name|>MessageReadedListener.java<|end_file_name|><|fim▁begin|>package org.erc.qmm.mq;
import java.util.EventListener;
/**
* The listener interface for receiving messageReaded events.
* The class that is interested in processing a messageReaded
* event implements this interface, and the object created
* with that class is registered with a component using the
* component's <code>addMessageReadedListener<code> method. When
* the messageReaded event occurs, that object's appropriate
* method is invoked.<|fim▁hole|> */
public interface MessageReadedListener extends EventListener {
/**
* Message readed.
*
* @param message the message
*/
void messageReaded(JMQMessage message);
}<|fim▁end|> | *
* @see MessageReadedEvent |
<|file_name|>arguments.ts<|end_file_name|><|fim▁begin|>function f() {<|fim▁hole|> var x=arguments[12];
}<|fim▁end|> | |
<|file_name|>tags.go<|end_file_name|><|fim▁begin|>/*
Copyright 2016 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 awstasks
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
)
func mapEC2TagsToMap(tags []*ec2.Tag) map[string]string {
if tags == nil {
return nil
}
m := make(map[string]string)
for _, t := range tags {
m[aws.StringValue(t.Key)] = aws.StringValue(t.Value)
}
return m
}
func findNameTag(tags []*ec2.Tag) *string {
for _, tag := range tags {
if aws.StringValue(tag.Key) == "Name" {
return tag.Value
}
}
return nil
}
// intersectTags returns the tags of interest from a specified list of AWS tags;
// because we only add tags, this set of tags of interest is the tags that occur in the desired seet.
func intersectTags(tags []*ec2.Tag, desired map[string]string) map[string]string {
if tags == nil {
return nil
}<|fim▁hole|> actual := make(map[string]string)
for _, t := range tags {
k := aws.StringValue(t.Key)
v := aws.StringValue(t.Value)
if _, found := desired[k]; found {
actual[k] = v
}
}
if len(actual) == 0 && desired == nil {
// Avoid problems with comparison between nil & {}
return nil
}
return actual
}<|fim▁end|> | |
<|file_name|>optimize.js<|end_file_name|><|fim▁begin|>/**
* @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details
*/
/*jslint sloppy: true, plusplus: true */
/*global define, java, Packages, com */
define(['logger', 'env!env/file'], function (logger, file) {
//Add .reduce to Rhino so UglifyJS can run in Rhino,
//inspired by https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce
//but rewritten for brevity, and to be good enough for use by UglifyJS.
if (!Array.prototype.reduce) {
Array.prototype.reduce = function (fn /*, initialValue */) {
var i = 0,
length = this.length,
accumulator;
if (arguments.length >= 2) {
accumulator = arguments[1];
} else {
if (length) {
while (!(i in this)) {
i++;
}
accumulator = this[i++];
}
}
for (; i < length; i++) {
if (i in this) {
accumulator = fn.call(undefined, accumulator, this[i], i, this);
}
}
return accumulator;
};
}
var JSSourceFilefromCode, optimize,
mapRegExp = /"file":"[^"]+"/;
//Bind to Closure compiler, but if it is not available, do not sweat it.
try {
JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.JSSourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]);
} catch (e) {}
//Helper for closure compiler, because of weird Java-JavaScript interactions.
function closurefromCode(filename, content) {
return JSSourceFilefromCode.invoke(null, [filename, content]);
}
function getFileWriter(fileName, encoding) {
var outFile = new java.io.File(fileName), outWriter, parentDir;
parentDir = outFile.getAbsoluteFile().getParentFile();
if (!parentDir.exists()) {
if (!parentDir.mkdirs()) {
throw "Could not create directory: " + parentDir.getAbsolutePath();
}
}
if (encoding) {
outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
} else {
outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
}
return new java.io.BufferedWriter(outWriter);
}
optimize = {
closure: function (fileName, fileContents, outFileName, keepLines, config) {
config = config || {};
var result, mappings, optimized, compressed, baseName, writer,
outBaseName, outFileNameMap, outFileNameMapContent,
srcOutFileName, concatNameMap,
jscomp = Packages.com.google.javascript.jscomp,
flags = Packages.com.google.common.flags,
//Set up source input
jsSourceFile = closurefromCode(String(fileName), String(fileContents)),
sourceListArray = new java.util.ArrayList(),
options, option, FLAG_compilation_level, compiler,
Compiler = Packages.com.google.javascript.jscomp.Compiler,
CommandLineRunner = Packages.com.google.javascript.jscomp.CommandLineRunner;
logger.trace("Minifying file: " + fileName);
baseName = (new java.io.File(fileName)).getName();
//Set up options
options = new jscomp.CompilerOptions();
for (option in config.CompilerOptions) {
// options are false by default and jslint wanted an if statement in this for loop
if (config.CompilerOptions[option]) {
options[option] = config.CompilerOptions[option];
}
}
options.prettyPrint = keepLines || options.prettyPrint;
FLAG_compilation_level = jscomp.CompilationLevel[config.CompilationLevel || 'SIMPLE_OPTIMIZATIONS'];
FLAG_compilation_level.setOptionsForCompilationLevel(options);
if (config.generateSourceMaps) {
mappings = new java.util.ArrayList();
mappings.add(new com.google.javascript.jscomp.SourceMap.LocationMapping(fileName, baseName + ".src.js"));
options.setSourceMapLocationMappings(mappings);
options.setSourceMapOutputPath(fileName + ".map");
}
//Trigger the compiler
Compiler.setLoggingLevel(Packages.java.util.logging.Level[config.loggingLevel || 'WARNING']);
compiler = new Compiler();
//fill the sourceArrrayList; we need the ArrayList because the only overload of compile
<|fim▁hole|>
result = compiler.compile(CommandLineRunner.getDefaultExterns(), sourceListArray, options);
if (result.success) {
optimized = String(compiler.toSource());
if (config.generateSourceMaps && result.sourceMap && outFileName) {
outBaseName = (new java.io.File(outFileName)).getName();
srcOutFileName = outFileName + ".src.js";
outFileNameMap = outFileName + ".map";
//If previous .map file exists, move it to the ".src.js"
//location. Need to update the sourceMappingURL part in the
//src.js file too.
if (file.exists(outFileNameMap)) {
concatNameMap = outFileNameMap.replace(/\.map$/, '.src.js.map');
file.saveFile(concatNameMap, file.readFile(outFileNameMap));
file.saveFile(srcOutFileName,
fileContents.replace(/\/\# sourceMappingURL=(.+).map/,
'/# sourceMappingURL=$1.src.js.map'));
} else {
file.saveUtf8File(srcOutFileName, fileContents);
}
writer = getFileWriter(outFileNameMap, "utf-8");
result.sourceMap.appendTo(writer, outFileName);
writer.close();
//Not sure how better to do this, but right now the .map file
//leaks the full OS path in the "file" property. Manually
//modify it to not do that.
file.saveFile(outFileNameMap,
file.readFile(outFileNameMap).replace(mapRegExp, '"file":"' + baseName + '"'));
fileContents = optimized + "\n//# sourceMappingURL=" + outBaseName + ".map";
} else {
fileContents = optimized;
}
return fileContents;
} else {
throw new Error('Cannot closure compile file: ' + fileName + '. Skipping it.');
}
return fileContents;
}
};
return optimize;
});<|fim▁end|> | //accepting the getDefaultExterns return value (a List) also wants the sources as a List
sourceListArray.add(jsSourceFile);
|
<|file_name|>DeleteLoadJobFilesServletHandlerTest.java<|end_file_name|><|fim▁begin|>package com.risevision.gcslogs.delete;
import com.risevision.gcslogs.auth.MockCredentialProvider;
import java.util.logging.Logger;
import java.util.Map;
import java.util.HashMap;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import static com.risevision.gcslogs.BuildConfig.*;
public class DeleteLoadJobFilesServletHandlerTest {
Map<String, String[]> params;
DeleteLoadJobFilesServletHandler deleter;
@Before public void setUp() {
params = new HashMap<String, String[]>();
params.put("jobId", new String[]{"testId"});
deleter =
new DeleteLoadJobFilesServletHandler(params, new MockCredentialProvider());
}
@Test public void itExists() {
assertThat("it exists", deleter, isA(DeleteLoadJobFilesServletHandler.class));
}
@Test public void itGetsTheJobId() {
assertThat("the id exists", deleter.jobId, is(not(nullValue())));
}
<|fim▁hole|> is("folder/name"));
}
@Test public void itExtractsBucketNamesFromUris() {
String uri = "gs://" + LOGS_BUCKET_NAME.toString() + "/folder/name";
assertThat("the bucket is correct", deleter.extractBucketName(uri),
is(LOGS_BUCKET_NAME.toString()));
}
}<|fim▁end|> | @Test public void itExtractsObjectNamesFromUris() {
String uri = "gs://" + LOGS_BUCKET_NAME.toString() + "/folder/name";
assertThat("the name is correct", deleter.extractObjectName(uri), |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'DESCRIPTION.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='jestocke-mangopaysdk',
version='3.0.6',
description='A client library written in python to work with mangopay v2 api',
long_description='This SDK is a client library for interacting with the Mangopay API.',
url='https://github.com/Mangopay/mangopay2-python-sdk',
author='Mangopay (www.mangopay.com)',
author_email='[email protected]',
license='MIT',
classifiers=[
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
],
keywords='mangopay api development emoney sdk',
packages=find_packages(exclude=['contrib', 'docs', 'tests*']),
install_requires=['requests', 'simplejson', 'blinker', 'six' ],
extras_require={
'dev': ['responses', 'nose', 'coverage', 'httplib2',
'pyopenssl', 'ndg-httpsclient', 'pyasn1', 'exam'],
'test': ['responses', 'nose', 'coverage', 'httplib2',
'pyopenssl', 'ndg-httpsclient', 'pyasn1', 'exam'],
},<|fim▁hole|> 'sample=sample:main',
],
},
)<|fim▁end|> | entry_points={
'console_scripts': [ |
<|file_name|>sequenced_executor.cpp<|end_file_name|><|fim▁begin|>#include <iostream>
#include <type_traits>
#include <vector>
#include <cassert><|fim▁hole|>#include <agency/execution/executor/executor_traits.hpp>
int main()
{
using namespace agency;
static_assert(is_bulk_synchronous_executor<sequenced_executor>::value,
"sequenced_executor should be a bulk synchronous executor");
static_assert(is_bulk_executor<sequenced_executor>::value,
"sequenced_executor should be a bulk executor");
static_assert(detail::is_detected_exact<sequenced_execution_tag, executor_execution_category_t, sequenced_executor>::value,
"sequenced_executor should have sequenced_execution_tag execution_category");
static_assert(detail::is_detected_exact<size_t, executor_shape_t, sequenced_executor>::value,
"sequenced_executor should have size_t shape_type");
static_assert(detail::is_detected_exact<size_t, executor_index_t, sequenced_executor>::value,
"sequenced_executor should have size_t index_type");
static_assert(detail::is_detected_exact<std::future<int>, executor_future_t, sequenced_executor, int>::value,
"sequenced_executor should have std::future furture");
static_assert(executor_execution_depth<sequenced_executor>::value == 1,
"sequenced_executor should have execution_depth == 1");
sequenced_executor exec;
size_t shape = 10;
auto result = exec.bulk_sync_execute(
[](size_t idx, std::vector<int>& results, std::vector<int>& shared_arg)
{
results[idx] = shared_arg[idx];
},
shape,
[=]{ return std::vector<int>(shape); }, // results
[=]{ return std::vector<int>(shape, 13); } // shared_arg
);
assert(std::vector<int>(10, 13) == result);
std::cout << "OK" << std::endl;
return 0;
}<|fim▁end|> |
#include <agency/execution/executor/sequenced_executor.hpp> |
<|file_name|>CorefSetToSem.java<|end_file_name|><|fim▁begin|>package eu.newsreader.eventcoreference.output;
import eu.newsreader.eventcoreference.input.CorefSaxParser;
import eu.newsreader.eventcoreference.objects.CoRefSetAgata;
import eu.newsreader.eventcoreference.objects.CorefTargetAgata;
import eu.newsreader.eventcoreference.objects.Triple;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
* User: kyoto
* Date: 10/11/13
* Time: 11:17 AM
* To change this template use File | Settings | File Templates.
*/
public class CorefSetToSem {
static public void main (String[] args) {
boolean STOP = false;
int sentenceRange = 0;
String eventFilePath = "/Users/kyoto/Desktop/Events/ECB/ECBcorpus_StanfordAnnotation/EECB1.0/results-1/lemma-cross-document-in-topic/" +
"eecb-events-kyoto-first-n-v-token-3.xml.sim.word-baseline.0.coref.xml";
String participantFilePath = "/Users/kyoto/Desktop/Events/ECB/ECBcorpus_StanfordAnnotation/EECB1.0/results-1/lemma-cross-document-in-topic/" +
"participants-30-july-2013.xml.sim.word-baseline.0.coref.xml";
String locationFilePath = "/Users/kyoto/Desktop/Events/ECB/ECBcorpus_StanfordAnnotation/EECB1.0/results-1/lemma-cross-document-in-topic/" +
"Location-26-jul-2013.xml.sim.word-baseline.0.coref.xml";
String timeFilePath = "/Users/kyoto/Desktop/Events/ECB/ECBcorpus_StanfordAnnotation/EECB1.0/results-1/lemma-cross-document-in-topic/" +
"Time-26-jul-2013.xml.sim.word-baseline.0.coref.xml";
String componentId = ".";
String outputlabel = "test";
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.equals("--event") && (args.length>i)) {
eventFilePath = args[i+1];
componentId+="e";
}
else if (arg.equals("--range") && (args.length>i)) {
try {
sentenceRange = Integer.parseInt(args[i+1]);
} catch (NumberFormatException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
else if (arg.equals("--participant") && (args.length>i)) {
participantFilePath = args[i+1];
componentId+="p";
}
else if (arg.equals("--time") && (args.length>i)) {
timeFilePath = args[i+1];
componentId+="t";
}
else if (arg.equals("--location") && (args.length>i)) {
locationFilePath = args[i+1];
componentId+="l";
}
else if (arg.equals("--label") && (args.length>i)) {
outputlabel = args[i+1];
}
}
if (eventFilePath.isEmpty()) {
System.out.println("Missing argument --event <path to coreference events file");
STOP = true;
}<|fim▁hole|> if (timeFilePath.isEmpty()) {
System.out.println("Missing argument --time <path to coreference time file");
}
if (locationFilePath.isEmpty()) {
System.out.println("Missing argument --location <path to coreference location file");
}
if (!STOP) {
try {
// String outputFilePath = eventFilePath+componentId+".sentenceRange."+sentenceRange+"."+outputlabel+"-semevent.xml";
String outputFilePath = new File(eventFilePath).getParent()+"/"+outputlabel+".sentenceRange."+sentenceRange+"."+"semevent.xml";
FileOutputStream fos = new FileOutputStream(outputFilePath);
String str ="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n";
str += "<SEM>"+"\n";
fos.write(str.getBytes());
// we read the events and their components using a coreference parser
// the parser builds up a HashMap with file identifiers as keys and arraylists with elements as data within that file
CorefSaxParser events = new CorefSaxParser();
events.parseFile(eventFilePath);
CorefSaxParser participants = new CorefSaxParser();
if (new File(participantFilePath).exists()) {
participants.parseFile(participantFilePath);
}
CorefSaxParser times = new CorefSaxParser();
if (new File(timeFilePath).exists()) {
times.parseFile(timeFilePath);
}
CorefSaxParser locations = new CorefSaxParser();
if (new File(locationFilePath).exists()) {
locations.parseFile(locationFilePath);
}
/// we first iterate over the map with file identifiers and the event coref maps
Set keySet = events.corefMap.keySet();
Iterator keys = keySet.iterator();
while (keys.hasNext()) {
String key = (String) keys.next();
/// keys are file identifiers
// We now get the components for the key (= particular file identifier), so just for one file
ArrayList<CoRefSetAgata> coRefSetsEventAgatas = events.corefMap.get(key);
ArrayList<CoRefSetAgata> participantSets = participants.corefMap.get(key);
ArrayList<CoRefSetAgata> timeSets = times.corefMap.get(key);
ArrayList<CoRefSetAgata> locationSets = locations.corefMap.get(key);
/// we create the initial output string
str = "<topic name=\""+key+"\" eventCount=\""+ coRefSetsEventAgatas.size()+"\"";
str += " participantCount=\"";
if (participantSets!=null) {
str += participantSets.size()+"\"";
}
else {
str += "0\"";
}
str += " timeCount=\"";
if (timeSets!=null) {
str += timeSets.size()+"\"";
}
else {
str += "0\"";
}
str += " locationCount=\"";
if (locationSets!=null) {
str += locationSets.size()+"\"";
}
else {
str += "0\"";
}
str += ">\n";
fos.write(str.getBytes());
if (coRefSetsEventAgatas !=null) {
/// we iterate over the events of a single file
str = "<semEvents>\n";
fos.write(str.getBytes());
for (int i = 0; i < coRefSetsEventAgatas.size(); i++) {
CoRefSetAgata coRefSetAgata = coRefSetsEventAgatas.get(i);
str = "\t<semEvent id=\""+key+"/e"+ coRefSetAgata.getId()+"\" lcs=\""+ coRefSetAgata.getLcs()+"\" score=\""+ coRefSetAgata.getScore()+"\" synset=\""+ coRefSetAgata.getMostFrequentSynset()+"\" label=\""+ coRefSetAgata.getMostFrequentLemma()+"\" mentions=\""+ coRefSetAgata.getTargets().size()+"\">\n";
fos.write(str.getBytes());
for (int j = 0; j < coRefSetAgata.getTargets().size(); j++) {
CorefTargetAgata eventTarget = coRefSetAgata.getTargets().get(j);
str = "\t"+eventTarget.toString();
fos.write(str.getBytes());
}
str = "\t</semEvent>\n";
fos.write(str.getBytes());
}
str = "</semEvents>\n";
fos.write(str.getBytes());
}
if (participantSets!=null) {
/// we iterate over the participants of a single file
str = "<semAgents>\n";
fos.write(str.getBytes());
for (int i = 0; i < participantSets.size(); i++) {
CoRefSetAgata coRefSetAgata = participantSets.get(i);
str = "\t<semAgent id=\""+key+"/a"+ coRefSetAgata.getId()+"\" lcs=\""+ coRefSetAgata.getLcs()+"\" score=\""+ coRefSetAgata.getScore()+"\" synset=\""+ coRefSetAgata.getMostFrequentSynset()+"\" label=\""+ coRefSetAgata.getMostFrequentLemma()+"\" mentions=\""+ coRefSetAgata.getTargets().size()+"\">\n";
fos.write(str.getBytes());
for (int j = 0; j < coRefSetAgata.getTargets().size(); j++) {
CorefTargetAgata eventTarget = coRefSetAgata.getTargets().get(j);
str = "\t"+eventTarget.toString();
fos.write(str.getBytes());
}
str = "\t</semAgent>\n";
fos.write(str.getBytes());
}
str = "</semAgents>\n";
fos.write(str.getBytes());
}
if (locationSets!=null) {
/// we iterate over the locations of a single file
str = "<semPlaces>\n";
fos.write(str.getBytes());
for (int i = 0; i < locationSets.size(); i++) {
CoRefSetAgata coRefSetAgata = locationSets.get(i);
str = "\t<semPlace id=\""+key+"/p"+ coRefSetAgata.getId()+"\" lcs=\""+ coRefSetAgata.getLcs()+"\" score=\""+ coRefSetAgata.getScore()+"\" synset=\""+ coRefSetAgata.getMostFrequentSynset()+"\" label=\""+ coRefSetAgata.getMostFrequentLemma()+"\" mentions=\""+ coRefSetAgata.getTargets().size()+"\">\n";
fos.write(str.getBytes());
for (int j = 0; j < coRefSetAgata.getTargets().size(); j++) {
CorefTargetAgata eventTarget = coRefSetAgata.getTargets().get(j);
str = "\t"+eventTarget.toString();
fos.write(str.getBytes());
}
str = "\t</semPlace>\n";
fos.write(str.getBytes());
}
str = "</semPlaces>\n";
fos.write(str.getBytes());
}
if (timeSets!=null) {
/// we iterate over the time of a single file
str = "<semTimes>\n";
fos.write(str.getBytes());
for (int i = 0; i < timeSets.size(); i++) {
CoRefSetAgata coRefSetAgata = timeSets.get(i);
str = " <semTime id=\""+key+"/t"+ coRefSetAgata.getId()+"\" lcs=\""+ coRefSetAgata.getLcs()+"\" score=\""+ coRefSetAgata.getScore()+"\" synset=\""+ coRefSetAgata.getMostFrequentSynset()+"\" label=\""+ coRefSetAgata.getMostFrequentLemma()+"\" mentions=\""+ coRefSetAgata.getTargets().size()+"\">\n";
fos.write(str.getBytes());
for (int j = 0; j < coRefSetAgata.getTargets().size(); j++) {
CorefTargetAgata eventTarget = coRefSetAgata.getTargets().get(j);
str = "\t"+eventTarget.toString();
fos.write(str.getBytes());
}
str = "\t</semTime>\n";
fos.write(str.getBytes());
}
str = "</semTimes>\n";
fos.write(str.getBytes());
}
/// now we get the relations
getRelations(fos, events.fileName, coRefSetsEventAgatas, participantSets, timeSets, locationSets, sentenceRange, key);
str = "</topic>\n";
fos.write(str.getBytes());
}
str = "</SEM>\n";
fos.write(str.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
/**
* <semEvents>
<semEvent id="eecb1.0/456>
<target id="corpus/filename_url/t115"/>
</semEvent>
</semEvents>
<semAgents>
<semAgent id="eecb1.0/2">
<target id="corpus/filename_url/t111"/>
</semAgent>
</semAgents>
<semTimes>
<semTime id="eecb1.0/1"/>
</semTimes>
<semPlaces>
<semPlace id="eecb1.0/6"/>
</semPlaces>
<semRelations>
<semRelation id = "eecb1.0/75698" predicate="semHasAgent" subject="eecb1.0/456" object="eecb1.0/2>
<target id="corpus/filename_url/pr23r3"/>
</semRelation>
<semRelation id = "eecb1.0/75698" predicate="semHasTime" subject="eecb1.0/456" object="eecb1.0/2/>
<semRelation id = "eecb1.0/75698" predicate="semHasPlace" subject="eecb1.0/456" object="eecb1.0/2/>
</semRelations>
*/
static void getRelations (FileOutputStream fos, String fileName,
ArrayList<CoRefSetAgata> coRefSetsEventAgatas,
ArrayList<CoRefSetAgata> participantSets,
ArrayList<CoRefSetAgata> timeSets,
ArrayList<CoRefSetAgata> locationSets,
int sentenceRange,
String key
) throws IOException {
String str = "<semRelations>\n";
fos.write(str.getBytes());
int relationCounter = 0;
/// we iterate over the events of a single file
ArrayList<Triple> triplesA = new ArrayList<Triple>();
ArrayList<Triple> triplesP = new ArrayList<Triple>();
ArrayList<Triple> triplesT = new ArrayList<Triple>();
for (int i = 0; i < coRefSetsEventAgatas.size(); i++) {
CoRefSetAgata coRefSetAgata = coRefSetsEventAgatas.get(i);
for (int j = 0; j < coRefSetAgata.getTargets().size(); j++) {
CorefTargetAgata eventTarget = coRefSetAgata.getTargets().get(j);
/// we obtain the sentence ids for the targets of the coreference set of the events
/// this sentence range determines which components belong to the event.
/// by passing in the sentenceRange parameter you can indicate the number of sentences before and after that are also valid contexts
//// if zero the context is restricted to the same sentence
ArrayList<String> rangeOfSentenceIds = getSentenceRange(eventTarget.getSentenceId(), sentenceRange);
if (participantSets!=null) {
// System.out.println("PARTICIPANTS");
for (int s = 0; s < participantSets.size(); s++) {
CoRefSetAgata refSet = participantSets.get(s);
//// loop to add results for range of sentences
for (int k = 0; k < rangeOfSentenceIds.size(); k++) {
String sentenceId = rangeOfSentenceIds.get(k);
if (refSet.containsTargetSentenceId(sentenceId)) {
for (int l = 0; l < refSet.getTargets().size(); l++) {
CorefTargetAgata corefTargetAgata = refSet.getTargets().get(l);
if (eventTarget.getDocId().equals(corefTargetAgata.getDocId())) {
String predicate = "semHasAgent";
String subject = key+"/e"+ coRefSetAgata.getId();
String object = key+"/a"+ refSet.getId();
Triple triple = new Triple(predicate, subject, object);
String target = "\t\t<target id =\""+ eventTarget.getDocId()+"/"+eventTarget.getSentenceId()+"\""+"/>";
target += " <!-- "+eventTarget.getWord()+"--"+predicate+"--"+ corefTargetAgata.getWord()+" -->";
int givenTriple = getTriple(triplesA, triple);
if (givenTriple==-1) {
relationCounter++;
String id = key+"/"+relationCounter;
triple.setId(id);
triple.addMentions(target);
triplesA.add(triple);
}
else {
if (!triplesA.get(givenTriple).getMentions().contains(target)) {
triplesA.get(givenTriple).addMentions(target);
}
}
}
else {
// System.out.println("corefTarget.getDocId() = " + corefTarget.getDocId());
// System.out.println("eventTarget.getDocId() = " + eventTarget.getDocId());
}
}
}
}
}
}
if (timeSets!=null) {
// System.out.println("TIME");
for (int s = 0; s < timeSets.size(); s++) {
CoRefSetAgata refSet = timeSets.get(s);
//// loop to add results for range of sentences
for (int k = 0; k < rangeOfSentenceIds.size(); k++) {
String sentenceId = rangeOfSentenceIds.get(k);
if (refSet.containsTargetSentenceId(sentenceId)) {
for (int l = 0; l < refSet.getTargets().size(); l++) {
CorefTargetAgata corefTargetAgata = refSet.getTargets().get(l);
if (eventTarget.getDocId().equals(corefTargetAgata.getDocId())) {
String predicate = "semHasTime";
String subject = key+"/e"+ coRefSetAgata.getId();
String object = key+"/t"+ refSet.getId();
Triple triple = new Triple(predicate, subject, object);
String target = "\t\t<target id =\""+ eventTarget.getDocId()+"/"+eventTarget.getSentenceId()+"\""+"/>";
target += " <!-- "+eventTarget.getWord()+"--"+predicate+"--"+ corefTargetAgata.getWord()+" -->";
int givenTriple = getTriple(triplesA, triple);
if (givenTriple==-1) {
relationCounter++;
String id = key+"/"+relationCounter;
triple.setId(id);
triple.addMentions(target);
triplesA.add(triple);
}
else {
if (!triplesA.get(givenTriple).getMentions().contains(target)) {
triplesA.get(givenTriple).addMentions(target);
}
}
}
else {
// System.out.println("corefTarget.getDocId() = " + corefTarget.getDocId());
// System.out.println("eventTarget.getDocId() = " + eventTarget.getDocId());
}
}
}
}
}
}
if (locationSets!=null) {
// System.out.println("PLACES");
for (int s = 0; s < locationSets.size(); s++) {
CoRefSetAgata refSet = locationSets.get(s);
//// loop to add results for range of sentences
for (int k = 0; k < rangeOfSentenceIds.size(); k++) {
String sentenceId = rangeOfSentenceIds.get(k);
if (refSet.containsTargetSentenceId(sentenceId)) {
for (int l = 0; l < refSet.getTargets().size(); l++) {
CorefTargetAgata corefTargetAgata = refSet.getTargets().get(l);
if (eventTarget.getDocId().equals(corefTargetAgata.getDocId())) {
String predicate = "semHasPlace";
String subject = key+"/e"+ coRefSetAgata.getId();
String object = key+"/p"+ refSet.getId();
Triple triple = new Triple(predicate, subject, object);
String target = "\t\t<target id =\""+ eventTarget.getDocId()+"/"+eventTarget.getSentenceId()+"\""+"/>";
target += " <!-- "+eventTarget.getWord()+"--"+predicate+"--"+ corefTargetAgata.getWord()+" -->";
int givenTriple = getTriple(triplesA, triple);
if (givenTriple==-1) {
relationCounter++;
String id = key+"/"+relationCounter;
triple.setId(id);
triple.addMentions(target);
triplesA.add(triple);
}
else {
if (!triplesA.get(givenTriple).getMentions().contains(target)) {
triplesA.get(givenTriple).addMentions(target);
}
}
}
else {
// System.out.println("corefTarget.getDocId() = " + corefTarget.getDocId());
// System.out.println("eventTarget.getDocId() = " + eventTarget.getDocId());
}
}
}
}
}
}
}
}
for (int k = 0; k < triplesA.size(); k++) {
Triple triple = triplesA.get(k);
str = triple.toString();
fos.write(str.getBytes());
}
for (int k = 0; k < triplesP.size(); k++) {
Triple triple = triplesP.get(k);
str = triple.toString();
fos.write(str.getBytes());
}
for (int k = 0; k < triplesT.size(); k++) {
Triple triple = triplesT.get(k);
str = triple.toString();
fos.write(str.getBytes());
}
}
static int getTriple (ArrayList<Triple> triples, Triple triple) {
for (int i = 0; i < triples.size(); i++) {
Triple triple1 = triples.get(i);
/*
System.out.println("triple1.toString() = " + triple1.toString());
System.out.println("triple.toString() = " + triple.toString());
*/
/*
if (triple.getSubject().equals("TOPIC_44_EVENT_COREFERENCE_CORPUS/e35")) {
System.out.println(triple.getObject()+":"+triple1.getObject());
}
*/
if ((triple1.getPredicate().equalsIgnoreCase(triple.getPredicate())) &&
(triple1.getSubject().equalsIgnoreCase(triple.getSubject())) &&
(triple1.getObject().equalsIgnoreCase(triple.getObject()))
) {
return i;
}
}
return -1;
}
/**
*
* @param corefMap
* @param sentenceIdString
* @param sentenceRange
* @return
*/
static ArrayList<CoRefSetAgata> getCorefSetFromRange (HashMap<String, ArrayList<CoRefSetAgata>> corefMap, String sentenceIdString, int sentenceRange) {
ArrayList<CoRefSetAgata> coRefSetAgatas = null;
coRefSetAgatas = corefMap.get(sentenceIdString);
if (sentenceRange>0) {
/// we assume that the sentence id is an integer
Integer sentenceId = Integer.parseInt(sentenceIdString);
if (sentenceId!=null) {
for (int i = sentenceId; i < sentenceRange; i++) {
ArrayList<CoRefSetAgata> nextSet = corefMap.get(sentenceId+i);
if (nextSet!=null) {
for (int j = 0; j < nextSet.size(); j++) {
CoRefSetAgata coRefSetAgata = nextSet.get(j);
coRefSetAgatas.add(coRefSetAgata);
}
}
}
/* for (int i = sentenceId; i < sentenceRange; i++) {
ArrayList<CoRefSet> nextSet = corefMap.get(sentenceId-i);
if (nextSet!=null) {
for (int j = 0; j < nextSet.size(); j++) {
CoRefSet coRefSet = nextSet.get(j);
coRefSets.add(coRefSet);
}
}
}*/
}
}
return coRefSetAgatas;
}
static ArrayList<String> getSentenceRange (String sentenceIdString, int sentenceRange) {
ArrayList<String> sentenceIdRange = new ArrayList<String>();
sentenceIdRange.add(sentenceIdString);
if (sentenceRange>0) {
/// we assume that the sentence id is an integer
Integer sentenceId = null;
try {
sentenceId = Integer.parseInt(sentenceIdString);
} catch (NumberFormatException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if (sentenceId!=null) {
for (int i = sentenceId; i < sentenceRange; i++) {
sentenceIdRange.add(new Integer(i).toString());
}
for (int i = sentenceId; i < sentenceRange; i++) {
sentenceIdRange.add(new Integer(i).toString());
}
}
}
return sentenceIdRange;
}
}<|fim▁end|> | if (participantFilePath.isEmpty()) {
System.out.println("Missing argument --participant <path to coreference participants file");
} |
<|file_name|>NiciraTunGpeNpTest.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2016-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<|fim▁hole|>package org.onosproject.driver.extensions;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import org.junit.Test;
import com.google.common.testing.EqualsTester;
/**
* Unit tests for NiciraTunGpeNp class.
*/
public class NiciraTunGpeNpTest {
final byte np1 = (byte) 1;
final byte np2 = (byte) 2;
/**
* Checks the operation of equals() methods.
*/
@Test
public void testEquals() {
final NiciraTunGpeNp tunGpeNp1 = new NiciraTunGpeNp(np1);
final NiciraTunGpeNp sameAsTunGpeNp1 = new NiciraTunGpeNp(np1);
final NiciraTunGpeNp tunGpeNp2 = new NiciraTunGpeNp(np2);
new EqualsTester().addEqualityGroup(tunGpeNp1, sameAsTunGpeNp1).addEqualityGroup(tunGpeNp2)
.testEquals();
}
/**
* Checks the construction of a NiciraTunGpeNp object.
*/
@Test
public void testConstruction() {
final NiciraTunGpeNp tunGpeNp1 = new NiciraTunGpeNp(np1);
assertThat(tunGpeNp1, is(notNullValue()));
assertThat(tunGpeNp1.tunGpeNp(), is(np1));
}
}<|fim▁end|> | * See the License for the specific language governing permissions and
* limitations under the License.
*/ |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>export { default } from './ui'<|fim▁hole|><|fim▁end|> | export * from './ui.selectors'
export * from './tabs' |
<|file_name|>build.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
from frappe.utils.minify import JavascriptMinify
"""
Build the `public` folders and setup languages
"""
import os, frappe, json, shutil, re
# from cssmin import cssmin
app_paths = None
def setup():
global app_paths
pymodules = []
for app in frappe.get_all_apps(True):
try:
pymodules.append(frappe.get_module(app))
except ImportError: pass
app_paths = [os.path.dirname(pymodule.__file__) for pymodule in pymodules]
def bundle(no_compress, make_copy=False, verbose=False):
"""concat / minify js files"""
# build js files
setup()
make_asset_dirs(make_copy=make_copy)
build(no_compress, verbose)
def watch(no_compress):
"""watch and rebuild if necessary"""
setup()
import time
compile_less()
build(no_compress=True)
while True:
compile_less()
if files_dirty():
build(no_compress=True)
time.sleep(3)
def make_asset_dirs(make_copy=False):
assets_path = os.path.join(frappe.local.sites_path, "assets")
for dir_path in [
os.path.join(assets_path, 'js'),
os.path.join(assets_path, 'css')]:
if not os.path.exists(dir_path):
os.makedirs(dir_path)
# symlink app/public > assets/app
for app_name in frappe.get_all_apps(True):
pymodule = frappe.get_module(app_name)
app_base_path = os.path.abspath(os.path.dirname(pymodule.__file__))
symlinks = []
symlinks.append([os.path.join(app_base_path, 'public'), os.path.join(assets_path, app_name)])
symlinks.append([os.path.join(app_base_path, 'docs'), os.path.join(assets_path, app_name + '_docs')])
for source, target in symlinks:
source = os.path.abspath(source)
if not os.path.exists(target) and os.path.exists(source):
if make_copy:
shutil.copytree(source, target)
else:
os.symlink(source, target)
def build(no_compress=False, verbose=False):
assets_path = os.path.join(frappe.local.sites_path, "assets")
for target, sources in get_build_maps().iteritems():
pack(os.path.join(assets_path, target), sources, no_compress, verbose)
def get_build_maps():
"""get all build.jsons with absolute paths"""
# framework js and css files
build_maps = {}
for app_path in app_paths:
path = os.path.join(app_path, 'public', 'build.json')
if os.path.exists(path):
with open(path) as f:
try:
for target, sources in json.loads(f.read()).iteritems():
# update app path
source_paths = []
for source in sources:
if isinstance(source, list):
s = frappe.get_pymodule_path(source[0], *source[1].split("/"))
else:
s = os.path.join(app_path, source)
source_paths.append(s)
build_maps[target] = source_paths
except ValueError, e:
print path
print 'JSON syntax error {0}'.format(str(e))
return build_maps
timestamps = {}
def pack(target, sources, no_compress, verbose):
from cStringIO import StringIO
outtype, outtxt = target.split(".")[-1], ''
jsm = JavascriptMinify()
for f in sources:
suffix = None
if ':' in f: f, suffix = f.split(':')
if not os.path.exists(f) or os.path.isdir(f):
print "did not find " + f
continue
timestamps[f] = os.path.getmtime(f)
try:
with open(f, 'r') as sourcefile:
data = unicode(sourcefile.read(), 'utf-8', errors='ignore')
extn = f.rsplit(".", 1)[1]
if outtype=="js" and extn=="js" and (not no_compress) and suffix!="concat" and (".min." not in f):
tmpin, tmpout = StringIO(data.encode('utf-8')), StringIO()
jsm.minify(tmpin, tmpout)
minified = tmpout.getvalue()
if minified:
outtxt += unicode(minified or '', 'utf-8').strip('\n') + ';'
if verbose:
print "{0}: {1}k".format(f, int(len(minified) / 1024))
elif outtype=="js" and extn=="html":
# add to frappe.templates
outtxt += html_to_js_template(f, data)
else:
outtxt += ('\n/*\n *\t%s\n */' % f)
outtxt += '\n' + data + '\n'
except Exception:
print "--Error in:" + f + "--"
print frappe.get_traceback()
if not no_compress and outtype == 'css':
pass
#outtxt = cssmin(outtxt)
with open(target, 'w') as f:
f.write(outtxt.encode("utf-8"))
print "Wrote %s - %sk" % (target, str(int(os.path.getsize(target)/1024)))
def html_to_js_template(path, content):
'''returns HTML template content as Javascript code, adding it to `frappe.templates`'''
return """frappe.templates["{key}"] = '{content}';\n""".format(\
key=path.rsplit("/", 1)[-1][:-5], content=scrub_html_template(content))
def scrub_html_template(content):
'''Returns HTML content with removed whitespace and comments'''
# remove whitespace to a single space
content = re.sub("\s+", " ", content)
# strip comments
content = re.sub("(<!--.*?-->)", "", content)
return content.replace("'", "\'")
def files_dirty():
for target, sources in get_build_maps().iteritems():
for f in sources:
if ':' in f: f, suffix = f.split(':')
if not os.path.exists(f) or os.path.isdir(f): continue
if os.path.getmtime(f) != timestamps.get(f):
print f + ' dirty'
return True
else:
return False
def compile_less():
from distutils.spawn import find_executable
if not find_executable("lessc"):
return
for path in app_paths:
less_path = os.path.join(path, "public", "less")
if os.path.exists(less_path):
for fname in os.listdir(less_path):
if fname.endswith(".less") and fname != "variables.less":
fpath = os.path.join(less_path, fname)
mtime = os.path.getmtime(fpath)<|fim▁hole|> continue
timestamps[fpath] = mtime
print "compiling {0}".format(fpath)
css_path = os.path.join(path, "public", "css", fname.rsplit(".", 1)[0] + ".css")
os.system("lessc {0} > {1}".format(fpath, css_path))<|fim▁end|> | if fpath in timestamps and mtime == timestamps[fpath]: |
<|file_name|>calendar-detail-ctrl.js<|end_file_name|><|fim▁begin|>/// <reference path="../../services/office365/scripts/utility.js" />
/// <reference path="../../services/office365/scripts/o365adal.js" /><|fim▁hole|>(function () {
'use strict';
angular.module('app365').controller('calendarDetailCtrl', ['$scope', '$stateParams', '$location', 'app365api', calendarDetailCtrl]);
function calendarDetailCtrl($scope, $stateParams, $location, app365api) {
var vm = this;
// Get event with specified event id.
vm.getEvent = function () {
var outlookClient = app365api.outlookClientObj();
NProgress.start();
outlookClient.me.calendar.events.getEvent($stateParams.id).fetch()
.then(function (event) {
// Get event detail like subject, location, attendees etc.
vm.subject = event.subject;
vm.start = event.start;
vm.end = event.end;
vm.bodypreview = event.bodyPreview;
vm.location = event.location.displayName;
var attendees;
event.attendees.forEach(function (attendee) {
if (typeof attendees == 'undefined') {
attendees = attendee.emailAddress.name
} else {
attendees += "," + attendee.emailAddress.name;
}
});
vm.attendees = attendees;
$scope.$apply();
NProgress.done();
});
};
vm.getEvent();
}
})();<|fim▁end|> | /// <reference path="../../services/office365/scripts/exchange.js" />
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
SMQTK Web Applications
"""
import inspect
import logging
import os
import flask
import smqtk.utils
from smqtk.utils import plugin
class SmqtkWebApp (flask.Flask, smqtk.utils.Configurable, plugin.Pluggable):
"""
Base class for SMQTK web applications
"""
@classmethod
def impl_directory(cls):
"""
:return: Directory in which this implementation is contained.
:rtype: str
"""
return os.path.dirname(os.path.abspath(inspect.getfile(cls)))
@classmethod
def get_default_config(cls):
"""
Generate and return a default configuration dictionary for this class.
This will be primarily used for generating what the configuration
dictionary would look like for this class without instantiating it.
This should be overridden in each implemented application class to add
appropriate configuration.
:return: Default configuration dictionary for the class.
:rtype: dict
"""
return {
"flask_app": {
"SECRET_KEY": "MySuperUltraSecret",
"BASIC_AUTH_USERNAME": "demo",
"BASIC_AUTH_PASSWORD": "demo"
},
"server": {
'host': "127.0.0.1",
'port': 5000
}
}
@classmethod
def from_config(cls, config_dict):
return cls(config_dict)
def __init__(self, json_config):
"""
Initialize application based of supplied JSON configuration
:param json_config: JSON configuration dictionary
:type json_config: dict
"""
super(SmqtkWebApp, self).__init__(
self.__class__.__name__,
static_folder=os.path.join(self.impl_directory(), 'static'),<|fim▁hole|>
#
# Configuration setup
#
self.json_config = json_config
# Factor 'flask_app' configuration properties into self.config
for k in self.json_config['flask_app']:
self.config[k] = self.json_config['flask_app'][k]
#
# Security
#
self.secret_key = self.config['SECRET_KEY']
def get_config(self):
return self.json_config
@property
def log(self):
return logging.getLogger('.'.join((self.__module__,
self.__class__.__name__)))
def run(self, host=None, port=None, debug=False, **options):
"""
Override of the run method, drawing running host and port from
configuration by default. 'host' and 'port' values specified as argument
or keyword will override the app configuration.
"""
super(SmqtkWebApp, self)\
.run(host=(host or self.json_config['server']['host']),
port=(port or self.json_config['server']['port']),
debug=debug,
**options)
def get_web_applications(reload_modules=False):
"""
Discover and return SmqtkWebApp implementation classes found in the plugin
directory. Keys in the returned map are the names of the discovered classes
and the paired values are the actual class type objects.
We look for modules (directories or files) that start with and alphanumeric
character ('_' prefixed files/directories are hidden, but not recommended).
Within a module, we first look for a helper variable by the name
``APPLICATION_CLASS``, which can either be a single class object or
an iterable of class objects, to be exported. If the variable is set to
None, we skip that module and do not import anything. If the variable is not
present, we look for a class by the same na e and casing as the module's
name. If neither are found, the module is skipped.
:param reload_modules: Explicitly reload discovered modules from source.
:type reload_modules: bool
:return: Map of discovered class objects of type ``SmqtkWebApp`` whose
keys are the string names of the classes.
:rtype: dict[str, type]
"""
import os
from smqtk.utils.plugin import get_plugins
this_dir = os.path.abspath(os.path.dirname(__file__))
env_var = "APPLICATION_PATH"
helper_var = "APPLICATION_CLASS"
return get_plugins(__name__, this_dir, env_var, helper_var, SmqtkWebApp,
reload_modules=reload_modules)<|fim▁end|> | template_folder=os.path.join(self.impl_directory(), 'templates')
) |
<|file_name|>htmllegendelement.rs<|end_file_name|><|fim▁begin|>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use crate::dom::bindings::codegen::Bindings::HTMLLegendElementBinding;
use crate::dom::bindings::codegen::Bindings::HTMLLegendElementBinding::HTMLLegendElementMethods;
use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::root::{DomRoot, MutNullableDom};
use crate::dom::document::Document;
use crate::dom::element::Element;
use crate::dom::htmlelement::HTMLElement;
use crate::dom::htmlfieldsetelement::HTMLFieldSetElement;
use crate::dom::htmlformelement::{FormControl, HTMLFormElement};
use crate::dom::node::{Node, UnbindContext};
use crate::dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
#[dom_struct]
pub struct HTMLLegendElement {
htmlelement: HTMLElement,
form_owner: MutNullableDom<HTMLFormElement>,
}
impl HTMLLegendElement {
fn new_inherited(
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> HTMLLegendElement {
HTMLLegendElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
form_owner: Default::default(),
}
}
#[allow(unrooted_must_root)]
pub fn new(
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> DomRoot<HTMLLegendElement> {
Node::reflect_node(
Box::new(HTMLLegendElement::new_inherited(
local_name, prefix, document,
)),
document,
HTMLLegendElementBinding::Wrap,
)
}
}
impl VirtualMethods for HTMLLegendElement {
fn super_type(&self) -> Option<&dyn VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
self.upcast::<Element>()
.check_ancestors_disabled_state_for_form_control();
}
fn unbind_from_tree(&self, context: &UnbindContext) {
self.super_type().unwrap().unbind_from_tree(context);
let node = self.upcast::<Node>();
let el = self.upcast::<Element>();
if node
.ancestors()
.any(|ancestor| ancestor.is::<HTMLFieldSetElement>())
{
el.check_ancestors_disabled_state_for_form_control();
} else {
el.check_disabled_attribute();
}
}
}
impl HTMLLegendElementMethods for HTMLLegendElement {
// https://html.spec.whatwg.org/multipage/#dom-legend-form
fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> {
let parent = self.upcast::<Node>().GetParentElement()?;
if parent.is::<HTMLFieldSetElement>() {
return self.form_owner();
}
None<|fim▁hole|> fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> {
self.form_owner.get()
}
fn set_form_owner(&self, form: Option<&HTMLFormElement>) {
self.form_owner.set(form);
}
fn to_element<'a>(&'a self) -> &'a Element {
self.upcast::<Element>()
}
}<|fim▁end|> | }
}
impl FormControl for HTMLLegendElement { |
<|file_name|>CCastleInterface.cpp<|end_file_name|><|fim▁begin|>/*
* CCastleInterface.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "StdInc.h"
#include "CCastleInterface.h"
#include "CAdvmapInterface.h"
#include "CHeroWindow.h"
#include "CTradeWindow.h"
#include "GUIClasses.h"
#include "../CBitmapHandler.h"
#include "../CGameInfo.h"
#include "../CMessage.h"
#include "../CMusicHandler.h"
#include "../CPlayerInterface.h"
#include "../Graphics.h"
#include "../gui/CGuiHandler.h"
#include "../gui/SDL_Extensions.h"
#include "../windows/InfoWindows.h"
#include "../widgets/MiscWidgets.h"
#include "../widgets/CComponent.h"
#include "../../CCallback.h"
#include "../../lib/CArtHandler.h"
#include "../../lib/CBuildingHandler.h"
#include "../../lib/CCreatureHandler.h"
#include "../../lib/CGeneralTextHandler.h"
#include "../../lib/CModHandler.h"
#include "../../lib/spells/CSpellHandler.h"
#include "../../lib/CTownHandler.h"
#include "../../lib/GameConstants.h"
#include "../../lib/mapObjects/CGHeroInstance.h"
#include "../../lib/mapObjects/CGTownInstance.h"
const CBuilding * CBuildingRect::getBuilding()
{
if (!str->building)
return nullptr;
if (str->hiddenUpgrade) // hidden upgrades, e.g. hordes - return base (dwelling for hordes)
return town->town->buildings.at(str->building->getBase());
return str->building;
}
CBuildingRect::CBuildingRect(CCastleBuildings * Par, const CGTownInstance *Town, const CStructure *Str)
:CShowableAnim(0, 0, Str->defName, CShowableAnim::BASE | CShowableAnim::USE_RLE),
parent(Par),
town(Town),
str(Str),
stateCounter(80)
{
recActions = ACTIVATE | DEACTIVATE | DISPOSE | SHARE_POS;
addUsedEvents(LCLICK | RCLICK | HOVER);
pos.x += str->pos.x;
pos.y += str->pos.y;
if (!str->borderName.empty())
border = BitmapHandler::loadBitmap(str->borderName, true);
else
border = nullptr;
if (!str->areaName.empty())
area = BitmapHandler::loadBitmap(str->areaName);
else
area = nullptr;
}
CBuildingRect::~CBuildingRect()
{
SDL_FreeSurface(border);
SDL_FreeSurface(area);
}
bool CBuildingRect::operator<(const CBuildingRect & p2) const
{
return (str->pos.z) < (p2.str->pos.z);
}
void CBuildingRect::hover(bool on)
{
if(on)
{
if(!(active & MOVE))
addUsedEvents(MOVE);
}
else
{
if(active & MOVE)
removeUsedEvents(MOVE);
if(parent->selectedBuilding == this)
{
parent->selectedBuilding = nullptr;
GH.statusbar->clear();
}
}
}
void CBuildingRect::clickLeft(tribool down, bool previousState)
{
if( previousState && getBuilding() && area && !down && (parent->selectedBuilding==this))
if (!CSDL_Ext::isTransparent(area, GH.current->motion.x-pos.x, GH.current->motion.y-pos.y) ) //inside building image
parent->buildingClicked(getBuilding()->bid);
}
void CBuildingRect::clickRight(tribool down, bool previousState)
{
if((!area) || (!((bool)down)) || (this!=parent->selectedBuilding) || getBuilding() == nullptr)
return;
if( !CSDL_Ext::isTransparent(area, GH.current->motion.x-pos.x, GH.current->motion.y-pos.y) ) //inside building image
{
BuildingID bid = getBuilding()->bid;
const CBuilding *bld = town->town->buildings.at(bid);
if (bid < BuildingID::DWELL_FIRST)
{
CRClickPopup::createAndPush(CInfoWindow::genText(bld->Name(), bld->Description()),
new CComponent(CComponent::building, bld->town->faction->index, bld->bid));
}
else
{
int level = ( bid - BuildingID::DWELL_FIRST ) % GameConstants::CREATURES_PER_TOWN;
GH.pushInt(new CDwellingInfoBox(parent->pos.x+parent->pos.w/2, parent->pos.y+parent->pos.h/2, town, level));
}
}
}
SDL_Color multiplyColors (const SDL_Color &b, const SDL_Color &a, double f)
{
SDL_Color ret;
ret.r = a.r*f + b.r*(1-f);
ret.g = a.g*f + b.g*(1-f);
ret.b = a.b*f + b.b*(1-f);
ret.a = a.a*f + b.b*(1-f);
return ret;
}
void CBuildingRect::show(SDL_Surface * to)
{
const ui32 stageDelay = 16;
const ui32 S1_TRANSP = 16; //0.5 sec building appear 0->100 transparency
const ui32 S2_WHITE_B = 32; //0.5 sec border glows from white to yellow
const ui32 S3_YELLOW_B= 48; //0.5 sec border glows from yellow to normal
const ui32 BUILDED = 80; // 1 sec delay, nothing happens
if (stateCounter < S1_TRANSP)
{
setAlpha(255*stateCounter/stageDelay);
CShowableAnim::show(to);
}
else
{
setAlpha(255);
CShowableAnim::show(to);
}
if (border && stateCounter > S1_TRANSP)
{
if (stateCounter == BUILDED)
{
if (parent->selectedBuilding == this)
blitAtLoc(border,0,0,to);
return;
}
if (border->format->palette != nullptr)
{
// key colors in glowing border
SDL_Color c1 = {200, 200, 200, 255};
SDL_Color c2 = {120, 100, 60, 255};
SDL_Color c3 = {200, 180, 110, 255};
ui32 colorID = SDL_MapRGB(border->format, c3.r, c3.g, c3.b);
SDL_Color oldColor = border->format->palette->colors[colorID];
SDL_Color newColor;
if (stateCounter < S2_WHITE_B)
newColor = multiplyColors(c1, c2, static_cast<double>(stateCounter % stageDelay) / stageDelay);
else
if (stateCounter < S3_YELLOW_B)
newColor = multiplyColors(c2, c3, static_cast<double>(stateCounter % stageDelay) / stageDelay);
else
newColor = oldColor;
SDL_SetColors(border, &newColor, colorID, 1);
blitAtLoc(border,0,0,to);
SDL_SetColors(border, &oldColor, colorID, 1);
}
}
if (stateCounter < BUILDED)
stateCounter++;
}
void CBuildingRect::showAll(SDL_Surface * to)
{
if (stateCounter == 0)
return;
CShowableAnim::showAll(to);
if(!active && parent->selectedBuilding == this && border)
blitAtLoc(border,0,0,to);
}
std::string CBuildingRect::getSubtitle()//hover text for building
{
if (!getBuilding())
return "";
int bid = getBuilding()->bid;
if (bid<30)//non-dwellings - only buiding name
return town->town->buildings.at(getBuilding()->bid)->Name();
else//dwellings - recruit %creature%
{
auto & availableCreatures = town->creatures[(bid-30)%GameConstants::CREATURES_PER_TOWN].second;
if(availableCreatures.size())
{
int creaID = availableCreatures.back();//taking last of available creatures
return CGI->generaltexth->allTexts[16] + " " + CGI->creh->creatures.at(creaID)->namePl;
}
else
{
logGlobal->warnStream() << "Problem: dwelling with id " << bid << " offers no creatures!";
return "#ERROR#";
}
}
}
void CBuildingRect::mouseMoved (const SDL_MouseMotionEvent & sEvent)
{
if(area && isItIn(&pos,sEvent.x, sEvent.y))
{
if(CSDL_Ext::isTransparent(area, GH.current->motion.x-pos.x, GH.current->motion.y-pos.y)) //hovered pixel is inside this building
{
if(parent->selectedBuilding == this)
{
parent->selectedBuilding = nullptr;
GH.statusbar->clear();
}
}
else //inside the area of this building
{
if(! parent->selectedBuilding //no building hovered
|| (*parent->selectedBuilding)<(*this)) //or we are on top
{
parent->selectedBuilding = this;
GH.statusbar->setText(getSubtitle());
}
}
}
}
CDwellingInfoBox::CDwellingInfoBox(int centerX, int centerY, const CGTownInstance *Town, int level):
CWindowObject(RCLICK_POPUP | PLAYER_COLORED, "CRTOINFO", Point(centerX, centerY))
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
const CCreature * creature = CGI->creh->creatures.at(Town->creatures.at(level).second.back());
title = new CLabel(80, 30, FONT_SMALL, CENTER, Colors::WHITE, creature->namePl);
animation = new CCreaturePic(30, 44, creature, true, true);
std::string text = boost::lexical_cast<std::string>(Town->creatures.at(level).first);
available = new CLabel(80,190, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[217] + text);
costPerTroop = new CLabel(80, 227, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[346]);
for(int i = 0; i<GameConstants::RESOURCE_QUANTITY; i++)
{
if(creature->cost[i])
{
resPicture.push_back(new CAnimImage("RESOURCE", i, 0, 0, 0));
resAmount.push_back(new CLabel(0,0, FONT_SMALL, CENTER, Colors::WHITE, boost::lexical_cast<std::string>(creature->cost[i])));
}
}
int posY = 238;
int posX = pos.w/2 - resAmount.size() * 25 + 5;
for (size_t i=0; i<resAmount.size(); i++)
{
resPicture[i]->moveBy(Point(posX, posY));
resAmount[i]->moveBy(Point(posX+16, posY+43));
posX += 50;
}
}
void CHeroGSlot::hover (bool on)
{
if(!on)
{
GH.statusbar->clear();
return;
}
CHeroGSlot *other = upg ? owner->garrisonedHero : owner->visitingHero;
std::string temp;
if(hero)
{
if(selection)//view NNN
{
temp = CGI->generaltexth->tcommands[4];
boost::algorithm::replace_first(temp,"%s",hero->name);
}
else if(other->hero && other->selection)//exchange
{
temp = CGI->generaltexth->tcommands[7];
boost::algorithm::replace_first(temp,"%s",hero->name);
boost::algorithm::replace_first(temp,"%s",other->hero->name);
}
else// select NNN (in ZZZ)
{
if(upg)//down - visiting
{
temp = CGI->generaltexth->tcommands[32];
boost::algorithm::replace_first(temp,"%s",hero->name);
}
else //up - garrison
{
temp = CGI->generaltexth->tcommands[12];
boost::algorithm::replace_first(temp,"%s",hero->name);
}
}
}
else //we are empty slot
{
if(other->selection && other->hero) //move NNNN
{
temp = CGI->generaltexth->tcommands[6];
boost::algorithm::replace_first(temp,"%s",other->hero->name);
}
else //empty
{
temp = CGI->generaltexth->allTexts[507];
}
}
if(temp.size())
GH.statusbar->setText(temp);
}
void CHeroGSlot::clickLeft(tribool down, bool previousState)
{
CHeroGSlot *other = upg ? owner->garrisonedHero : owner->visitingHero;
if(!down)
{
owner->garr->setSplittingMode(false);
owner->garr->selectSlot(nullptr);
if(hero && selection)
{
setHighlight(false);
LOCPLINT->openHeroWindow(hero);
}
else if(other->hero && other->selection)
{
bool allow = true;
if(upg) //moving hero out of town - check if it is allowed
{
if(!hero && LOCPLINT->cb->howManyHeroes(false) >= VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER)
{
std::string tmp = CGI->generaltexth->allTexts[18]; //You already have %d adventuring heroes under your command.
boost::algorithm::replace_first(tmp,"%d",boost::lexical_cast<std::string>(LOCPLINT->cb->howManyHeroes(false)));
LOCPLINT->showInfoDialog(tmp,std::vector<CComponent*>(), soundBase::sound_todo);
allow = false;
}
else if(!other->hero->stacksCount()) //hero has no creatures - strange, but if we have appropriate error message...
{
LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[19],std::vector<CComponent*>(), soundBase::sound_todo); //This hero has no creatures. A hero must have creatures before he can brave the dangers of the countryside.
allow = false;
}
}
setHighlight(false);
other->setHighlight(false);
if(allow)
{
owner->swapArmies();
hero = other->hero;
}
}
else if(hero)
{
setHighlight(true);
owner->garr->selectSlot(nullptr);
showAll(screen2);
}
hover(false);hover(true); //refresh statusbar
}
}
void CHeroGSlot::clickRight(tribool down, bool previousState)
{
if(hero && down)
{
GH.pushInt(new CInfoBoxPopup(Point(pos.x + 175, pos.y + 100), hero));
}
}
void CHeroGSlot::deactivate()
{
vstd::clear_pointer(selection);
CIntObject::deactivate();
}
CHeroGSlot::CHeroGSlot(int x, int y, int updown, const CGHeroInstance *h, HeroSlots * Owner)
{
owner = Owner;
pos.x += x;
pos.y += y;
pos.w = 58;
pos.h = 64;
upg = updown;
selection = nullptr;
image = nullptr;
set(h);
addUsedEvents(LCLICK | RCLICK | HOVER);
}
CHeroGSlot::~CHeroGSlot()
{
}
void CHeroGSlot::setHighlight( bool on )
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
vstd::clear_pointer(selection);
if (on)
selection = new CAnimImage("TWCRPORT", 1, 0);
if(owner->garrisonedHero->hero && owner->visitingHero->hero) //two heroes in town
{
for(auto & elem : owner->garr->splitButtons) //splitting enabled when slot higlighted
elem->block(!on);
}
}
void CHeroGSlot::set(const CGHeroInstance *newHero)
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
if (image)
delete image;
hero = newHero;
if (newHero)
image = new CAnimImage("PortraitsLarge", newHero->portrait, 0, 0, 0);
else if(!upg && owner->showEmpty) //up garrison
image = new CAnimImage("CREST58", LOCPLINT->castleInt->town->getOwner().getNum(), 0, 0, 0);
else
image = nullptr;
}
template <class ptr>
class SORTHELP
{
public:
bool operator ()
(const ptr *a ,
const ptr *b)
{
return (*a)<(*b);
}
};
SORTHELP<CBuildingRect> buildSorter;
SORTHELP<CStructure> structSorter;
CCastleBuildings::CCastleBuildings(const CGTownInstance* Town):
town(Town),
selectedBuilding(nullptr)
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
background = new CPicture(town->town->clientInfo.townBackground);
pos.w = background->pos.w;
pos.h = background->pos.h;
recreate();
}
void CCastleBuildings::recreate()
{
selectedBuilding = nullptr;
OBJ_CONSTRUCTION_CAPTURING_ALL;
//clear existing buildings
for(auto build : buildings)
delete build;
buildings.clear();
groups.clear();
//Generate buildings list
auto buildingsCopy = town->builtBuildings;// a bit modified copy of built buildings
if(vstd::contains(town->builtBuildings, BuildingID::SHIPYARD))
{
auto bayPos = town->bestLocation();
if(!bayPos.valid())
logGlobal->warnStream() << "Shipyard in non-coastal town!";
std::vector <const CGObjectInstance *> vobjs = LOCPLINT->cb->getVisitableObjs(bayPos, false);
//there is visitable obj at shipyard output tile and it's a boat or hero (on boat)
if(!vobjs.empty() && (vobjs.front()->ID == Obj::BOAT || vobjs.front()->ID == Obj::HERO))
{
buildingsCopy.insert(BuildingID::SHIP);
}
}
for(const CStructure * structure : town->town->clientInfo.structures)
{
if (!structure->building)
{
buildings.push_back(new CBuildingRect(this, town, structure));
continue;
}
if (vstd::contains(buildingsCopy, structure->building->bid))
{
groups[structure->building->getBase()].push_back(structure);
}
}
for(auto & entry : groups)
{
const CBuilding * build = town->town->buildings.at(entry.first);
const CStructure * toAdd = *boost::max_element(entry.second, [=](const CStructure * a, const CStructure * b)
{
return build->getDistance(a->building->bid)
< build->getDistance(b->building->bid);
});
buildings.push_back(new CBuildingRect(this, town, toAdd));
}
boost::sort(buildings, [] (const CBuildingRect * a, const CBuildingRect * b)
{
return *a < *b;
});
}
CCastleBuildings::~CCastleBuildings()
{
}
void CCastleBuildings::addBuilding(BuildingID building)
{
//FIXME: implement faster method without complete recreation of town
BuildingID base = town->town->buildings.at(building)->getBase();
recreate();
auto & structures = groups.at(base);
for(CBuildingRect * rect : buildings)
{
if (vstd::contains(structures, rect->str))
{
//reset animation
if (structures.size() == 1)
rect->stateCounter = 0; // transparency -> fully visible stage
else
rect->stateCounter = 16; // already in fully visible stage
break;
}
}
}
void CCastleBuildings::removeBuilding(BuildingID building)
{
//FIXME: implement faster method without complete recreation of town
recreate();
}
void CCastleBuildings::show(SDL_Surface * to)
{
CIntObject::show(to);
for(CBuildingRect * str : buildings)
str->show(to);
}
void CCastleBuildings::showAll(SDL_Surface * to)
{
CIntObject::showAll(to);
for(CBuildingRect * str : buildings)
str->showAll(to);
}
const CGHeroInstance* CCastleBuildings::getHero()
{
if (town->visitingHero)
return town->visitingHero;
if (town->garrisonHero)
return town->garrisonHero;
return nullptr;
}
void CCastleBuildings::buildingClicked(BuildingID building)
{
logGlobal->traceStream()<<"You've clicked on "<<building;
const CBuilding *b = town->town->buildings.find(building)->second;
if(building >= BuildingID::DWELL_FIRST)
{
enterDwelling((building-BuildingID::DWELL_FIRST)%GameConstants::CREATURES_PER_TOWN);
}
else
{
switch(building)
{
case BuildingID::MAGES_GUILD_1:
case BuildingID::MAGES_GUILD_2:
case BuildingID::MAGES_GUILD_3:
case BuildingID::MAGES_GUILD_4:
case BuildingID::MAGES_GUILD_5:
enterMagesGuild();
break;
case BuildingID::TAVERN:
LOCPLINT->showTavernWindow(town);
break;
case BuildingID::SHIPYARD:
if(town->shipyardStatus() == IBoatGenerator::GOOD)
LOCPLINT->showShipyardDialog(town);
else if(town->shipyardStatus() == IBoatGenerator::BOAT_ALREADY_BUILT)
LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[51]);
break;
case BuildingID::FORT:
case BuildingID::CITADEL:
case BuildingID::CASTLE:
GH.pushInt(new CFortScreen(town));
break;
case BuildingID::VILLAGE_HALL:
case BuildingID::CITY_HALL:
case BuildingID::TOWN_HALL:
case BuildingID::CAPITOL:
enterTownHall();
break;
case BuildingID::MARKETPLACE:
GH.pushInt(new CMarketplaceWindow(town, town->visitingHero));
break;
case BuildingID::BLACKSMITH:
enterBlacksmith(town->town->warMachine);
break;
case BuildingID::SPECIAL_1:
switch(town->subID)
{
case ETownType::RAMPART://Mystic Pond
enterFountain(building);
break;
case ETownType::TOWER:
case ETownType::DUNGEON://Artifact Merchant
case ETownType::CONFLUX:
if(town->visitingHero)
GH.pushInt(new CMarketplaceWindow(town, town->visitingHero, EMarketMode::RESOURCE_ARTIFACT));
else
LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[273]) % b->Name())); //Only visiting heroes may use the %s.
break;
default:
enterBuilding(building);
break;
}
break;
case BuildingID::SHIP:
LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[51]); //Cannot build another boat
break;
case BuildingID::SPECIAL_2:
switch(town->subID)
{
case ETownType::RAMPART: //Fountain of Fortune
enterFountain(building);
break;
case ETownType::STRONGHOLD: //Freelancer's Guild
if(getHero())
GH.pushInt(new CMarketplaceWindow(town, getHero(), EMarketMode::CREATURE_RESOURCE));
else
LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[273]) % b->Name())); //Only visiting heroes may use the %s.
break;
case ETownType::CONFLUX: //Magic University
if (getHero())
GH.pushInt(new CUniversityWindow(getHero(), town));
else
enterBuilding(building);
break;
default:
enterBuilding(building);
break;
}
break;
case BuildingID::SPECIAL_3:
switch(town->subID)
{
case ETownType::CASTLE: //Brotherhood of sword
LOCPLINT->showTavernWindow(town);
break;
case ETownType::INFERNO: //Castle Gate
enterCastleGate();
break;
case ETownType::NECROPOLIS: //Skeleton Transformer
GH.pushInt( new CTransformerWindow(getHero(), town) );
break;
case ETownType::DUNGEON: //Portal of Summoning
if (town->creatures[GameConstants::CREATURES_PER_TOWN].second.empty())//No creatures
LOCPLINT->showInfoDialog(CGI->generaltexth->tcommands[30]);
else
enterDwelling(GameConstants::CREATURES_PER_TOWN);
break;
case ETownType::STRONGHOLD: //Ballista Yard
enterBlacksmith(ArtifactID::BALLISTA);
break;
default:
enterBuilding(building);
break;
}
break;
default:
enterBuilding(building);
break;
}
}
}
void CCastleBuildings::enterBlacksmith(ArtifactID artifactID)
{
const CGHeroInstance *hero = town->visitingHero;
if(!hero)
{
LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[273]) % town->town->buildings.find(BuildingID::BLACKSMITH)->second->Name()));
return;
}
int price = CGI->arth->artifacts[artifactID]->price;
bool possible = LOCPLINT->cb->getResourceAmount(Res::GOLD) >= price && !hero->hasArt(artifactID);
CreatureID cre = artifactID.toArtifact()->warMachine;
GH.pushInt(new CBlacksmithDialog(possible, cre, artifactID, hero->id));
}
void CCastleBuildings::enterBuilding(BuildingID building)
{
std::vector<CComponent*> comps(1, new CComponent(CComponent::building, town->subID, building));
LOCPLINT->showInfoDialog(
town->town->buildings.find(building)->second->Description(),comps);
}
void CCastleBuildings::enterCastleGate()
{
if (!town->visitingHero)
{
LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[126]);
return;//only visiting hero can use castle gates
}
std::vector <int> availableTowns;
std::vector <const CGTownInstance*> Towns = LOCPLINT->cb->getTownsInfo(true);
for(auto & Town : Towns)
{
const CGTownInstance *t = Town;
if (t->id != this->town->id && t->visitingHero == nullptr && //another town, empty and this is
t->hasBuilt(BuildingID::CASTLE_GATE, ETownType::INFERNO))
{
availableTowns.push_back(t->id.getNum());//add to the list
}
}
auto gateIcon = new CAnimImage(town->town->clientInfo.buildingsIcons, BuildingID::CASTLE_GATE);//will be deleted by selection window
GH.pushInt (new CObjectListWindow(availableTowns, gateIcon, CGI->generaltexth->jktexts[40],
CGI->generaltexth->jktexts[41], std::bind (&CCastleInterface::castleTeleport, LOCPLINT->castleInt, _1)));
}
void CCastleBuildings::enterDwelling(int level)
{
assert(level >= 0 && level < town->creatures.size());
auto recruitCb = [=](CreatureID id, int count){ LOCPLINT->cb->recruitCreatures(town, town->getUpperArmy(), id, count, level); };
GH.pushInt(new CRecruitmentWindow(town, level, town, recruitCb, -87));
}
void CCastleBuildings::enterFountain(BuildingID building)
{
std::vector<CComponent*> comps(1, new CComponent(CComponent::building,town->subID,building));
std::string descr = town->town->buildings.find(building)->second->Description();
if ( building == BuildingID::FOUNTAIN_OF_FORTUNE)
descr += "\n\n"+town->town->buildings.find(BuildingID::MYSTIC_POND)->second->Description();
if (town->bonusValue.first == 0)//fountain was builded this week
descr += "\n\n"+ CGI->generaltexth->allTexts[677];
else//fountain produced something;
{
descr+= "\n\n"+ CGI->generaltexth->allTexts[678];
boost::algorithm::replace_first(descr,"%s",CGI->generaltexth->restypes[town->bonusValue.first]);
boost::algorithm::replace_first(descr,"%d",boost::lexical_cast<std::string>(town->bonusValue.second));
}
LOCPLINT->showInfoDialog(descr, comps);
}
void CCastleBuildings::enterMagesGuild()
{
const CGHeroInstance *hero = getHero();
if(hero && !hero->hasSpellbook()) //hero doesn't have spellbok
{
if(LOCPLINT->cb->getResourceAmount(Res::GOLD) < 500) //not enough gold to buy spellbook
{
openMagesGuild();
LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[213]);
}
else
{
CFunctionList<void()> onYes = [this](){ openMagesGuild(); };
CFunctionList<void()> onNo = onYes;
onYes += [hero](){ LOCPLINT->cb->buyArtifact(hero, ArtifactID::SPELLBOOK); };
std::vector<CComponent*> components(1, new CComponent(CComponent::artifact,ArtifactID::SPELLBOOK,0));
LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[214], onYes, onNo, true, components);
}
}
else
{
openMagesGuild();
}
}
void CCastleBuildings::enterTownHall()
{
if(town->visitingHero && town->visitingHero->hasArt(2) &&
!vstd::contains(town->builtBuildings, BuildingID::GRAIL)) //hero has grail, but town does not have it
{
if(!vstd::contains(town->forbiddenBuildings, BuildingID::GRAIL))
{
LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[597], //Do you wish this to be the permanent home of the Grail?
[&](){ LOCPLINT->cb->buildBuilding(town, BuildingID::GRAIL); },
[&](){ openTownHall(); },
true);
}
else
{
LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[673]);
dynamic_cast<CInfoWindow*>(GH.topInt())->buttons[0]->addCallback(std::bind(&CCastleBuildings::openTownHall, this));
}
}
else
{
openTownHall();
}
}
void CCastleBuildings::openMagesGuild()
{
std::string mageGuildBackground;
mageGuildBackground = LOCPLINT->castleInt->town->town->clientInfo.guildBackground;
GH.pushInt(new CMageGuildScreen(LOCPLINT->castleInt,mageGuildBackground));
}
void CCastleBuildings::openTownHall()
{
GH.pushInt(new CHallInterface(town));
}
CCastleInterface::CCastleInterface(const CGTownInstance * Town, const CGTownInstance * from):
CWindowObject(PLAYER_COLORED | BORDERED),
hall(nullptr),
fort(nullptr),
town(Town)
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
LOCPLINT->castleInt = this;
addUsedEvents(KEYBOARD);
builds = new CCastleBuildings(town);
panel = new CPicture("TOWNSCRN", 0, builds->pos.h);
panel->colorize(LOCPLINT->playerID);
pos.w = panel->pos.w;
pos.h = builds->pos.h + panel->pos.h;
center();
updateShadow();
garr = new CGarrisonInt(305, 387, 4, Point(0,96), panel->bg, Point(62,374), town->getUpperArmy(), town->visitingHero);
garr->type |= REDRAW_PARENT;
heroes = new HeroSlots(town, Point(241, 387), Point(241, 483), garr, true);
title = new CLabel(85, 387, FONT_MEDIUM, TOPLEFT, Colors::WHITE, town->name);
income = new CLabel(195, 443, FONT_SMALL, CENTER);
icon = new CAnimImage("ITPT", 0, 0, 15, 387);
exit = new CButton(Point(744, 544), "TSBTNS", CButton::tooltip(CGI->generaltexth->tcommands[8]), [&](){close();}, SDLK_RETURN);
exit->assignedKeys.insert(SDLK_ESCAPE);
exit->setImageOrder(4, 5, 6, 7);
split = new CButton(Point(744, 382), "TSBTNS.DEF", CButton::tooltip(CGI->generaltexth->tcommands[3]), [&](){garr->splitClick();});
split->addCallback(std::bind(&HeroSlots::splitClicked, heroes));
garr->addSplitBtn(split);
Rect barRect(9, 182, 732, 18);
statusbar = new CGStatusBar(new CPicture(*panel, barRect, 9, 555, false));
resdatabar = new CResDataBar("ARESBAR", 3, 575, 32, 2, 85, 85);
townlist = new CTownList(3, Point(744, 414), "IAM014", "IAM015");
if (from)
townlist->select(from);
townlist->select(town); //this will scroll list to select current town
townlist->onSelect = std::bind(&CCastleInterface::townChange, this);
recreateIcons();
CCS->musich->playMusic(town->town->clientInfo.musicTheme, true);
}
CCastleInterface::~CCastleInterface()
{
LOCPLINT->castleInt = nullptr;
}
void CCastleInterface::close()
{
if(town->tempOwner == LOCPLINT->playerID) //we may have opened window for an allied town
{
if(town->visitingHero && town->visitingHero->tempOwner == LOCPLINT->playerID)
adventureInt->select(town->visitingHero);
else
adventureInt->select(town);
}
CWindowObject::close();
}
void CCastleInterface::castleTeleport(int where)
{
const CGTownInstance * dest = LOCPLINT->cb->getTown(ObjectInstanceID(where));
LOCPLINT->cb->teleportHero(town->visitingHero, dest);
LOCPLINT->eraseCurrentPathOf(town->visitingHero, false);
}
void CCastleInterface::townChange()
{
const CGTownInstance * dest = LOCPLINT->towns[townlist->getSelectedIndex()];
const CGTownInstance * town = this->town;// "this" is going to be deleted
if ( dest == town )
return;
close();
GH.pushInt(new CCastleInterface(dest, town));
}
void CCastleInterface::addBuilding(BuildingID bid)
{
deactivate();
builds->addBuilding(bid);
recreateIcons();
activate();
}
void CCastleInterface::removeBuilding(BuildingID bid)
{
deactivate();
builds->removeBuilding(bid);
recreateIcons();
activate();
}
void CCastleInterface::recreateIcons()
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
delete fort;
delete hall;
size_t iconIndex = town->town->clientInfo.icons[town->hasFort()][town->builded >= CGI->modh->settings.MAX_BUILDING_PER_TURN];
icon->setFrame(iconIndex);
TResources townIncome = town->dailyIncome();
income->setText(boost::lexical_cast<std::string>(townIncome[Res::GOLD]));
hall = new CTownInfo( 80, 413, town, true);
fort = new CTownInfo(122, 413, town, false);
for (auto & elem : creainfo)
delete elem;
creainfo.clear();
for (size_t i=0; i<4; i++)
creainfo.push_back(new CCreaInfo(Point(14+55*i, 459), town, i));
for (size_t i=0; i<4; i++)
creainfo.push_back(new CCreaInfo(Point(14+55*i, 507), town, i+4));
}
CCreaInfo::CCreaInfo(Point position, const CGTownInstance *Town, int Level, bool compact, bool ShowAvailable):
town(Town),
level(Level),
showAvailable(ShowAvailable)
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
pos += position;
if ( town->creatures.size() <= level || town->creatures[level].second.empty())
{
level = -1;
label = nullptr;
picture = nullptr;
creature = nullptr;
return;//No creature
}
addUsedEvents(LCLICK | RCLICK | HOVER);
ui32 creatureID = town->creatures[level].second.back();
creature = CGI->creh->creatures[creatureID];
picture = new CAnimImage("CPRSMALL", creature->iconIndex, 0, 8, 0);
std::string value;
if (showAvailable)
value = boost::lexical_cast<std::string>(town->creatures[level].first);
else
value = boost::lexical_cast<std::string>(town->creatureGrowth(level));
if (compact)
{
label = new CLabel(40, 32, FONT_TINY, BOTTOMRIGHT, Colors::WHITE, value);
pos.x += 8;
pos.w = 32;
pos.h = 32;
}
else
{
label = new CLabel(24, 40, FONT_SMALL, CENTER, Colors::WHITE, value);
pos.w = 48;
pos.h = 48;
}
}
void CCreaInfo::update()
{
if (label)
{
std::string value;
if (showAvailable)
value = boost::lexical_cast<std::string>(town->creatures[level].first);
else
value = boost::lexical_cast<std::string>(town->creatureGrowth(level));
if (value != label->text)
label->setText(value);
}
}
void CCreaInfo::hover(bool on)
{
std::string message = CGI->generaltexth->allTexts[588];
boost::algorithm::replace_first(message,"%s",creature->namePl);
if(on)
{
GH.statusbar->setText(message);
}
else if (message == GH.statusbar->getText())
GH.statusbar->clear();
}
void CCreaInfo::clickLeft(tribool down, bool previousState)
{
if(previousState && (!down))
{
int offset = LOCPLINT->castleInt? (-87) : 0;
auto recruitCb = [=](CreatureID id, int count) { LOCPLINT->cb->recruitCreatures(town, town->getUpperArmy(), id, count, level); };
GH.pushInt(new CRecruitmentWindow(town, level, town, recruitCb, offset));
}
}
int CCreaInfo::AddToString(std::string from, std::string & to, int numb)
{
if (numb == 0)
return 0;
boost::algorithm::replace_first(from,"%+d", (numb > 0 ? "+" : "")+boost::lexical_cast<std::string>(numb)); //negative values don't need "+"
to+="\n"+from;
return numb;
}
std::string CCreaInfo::genGrowthText()
{
GrowthInfo gi = town->getGrowthInfo(level);
std::string descr = boost::str(boost::format(CGI->generaltexth->allTexts[589]) % creature->nameSing % gi.totalGrowth());
for(const GrowthInfo::Entry &entry : gi.entries)
{
descr +="\n" + entry.description;
}
return descr;
}
void CCreaInfo::clickRight(tribool down, bool previousState)
{
if(down)
{
if (showAvailable)
GH.pushInt(new CDwellingInfoBox(screen->w/2, screen->h/2, town, level));
else
CRClickPopup::createAndPush(genGrowthText(), new CComponent(CComponent::creature, creature->idNumber));
}
}
CTownInfo::CTownInfo(int posX, int posY, const CGTownInstance* Town, bool townHall):
town(Town),
building(nullptr)
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
addUsedEvents(RCLICK | HOVER);
pos.x += posX;
pos.y += posY;
int buildID;
picture = nullptr;
if (townHall)
{
buildID = 10 + town->hallLevel();
picture = new CAnimImage("ITMTL.DEF", town->hallLevel());
}
else
{
buildID = 6 + town->fortLevel();
if (buildID == 6)
return;//FIXME: suspicious statement, fix or comment
picture = new CAnimImage("ITMCL.DEF", town->fortLevel()-1);
}
building = town->town->buildings.at(BuildingID(buildID));
pos = picture->pos;
}
void CTownInfo::hover(bool on)
{
if(on)
{
if ( building )
GH.statusbar->setText(building->Name());
}
else
GH.statusbar->clear();
}
void CTownInfo::clickRight(tribool down, bool previousState)
{
if(building && down)
CRClickPopup::createAndPush(CInfoWindow::genText(building->Name(), building->Description()),
new CComponent(CComponent::building, building->town->faction->index, building->bid));
}
void CCastleInterface::keyPressed( const SDL_KeyboardEvent & key )
{
if(key.state != SDL_PRESSED) return;
switch(key.keysym.sym)
{
#if 0 // code that can be used to fix blit order in towns using +/- keys. Quite ugly but works
case SDLK_KP_PLUS :
if (builds->selectedBuilding)
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
CStructure * str = const_cast<CStructure *>(builds->selectedBuilding->str);
str->pos.z++;
delete builds;
builds = new CCastleBuildings(town);
for(const CStructure * str : town->town->clientInfo.structures)
{
if (str->building)
logGlobal->errorStream() << int(str->building->bid) << " -> " << int(str->pos.z);
}
}
break;
case SDLK_KP_MINUS:
if (builds->selectedBuilding)
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
CStructure * str = const_cast<CStructure *>(builds->selectedBuilding->str);
str->pos.z--;
delete builds;
builds = new CCastleBuildings(town);
for(const CStructure * str : town->town->clientInfo.structures)
{
if (str->building)
logGlobal->errorStream() << int(str->building->bid) << " -> " << int(str->pos.z);
}
}
break;
#endif
case SDLK_UP:
townlist->selectPrev();
break;
case SDLK_DOWN:
townlist->selectNext();
break;
case SDLK_SPACE:
heroes->swapArmies();
break;
case SDLK_t:
if(town->hasBuilt(BuildingID::TAVERN))
LOCPLINT->showTavernWindow(town);
break;
default:
break;
}
}
HeroSlots::HeroSlots(const CGTownInstance * Town, Point garrPos, Point visitPos, CGarrisonInt *Garrison, bool ShowEmpty):
showEmpty(ShowEmpty),
town(Town),
garr(Garrison)
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
garrisonedHero = new CHeroGSlot(garrPos.x, garrPos.y, 0, town->garrisonHero, this);
visitingHero = new CHeroGSlot(visitPos.x, visitPos.y, 1, town->visitingHero, this);
}
void HeroSlots::update()
{
garrisonedHero->set(town->garrisonHero);
visitingHero->set(town->visitingHero);
}
void HeroSlots::splitClicked()
{
if(!!town->visitingHero && town->garrisonHero && (visitingHero->selection || garrisonedHero->selection))
{
LOCPLINT->heroExchangeStarted(town->visitingHero->id, town->garrisonHero->id, QueryID(-1));
}
}
void HeroSlots::swapArmies()
{
if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
{
if(!town->visitingHero->canBeMergedWith(*town))
{
LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[275], std::vector<CComponent*>(), soundBase::sound_todo);
return;
}
}
LOCPLINT->cb->swapGarrisonHero(town);
}
void CHallInterface::CBuildingBox::hover(bool on)
{
if(on)
{
std::string toPrint;
if(state==EBuildingState::PREREQUIRES || state == EBuildingState::MISSING_BASE)
toPrint = CGI->generaltexth->hcommands[5];
else if(state==EBuildingState::CANT_BUILD_TODAY)
toPrint = CGI->generaltexth->allTexts[223];
else
toPrint = CGI->generaltexth->hcommands[state];
boost::algorithm::replace_first(toPrint,"%s",building->Name());
GH.statusbar->setText(toPrint);
}
else
GH.statusbar->clear();
}
void CHallInterface::CBuildingBox::clickLeft(tribool down, bool previousState)
{
if(previousState && (!down))
GH.pushInt(new CBuildWindow(town,building,state,0));
}
void CHallInterface::CBuildingBox::clickRight(tribool down, bool previousState)
{
if(down)
GH.pushInt(new CBuildWindow(town,building,state,1));
}
CHallInterface::CBuildingBox::CBuildingBox(int x, int y, const CGTownInstance * Town, const CBuilding * Building):
town(Town),
building(Building)
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
addUsedEvents(LCLICK | RCLICK | HOVER);
pos.x += x;
pos.y += y;
pos.w = 154;
pos.h = 92;
state = LOCPLINT->cb->canBuildStructure(town,building->bid);
static int panelIndex[12] = { 3, 3, 3, 0, 0, 2, 2, 1, 2, 2, 3, 3};
static int iconIndex[12] = {-1, -1, -1, 0, 0, 1, 2, -1, 1, 1, -1, -1};
new CAnimImage(town->town->clientInfo.buildingsIcons, building->bid, 0, 2, 2);
new CAnimImage("TPTHBAR", panelIndex[state], 0, 1, 73);
if (iconIndex[state] >=0)
new CAnimImage("TPTHCHK", iconIndex[state], 0, 136, 56);
new CLabel(75, 81, FONT_SMALL, CENTER, Colors::WHITE, building->Name());
//todo: add support for all possible states
if(state >= EBuildingState::BUILDING_ERROR)
state = EBuildingState::FORBIDDEN;
}
CHallInterface::CHallInterface(const CGTownInstance *Town):
CWindowObject(PLAYER_COLORED | BORDERED, Town->town->clientInfo.hallBackground),
town(Town)
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
resdatabar = new CMinorResDataBar();
resdatabar->pos.x += pos.x;
resdatabar->pos.y += pos.y;
Rect barRect(5, 556, 740, 18);
statusBar = new CGStatusBar(new CPicture(*background, barRect, 5, 556, false));
title = new CLabel(399, 12, FONT_MEDIUM, CENTER, Colors::WHITE, town->town->buildings.at(BuildingID(town->hallLevel()+BuildingID::VILLAGE_HALL))->Name());
exit = new CButton(Point(748, 556), "TPMAGE1.DEF", CButton::tooltip(CGI->generaltexth->hcommands[8]), [&](){close();}, SDLK_RETURN);
exit->assignedKeys.insert(SDLK_ESCAPE);
auto & boxList = town->town->clientInfo.hallSlots;
boxes.resize(boxList.size());
for(size_t row=0; row<boxList.size(); row++) //for each row
{
for(size_t col=0; col<boxList[row].size(); col++) //for each box
{
const CBuilding *building = nullptr;
for(auto & elem : boxList[row][col])//we are looking for the first not build structure
{
auto buildingID = elem;
building = town->town->buildings.at(buildingID);
if(!vstd::contains(town->builtBuildings,buildingID))
break;
}
int posX = pos.w/2 - boxList[row].size()*154/2 - (boxList[row].size()-1)*20 + 194*col,
posY = 35 + 104*row;
if (building)
boxes[row].push_back(new CBuildingBox(posX, posY, town, building));
}
}
}
void CBuildWindow::buyFunc()
{
LOCPLINT->cb->buildBuilding(town,building->bid);
GH.popInts(2); //we - build window and hall screen
}
std::string CBuildWindow::getTextForState(int state)
{
std::string ret;
if(state < EBuildingState::ALLOWED)
ret = CGI->generaltexth->hcommands[state];
switch (state)
{
case EBuildingState::ALREADY_PRESENT:
case EBuildingState::CANT_BUILD_TODAY:
case EBuildingState::NO_RESOURCES:
ret.replace(ret.find_first_of("%s"), 2, building->Name());
break;
case EBuildingState::ALLOWED:
return CGI->generaltexth->allTexts[219]; //all prereq. are met
case EBuildingState::PREREQUIRES:
{
auto toStr = [&](const BuildingID build) -> std::string
{
return town->town->buildings.at(build)->Name();
};
ret = CGI->generaltexth->allTexts[52];
ret += "\n" + town->genBuildingRequirements(building->bid).toString(toStr);
break;
}
case EBuildingState::MISSING_BASE:
{
std::string msg = CGI->generaltexth->localizedTexts["townHall"]["missingBase"].String();
ret = boost::str(boost::format(msg) % town->town->buildings.at(building->upgrade)->Name());
break;
}
}
return ret;
}
CBuildWindow::CBuildWindow(const CGTownInstance *Town, const CBuilding * Building, int state, bool rightClick):
CWindowObject(PLAYER_COLORED | (rightClick ? RCLICK_POPUP : 0), "TPUBUILD"),
town(Town),
building(Building)
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
new CAnimImage(town->town->clientInfo.buildingsIcons, building->bid, 0, 125, 50);
new CGStatusBar(new CPicture(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
new CLabel(197, 30, FONT_MEDIUM, CENTER, Colors::WHITE,
boost::str(boost::format(CGI->generaltexth->hcommands[7]) % building->Name()));
new CTextBox(building->Description(), Rect(33, 135, 329, 67), 0, FONT_MEDIUM, CENTER);
new CTextBox(getTextForState(state), Rect(33, 216, 329, 67), 0, FONT_SMALL, CENTER);
//Create components for all required resources
std::vector<CComponent *> components;
for(int i = 0; i<GameConstants::RESOURCE_QUANTITY; i++)
{
if(building->resources[i])
{
components.push_back(new CComponent(CComponent::resource, i, building->resources[i], CComponent::small));
}
}
new CComponentBox(components, Rect(25, 300, pos.w - 50, 130));
if(!rightClick)
{ //normal window
std::string tooltipYes = boost::str(boost::format(CGI->generaltexth->allTexts[595]) % building->Name());
std::string tooltipNo = boost::str(boost::format(CGI->generaltexth->allTexts[596]) % building->Name());
CButton * buy = new CButton(Point(45, 446), "IBUY30", CButton::tooltip(tooltipYes), [&](){ buyFunc(); }, SDLK_RETURN);
buy->borderColor = Colors::METALLIC_GOLD;
<|fim▁hole|> buy->block(state!=7 || LOCPLINT->playerID != town->tempOwner);
CButton * cancel = new CButton(Point(290, 445), "ICANCEL", CButton::tooltip(tooltipNo), [&](){ close();}, SDLK_ESCAPE);
cancel->borderColor = Colors::METALLIC_GOLD;
}
}
std::string CFortScreen::getBgName(const CGTownInstance *town)
{
ui32 fortSize = town->creatures.size();
if (fortSize > GameConstants::CREATURES_PER_TOWN && town->creatures.back().second.empty())
fortSize--;
if (fortSize == GameConstants::CREATURES_PER_TOWN)
return "TPCASTL7";
else
return "TPCASTL8";
}
CFortScreen::CFortScreen(const CGTownInstance * town):
CWindowObject(PLAYER_COLORED | BORDERED, getBgName(town))
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
ui32 fortSize = town->creatures.size();
if (fortSize > GameConstants::CREATURES_PER_TOWN && town->creatures.back().second.empty())
fortSize--;
const CBuilding *fortBuilding = town->town->buildings.at(BuildingID(town->fortLevel()+6));
title = new CLabel(400, 12, FONT_BIG, CENTER, Colors::WHITE, fortBuilding->Name());
std::string text = boost::str(boost::format(CGI->generaltexth->fcommands[6]) % fortBuilding->Name());
exit = new CButton(Point(748, 556), "TPMAGE1", CButton::tooltip(text), [&](){ close(); }, SDLK_RETURN);
exit->assignedKeys.insert(SDLK_ESCAPE);
std::vector<Point> positions =
{
Point(10, 22), Point(404, 22),
Point(10, 155), Point(404,155),
Point(10, 288), Point(404,288)
};
if (fortSize == GameConstants::CREATURES_PER_TOWN)
positions.push_back(Point(206,421));
else
{
positions.push_back(Point(10, 421));
positions.push_back(Point(404,421));
}
for (ui32 i=0; i<fortSize; i++)
{
BuildingID buildingID;
if (fortSize == GameConstants::CREATURES_PER_TOWN)
{
if (vstd::contains(town->builtBuildings, BuildingID::DWELL_UP_FIRST+i))
buildingID = BuildingID(BuildingID::DWELL_UP_FIRST+i);
else
buildingID = BuildingID(BuildingID::DWELL_FIRST+i);
}
else
buildingID = BuildingID::SPECIAL_3;
recAreas.push_back(new RecruitArea(positions[i].x, positions[i].y, town, i));
}
resdatabar = new CMinorResDataBar();
resdatabar->pos.x += pos.x;
resdatabar->pos.y += pos.y;
Rect barRect(4, 554, 740, 18);
statusBar = new CGStatusBar(new CPicture(*background, barRect, 4, 554, false));
}
void CFortScreen::creaturesChanged()
{
for (auto & elem : recAreas)
elem->creaturesChanged();
}
LabeledValue::LabeledValue(Rect size, std::string name, std::string descr, int min, int max)
{
pos.x+=size.x;
pos.y+=size.y;
pos.w = size.w;
pos.h = size.h;
init(name, descr, min, max);
}
LabeledValue::LabeledValue(Rect size, std::string name, std::string descr, int val)
{
pos.x+=size.x;
pos.y+=size.y;
pos.w = size.w;
pos.h = size.h;
init(name, descr, val, val);
}
void LabeledValue::init(std::string nameText, std::string descr, int min, int max)
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
addUsedEvents(HOVER);
hoverText = descr;
std::string valueText;
if (min && max)
{
valueText = boost::lexical_cast<std::string>(min);
if (min != max)
valueText += '-' + boost::lexical_cast<std::string>(max);
}
name = new CLabel(3, 0, FONT_SMALL, TOPLEFT, Colors::WHITE, nameText);
value = new CLabel(pos.w-3, pos.h-2, FONT_SMALL, BOTTOMRIGHT, Colors::WHITE, valueText);
}
void LabeledValue::hover(bool on)
{
if(on)
GH.statusbar->setText(hoverText);
else
{
GH.statusbar->clear();
parent->hovered = false;
}
}
const CCreature * CFortScreen::RecruitArea::getMyCreature()
{
if (!town->creatures.at(level).second.empty()) // built
return VLC->creh->creatures[town->creatures.at(level).second.back()];
if (!town->town->creatures.at(level).empty()) // there are creatures on this level
return VLC->creh->creatures[town->town->creatures.at(level).front()];
return nullptr;
}
const CBuilding * CFortScreen::RecruitArea::getMyBuilding()
{
BuildingID myID = BuildingID(BuildingID::DWELL_FIRST).advance(level);
if (level == GameConstants::CREATURES_PER_TOWN)
return town->town->buildings.at(BuildingID::PORTAL_OF_SUMMON);
if (!town->town->buildings.count(myID))
return nullptr;
const CBuilding * build = town->town->buildings.at(myID);
while (town->town->buildings.count(myID))
{
if (town->hasBuilt(myID))
build = town->town->buildings.at(myID);
myID.advance(GameConstants::CREATURES_PER_TOWN);
}
return build;
}
CFortScreen::RecruitArea::RecruitArea(int posX, int posY, const CGTownInstance *Town, int Level):
town(Town),
level(Level),
availableCount(nullptr)
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
pos.x +=posX;
pos.y +=posY;
pos.w = 386;
pos.h = 126;
if (!town->creatures[level].second.empty())
addUsedEvents(LCLICK | RCLICK | HOVER);//Activate only if dwelling is present
icons = new CPicture("TPCAINFO", 261, 3);
if (getMyBuilding() != nullptr)
{
new CAnimImage(town->town->clientInfo.buildingsIcons, getMyBuilding()->bid, 0, 4, 21);
new CLabel(78, 101, FONT_SMALL, CENTER, Colors::WHITE, getMyBuilding()->Name());
if (vstd::contains(town->builtBuildings, getMyBuilding()->bid))
{
ui32 available = town->creatures[level].first;
std::string availableText = CGI->generaltexth->allTexts[217]+ boost::lexical_cast<std::string>(available);
availableCount = new CLabel(78, 119, FONT_SMALL, CENTER, Colors::WHITE, availableText);
}
}
if (getMyCreature() != nullptr)
{
hoverText = boost::str(boost::format(CGI->generaltexth->tcommands[21]) % getMyCreature()->namePl);
new CCreaturePic(159, 4, getMyCreature(), false);
new CLabel(78, 11, FONT_SMALL, CENTER, Colors::WHITE, getMyCreature()->namePl);
Rect sizes(287, 4, 96, 18);
values.push_back(new LabeledValue(sizes, CGI->generaltexth->allTexts[190], CGI->generaltexth->fcommands[0], getMyCreature()->Attack()));
sizes.y+=20;
values.push_back(new LabeledValue(sizes, CGI->generaltexth->allTexts[191], CGI->generaltexth->fcommands[1], getMyCreature()->Defense()));
sizes.y+=21;
values.push_back(new LabeledValue(sizes, CGI->generaltexth->allTexts[199], CGI->generaltexth->fcommands[2], getMyCreature()->getMinDamage(), getMyCreature()->getMaxDamage()));
sizes.y+=20;
values.push_back(new LabeledValue(sizes, CGI->generaltexth->allTexts[388], CGI->generaltexth->fcommands[3], getMyCreature()->MaxHealth()));
sizes.y+=21;
values.push_back(new LabeledValue(sizes, CGI->generaltexth->allTexts[193], CGI->generaltexth->fcommands[4], getMyCreature()->valOfBonuses(Bonus::STACKS_SPEED)));
sizes.y+=20;
values.push_back(new LabeledValue(sizes, CGI->generaltexth->allTexts[194], CGI->generaltexth->fcommands[5], town->creatureGrowth(level)));
}
}
void CFortScreen::RecruitArea::hover(bool on)
{
if(on)
GH.statusbar->setText(hoverText);
else
GH.statusbar->clear();
}
void CFortScreen::RecruitArea::creaturesChanged()
{
if (availableCount)
{
std::string availableText = CGI->generaltexth->allTexts[217] +
boost::lexical_cast<std::string>(town->creatures[level].first);
availableCount->setText(availableText);
}
}
void CFortScreen::RecruitArea::clickLeft(tribool down, bool previousState)
{
if(!down && previousState)
LOCPLINT->castleInt->builds->enterDwelling(level);
}
void CFortScreen::RecruitArea::clickRight(tribool down, bool previousState)
{
clickLeft(down, false); //r-click does same as l-click - opens recr. window
}
CMageGuildScreen::CMageGuildScreen(CCastleInterface * owner,std::string imagem) :CWindowObject(BORDERED,imagem)
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
window = new CPicture(owner->town->town->clientInfo.guildWindow , 332, 76);
resdatabar = new CMinorResDataBar();
resdatabar->pos.x += pos.x;
resdatabar->pos.y += pos.y;
Rect barRect(7, 556, 737, 18);
statusBar = new CGStatusBar(new CPicture(*background, barRect, 7, 556, false));
exit = new CButton(Point(748, 556), "TPMAGE1.DEF", CButton::tooltip(CGI->generaltexth->allTexts[593]), [&](){ close(); }, SDLK_RETURN);
exit->assignedKeys.insert(SDLK_ESCAPE);
static const std::vector<std::vector<Point> > positions =
{
{Point(222,445), Point(312,445), Point(402,445), Point(520,445), Point(610,445), Point(700,445)},
{Point(48,53), Point(48,147), Point(48,241), Point(48,335), Point(48,429)},
{Point(570,82), Point(672,82), Point(570,157), Point(672,157)},
{Point(183,42), Point(183,148), Point(183,253)},
{Point(491,325), Point(591,325)}
};
for(size_t i=0; i<owner->town->town->mageLevel; i++)
{
size_t spellCount = owner->town->spellsAtLevel(i+1,false); //spell at level with -1 hmmm?
for(size_t j=0; j<spellCount; j++)
{
if(i<owner->town->mageGuildLevel() && owner->town->spells[i].size()>j)
spells.push_back( new Scroll(positions[i][j], CGI->spellh->objects[owner->town->spells[i][j]]));
else
new CAnimImage("TPMAGES.DEF", 1, 0, positions[i][j].x, positions[i][j].y);//closed scroll
}
}
}
CMageGuildScreen::Scroll::Scroll(Point position, const CSpell *Spell)
:spell(Spell)
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
addUsedEvents(LCLICK | RCLICK | HOVER);
pos += position;
image = new CAnimImage("SPELLSCR", spell->id);
pos = image->pos;
}
void CMageGuildScreen::Scroll::clickLeft(tribool down, bool previousState)
{
if(down)
LOCPLINT->showInfoDialog(spell->getLevelInfo(0).description, new CComponent(CComponent::spell,spell->id));
}
void CMageGuildScreen::Scroll::clickRight(tribool down, bool previousState)
{
if(down)
CRClickPopup::createAndPush(spell->getLevelInfo(0).description, new CComponent(CComponent::spell, spell->id));
}
void CMageGuildScreen::Scroll::hover(bool on)
{
if(on)
GH.statusbar->setText(spell->name);
else
GH.statusbar->clear();
}
CBlacksmithDialog::CBlacksmithDialog(bool possible, CreatureID creMachineID, ArtifactID aid, ObjectInstanceID hid):
CWindowObject(PLAYER_COLORED, "TPSMITH")
{
OBJ_CONSTRUCTION_CAPTURING_ALL;
statusBar = new CGStatusBar(new CPicture(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
animBG = new CPicture("TPSMITBK", 64, 50);
animBG->needRefresh = true;
const CCreature *creature = CGI->creh->creatures[creMachineID];
anim = new CCreatureAnim(64, 50, creature->animDefName, Rect());
anim->clipRect(113,125,200,150);
title = new CLabel(165, 28, FONT_BIG, CENTER, Colors::YELLOW,
boost::str(boost::format(CGI->generaltexth->allTexts[274]) % creature->nameSing));
costText = new CLabel(165, 218, FONT_MEDIUM, CENTER, Colors::WHITE, CGI->generaltexth->jktexts[43]);
costValue = new CLabel(165, 290, FONT_MEDIUM, CENTER, Colors::WHITE,
boost::lexical_cast<std::string>(CGI->arth->artifacts[aid]->price));
std::string text = boost::str(boost::format(CGI->generaltexth->allTexts[595]) % creature->nameSing);
buy = new CButton(Point(42, 312), "IBUY30.DEF", CButton::tooltip(text), [&](){ close(); }, SDLK_RETURN);
text = boost::str(boost::format(CGI->generaltexth->allTexts[596]) % creature->nameSing);
cancel = new CButton(Point(224, 312), "ICANCEL.DEF", CButton::tooltip(text), [&](){ close(); }, SDLK_ESCAPE);
if(possible)
buy->addCallback([=](){ LOCPLINT->cb->buyArtifact(LOCPLINT->cb->getHero(hid),aid); });
else
buy->block(true);
new CAnimImage("RESOURCE", 6, 0, 148, 244);
}<|fim▁end|> | |
<|file_name|>ProjCoordinate.java<|end_file_name|><|fim▁begin|>/*
Copyright 2006 Jerry Huxtable
Copyright 2009 Martin Davis
Copyright 2012 Antoine Gourlay
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.jproj;
import java.text.DecimalFormat;
/**
* Stores a the coordinates for a position
* defined relative to some {@link CoordinateReferenceSystem}.
* The coordinate is defined via X, Y, and optional Z ordinates.
* Provides utility methods for comparing the ordinates of two positions and
* for creating positions from Strings/storing positions as strings.
* <p>
* The primary use of this class is to represent coordinate
* values which are to be transformed
* by a {@link CoordinateTransform}.
*/
public class ProjCoordinate {
private static final String DECIMAL_FORMAT_PATTERN = "0.0###############";
// a DecimalFormat is not ThreadSafe, hence the ThreadLocal variable.
private static final ThreadLocal<DecimalFormat> DECIMAL_FORMAT = new ThreadLocal<DecimalFormat>() {
@Override
protected DecimalFormat initialValue() {
return new DecimalFormat(DECIMAL_FORMAT_PATTERN);
}
};
/**
* The X ordinate for this point.
* <p>
* Note: This member variable
* can be accessed directly. In the future this direct access should
* be replaced with getter and setter methods. This will require
* refactoring of the Proj4J code base.
*/
public double x;
/**
* The Y ordinate for this point.
* <p>
* Note: This member variable
* can be accessed directly. In the future this direct access should
* be replaced with getter and setter methods. This will require
* refactoring of the Proj4J code base.
*/
public double y;
/**
* The Z ordinate for this point.
* If this variable has the value <tt>Double.NaN</tt>
* then this coordinate does not have a Z value.
* <p>
* Note: This member variable
* can be accessed directly. In the future this direct access should
* be replaced with getter and setter methods. This will require
* refactoring of the Proj4J code base.
*/
public double z;
/**
* Creates a ProjCoordinate with default ordinate values.
*
*/
public ProjCoordinate() {
this(0.0, 0.0);
}
/**
* Creates a ProjCoordinate with values copied from the given coordinate object.
* @param pt a ProjCoordinate to copy
*/
public ProjCoordinate(ProjCoordinate pt) {
this(pt.x, pt.y, pt.z);
}
/**
* Creates a ProjCoordinate using the provided double parameters.
* The first double parameter is the x ordinate (or easting),
* the second double parameter is the y ordinate (or northing),
* and the third double parameter is the z ordinate (elevation or height).
*
* Valid values should be passed for all three (3) double parameters. If
* you want to create a horizontal-only point without a valid Z value, use
* the constructor defined in this class that only accepts two (2) double
* parameters.
*
* @param argX
* @param argY
* @param argZ
* @see #ProjCoordinate(double argX, double argY)
*/
public ProjCoordinate(double argX, double argY, double argZ) {
this.x = argX;
this.y = argY;
this.z = argZ;
}
/**
* Creates a ProjCoordinate using the provided double parameters.
* The first double parameter is the x ordinate (or easting),
* the second double parameter is the y ordinate (or northing).
* This constructor is used to create a "2D" point, so the Z ordinate
* is automatically set to Double.NaN.
* @param argX
* @param argY
*/
public ProjCoordinate(double argX, double argY) {
this.x = argX;
this.y = argY;
this.z = Double.NaN;
}
/**
* Create a ProjCoordinate by parsing a String in the same format as returned
* by the toString method defined by this class.
*
* @param argToParse the string to parse
*/
public ProjCoordinate(String argToParse) {
// Make sure the String starts with "ProjCoordinate: ".
if (!argToParse.startsWith("ProjCoordinate: ")) {
throw new IllegalArgumentException("The input string was not in the proper format.");
}
// 15 characters should cut out "ProjCoordinate: ".
String chomped = argToParse.substring(16);
// Get rid of the starting and ending square brackets.
String withoutFrontBracket = chomped.substring(1);
// Calc the position of the last bracket.
int length = withoutFrontBracket.length();
int positionOfCharBeforeLast = length - 2;
String withoutBackBracket = withoutFrontBracket.substring(0,
positionOfCharBeforeLast);
// We should be left with just the ordinate values as strings,
// separated by spaces. Split them into an array of Strings.
String[] parts = withoutBackBracket.split(" ");
// Get number of elements in Array. There should be two (2) elements
// or three (3) elements.
// If we don't have an array with two (2) or three (3) elements,
// then we need to throw an exception.
if (parts.length != 2 && parts.length != 3) {
throw new IllegalArgumentException("The input string was not in the proper format.");
}
// Convert strings to doubles.
this.x = "NaN".equals(parts[0]) ? Double.NaN : Double.parseDouble(parts[0]);
this.y = "NaN".equals(parts[1]) ? Double.NaN : Double.parseDouble(parts[1]);
// You might not always have a Z ordinate. If you do, set it.
if (parts.length == 3) {
this.z = "NaN".equals(parts[2]) ? Double.NaN : Double.parseDouble(parts[2]);
} else {
this.z = Double.NaN;
}
}
/**
* Sets the value of this coordinate to
* be equal to the given coordinate's ordinates.
*
* @param p the coordinate to copy
*/
<|fim▁hole|> this.z = p.z;
}
/**
* Returns a boolean indicating if the X ordinate value of the
* ProjCoordinate provided as an ordinate is equal to the X ordinate
* value of this ProjCoordinate. Because we are working with floating
* point numbers the ordinates are considered equal if the difference
* between them is less than the specified tolerance.
* @param argToCompare
* @param argTolerance
* @return
*/
public boolean areXOrdinatesEqual(ProjCoordinate argToCompare, double argTolerance) {
// Subtract the x ordinate values and then see if the difference
// between them is less than the specified tolerance. If the difference
// is less, return true.
return argToCompare.x - this.x <= argTolerance;
}
/**
* Returns a boolean indicating if the Y ordinate value of the
* ProjCoordinate provided as an ordinate is equal to the Y ordinate
* value of this ProjCoordinate. Because we are working with floating
* point numbers the ordinates are considered equal if the difference
* between them is less than the specified tolerance.
* @param argToCompare
* @param argTolerance
* @return
*/
public boolean areYOrdinatesEqual(ProjCoordinate argToCompare, double argTolerance) {
// Subtract the y ordinate values and then see if the difference
// between them is less than the specified tolerance. If the difference
// is less, return true.
return argToCompare.y - this.y <= argTolerance;
}
/**
* Returns a boolean indicating if the Z ordinate value of the
* ProjCoordinate provided as an ordinate is equal to the Z ordinate
* value of this ProjCoordinate. Because we are working with floating
* point numbers the ordinates are considered equal if the difference
* between them is less than the specified tolerance.
*
* If both Z ordinate values are Double.NaN this method will return
* true. If one Z ordinate value is a valid double value and one is
* Double.Nan, this method will return false.
* @param argToCompare
* @param argTolerance
* @return
*/
public boolean areZOrdinatesEqual(ProjCoordinate argToCompare, double argTolerance) {
// We have to handle Double.NaN values here, because not every
// ProjCoordinate will have a valid Z Value.
if (Double.isNaN(z)) {
return Double.isNaN(argToCompare.z);
// if true, both the z ordinate values are Double.Nan.
// else, We've got one z ordinate with a valid value and one with
// a Double.NaN value.
} // We have a valid z ordinate value in this ProjCoordinate object.
else {
if (Double.isNaN(argToCompare.z)) {
// We've got one z ordinate with a valid value and one with
// a Double.NaN value. Return false.
return false;
}
// If we get to this point in the method execution, we have to
// z ordinates with valid values, and we need to do a regular
// comparison. This is done in the remainder of the method.
}
// Subtract the z ordinate values and then see if the difference
// between them is less than the specified tolerance. If the difference
// is less, return true.
return argToCompare.z - this.z <= argTolerance;
}
/**
* Returns a string representing the ProjPoint in the format:
* <tt>ProjCoordinate[X Y Z]</tt>.
* <p>
* Example:
* <pre>
* ProjCoordinate[6241.11 5218.25 12.3]
* </pre>
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ProjCoordinate[");
if (Double.isNaN(x)) {
builder.append("NaN");
} else {
builder.append(x);
}
builder.append(" ");
if (Double.isNaN(x)) {
builder.append("NaN");
} else {
builder.append(y);
}
builder.append(" ");
if (Double.isNaN(x)) {
builder.append("NaN");
} else {
builder.append(z);
}
builder.append("]");
return builder.toString();
}
/**
* Returns a string representing the ProjPoint in the format:
* <tt>[X Y]</tt>
* or <tt>[X, Y, Z]</tt>.
* Z is not displayed if it is NaN.
* <p>
* Example:
* <pre>
* [6241.11, 5218.25, 12.3]
* </pre>
* @return
*/
public String toShortString() {
StringBuilder builder = new StringBuilder();
builder.append("[");
if (Double.isNaN(x)) {
builder.append("NaN");
} else {
builder.append(DECIMAL_FORMAT.get().format(x));
}
builder.append(", ");
if (Double.isNaN(y)) {
builder.append("NaN");
} else {
builder.append(DECIMAL_FORMAT.get().format(y));
}
if (!Double.isNaN(z)) {
builder.append(", ");
builder.append(this.z);
}
builder.append("]");
return builder.toString();
}
public boolean hasValidZOrdinate() {
return !Double.isNaN(z);
}
/**
* Indicates if this ProjCoordinate has valid X ordinate and Y ordinate
* values. Values are considered invalid if they are Double.NaN or
* positive/negative infinity.
* @return
*/
public boolean hasValidXandYOrdinates() {
return !Double.isNaN(x) && !Double.isInfinite(x) && !Double.isNaN(y) && !Double.isInfinite(y);
}
}<|fim▁end|> | public void setValue(ProjCoordinate p) {
this.x = p.x;
this.y = p.y;
|
<|file_name|>compat.py<|end_file_name|><|fim▁begin|>"""Python 2/3 compatibility definitions.
<|fim▁hole|>"""
import sys
if sys.version_info >= (3, 0):
PYTHON3 = True
from io import StringIO
def ensure_not_unicode(obj):
return obj
else:
PYTHON3 = False
from StringIO import StringIO # noqa
def ensure_not_unicode(obj):
"""Return obj. If it's a unicode string, convert it to str first.
Pydoc functions simply don't find anything for unicode
strings. No idea why.
"""
if isinstance(obj, unicode):
return obj.encode("utf-8")
else:
return obj<|fim▁end|> | These are used by the rest of Elpy to keep compatibility definitions
in one place.
|
<|file_name|>newtypes.rs<|end_file_name|><|fim▁begin|>//! Newtype structures.
//!
//! Mostly implementation of a fixed point Km representation.
use std::ops::{Add, Sub, Mul, Div};
use num::Zero;
use std::f64;
/// Distance measure in kilometers
#[derive(Clone, Copy, PartialEq, Debug, Eq, PartialOrd, Ord)]
pub struct Km(u64);
const POINT : usize = 32;
/// Can be cast to a f64
pub trait ToF64 {
/// Cast
fn to_f64(&self) -> f64;
}
impl Km {
/// Create a new Km struct, or Km::zero if something goes wrong (NaN, Out of Bounds).
pub fn from_f64(f: f64) -> Km {
Km((f * (1u64<<POINT) as f64) as u64)
}
/// Create a new Km struct, or None if something goes wrong (NaN, Out of Bounds).
///
/// # Examples
/// ```
/// use newtypes::Km;
/// use std::u32;
/// let valid = Km::from_f64_checked(0.0);
/// assert!(valid.is_some());
/// let invalid = Km::from_f64_checked(u32::MAX as f64 + 1.0);
/// assert_eq!(invalid, None, "Failed at 1");
/// let invalid = Km::from_f64_checked(-1.0);
/// assert_eq!(invalid, None, "Failed at 2");
/// ```
pub fn from_f64_checked(f : f64) -> Option<Km> {
// Beware rounding errors!
if f >= Km(u64::max_value()).to_f64() {
None
} else if f < Km(u64::min_value()).to_f64() {
None
} else {Some(Km::from_f64(f))}
}<|fim▁hole|>impl ToF64 for Km {
fn to_f64(&self) -> f64 {
self.0 as f64/((1u64 << POINT) as f64)
}
}
impl ToF64 for Option<Km> {
fn to_f64(&self) -> f64 {
self.map(|Km(u)| u as f64/((1u64 << POINT) as f64)).unwrap_or(f64::INFINITY)
}
}
impl Add<Km> for Km {
type Output = Km;
fn add(self, other: Km) -> Km {
Km(self.0 + other.0)
}
}
impl Sub<Km> for Km {
type Output = Km;
fn sub(self, other: Km) -> Km {
Km(self.0 - other.0)
}
}
impl Mul<f64> for Km {
type Output = Km;
fn mul(self, other: f64) -> Km {
Km::from_f64(self.to_f64() * other)
}
}
impl Div<Km> for Km {
type Output = f64;
fn div(self, other: Km) -> f64 {
(self.0 as f64 / other.0 as f64)
}
}
impl Div<Option<Km>> for Km {
type Output = f64;
fn div(self, other: Option<Km>) -> f64 {
other.map(|o| (self.0 as f64 / o.0 as f64))
.unwrap_or(0.0)
}
}
impl Zero for Km {
fn zero() -> Km {
Km(0)
}
fn is_zero(&self) -> bool {
self.0 == 0
}
}
use std::fmt;
impl fmt::Display for Km {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
self.to_f64().fmt(fmt)?;
fmt.write_str(" Km")
}
}<|fim▁end|> | }
|
<|file_name|>gen_figure_rst.py<|end_file_name|><|fim▁begin|>import os
from example_builder import ExampleBuilder
RST_TEMPLATE = """
.. _%(sphinx_tag)s:
%(docstring)s
%(image_list)s
.. raw:: html
<div class="toggle_trigger"><a href="#">
**Code output:**
.. raw:: html
</a></div>
<div class="toggle_container">
.. literalinclude:: %(stdout)s
.. raw:: html
</div>
<div class="toggle_trigger" id="start_open"><a href="#">
**Python source code:**
.. raw:: html
</a></div>
<div class="toggle_container">
.. literalinclude:: %(fname)s
:lines: %(end_line)s-
.. raw:: html
</div>
<div align="right">
:download:`[download source: %(fname)s] <%(fname)s>`
.. raw:: html
</div>
"""
def main(app):
target_dir = os.path.join(app.builder.srcdir, 'book_figures')
source_dir = os.path.abspath(app.builder.srcdir + '/../' + 'examples')
try:
plot_gallery = eval(app.builder.config.plot_gallery)
except TypeError:
plot_gallery = bool(app.builder.config.plot_gallery)
if not os.path.exists(source_dir):
os.makedirs(source_dir)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
EB = ExampleBuilder(source_dir, target_dir,
execute_files=plot_gallery,
contents_file='contents.txt',
dir_info_file='README.rst',
dir_footer_file='FOOTER.rst',
sphinx_tag_base='book_fig',<|fim▁hole|> EB.run()
def setup(app):
app.connect('builder-inited', main)
#app.add_config_value('plot_gallery', True, 'html')<|fim▁end|> | template_example=RST_TEMPLATE) |
<|file_name|>quasiquote.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 Pierre Talbot (IRCAM)
// 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.
use rust;
use rust::Token as rtok;
use rust::{TokenAndSpan, Span, token_to_string};
use compiler::*;
use std::collections::hash_map::HashMap;
pub struct Quasiquote<'a, 'b:'a, 'c, C> where C: 'c
{
cx: &'a rust::ExtCtxt<'b>,
compiler: &'c mut C,
tokens: Vec<TokenAndSpan>,
current_idx: usize,
unquoted_tokens: Vec<TokenAndSpan>
}
impl<'a, 'b, 'c, C> Quasiquote<'a, 'b, 'c, C> where
C: 'c + Compiler
{
pub fn compile(cx: &'a rust::ExtCtxt<'b>, tokens: Vec<TokenAndSpan>, compiler: &'c mut C)
-> Vec<TokenAndSpan>
{
let mut quasiquote = Quasiquote::new(cx, compiler, tokens);
quasiquote.unquote_all();
quasiquote.unquoted_tokens
}
fn new(cx: &'a rust::ExtCtxt<'b>, compiler: &'c mut C, tokens: Vec<TokenAndSpan>)
-> Quasiquote<'a, 'b, 'c, C>
{
Quasiquote {
cx: cx,
compiler: compiler,
tokens: tokens,
current_idx: 0,
unquoted_tokens: vec![]
}
}
fn unquote_all(&mut self) {
while !self.at_end() {
match self.peek_unquote() {
None => {
let tok = self.token();
self.unquoted_tokens.push(tok);
}
Some(d) => {
self.unquote(d);
}
}
self.bump(1);
}
}
fn bump(&mut self, n: usize) {
self.current_idx = self.current_idx + n;
}
fn at_end(&self) -> bool {
self.current_idx >= self.tokens.len()
}
fn token(&self) -> TokenAndSpan {
self.tokens[self.current_idx].clone()
}
fn peek_unquote(&self) -> Option<rust::DelimToken> {
if self.current_idx + 1 < self.tokens.len()
&& self.tokens[self.current_idx].tok == rtok::Pound
{
match self.tokens[self.current_idx + 1].tok {
rtok::OpenDelim(d@rust::DelimToken::Paren) |
rtok::OpenDelim(d@rust::DelimToken::Brace) => Some(d),
_ => None
}
}
else {
None
}
}
fn unquote(&mut self, delim: rust::DelimToken) {
let pound_idx = self.current_idx;
let mut opened_delims = 1isize;
self.bump(2);<|fim▁hole|> while !self.at_end()
&& self.still_in_quote(delim, opened_delims)
{
opened_delims = opened_delims + self.count_delim(delim);
self.bump(1);
}
if self.at_end() || opened_delims != 1 {
self.cx.span_fatal(self.tokens[pound_idx + 1].sp,
"unclosed delimiter of anynomous macro.");
}
let unquote = self.make_unquote(pound_idx);
self.compile_unquote(delim, unquote);
}
fn still_in_quote(&self, delim: rust::DelimToken,
opened_delims: isize) -> bool
{
opened_delims != 1
|| self.token().tok != rtok::CloseDelim(delim)
}
fn count_delim(&self, delim: rust::DelimToken) -> isize {
match self.token().tok {
rtok::CloseDelim(d) if d == delim => -1,
rtok::OpenDelim(d) if d == delim => 1,
_ => 0
}
}
fn compile_unquote(&mut self, delim: rust::DelimToken, unquote: Unquote) {
let span = unquote.span;
let non_terminal =
match delim {
rust::DelimToken::Paren => {
rust::Nonterminal::NtExpr(self.compiler.compile_expr(unquote))
}
rust::DelimToken::Brace => {
rust::Nonterminal::NtBlock(self.compiler.compile_block(unquote))
}
d => panic!("compile_unquote: unrecognized delimiter {:?}", d)
};
let interpolated_tok = rtok::Interpolated(non_terminal);
let unquoted_tok = TokenAndSpan {
tok: interpolated_tok,
sp: span
};
self.unquoted_tokens.push(unquoted_tok);
}
fn make_unquote(&self, start_idx: usize) -> Unquote {
let mut code = String::new();
let mut text_to_ident = HashMap::new();
for idx in (start_idx+2)..self.current_idx {
if let rtok::Ident(id) = self.tokens[idx].tok {
text_to_ident.insert(format!("{}", id), id);
}
code.extend(token_to_string(&self.tokens[idx].tok).chars());
code.push(' ');
}
Unquote {
text_to_ident: text_to_ident,
code: code,
span: self.span_from(start_idx)
}
}
fn span_from(&self, start_idx: usize) -> Span {
let mut span = self.tokens[start_idx].sp;
span.hi = self.token().sp.hi;
span
}
}<|fim▁end|> | |
<|file_name|>test_exon_id.py<|end_file_name|><|fim▁begin|>"""
Exon IDs of the TP53 gene and one of its transcripts (TP53-026) were copied
from the Ensembl website, make sure same IDs are found by pyensembl.
"""
from __future__ import absolute_import
from pyensembl import cached_release
ensembl = cached_release(77)
# all exons associated with TP53 gene in Ensembl release 77
TP53_EXON_IDS_RELEASE_77 = [
'ENSE00002337729', 'ENSE00002419584',
'ENSE00003625790', 'ENSE00003518480',
'ENSE00003723991', 'ENSE00003712342',
'ENSE00001657961', 'ENSE00003725258',
'ENSE00003740946', 'ENSE00002204316',
'ENSE00002064269', 'ENSE00003750554',
'ENSE00003634848', 'ENSE00003492844',
'ENSE00003735852', 'ENSE00003545950',
'ENSE00003605891', 'ENSE00002051192',
'ENSE00002084733', 'ENSE00003726882',
'ENSE00001146308', 'ENSE00002667911',
'ENSE00003752869', 'ENSE00003739898',
'ENSE00003753508', 'ENSE00002034209',
'ENSE00002030826', 'ENSE00001596491',
'ENSE00002037735', 'ENSE00003736616',
'ENSE00002672443', 'ENSE00002226620',
'ENSE00003715195', 'ENSE00003750794',
'ENSE00003745267', 'ENSE00003746220',
'ENSE00003656695', 'ENSE00003669712',
'ENSE00002051873', 'ENSE00002048269',<|fim▁hole|> 'ENSE00002670535', 'ENSE00002677565',
'ENSE00003532881', 'ENSE00003520683',
'ENSE00002076714', 'ENSE00002062958',
'ENSE00002073243', 'ENSE00003670707',
'ENSE00002065802', 'ENSE00002362269'
]
def test_exon_ids_of_gene_id():
"""
test_exon_ids_of_gene_id: Ensure that gene_id ENSG00000141510 (name=TP53),
has all the same exon IDs found on the Ensembl website.
"""
exon_ids = ensembl.exon_ids_of_gene_id('ENSG00000141510')
assert len(exon_ids) == len(TP53_EXON_IDS_RELEASE_77), \
"Wrong number of exons, expected %d but got %d (n_distinct=%d)" % (
len(TP53_EXON_IDS_RELEASE_77),
len(exon_ids),
len(set(exon_ids)))
assert all(exon_id in TP53_EXON_IDS_RELEASE_77 for exon_id in exon_ids)
def test_exon_ids_of_gene_name():
"""
test_exon_ids_of_gene_name: Ensure that TP53 has the same exon IDs found
on the Ensembl website.
"""
exon_ids = ensembl.exon_ids_of_gene_name("TP53")
assert len(exon_ids) == len(TP53_EXON_IDS_RELEASE_77), \
"Wrong number of exons, expected %d but got %d (n_distinct=%d)" % (
len(TP53_EXON_IDS_RELEASE_77),
len(exon_ids),
len(set(exon_ids)))
assert all(exon_id in TP53_EXON_IDS_RELEASE_77 for exon_id in exon_ids)
# Exon IDs of transcript TP53-026
TP53_TRANSCRIPT_26_EXON_IDS_RELEASE_77 = [
'ENSE00002064269',
'ENSE00003723991',
'ENSE00003712342',
'ENSE00003725258',
'ENSE00003740946',
'ENSE00003750554',
'ENSE00003634848',
'ENSE00003492844'
]
def test_exon_ids_of_transcript_name():
"""
test_exon_ids_of_transcript_name : Look up exon IDs of transcript TP53-026
by name and ensure that the exon IDs match what we find on Ensembl's website
for release 77
"""
exon_ids = ensembl.exon_ids_of_transcript_name("TP53-026")
assert len(exon_ids) == len(TP53_TRANSCRIPT_26_EXON_IDS_RELEASE_77), \
"Expected %d exons, got %d" % (
len(TP53_TRANSCRIPT_26_EXON_IDS_RELEASE_77),
len(exon_ids))
assert all(
exon_id in TP53_TRANSCRIPT_26_EXON_IDS_RELEASE_77
for exon_id in exon_ids)
def exon_ids_of_transcript_id():
"""
exon_ids_of_transcript_id : Look up exon IDs of transcript
ENST00000610623 (name: TP53-026) by its ID and make sure they match
what we find on the Ensembl website.
"""
exon_ids = ensembl.exon_ids_of_transcript_id("ENST00000610623")
assert len(exon_ids) == len(TP53_TRANSCRIPT_26_EXON_IDS_RELEASE_77), \
"Expected %d exons, got %d" % (
len(TP53_TRANSCRIPT_26_EXON_IDS_RELEASE_77),
len(exon_ids))
assert all(
exon_id in TP53_TRANSCRIPT_26_EXON_IDS_RELEASE_77
for exon_id in exon_ids)<|fim▁end|> | |
<|file_name|>e2e-lint.ts<|end_file_name|><|fim▁begin|>/**
* Gulp tasks for linting modules.
*/
import * as gulp from "gulp";<|fim▁hole|>
// Generated by UniteJS<|fim▁end|> |
gulp.task("e2e-lint", () => {
}); |
<|file_name|>DirectReadWriteFloatBufferAdapter.java<|end_file_name|><|fim▁begin|>/* 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 java.nio;
import com.google.gwt.typedarrays.shared.ArrayBufferView;
import com.google.gwt.typedarrays.shared.Float32Array;
import com.google.gwt.typedarrays.shared.TypedArrays;
/** This class wraps a byte buffer to be a float buffer.
* <p>
* Implementation notice:
* <ul>
* <li>After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the
* adapter any more.</li>
* <li>The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position
* and limit.</li>
* </ul>
* </p> */
final class DirectReadWriteFloatBufferAdapter extends FloatBuffer implements HasArrayBufferView {
// implements DirectBuffer {
static FloatBuffer wrap (DirectReadWriteByteBuffer byteBuffer) {
return new DirectReadWriteFloatBufferAdapter((DirectReadWriteByteBuffer)byteBuffer.slice());
}
private final DirectReadWriteByteBuffer byteBuffer;
private final Float32Array floatArray;
DirectReadWriteFloatBufferAdapter (DirectReadWriteByteBuffer byteBuffer) {
super((byteBuffer.capacity() >> 2));
this.byteBuffer = byteBuffer;
this.byteBuffer.clear();
this.floatArray = TypedArrays.createFloat32Array(byteBuffer.byteArray.buffer(), byteBuffer.byteArray.byteOffset(), capacity);
}
// TODO(haustein) This will be slow
@Override
public FloatBuffer asReadOnlyBuffer () {
DirectReadOnlyFloatBufferAdapter buf = new DirectReadOnlyFloatBufferAdapter(byteBuffer);
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public FloatBuffer compact () {
byteBuffer.limit(limit << 2);
byteBuffer.position(position << 2);
byteBuffer.compact();
byteBuffer.clear();
position = limit - position;
limit = capacity;
mark = UNSET_MARK;
return this;
}
@Override
public FloatBuffer duplicate () {
DirectReadWriteFloatBufferAdapter buf = new DirectReadWriteFloatBufferAdapter(
(DirectReadWriteByteBuffer)byteBuffer.duplicate());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public float get () {
// if (position == limit) {
// throw new BufferUnderflowException();
// }
return floatArray.get(position++);
}
@Override
public float get (int index) {
// if (index < 0 || index >= limit) {
// throw new IndexOutOfBoundsException();
// }
return floatArray.get(index);
}
@Override
public boolean isDirect () {
return true;
}
@Override
public boolean isReadOnly () {
return false;
}
@Override
public ByteOrder order () {
return byteBuffer.order();
}
@Override
protected float[] protectedArray () {
throw new UnsupportedOperationException();
}
@Override
protected int protectedArrayOffset () {
throw new UnsupportedOperationException();
}
@Override
protected boolean protectedHasArray () {
return false;
}
@Override
public FloatBuffer put (float c) {
// if (position == limit) {
// throw new BufferOverflowException();
// }
floatArray.set(position++, c);<|fim▁hole|> }
@Override
public FloatBuffer put (int index, float c) {
// if (index < 0 || index >= limit) {
// throw new IndexOutOfBoundsException();
// }
floatArray.set(index, c);
return this;
}
@Override
public FloatBuffer slice () {
byteBuffer.limit(limit << 2);
byteBuffer.position(position << 2);
FloatBuffer result = new DirectReadWriteFloatBufferAdapter((DirectReadWriteByteBuffer)byteBuffer.slice());
byteBuffer.clear();
return result;
}
public ArrayBufferView getTypedArray () {
return floatArray;
}
public int getElementSize () {
return 4;
}
}<|fim▁end|> | return this; |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>from setuptools import setup
setup(name='decision_tree',
version='0.04',
description='Practice implementation of a classification decision tree',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
keywords='classification decision tree machine learning random forest',
url='https://github.com/metjush/decision_tree',<|fim▁hole|> author_email='[email protected]',
license='MIT',
packages=['decision_tree'],
install_requires=[
'numpy',
'sklearn'
],
include_package_data=True,
zip_safe=False)<|fim▁end|> | author='metjush', |
<|file_name|>DruidJdbcConfig.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2015-2016 the original author or 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 org.nanoframework.orm.jdbc.config;
import java.util.Properties;
import org.nanoframework.commons.util.Assert;
/**
* @author yanghe
* @since 1.2
*/
public class DruidJdbcConfig extends JdbcConfig {
private static final long serialVersionUID = -565746278164485851L;
@Property("druid.initialSize")
private Integer initialSize;
@Property("druid.maxActive")
private Integer maxActive;
@Property("druid.maxIdle")
private Integer maxIdle;
@Property("druid.minIdle")
private Integer minIdle;
@Property("druid.maxWait")
private Long maxWait;
@Property("druid.removeAbandoned")
private Boolean removeAbandoned;
@Property("druid.removeAbandonedTimeout")
private Integer removeAbandonedTimeout;
@Property("druid.timeBetweenEvictionRunsMillis")
private Long timeBetweenEvictionRunsMillis;
@Property("druid.minEvictableIdleTimeMillis")
private Long minEvictableIdleTimeMillis;
@Property("druid.validationQuery")
private String validationQuery;
@Property("druid.testWhileIdle")
private Boolean testWhileIdle;
@Property("druid.testOnBorrow")<|fim▁hole|> private Boolean testOnBorrow;
@Property("druid.testOnReturn")
private Boolean testOnReturn;
@Property("druid.poolPreparedStatements")
private Boolean poolPreparedStatements;
@Property("druid.maxPoolPreparedStatementPerConnectionSize")
private Integer maxPoolPreparedStatementPerConnectionSize;
@Property("druid.filters")
private String filters;
public DruidJdbcConfig() {
}
public DruidJdbcConfig(Properties properties) {
Assert.notNull(properties);
this.setProperties(properties);
}
public Integer getInitialSize() {
return initialSize;
}
public void setInitialSize(Integer initialSize) {
this.initialSize = initialSize;
}
public Integer getMaxActive() {
return maxActive;
}
public void setMaxActive(Integer maxActive) {
this.maxActive = maxActive;
}
public Integer getMaxIdle() {
return maxIdle;
}
public void setMaxIdle(Integer maxIdle) {
this.maxIdle = maxIdle;
}
public Integer getMinIdle() {
return minIdle;
}
public void setMinIdle(Integer minIdle) {
this.minIdle = minIdle;
}
public Long getMaxWait() {
return maxWait;
}
public void setMaxWait(Long maxWait) {
this.maxWait = maxWait;
}
public Boolean getRemoveAbandoned() {
return removeAbandoned;
}
public void setRemoveAbandoned(Boolean removeAbandoned) {
this.removeAbandoned = removeAbandoned;
}
public Integer getRemoveAbandonedTimeout() {
return removeAbandonedTimeout;
}
public void setRemoveAbandonedTimeout(Integer removeAbandonedTimeout) {
this.removeAbandonedTimeout = removeAbandonedTimeout;
}
public Long getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public void setTimeBetweenEvictionRunsMillis(Long timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public Long getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(Long minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public Boolean getTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(Boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public Boolean getTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(Boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public Boolean getTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(Boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public Boolean getPoolPreparedStatements() {
return poolPreparedStatements;
}
public void setPoolPreparedStatements(Boolean poolPreparedStatements) {
this.poolPreparedStatements = poolPreparedStatements;
}
public Integer getMaxPoolPreparedStatementPerConnectionSize() {
return maxPoolPreparedStatementPerConnectionSize;
}
public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) {
this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
}
public String getFilters() {
return filters;
}
public void setFilters(String filters) {
this.filters = filters;
}
}<|fim▁end|> | |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
<|fim▁hole|>import platform
import asyncio
import json
from base.logger import LOG
def singleton(cls, *args, **kw):
instances = {}
def _singleton(*args, **kw):
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return _singleton
def func_coroutine(func):
"""make the decorated function run in EventLoop
"""
def wrapper(*args, **kwargs):
LOG.debug("In func_coroutine: before call ")
LOG.debug("function name is : " + func.__name__)
APP_EVENT_LOOP = asyncio.get_event_loop()
APP_EVENT_LOOP.call_soon(func, *args)
LOG.debug("In func_coroutine: after call ")
return wrapper
def write_json_into_file(data_json, filepath):
try:
with open(filepath, "w") as f:
data_str = json.dumps(data_json, indent=4)
f.write(data_str)
return True
except Exception as e:
LOG.error(str(e))
LOG.error("Write json into file failed")
return False<|fim▁end|> | |
<|file_name|>Types.hpp<|end_file_name|><|fim▁begin|>/**<|fim▁hole|> * @file Types.hpp
* @author Adam Wolniakowski
* @date 2015-07-14
*/
#pragma once
#include <rwlibs/task/GraspTask.hpp>
namespace gripperz {
namespace grasps {
//! A type for grasp set
typedef rwlibs::task::GraspTask::Ptr Grasps;
//! Copies grasp set
Grasps copyGrasps(const Grasps tasks, bool onlySuccesses = false);
} /* grasps */
} /* gripperz */<|fim▁end|> | |
<|file_name|>test_chapter1_solutions.py<|end_file_name|><|fim▁begin|><|fim▁hole|>Created on 30 de set de 2017
@author: fernando
'''
import unittest
from chapter1.solution_1_1 import has_all_unique_characters
from chapter1.solution_1_4 import are_anagrams
class Test(unittest.TestCase):
def testSolution1_1(self):
result = has_all_unique_characters("cafdgbc")
assert(result == False)
result = has_all_unique_characters("adfegbc")
assert(result)
def testSolution1_4(self):
result = are_anagrams('ovo', 'voo')
assert(result)
result = are_anagrams('voo', 'vo')
assert(result == False)
result = are_anagrams('ovo', 'novo')
assert(result == False)
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testSolution1_1']
unittest.main()<|fim▁end|> | ''' |
<|file_name|>LiveWatchViewModel.ts<|end_file_name|><|fim▁begin|>"use strict";<|fim▁hole|>import { BroadCastApiModelInterface } from '../../../Model/Api/BroadCastApiModel';
import { LiveWatchStopStreamApiModelInterface } from '../../../Model/Api/Live/Watch/LiveWatchStopStreamApiModel';
import { LiveConfigEnableApiModelInterface } from '../../../Model/Api/Live/LiveConfigEnableApiModel';
/**
* LiveWatch の ViewModel
*/
class LiveWatchViewModel extends ViewModel {
private broadCastApiModel: BroadCastApiModelInterface;
private stopStreamApiModel: LiveWatchStopStreamApiModelInterface;
private liveConfigEnableApiModel: LiveConfigEnableApiModelInterface;
public tabStatus = false;
constructor(
_broadCast: BroadCastApiModelInterface,
_stopStreamApiModel: LiveWatchStopStreamApiModelInterface,
_liveConfigEnableApiModel: LiveConfigEnableApiModelInterface
) {
super();
this.broadCastApiModel = _broadCast;
this.stopStreamApiModel = _stopStreamApiModel;
this.liveConfigEnableApiModel = _liveConfigEnableApiModel;
}
//初期化処理
public init(): void {
//tab の状態を初期化する
this.tabStatus = false;
}
//有効な放送波を返す
public getBroadCastList(): string[] {
return this.broadCastApiModel.getList();
}
/**
* stream 停止
* @param streamId stream id
*/
public stopStream(streamId: number): void {
this.stopStreamApiModel.update(streamId);
}
/**
* live stream が有効か返す true: 有効, false: 無効
*/
public liveIsEnable(): boolean {
return this.liveConfigEnableApiModel.getHLSLive() || ( this.liveConfigEnableApiModel.getHttpPCLive() && m.route.param("stream") == null);
}
}
export default LiveWatchViewModel;<|fim▁end|> |
import * as m from 'mithril';
import ViewModel from '../../ViewModel'; |
<|file_name|>Media.tsx<|end_file_name|><|fim▁begin|>import React from 'react';
import { FileInfo } from '../../interfaces';
interface MediaProps {<|fim▁hole|>export const Media = ({ file }: MediaProps) => {
if (file.type.startsWith('image')) {
return <img src={file.data} className="img-fluid rounded-top" />;
}
if (file.type.startsWith('video')) {
return (
<video autoPlay={false} controls className="mw-full">
<source src={file.data} />
</video>
);
}
return <React.Fragment></React.Fragment>;
};<|fim▁end|> | file: FileInfo;
}
|
<|file_name|>ObservableBinding.ts<|end_file_name|><|fim▁begin|>import binding = require('../interfaces');
import Binding = require('../Binding');
import core = require('../../interfaces');
/**
* The ObservableBinding class enables binding to {@link module:mayhem/Observable} objects.
*/
class ObservableBinding<T> extends Binding<T> {
static test(kwArgs:binding.IBindingArguments):boolean {
var object = <core.IObservable> kwArgs.object;
return object != null && typeof object.get === 'function' &&<|fim▁hole|> typeof kwArgs.path === 'string';
}
/**
* The watch handle for the bound object.
*/
private _handle:IHandle;
/**
* The object containing the final property to be bound.
*/
private _object:core.IObservable;
/**
* The key for the final property to be bound.
*/
private _property:string;
constructor(kwArgs:binding.IBindingArguments) {
super(kwArgs);
var object = this._object = <core.IObservable> kwArgs.object;
this._property = kwArgs.path;
var self = this;
this._handle = object.observe(kwArgs.path, function (newValue:T, oldValue:T):void {
self.notify({ oldValue: oldValue, value: newValue });
});
}
destroy():void {
super.destroy();
this._handle.remove();
this._handle = this._object = null;
}
get():T {
return this._object ? <any> this._object.get(this._property) : undefined;
}
getObject():{} {
return this._object;
}
set(value:T):void {
this._object && this._object.set(this._property, value);
}
}
export = ObservableBinding;<|fim▁end|> | typeof object.set === 'function' &&
typeof object.observe === 'function' && |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, MapR Technologies
#
# 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<|fim▁hole|># Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from sahara.i18n import _
import sahara.plugins.mapr.versions.version_handler_factory as vhf
import sahara.plugins.provisioning as p
class MapRPlugin(p.ProvisioningPluginBase):
title = 'MapR Hadoop Distribution'
description = _('The MapR Distribution provides a full Hadoop stack that'
' includes the MapR File System (MapR-FS), MapReduce,'
' a complete Hadoop ecosystem, and the MapR Control System'
' user interface')
def _get_handler(self, hadoop_version):
return vhf.VersionHandlerFactory.get().get_handler(hadoop_version)
def get_title(self):
return MapRPlugin.title
def get_description(self):
return MapRPlugin.description
def get_versions(self):
return vhf.VersionHandlerFactory.get().get_versions()
def get_node_processes(self, hadoop_version):
return self._get_handler(hadoop_version).get_node_processes()
def get_configs(self, hadoop_version):
return self._get_handler(hadoop_version).get_configs()
def configure_cluster(self, cluster):
self._get_handler(cluster.hadoop_version).configure_cluster(cluster)
def start_cluster(self, cluster):
self._get_handler(cluster.hadoop_version).start_cluster(cluster)
def validate(self, cluster):
self._get_handler(cluster.hadoop_version).validate(cluster)
def validate_scaling(self, cluster, existing, additional):
v_handler = self._get_handler(cluster.hadoop_version)
v_handler.validate_scaling(cluster, existing, additional)
def scale_cluster(self, cluster, instances):
v_handler = self._get_handler(cluster.hadoop_version)
v_handler.scale_cluster(cluster, instances)
def decommission_nodes(self, cluster, instances):
v_handler = self._get_handler(cluster.hadoop_version)
v_handler.decommission_nodes(cluster, instances)
def get_edp_engine(self, cluster, job_type):
v_handler = self._get_handler(cluster.hadoop_version)
return v_handler.get_edp_engine(cluster, job_type)
def get_open_ports(self, node_group):
v_handler = self._get_handler(node_group.cluster.hadoop_version)
return v_handler.get_open_ports(node_group)<|fim▁end|> | # a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# |
<|file_name|>kudos-notification-transaction.service.js<|end_file_name|><|fim▁begin|>(function () {
"use strict";
angular.module("myApp.components.notifications")
.factory("KudosNotificationService", KudosNotificationService);
KudosNotificationService.$inject = [
"Transaction"
];
function KudosNotificationService(transactionBackend) {
var service = {
getNewTransactions: getNewTransactions,
setLastTransaction: setLastSeenTransaction
};
return service;
function getNewTransactions() {
return transactionBackend.getNewTransactions()
}
<|fim▁hole|>})();<|fim▁end|> | function setLastSeenTransaction(timestamp) {
return transactionBackend.setLastSeenTransactionTimestamp(timestamp)
}
} |
<|file_name|>QuarterBukkitExceptionListener.java<|end_file_name|><|fim▁begin|>/*
* This file is part of QuarterBukkit-Plugin.
* Copyright (c) 2012 QuarterCode <http://www.quartercode.com/>
*
* QuarterBukkit-Plugin 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.
*
* QuarterBukkit-Plugin 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 QuarterBukkit-Plugin. If not, see <http://www.gnu.org/licenses/>.
*/
package com.quartercode.quarterbukkit.util;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import com.quartercode.quarterbukkit.api.exception.InstallException;
import com.quartercode.quarterbukkit.api.exception.InternalException;
public class QuarterBukkitExceptionListener implements Listener {
private final Plugin plugin;
public QuarterBukkitExceptionListener(Plugin plugin) {
this.plugin = plugin;
Bukkit.getPluginManager().registerEvents(this, plugin);
}
@EventHandler<|fim▁hole|> if (exception.getCause() != null) {
exception.getCauser().sendMessage(ChatColor.RED + "Reason: " + exception.getCause().toString());
}
} else {
plugin.getLogger().warning("Can't update " + plugin.getName() + ": " + exception.getMessage());
if (exception.getCause() != null) {
plugin.getLogger().warning("Reason: " + exception.getCause().toString());
}
}
}
@EventHandler
public void internalException(InternalException exception) {
exception.getCause().printStackTrace();
}
}<|fim▁end|> | public void installException(InstallException exception) {
if (exception.getCauser() != null) {
exception.getCauser().sendMessage(ChatColor.RED + "Can't update " + plugin.getName() + ": " + exception.getMessage()); |
<|file_name|>styleTs.js<|end_file_name|><|fim▁begin|>angular.module('n52.core.base')
.factory('styleService', ['$rootScope', 'settingsService', 'colorService', '$injector', "styleServiceStandalone",
function($rootScope, settingsService, colorService, $injector, styleServiceStandalone) {
var intervalList = settingsService.intervalList;
function createStylesInTs(ts) {
var styles, color, visible, selected, zeroScaled, groupedAxis;
if (!ts.styles) {
ts.styles = {};
}
color = ts.styles.color || ts.renderingHints && ts.renderingHints.properties.color || colorService.getColor(ts.id);
visible = true;
selected = false;
if (angular.isUndefined(ts.styles.zeroScaled)) {
zeroScaled = settingsService.defaultZeroScale;
}
if (angular.isUndefined(ts.styles.groupedAxis)) {
groupedAxis = settingsService.defaultGroupedAxis;
}
styles = styleServiceStandalone.createStyle(ts, color, zeroScaled, groupedAxis, selected, visible);
angular.merge(ts.styles, styles);
angular.forEach(ts.referenceValues, function(refValue) {
refValue.color = colorService.getRefColor(refValue.referenceValueId);
});
}
function deleteStyle(ts) {
colorService.removeColor(ts.styles.color);
angular.forEach(ts.referenceValues, function(refValue) {
colorService.removeRefColor(refValue.color);
});
}
function toggleSelection(ts) {
ts.styles.selected = !ts.styles.selected;
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
function setSelection(ts, selected, quiet) {
ts.styles.selected = selected;
if (!quiet) {<|fim▁hole|> $rootScope.$emit('timeseriesChanged', ts.internalId);
}
}
function toggleTimeseriesVisibility(ts) {
ts.styles.visible = !ts.styles.visible;
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
function updateColor(ts, color) {
ts.styles.color = color;
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
function updateZeroScaled(ts) {
ts.styles.zeroScaled = !ts.styles.zeroScaled;
if (ts.styles.groupedAxis) {
var tsSrv = $injector.get('timeseriesService');
angular.forEach(tsSrv.getAllTimeseries(), function(timeseries) {
if (timeseries.uom === ts.uom && timeseries.styles.groupedAxis) {
timeseries.styles.zeroScaled = ts.styles.zeroScaled;
}
});
}
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
function updateGroupAxis(ts) {
ts.styles.groupedAxis = !ts.styles.groupedAxis;
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
function updateInterval(ts, interval) {
ts.renderingHints.properties.interval = interval.caption;
ts.renderingHints.properties.value = interval.value;
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
function notifyAllTimeseriesChanged() {
$rootScope.$emit('allTimeseriesChanged');
}
function triggerStyleUpdate(ts) {
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
return {
createStylesInTs: createStylesInTs,
deleteStyle: deleteStyle,
notifyAllTimeseriesChanged: notifyAllTimeseriesChanged,
toggleSelection: toggleSelection,
setSelection: setSelection,
toggleTimeseriesVisibility: toggleTimeseriesVisibility,
updateColor: updateColor,
updateZeroScaled: updateZeroScaled,
updateGroupAxis: updateGroupAxis,
updateInterval: updateInterval,
intervalList: intervalList,
triggerStyleUpdate: triggerStyleUpdate
};
}
]);<|fim▁end|> | |
<|file_name|>add_docker_metadata.go<|end_file_name|><|fim▁begin|>package add_docker_metadata
import (
"fmt"
"strings"
"github.com/elastic/beats/libbeat/beat"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/common/cfgwarn"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/libbeat/processors"
"github.com/elastic/beats/libbeat/processors/actions"
)
func init() {
processors.RegisterPlugin("add_docker_metadata", newDockerMetadataProcessor)
}
type addDockerMetadata struct {
watcher Watcher
fields []string
sourceProcessor processors.Processor
}
func newDockerMetadataProcessor(cfg *common.Config) (processors.Processor, error) {
return buildDockerMetadataProcessor(cfg, NewWatcher)
}
func buildDockerMetadataProcessor(cfg *common.Config, watcherConstructor WatcherConstructor) (processors.Processor, error) {
cfgwarn.Beta("The add_docker_metadata processor is beta")
config := defaultConfig()
err := cfg.Unpack(&config)
if err != nil {
return nil, fmt.Errorf("fail to unpack the add_docker_metadata configuration: %s", err)
}
watcher, err := watcherConstructor(config.Host, config.TLS)
if err != nil {
return nil, err
}
if err = watcher.Start(); err != nil {
return nil, err
}
// Use extract_field processor to get container id from source file path
var sourceProcessor processors.Processor
if config.MatchSource {
var procConf, _ = common.NewConfigFrom(map[string]interface{}{
"field": "source",
"separator": "/",
"index": config.SourceIndex,
"target": "docker.container.id",
})
sourceProcessor, err = actions.NewExtractField(procConf)
if err != nil {
return nil, err
}
// Ensure `docker.container.id` is matched:
config.Fields = append(config.Fields, "docker.container.id")
}
return &addDockerMetadata{
watcher: watcher,
fields: config.Fields,
sourceProcessor: sourceProcessor,
}, nil
}
func (d *addDockerMetadata) Run(event *beat.Event) (*beat.Event, error) {
var cid string
var err error
// Process source field
if d.sourceProcessor != nil {
if event.Fields["source"] != nil {
event, err = d.sourceProcessor.Run(event)
if err != nil {
logp.Debug("docker", "Error while extracting container ID from source path: %v", err)
return event, nil
}<|fim▁hole|>
for _, field := range d.fields {
value, err := event.GetValue(field)
if err != nil {
continue
}
if strValue, ok := value.(string); ok {
cid = strValue
}
}
if cid == "" {
return event, nil
}
container := d.watcher.Container(cid)
if container != nil {
meta := common.MapStr{}
metaIface, ok := event.Fields["docker"]
if ok {
meta = metaIface.(common.MapStr)
}
if len(container.Labels) > 0 {
labels := common.MapStr{}
for k, v := range container.Labels {
labels.Put(k, v)
}
meta.Put("container.labels", labels)
}
meta.Put("container.id", container.ID)
meta.Put("container.image", container.Image)
meta.Put("container.name", container.Name)
event.Fields["docker"] = meta
} else {
logp.Debug("docker", "Container not found: %s", cid)
}
return event, nil
}
func (d *addDockerMetadata) String() string {
return "add_docker_metadata=[fields=" + strings.Join(d.fields, ", ") + "]"
}<|fim▁end|> | }
} |
<|file_name|>UserCard.tsx<|end_file_name|><|fim▁begin|>/**
* @author Adam Charron <[email protected]>
* @copyright 2009-2021 Vanilla Forums Inc.
* @license gpl-2.0-only
*/
import { cx } from "@emotion/css";
import { LoadStatus } from "@library/@types/api/core";
import { IUser, IUserFragment } from "@library/@types/api/users";
import { hasUserViewPermission } from "@library/features/users/modules/hasUserViewPermission";
import { useUser, useCurrentUserID } from "@library/features/users/userHooks";
import { dropDownClasses } from "@library/flyouts/dropDownStyles";
import { useDevice, Devices } from "@library/layout/DeviceContext";
import LazyModal from "@library/modal/LazyModal";
import ModalSizes from "@library/modal/ModalSizes";
import { UserCardContext, useUserCardContext } from "@library/features/userCard/UserCard.context";
import { UserCardMinimal, UserCardSkeleton, UserCardView } from "@library/features/userCard/UserCard.views";
import { useUniqueID } from "@library/utility/idUtils";
import Popover, { positionDefault } from "@reach/popover";
import { t } from "@vanilla/i18n";
import { useFocusWatcher } from "@vanilla/react-utils";
import React, { useCallback, useRef, useState } from "react";
import { UserCardError } from "@library/features/userCard/UserCard.views";
import { hasPermission } from "@library/features/users/Permission";
import { getMeta } from "@library/utility/appUtils";
interface IProps {
/** UserID of the user being loaded. */
userID: number;
/** A fragment can help display some data while the full user is loaded. */
userFragment?: Partial<IUserFragment>;
/** If a full user is passed, no network requests will be made, and the user will be displayed immediately. */
user?: IUser;
/** Callback in the even the close button in the card is clicked. */
onClose?: () => void;
/** Show a skeleton */
forceSkeleton?: boolean;
}
/**
* Component representing the inner contents of a user card.
*/
export function UserCard(props: IProps) {
if (!hasUserViewPermission()) {
return <></>;
}
if (props.user) {
// We have a full user, just render the view.
return <UserCardView user={props.user} onClose={props.onClose} />;
} else {
return <UserCardDynamic {...props} />;
}
}
export function UserCardPopup(props: React.PropsWithChildren<IProps> & { forceOpen?: boolean }) {
const [_isOpen, _setIsOpen] = useState(false);
const isOpen = props.forceOpen ?? _isOpen;
function setIsOpen(newOpen: boolean) {
_setIsOpen(newOpen);
// Kludge for interaction with old flyout system.
if (newOpen && window.closeAllFlyouts) {
window.closeAllFlyouts();
}
}
const triggerID = useUniqueID("popupTrigger");
const contentID = triggerID + "-content";
const triggerRef = useRef<HTMLElement>(null);
const contentRef = useRef<HTMLElement>(null);
const device = useDevice();
const forceModal = device === Devices.MOBILE || device === Devices.XS;
if (!hasUserViewPermission()) {
return <>{props.children}</>;
}
return (
<UserCardContext.Provider
value={{
isOpen,
setIsOpen,
triggerRef,
contentRef,
triggerID,
contentID,
}}
>
{props.children}
{!forceModal && isOpen && (
// If we aren't a modal, and we're open, show the flyout.
<Popover targetRef={triggerRef} position={positionPreferTopMiddle}>
<UserCardFlyout
{...props}
onClose={() => {
setIsOpen(false);
}}
/>
</Popover>
)}
{forceModal && (
// On mobile we are forced into a modal, which is controlled by the `isVisible` param instead of conditional rendering.
<LazyModal
isVisible={isOpen}
size={ModalSizes.SMALL}
exitHandler={() => {
setIsOpen(false);
}}
>
<UserCard
{...props}
onClose={() => {
setIsOpen(false);
}}
/>
</LazyModal>
)}
</UserCardContext.Provider>
);
}
/**
* Call this hook to get the props for a user card trigger.
* Simply spread the `props` over the component and pass the `triggerRef` to the underlying element.
*/
export function useUserCardTrigger(): {
props: React.HTMLAttributes<HTMLElement>;
triggerRef: React.RefObject<HTMLElement | null>;
isOpen?: boolean;
} {
const context = useUserCardContext();
const handleFocusChange = useCallback(
(hasFocus, newActiveElement) => {
if (
!hasFocus &&
newActiveElement !== context.contentRef.current &&
!context.contentRef.current?.contains(newActiveElement)
) {
context.setIsOpen(false);
}
},
[context.setIsOpen, context.contentRef],
);
useFocusWatcher(context.triggerRef, handleFocusChange);
return {
props: hasUserViewPermission()
? {
"aria-controls": context.contentID,
"aria-expanded": context.isOpen,
"aria-haspopup": context.isOpen,
role: "button",
onClick: (e) => {
e.preventDefault();
context.setIsOpen(!context.isOpen);
},
onKeyPress: (e) => {
if (e.key === " " || e.key === "Enter") {
e.preventDefault();
context.setIsOpen(!context.isOpen);
}
if (e.key === "Escape") {
e.preventDefault();
context.setIsOpen(false);
context.triggerRef.current?.focus();
}
},
}
: {},
triggerRef: context.triggerRef,
isOpen: context.isOpen,
};
}
/**
* Calculate a position for the user card that is centered if possible.
*/
function positionPreferTopMiddle(targetRect?: DOMRect | null, popoverRect?: DOMRect | null): React.CSSProperties {
const posDefault = positionDefault(targetRect, popoverRect);
const halfPopoverWidth = (popoverRect?.width ?? 0) / 2;
const halfTriggerWidth = (targetRect?.width ?? 0) / 2;
const left = (targetRect?.left ?? 0) + halfTriggerWidth + window.pageXOffset - halfPopoverWidth;
const minimumInset = 16;
if (left < minimumInset || left + halfPopoverWidth * 2 > window.innerWidth - minimumInset) {
// We have a collision.
// Just use default positioning.
return posDefault;
}
return {
...posDefault,
left,
};
}
/**
* The content of the user card, wrapped in a flyout.
*/
export function UserCardFlyout(props: React.ComponentProps<typeof UserCard>) {
const context = useUserCardContext();
const handleFocusChange = useCallback(
(hasFocus, newActiveElement) => {
if (newActiveElement && !hasFocus && newActiveElement !== context.triggerRef.current) {
context.setIsOpen(false);
}
},
[context.setIsOpen, context.triggerRef],
);
useFocusWatcher(context.contentRef, handleFocusChange);
return (
<div
ref={context.contentRef as any}
className={cx(dropDownClasses().contentsBox, "isMedium")}
onKeyDown={(e) => {
if (e.key === "Escape") {
e.preventDefault();
context.setIsOpen(false);
context.triggerRef.current?.focus();<|fim▁hole|> e.stopPropagation();
e.nativeEvent.stopPropagation();
e.nativeEvent.stopImmediatePropagation();
}}
>
<UserCard {...props} />
</div>
);
}
/**
* Wrapper around `UserCardView` that loads the data dynamically.
*/
function UserCardDynamic(props: IProps) {
const { userFragment, forceSkeleton = false } = props;
const user = useUser({ userID: props.userID });
const currentUseID = useCurrentUserID();
const isOwnUser = userFragment?.userID === currentUseID;
const hasPersonalInfoView = hasPermission("personalInfo.view");
let bannedPrivateProfile = getMeta("ui.bannedPrivateProfile", "0");
bannedPrivateProfile = bannedPrivateProfile === "" ? "0" : "1";
const privateBannedProfileEnabled = bannedPrivateProfile !== "0";
let banned = userFragment?.banned ?? 0;
let isBanned = banned === 1;
if ((userFragment?.private || (privateBannedProfileEnabled && isBanned)) && !hasPersonalInfoView && !isOwnUser) {
return <UserCardMinimal userFragment={userFragment} onClose={props.onClose} />;
}
if (forceSkeleton || user.status === LoadStatus.PENDING || user.status === LoadStatus.LOADING) {
return <UserCardSkeleton userFragment={userFragment} onClose={props.onClose} />;
}
if (user.error && user?.error?.response.status === 404) {
return <UserCardError onClose={props.onClose} />;
}
if (!user.data || user.status === LoadStatus.ERROR) {
return <UserCardError error={t("Failed to load user")} onClose={props.onClose} />;
}
return <UserCardView user={user.data} onClose={props.onClose} />;
}<|fim▁end|> | }
}}
onClick={(e) => { |
<|file_name|>themes.js<|end_file_name|><|fim▁begin|>const Promise = require('bluebird');
const fs = require('fs-extra');
const debug = require('ghost-ignition').debug('api:themes');
const common = require('../../lib/common');
const themeService = require('../../services/themes');
const settingsCache = require('../../services/settings/cache');
const models = require('../../models');
module.exports = {
docName: 'themes',
browse: {
permissions: true,
query() {
return themeService.toJSON();
}
},
activate: {
headers: {
cacheInvalidate: true
},
options: [
'name'
],
validation: {
options: {
name: {
required: true
}
}
},
permissions: true,
query(frame) {
let themeName = frame.options.name;
let checkedTheme;
const newSettings = [{
key: 'active_theme',
value: themeName
}];
const loadedTheme = themeService.list.get(themeName);
if (!loadedTheme) {
return Promise.reject(new common.errors.ValidationError({
message: common.i18n.t('notices.data.validation.index.themeCannotBeActivated', {themeName: themeName}),
errorDetails: newSettings
}));
}
return themeService.validate.checkSafe(loadedTheme)
.then((_checkedTheme) => {
checkedTheme = _checkedTheme;
// @NOTE: we use the model, not the API here, as we don't want to trigger permissions
return models.Settings.edit(newSettings, frame.options);
})
.then(() => {
debug('Activating theme (method B on API "activate")', themeName);
themeService.activate(loadedTheme, checkedTheme);
return themeService.toJSON(themeName, checkedTheme);
});
}
},
upload: {
headers: {},
permissions: {
method: 'add'
},
query(frame) {
// @NOTE: consistent filename uploads
frame.options.originalname = frame.file.originalname.toLowerCase();
let zip = {
path: frame.file.path,
name: frame.file.originalname,
shortName: themeService.storage.getSanitizedFileName(frame.file.originalname.split('.zip')[0])
};
let checkedTheme;
// check if zip name is casper.zip
if (zip.name === 'casper.zip') {
throw new common.errors.ValidationError({
message: common.i18n.t('errors.api.themes.overrideCasper')
});
}
return themeService.validate.checkSafe(zip, true)
.then((_checkedTheme) => {
checkedTheme = _checkedTheme;
return themeService.storage.exists(zip.shortName);
})
.then((themeExists) => {
// CASE: delete existing theme
if (themeExists) {
return themeService.storage.delete(zip.shortName);
}
})
.then(() => {
// CASE: store extracted theme
return themeService.storage.save({
name: zip.shortName,
path: checkedTheme.path
});
})
.then(() => {
// CASE: loads the theme from the fs & sets the theme on the themeList
return themeService.loadOne(zip.shortName);
})
.then((loadedTheme) => {
// CASE: if this is the active theme, we are overriding
if (zip.shortName === settingsCache.get('active_theme')) {
debug('Activating theme (method C, on API "override")', zip.shortName);
themeService.activate(loadedTheme, checkedTheme);
<|fim▁hole|>
common.events.emit('theme.uploaded');
// @TODO: unify the name across gscan and Ghost!
return themeService.toJSON(zip.shortName, checkedTheme);
})
.finally(() => {
// @TODO: we should probably do this as part of saving the theme
// CASE: remove extracted dir from gscan
// happens in background
if (checkedTheme) {
fs.remove(checkedTheme.path)
.catch((err) => {
common.logging.error(new common.errors.GhostError({err: err}));
});
}
});
}
},
download: {
options: [
'name'
],
validation: {
options: {
name: {
required: true
}
}
},
permissions: {
method: 'read'
},
query(frame) {
let themeName = frame.options.name;
const theme = themeService.list.get(themeName);
if (!theme) {
return Promise.reject(new common.errors.BadRequestError({
message: common.i18n.t('errors.api.themes.invalidThemeName')
}));
}
return themeService.storage.serve({
name: themeName
});
}
},
destroy: {
statusCode: 204,
headers: {
cacheInvalidate: true
},
options: [
'name'
],
validation: {
options: {
name: {
required: true
}
}
},
permissions: true,
query(frame) {
let themeName = frame.options.name;
if (themeName === 'casper') {
throw new common.errors.ValidationError({
message: common.i18n.t('errors.api.themes.destroyCasper')
});
}
if (themeName === settingsCache.get('active_theme')) {
throw new common.errors.ValidationError({
message: common.i18n.t('errors.api.themes.destroyActive')
});
}
const theme = themeService.list.get(themeName);
if (!theme) {
throw new common.errors.NotFoundError({
message: common.i18n.t('errors.api.themes.themeDoesNotExist')
});
}
return themeService.storage.delete(themeName)
.then(() => {
themeService.list.del(themeName);
});
}
}
};<|fim▁end|> | // CASE: clear cache
this.headers.cacheInvalidate = true;
} |
<|file_name|>window.rs<|end_file_name|><|fim▁begin|>use std::collections::vec_deque::IntoIter as VecDequeIter;
use std::default::Default;
use std::path::PathBuf;
use Api;
use ContextError;
use CreationError;
use CursorState;
use Event;
use GlContext;
use GlProfile;
use GlRequest;
use MouseCursor;
use PixelFormat;
use Robustness;
use Window;
use WindowID;
use WindowBuilder;
use native_monitor::NativeMonitorId;
use libc;
use platform;
impl<'a> WindowBuilder<'a> {
/// Initializes a new `WindowBuilder` with default values.
#[inline]
pub fn new() -> WindowBuilder<'a> {
WindowBuilder {
pf_reqs: Default::default(),
window: Default::default(),
opengl: Default::default(),
platform_specific: Default::default(),
}
}
/// Requests the window to be of specific dimensions.
///
/// Width and height are in pixels.
#[inline]
pub fn with_dimensions(mut self, width: u32, height: u32) -> WindowBuilder<'a> {
self.window.dimensions = Some((width, height));
self
}
/// Sets a minimum dimension size for the window
///
/// Width and height are in pixels.
#[inline]
pub fn with_min_dimensions(mut self, width: u32, height: u32) -> WindowBuilder<'a> {
self.window.min_dimensions = Some((width, height));
self
}
/// Sets a maximum dimension size for the window
///
/// Width and height are in pixels.
#[inline]
pub fn with_max_dimensions(mut self, width: u32, height: u32) -> WindowBuilder<'a> {
self.window.max_dimensions = Some((width, height));
self
}
/// Requests a specific title for the window.
#[inline]
pub fn with_title<T: Into<String>>(mut self, title: T) -> WindowBuilder<'a> {
self.window.title = title.into();
self
}
/// Requests fullscreen mode.
///
/// If you don't specify dimensions for the window, it will match the monitor's.
#[inline]
pub fn with_fullscreen(mut self, monitor: MonitorId) -> WindowBuilder<'a> {
let MonitorId(monitor) = monitor;
self.window.monitor = Some(monitor);
self
}
/// The created window will share all its OpenGL objects with the window in the parameter.
///
/// There are some exceptions, like FBOs or VAOs. See the OpenGL documentation.
#[inline]
pub fn with_shared_lists(mut self, other: &'a Window) -> WindowBuilder<'a> {
self.opengl.sharing = Some(&other.window);
self
}
/// Sets how the backend should choose the OpenGL API and version.
#[inline]
pub fn with_gl(mut self, request: GlRequest) -> WindowBuilder<'a> {
self.opengl.version = request;
self
}
/// Sets the desired OpenGL context profile.
#[inline]
pub fn with_gl_profile(mut self, profile: GlProfile) -> WindowBuilder<'a> {
self.opengl.profile = Some(profile);
self
}
/// Sets the *debug* flag for the OpenGL context.
///
/// The default value for this flag is `cfg!(debug_assertions)`, which means that it's enabled
/// when you run `cargo build` and disabled when you run `cargo build --release`.
#[inline]
pub fn with_gl_debug_flag(mut self, flag: bool) -> WindowBuilder<'a> {
self.opengl.debug = flag;
self
}
/// Sets the robustness of the OpenGL context. See the docs of `Robustness`.
#[inline]
pub fn with_gl_robustness(mut self, robustness: Robustness) -> WindowBuilder<'a> {
self.opengl.robustness = robustness;
self
}
/// Requests that the window has vsync enabled.
#[inline]
pub fn with_vsync(mut self) -> WindowBuilder<'a> {
self.opengl.vsync = true;
self
}
/// Sets whether the window will be initially hidden or visible.
#[inline]
pub fn with_visibility(mut self, visible: bool) -> WindowBuilder<'a> {
self.window.visible = visible;
self
}
/// Sets the multisampling level to request.
///
/// # Panic
///
/// Will panic if `samples` is not a power of two.
#[inline]
pub fn with_multisampling(mut self, samples: u16) -> WindowBuilder<'a> {
assert!(samples.is_power_of_two());
self.pf_reqs.multisampling = Some(samples);
self
}
/// Sets the number of bits in the depth buffer.
#[inline]
pub fn with_depth_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.pf_reqs.depth_bits = Some(bits);
self
}
/// Sets the number of bits in the stencil buffer.
#[inline]
pub fn with_stencil_buffer(mut self, bits: u8) -> WindowBuilder<'a> {
self.pf_reqs.stencil_bits = Some(bits);
self
}
/// Sets the number of bits in the color buffer.
#[inline]
pub fn with_pixel_format(mut self, color_bits: u8, alpha_bits: u8) -> WindowBuilder<'a> {
self.pf_reqs.color_bits = Some(color_bits);
self.pf_reqs.alpha_bits = Some(alpha_bits);
self
}
/// Request the backend to be stereoscopic.
#[inline]
pub fn with_stereoscopy(mut self) -> WindowBuilder<'a> {
self.pf_reqs.stereoscopy = true;
self
}
/// Sets whether sRGB should be enabled on the window. `None` means "I don't care".
#[inline]
pub fn with_srgb(mut self, srgb_enabled: Option<bool>) -> WindowBuilder<'a> {
self.pf_reqs.srgb = srgb_enabled.unwrap_or(false);
self
}
/// Sets whether the background of the window should be transparent.
#[inline]
pub fn with_transparency(mut self, transparent: bool) -> WindowBuilder<'a> {
self.window.transparent = transparent;
self
}
/// Sets whether the window should have a border, a title bar, etc.
#[inline]
pub fn with_decorations(mut self, decorations: bool) -> WindowBuilder<'a> {
self.window.decorations = decorations;
self
}
/// Enables multitouch
#[inline]
pub fn with_multitouch(mut self) -> WindowBuilder<'a> {
self.window.multitouch = true;
self
}
/// Sets the icon for the window. The supplied path must reference a PNG file.
#[inline]
pub fn with_icon(mut self, icon_path: PathBuf) -> WindowBuilder<'a> {
self.window.icon = Some(icon_path);
self
}
/// Sets the parent window
pub fn with_parent(mut self, parent: Option<WindowID>) -> WindowBuilder<'a> {
self.window.parent = parent;
self
}
/// Builds the window.
///
/// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
pub fn build(mut self) -> Result<Window, CreationError> {
// resizing the window to the dimensions of the monitor when fullscreen
if self.window.dimensions.is_none() && self.window.monitor.is_some() {
self.window.dimensions = Some(self.window.monitor.as_ref().unwrap().get_dimensions())
}
// default dimensions
if self.window.dimensions.is_none() {
self.window.dimensions = Some((1024, 768));
}
// building
platform::Window::new(&self.window, &self.pf_reqs, &self.opengl, &self.platform_specific)
.map(|w| Window { window: w })
}
/// Builds the window.
///
/// The context is build in a *strict* way. That means that if the backend couldn't give
/// you what you requested, an `Err` will be returned.
#[inline]
pub fn build_strict(self) -> Result<Window, CreationError> {
self.build()
}
}
impl Default for Window {
#[inline]
fn default() -> Window {
Window::new().unwrap()
}
}
impl Window {
/// Creates a new OpenGL context, and a Window for platforms where this is appropriate.
///
/// This function is equivalent to `WindowBuilder::new().build()`.
///
/// Error should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
#[inline]
pub fn new() -> Result<Window, CreationError> {
let builder = WindowBuilder::new();
builder.build()
}
/// Modifies the title of the window.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_title(&self, title: &str) {
self.window.set_title(title)
}
/// Shows the window if it was hidden.
///
/// ## Platform-specific
///
/// - Has no effect on Android
///
#[inline]
pub fn show(&self) {
self.window.show()
}
/// Hides the window if it was visible.
///
/// ## Platform-specific
///
/// - Has no effect on Android
///
#[inline]
pub fn hide(&self) {
self.window.hide()
}
/// Returns the position of the top-left hand corner of the window relative to the
/// top-left hand corner of the desktop.
///
/// Note that the top-left hand corner of the desktop is not necessarily the same as
/// the screen. If the user uses a desktop with multiple monitors, the top-left hand corner
/// of the desktop is the top-left hand corner of the monitor at the top-left of the desktop.
///
/// The coordinates can be negative if the top-left hand corner of the window is outside
/// of the visible screen region.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_position(&self) -> Option<(i32, i32)> {
self.window.get_position()
}
/// Modifies the position of the window.
///
/// See `get_position` for more informations about the coordinates.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_position(&self, x: i32, y: i32) {
self.window.set_position(x, y)
}
/// Returns the size in points of the client area of the window.
///
/// The client area is the content of the window, excluding the title bar and borders.
/// To get the dimensions of the frame buffer when calling `glViewport`, multiply with hidpi factor.
///
/// Returns `None` if the window no longer exists.
///
/// DEPRECATED
#[inline]
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
self.window.get_inner_size()
}
/// Returns the size in points of the client area of the window.
///
/// The client area is the content of the window, excluding the title bar and borders.
/// To get the dimensions of the frame buffer when calling `glViewport`, multiply with hidpi factor.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_inner_size_points(&self) -> Option<(u32, u32)> {
self.window.get_inner_size()
}
/// Returns the size in pixels of the client area of the window.
///
/// The client area is the content of the window, excluding the title bar and borders.
/// These are the dimensions of the frame buffer, and the dimensions that you should use
/// when you call `glViewport`.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_inner_size_pixels(&self) -> Option<(u32, u32)> {
self.window.get_inner_size().map(|(x, y)| {
let hidpi = self.hidpi_factor();
((x as f32 * hidpi) as u32, (y as f32 * hidpi) as u32)
})
}
/// Returns the size in pixels of the window.
///
/// These dimensions include title bar and borders. If you don't want these, you should use
/// use `get_inner_size` instead.
///
/// Returns `None` if the window no longer exists.
#[inline]
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.window.get_outer_size()
}
/// Modifies the inner size of the window.
///
/// See `get_inner_size` for more informations about the values.
///
/// This is a no-op if the window has already been closed.
#[inline]
pub fn set_inner_size(&self, x: u32, y: u32) {
self.window.set_inner_size(x, y)
}
/// Returns an iterator that poll for the next event in the window's events queue.
/// Returns `None` if there is no event in the queue.
///
/// Contrary to `wait_events`, this function never blocks.
#[inline]
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator(self.window.poll_events())
}
/// Returns an iterator that returns events one by one, blocking if necessary until one is
/// available.
///
/// The iterator never returns `None`.
#[inline]
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator(self.window.wait_events())
}
/// Sets the context as the current context.
#[inline]
pub unsafe fn make_current(&self) -> Result<(), ContextError> {
self.window.make_current()
}
/// Returns true if this context is the current one in this thread.
#[inline]
pub fn is_current(&self) -> bool {
self.window.is_current()
}
/// Returns the address of an OpenGL function.
///
/// Contrary to `wglGetProcAddress`, all available OpenGL functions return an address.
#[inline]
pub fn get_proc_address(&self, addr: &str) -> *const () {
self.window.get_proc_address(addr)
}
/// Swaps the buffers in case of double or triple buffering.
///
/// You should call this function every time you have finished rendering, or the image
/// may not be displayed on the screen.
///
/// **Warning**: if you enabled vsync, this function will block until the next time the screen
/// is refreshed. However drivers can choose to override your vsync settings, which means that
/// you can't know in advance whether `swap_buffers` will block or not.
#[inline]
pub fn swap_buffers(&self) -> Result<(), ContextError> {
self.window.swap_buffers()
}
/// DEPRECATED. Gets the native platform specific display for this window.
/// This is typically only required when integrating with
/// other libraries that need this information.
#[inline]
pub unsafe fn platform_display(&self) -> *mut libc::c_void {
self.window.platform_display()
}
/// DEPRECATED. Gets the native platform specific window handle. This is
/// typically only required when integrating with other libraries
/// that need this information.
#[inline]
pub unsafe fn platform_window(&self) -> *mut libc::c_void {
self.window.platform_window()
}
/// Returns the API that is currently provided by this window.
///
/// - On Windows and OS/X, this always returns `OpenGl`.
/// - On Android, this always returns `OpenGlEs`.
/// - On Linux, it must be checked at runtime.
#[inline]
pub fn get_api(&self) -> Api {
self.window.get_api()
}
/// Returns the pixel format of this window.
#[inline]
pub fn get_pixel_format(&self) -> PixelFormat {
self.window.get_pixel_format()
}
/// Create a window proxy for this window, that can be freely
/// passed to different threads.
#[inline]
pub fn create_window_proxy(&self) -> WindowProxy {
WindowProxy {
proxy: self.window.create_window_proxy()
}
}
/// Sets a resize callback that is called by Mac (and potentially other
/// operating systems) during resize operations. This can be used to repaint
/// during window resizing.
#[inline]
pub fn set_window_resize_callback(&mut self, callback: Option<fn(u32, u32)>) {
self.window.set_window_resize_callback(callback);
}
/// Modifies the mouse cursor of the window.
/// Has no effect on Android.
pub fn set_cursor(&self, cursor: MouseCursor) {
self.window.set_cursor(cursor);
}
/// Returns the ratio between the backing framebuffer resolution and the
/// window size in screen pixels. This is typically one for a normal display
/// and two for a retina display.
#[inline]
pub fn hidpi_factor(&self) -> f32 {
self.window.hidpi_factor()
}
/// Changes the position of the cursor in window coordinates.
#[inline]
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
self.window.set_cursor_position(x, y)
}
/// Sets how glutin handles the cursor. See the documentation of `CursorState` for details.
///
/// Has no effect on Android.
#[inline]
pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> {
self.window.set_cursor_state(state)
}
}
impl GlContext for Window {
#[inline]
unsafe fn make_current(&self) -> Result<(), ContextError> {
self.make_current()
}
#[inline]
fn is_current(&self) -> bool {
self.is_current()
}
#[inline]
fn get_proc_address(&self, addr: &str) -> *const () {
self.get_proc_address(addr)
}
#[inline]
fn swap_buffers(&self) -> Result<(), ContextError> {
self.swap_buffers()
}
#[inline]
fn get_api(&self) -> Api {
self.get_api()<|fim▁hole|> #[inline]
fn get_pixel_format(&self) -> PixelFormat {
self.get_pixel_format()
}
}
/// Represents a thread safe subset of operations that can be called
/// on a window. This structure can be safely cloned and sent between
/// threads.
#[derive(Clone)]
pub struct WindowProxy {
proxy: platform::WindowProxy,
}
impl WindowProxy {
/// Triggers a blocked event loop to wake up. This is
/// typically called when another thread wants to wake
/// up the blocked rendering thread to cause a refresh.
#[inline]
pub fn wakeup_event_loop(&self) {
self.proxy.wakeup_event_loop();
}
}
/// An iterator for the `poll_events` function.
pub struct PollEventsIterator<'a>(platform::PollEventsIterator<'a>);
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
#[inline]
fn next(&mut self) -> Option<Event> {
self.0.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An iterator for the `wait_events` function.
pub struct WaitEventsIterator<'a>(platform::WaitEventsIterator<'a>);
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
#[inline]
fn next(&mut self) -> Option<Event> {
self.0.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An iterator for the list of available monitors.
// Implementation note: we retreive the list once, then serve each element by one by one.
// This may change in the future.
pub struct AvailableMonitorsIter {
data: VecDequeIter<platform::MonitorId>,
}
impl Iterator for AvailableMonitorsIter {
type Item = MonitorId;
#[inline]
fn next(&mut self) -> Option<MonitorId> {
self.data.next().map(|id| MonitorId(id))
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.data.size_hint()
}
}
/// Returns the list of all available monitors.
#[inline]
pub fn get_available_monitors() -> AvailableMonitorsIter {
let data = platform::get_available_monitors();
AvailableMonitorsIter{ data: data.into_iter() }
}
/// Returns the primary monitor of the system.
#[inline]
pub fn get_primary_monitor() -> MonitorId {
MonitorId(platform::get_primary_monitor())
}
/// Identifier for a monitor.
pub struct MonitorId(platform::MonitorId);
impl MonitorId {
/// Returns a human-readable name of the monitor.
#[inline]
pub fn get_name(&self) -> Option<String> {
let &MonitorId(ref id) = self;
id.get_name()
}
/// Returns the native platform identifier for this monitor.
#[inline]
pub fn get_native_identifier(&self) -> NativeMonitorId {
let &MonitorId(ref id) = self;
id.get_native_identifier()
}
/// Returns the number of pixels currently displayed on the monitor.
#[inline]
pub fn get_dimensions(&self) -> (u32, u32) {
let &MonitorId(ref id) = self;
id.get_dimensions()
}
}<|fim▁end|> | }
|
<|file_name|>index.js<|end_file_name|><|fim▁begin|>/*
* Copyright 2015 NamieTown<|fim▁hole|> * http://www.town.namie.fukushima.jp/
* 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.
*/
define(function(require, exports, module) {
"use strict";
module.exports = {
HeaderView : require("./HeaderView")
};
});<|fim▁end|> | |
<|file_name|>TrackButtons.cpp<|end_file_name|><|fim▁begin|>/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
/*
Rosegarden
A MIDI and audio sequencer and musical notation editor.
Copyright 2000-2018 the Rosegarden development team.
Other copyrights also apply to some parts of this work. Please
see the AUTHORS file and individual file headers for details.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version. See the file
COPYING included with this distribution for more information.
*/
#define RG_MODULE_STRING "[TrackButtons]"
#include "TrackButtons.h"
#include "TrackLabel.h"
#include "TrackVUMeter.h"
#include "misc/Debug.h"
#include "misc/Strings.h"
#include "base/AudioPluginInstance.h"
#include "base/Composition.h"
#include "base/Device.h"
#include "base/Instrument.h"
#include "base/InstrumentStaticSignals.h"
#include "base/MidiProgram.h"
#include "base/Studio.h"
#include "base/Track.h"
#include "commands/segment/RenameTrackCommand.h"
#include "document/RosegardenDocument.h"
#include "document/CommandHistory.h"
#include "gui/application/RosegardenMainWindow.h"
#include "gui/general/GUIPalette.h"
#include "gui/general/IconLoader.h"
#include "gui/seqmanager/SequenceManager.h"
#include "gui/widgets/LedButton.h"
#include "sound/AudioFileManager.h"
#include "sound/ControlBlock.h"
#include "sound/PluginIdentifier.h"
#include "sequencer/RosegardenSequencer.h"
#include <QApplication>
#include <QLayout>
#include <QMessageBox>
#include <QCursor>
#include <QFrame>
#include <QIcon>
#include <QLabel>
#include <QObject>
#include <QPixmap>
#include <QMenu>
#include <QSignalMapper>
#include <QString>
#include <QTimer>
#include <QWidget>
#include <QStackedWidget>
#include <QToolTip>
namespace Rosegarden
{
// Constants
const int TrackButtons::m_borderGap = 1;
const int TrackButtons::m_buttonGap = 8;
const int TrackButtons::m_vuWidth = 20;
const int TrackButtons::m_vuSpacing = 2;
TrackButtons::TrackButtons(RosegardenDocument* doc,
int trackCellHeight,
int trackLabelWidth,
bool showTrackLabels,
int overallHeight,
QWidget* parent) :
QFrame(parent),
m_doc(doc),
m_layout(new QVBoxLayout(this)),
m_recordSigMapper(new QSignalMapper(this)),
m_muteSigMapper(new QSignalMapper(this)),
m_soloSigMapper(new QSignalMapper(this)),
m_clickedSigMapper(new QSignalMapper(this)),
m_instListSigMapper(new QSignalMapper(this)),
m_tracks(doc->getComposition().getNbTracks()),
// m_offset(4),
m_cellSize(trackCellHeight),
m_trackLabelWidth(trackLabelWidth),
m_popupTrackPos(0),
m_lastSelected(-1)
{
setFrameStyle(Plain);
QPalette pal = palette();
pal.setColor(backgroundRole(), QColor(0xDD, 0xDD, 0xDD));
pal.setColor(foregroundRole(), Qt::black);
setPalette(pal);
// when we create the widget, what are we looking at?
if (showTrackLabels) {
m_labelDisplayMode = TrackLabel::ShowTrack;
} else {
m_labelDisplayMode = TrackLabel::ShowInstrument;
}
m_layout->setMargin(0);
// Set the spacing between vertical elements
m_layout->setSpacing(m_borderGap);
// Now draw the buttons and labels and meters
//
makeButtons();
m_layout->addStretch(20);
connect(m_recordSigMapper, SIGNAL(mapped(int)),
this, SLOT(slotToggleRecord(int)));
connect(m_muteSigMapper, SIGNAL(mapped(int)),
this, SLOT(slotToggleMute(int)));
connect(m_soloSigMapper, SIGNAL(mapped(int)),
this, SLOT(slotToggleSolo(int)));
// connect signal mappers
connect(m_instListSigMapper, SIGNAL(mapped(int)),
this, SLOT(slotInstrumentMenu(int)));
connect(m_clickedSigMapper, SIGNAL(mapped(int)),
this, SLOT(slotTrackSelected(int)));
// We have to force the height for the moment
//
setMinimumHeight(overallHeight);
m_doc->getComposition().addObserver(this);
// We do not care about documentChanged() because if the
// document is changing, we are going away. A new TrackButtons
// is created for each new document.
//connect(RosegardenMainWindow::self(),
// SIGNAL(documentChanged(RosegardenDocument *)),
// SLOT(slotNewDocument(RosegardenDocument *)));
}
TrackButtons::~TrackButtons() {
// CRASH! Probably m_doc is gone...
// Probably don't need to disconnect as we only go away when the
// doc and composition do. shared_ptr would help here.
// m_doc->getComposition().removeObserver(this);
}
void
TrackButtons::updateUI(Track *track)
{
if (!track)
return;
int pos = track->getPosition();
if (pos < 0 || pos >= m_tracks)
return;
// *** Archive Background
QFrame *hbox = m_trackHBoxes.at(pos);
if (track->isArchived()) {
// Go with the dark gray background.
QPalette palette = hbox->palette();
palette.setColor(hbox->backgroundRole(), QColor(0x88, 0x88, 0x88));
hbox->setPalette(palette);
} else {
// Go with the parent's background color.
QColor parentBackground = palette().color(backgroundRole());
QPalette palette = hbox->palette();
palette.setColor(hbox->backgroundRole(), parentBackground);
hbox->setPalette(palette);
}
// *** Mute LED
if (track->isMuted()) {
m_muteLeds[pos]->off();
} else {
m_muteLeds[pos]->on();
}
// *** Record LED
Instrument *ins =
m_doc->getStudio().getInstrumentById(track->getInstrument());
m_recordLeds[pos]->setColor(getRecordLedColour(ins));
// Note: setRecord() used to be used to do this. But that would
// set the track in the composition to record as well as setting
// the button on the UI. This seems better and works fine.
bool recording =
m_doc->getComposition().isTrackRecording(track->getId());
setRecordButton(pos, recording);
// *** Solo LED
// ??? An Led::setState(bool) would be handy.
m_soloLeds[pos]->setState(track->isSolo() ? Led::On : Led::Off);
// *** Track Label
TrackLabel *label = m_trackLabels[pos];
if (!label)
return;
// In case the tracks have been moved around, update the mapping.
label->setId(track->getId());
setButtonMapping(label, track->getId());
label->setPosition(pos);
if (track->getLabel() == "") {
if (ins && ins->getType() == Instrument::Audio) {
label->setTrackName(tr("<untitled audio>"));
} else {
label->setTrackName(tr("<untitled>"));
}
} else {
label->setTrackName(strtoqstr(track->getLabel()));
label->setShortName(strtoqstr(track->getShortLabel()));
}
initInstrumentNames(ins, label);
label->updateLabel();
}
void
TrackButtons::makeButtons()
{
if (!m_doc)
return;
//RG_DEBUG << "makeButtons()";
// Create a horizontal box filled with widgets for each track
for (int i = 0; i < m_tracks; ++i) {
Track *track = m_doc->getComposition().getTrackByPosition(i);
if (!track)
continue;
QFrame *trackHBox = makeButton(track);
if (trackHBox) {
trackHBox->setObjectName("TrackButtonFrame");
m_layout->addWidget(trackHBox);
m_trackHBoxes.push_back(trackHBox);
}
}
populateButtons();
}
void
TrackButtons::setButtonMapping(TrackLabel* trackLabel, TrackId trackId)
{
m_clickedSigMapper->setMapping(trackLabel, trackId);
m_instListSigMapper->setMapping(trackLabel, trackId);
}
void
TrackButtons::initInstrumentNames(Instrument *ins, TrackLabel *label)
{
if (!label)
return;
if (ins) {
label->setPresentationName(ins->getLocalizedPresentationName());
if (ins->sendsProgramChange()) {
label->setProgramChangeName(
QObject::tr(ins->getProgramName().c_str()));
} else {
label->setProgramChangeName("");
}
} else {
label->setPresentationName(tr("<no instrument>"));
}
}
void
TrackButtons::populateButtons()
{
//RG_DEBUG << "populateButtons()";
// For each track, copy info from Track object to the widgets
for (int i = 0; i < m_tracks; ++i) {
Track *track = m_doc->getComposition().getTrackByPosition(i);
if (!track)
continue;
updateUI(track);
}
}
void
TrackButtons::slotToggleMute(int pos)
{
//RG_DEBUG << "TrackButtons::slotToggleMute( position =" << pos << ")";
if (!m_doc)
return;
if (pos < 0 || pos >= m_tracks)
return;
Composition &comp = m_doc->getComposition();
Track *track = comp.getTrackByPosition(pos);
if (!track)
return;
// Toggle the mute state
track->setMuted(!track->isMuted());
// Notify observers
comp.notifyTrackChanged(track);
m_doc->slotDocumentModified();
}
void TrackButtons::toggleSolo()
{
if (!m_doc)
return;
Composition &comp = m_doc->getComposition();
int pos = comp.getTrackPositionById(comp.getSelectedTrack());
if (pos == -1)
return;
slotToggleSolo(pos);
}
void
TrackButtons::slotToggleSolo(int pos)
{
//RG_DEBUG << "slotToggleSolo( position =" << pos << ")";
if (!m_doc)
return;
if (pos < 0 || pos >= m_tracks)
return;
Composition &comp = m_doc->getComposition();
Track *track = comp.getTrackByPosition(pos);
if (!track)
return;
bool state = !track->isSolo();
// If we're setting solo on this track and shift isn't being held down,
// clear solo on all tracks (canceling mode). If shift is being held
// down, multiple tracks can be put into solo (latching mode).
if (state &&
QApplication::keyboardModifiers() != Qt::ShiftModifier) {
// For each track
for (int i = 0; i < m_tracks; ++i) {
// Except the one that is being toggled.
if (i == pos)
continue;
Track *track2 = comp.getTrackByPosition(i);
if (!track2)
continue;
if (track2->isSolo()) {
// Clear solo
track2->setSolo(false);
comp.notifyTrackChanged(track2);
}
}
}
// Toggle the solo state
track->setSolo(state);
// Notify observers
comp.notifyTrackChanged(track);
m_doc->slotDocumentModified();
}
void
TrackButtons::removeButtons(int position)
{
//RG_DEBUG << "removeButtons() - deleting track button at position:" << position;
if (position < 0 || position >= m_tracks) {
RG_DEBUG << "%%%%%%%%% BIG PROBLEM : TrackButtons::removeButtons() was passed a non-existing index\n";
return;
}
std::vector<TrackLabel*>::iterator tit = m_trackLabels.begin();
tit += position;
m_trackLabels.erase(tit);
std::vector<TrackVUMeter*>::iterator vit = m_trackMeters.begin();
vit += position;
m_trackMeters.erase(vit);
std::vector<LedButton*>::iterator mit = m_muteLeds.begin();
mit += position;
m_muteLeds.erase(mit);
mit = m_recordLeds.begin();
mit += position;
m_recordLeds.erase(mit);
m_soloLeds.erase(m_soloLeds.begin() + position);
// Delete all child widgets (button, led, label...)
delete m_trackHBoxes[position];
m_trackHBoxes[position] = nullptr;
std::vector<QFrame*>::iterator it = m_trackHBoxes.begin();
it += position;
m_trackHBoxes.erase(it);
}
void
TrackButtons::slotUpdateTracks()
{
//RG_DEBUG << "slotUpdateTracks()";
#if 0
static QTime t;
RG_DEBUG << " elapsed: " << t.restart();
#endif
if (!m_doc)
return;
Composition &comp = m_doc->getComposition();
const int newNbTracks = comp.getNbTracks();
if (newNbTracks < 0) {
RG_WARNING << "slotUpdateTracks(): WARNING: New number of tracks was negative:" << newNbTracks;
return;
}
//RG_DEBUG << "TrackButtons::slotUpdateTracks > newNbTracks = " << newNbTracks;
// If a track or tracks were deleted
if (newNbTracks < m_tracks) {
// For each deleted track, remove a button from the end.
for (int i = m_tracks; i > newNbTracks; --i)
removeButtons(i - 1);
} else if (newNbTracks > m_tracks) { // if added
// For each added track
for (int i = m_tracks; i < newNbTracks; ++i) {
Track *track = m_doc->getComposition().getTrackByPosition(i);
if (track) {
// Make a new button
QFrame *trackHBox = makeButton(track);
if (trackHBox) {
trackHBox->show();
// Add the new button to the layout.
m_layout->insertWidget(i, trackHBox);
m_trackHBoxes.push_back(trackHBox);
}
} else
RG_DEBUG << "TrackButtons::slotUpdateTracks - can't find TrackId for position " << i;
}
}
m_tracks = newNbTracks;
if (m_tracks != (int)m_trackHBoxes.size())
RG_DEBUG << "WARNING TrackButtons::slotUpdateTracks(): m_trackHBoxes.size() != m_tracks";
if (m_tracks != (int)m_trackLabels.size())
RG_DEBUG << "WARNING TrackButtons::slotUpdateTracks(): m_trackLabels.size() != m_tracks";
// For each track
for (int i = 0; i < m_tracks; ++i) {
Track *track = comp.getTrackByPosition(i);
if (!track)
continue;
// *** Set Track Size ***
// Track height can change when the user moves segments around and
// they overlap.
m_trackHBoxes[i]->setMinimumSize(labelWidth(), trackHeight(track->getId()));
m_trackHBoxes[i]->setFixedHeight(trackHeight(track->getId()));
}
populateButtons();
// This is necessary to update the widgets's sizeHint to reflect any change in child widget sizes
// Make the TrackButtons QFrame big enough to hold all the track buttons.
// Some may have grown taller due to segments that overlap.
// Note: This appears to no longer be needed. But it doesn't hurt.
adjustSize();
}
void
TrackButtons::slotToggleRecord(int position)
{
//RG_DEBUG << "TrackButtons::slotToggleRecord(" << position << ")";
if (position < 0 || position >= m_tracks)
return;
if (!m_doc)
return;
Composition &comp = m_doc->getComposition();
Track *track = comp.getTrackByPosition(position);
if (!track)
return;
// Toggle
bool state = !comp.isTrackRecording(track->getId());
// Update the Track
comp.setTrackRecording(track->getId(), state);
comp.notifyTrackChanged(track);
m_doc->checkAudioPath(track);
}
void
TrackButtons::setRecordButton(int position, bool record)
{
if (position < 0 || position >= m_tracks)
return;
m_recordLeds[position]->setState(record ? Led::On : Led::Off);
}
void
TrackButtons::selectTrack(int position)
{
if (position < 0 || position >= m_tracks)
return;
// No sense doing anything if the selection isn't changing
if (position == m_lastSelected)
return;
// Unselect the previously selected
if (m_lastSelected >= 0 && m_lastSelected < m_tracks) {
m_trackLabels[m_lastSelected]->setSelected(false);
}
// Select the newly selected
m_trackLabels[position]->setSelected(true);
m_lastSelected = position;
}
#if 0
// unused
std::vector<int>
TrackButtons::getHighlightedTracks()
{
std::vector<int> retList;
for (int i = 0; i < m_trackLabels.size(); ++i) {
if (m_trackLabels[i]->isSelected())
retList.push_back(i);
}
return retList;
}
#endif
void
TrackButtons::slotRenameTrack(QString longLabel, QString shortLabel, TrackId trackId)
{
if (!m_doc) return;
Track *track = m_doc->getComposition().getTrackById(trackId);
if (!track) return;
TrackLabel *label = m_trackLabels[track->getPosition()];
// If neither label is changing, skip it
if (label->getTrackName() == longLabel &&
QString::fromStdString(track->getShortLabel()) == shortLabel) return;
// Rename the track
CommandHistory::getInstance()->addCommand(
new RenameTrackCommand(&m_doc->getComposition(),
trackId,
longLabel,
shortLabel));
}
void
TrackButtons::slotSetTrackMeter(float value, int position)
{
if (position < 0 || position >= m_tracks)
return;
m_trackMeters[position]->setLevel(value);
}
void
TrackButtons::slotSetMetersByInstrument(float value,
InstrumentId id)
{
Composition &comp = m_doc->getComposition();
for (int i = 0; i < m_tracks; ++i) {
Track *track = comp.getTrackByPosition(i);
if (track && track->getInstrument() == id) {
m_trackMeters[i]->setLevel(value);
}
}
}
void
TrackButtons::slotInstrumentMenu(int trackId)
{
//RG_DEBUG << "TrackButtons::slotInstrumentMenu( trackId =" << trackId << ")";
Composition &comp = m_doc->getComposition();
const int position = comp.getTrackById(trackId)->getPosition();
Track *track = comp.getTrackByPosition(position);
Instrument *instrument = nullptr;
if (track != nullptr) {
instrument = m_doc->getStudio().getInstrumentById(
track->getInstrument());
}
// *** Force The Track Label To Show The Presentation Name ***
// E.g. "General MIDI Device #1"
m_trackLabels[position]->forcePresentationName(true);
m_trackLabels[position]->updateLabel();
// *** Launch The Popup ***
// Yes, well as we might've changed the Device name in the
// Device/Bank dialog then we reload the whole menu here.
QMenu instrumentPopup(this);
populateInstrumentPopup(instrument, &instrumentPopup);
// Store the popup item position for slotInstrumentSelected().
m_popupTrackPos = position;
instrumentPopup.exec(QCursor::pos());
// *** Restore The Track Label ***
// Turn off the presentation name
m_trackLabels[position]->forcePresentationName(false);
m_trackLabels[position]->updateLabel();
}
// ??? Break this stuff off into an InstrumentPopup class. This class is too
// big.
void
TrackButtons::populateInstrumentPopup(Instrument *thisTrackInstr, QMenu* instrumentPopup)
{
// pixmaps for icons to show connection states as variously colored boxes
// ??? Factor out the icon-related stuff to make this routine clearer.
// getIcon(Instrument *) would be ideal, but might not be easy.
// getIcon(Device *) would also be needed.
static QPixmap connectedPixmap, unconnectedPixmap,
connectedUsedPixmap, unconnectedUsedPixmap,
connectedSelectedPixmap, unconnectedSelectedPixmap;
static bool havePixmaps = false;
if (!havePixmaps) {
IconLoader il;
connectedPixmap = il.loadPixmap("connected");
connectedUsedPixmap = il.loadPixmap("connected-used");
connectedSelectedPixmap = il.loadPixmap("connected-selected");
unconnectedPixmap = il.loadPixmap("unconnected");
unconnectedUsedPixmap = il.loadPixmap("unconnected-used");
unconnectedSelectedPixmap = il.loadPixmap("unconnected-selected");
havePixmaps = true;
}
Composition &comp = m_doc->getComposition();
// clear the popup
instrumentPopup->clear();
QMenu *currentSubMenu = nullptr;
// position index
int count = 0;
int currentDevId = -1;
// Get the list
Studio &studio = m_doc->getStudio();
InstrumentList list = studio.getPresentationInstruments();
// For each instrument
for (InstrumentList::iterator it = list.begin(); it != list.end(); ++it) {
if (!(*it)) continue; // sanity check
// get the Localized instrument name, with the string hackery performed
// in Instrument
QString iname((*it)->getLocalizedPresentationName());
// translate the program name
//
// Note we are converting the string from std to Q back to std then to
// C. This is obviously ridiculous, but the fact that we have programName
// here at all makes me think it exists as some kind of necessary hack
// to coax tr() into behaving nicely. I decided to change it as little
// as possible to get it to compile, and not refactor this down to the
// simplest way to call tr() on a C string.
QString programName(strtoqstr((*it)->getProgramName()));
programName = QObject::tr(programName.toStdString().c_str());
Device *device = (*it)->getDevice();
DeviceId devId = device->getId();
bool connectedIcon = false;
// Determine the proper program name and whether it is connected
if ((*it)->getType() == Instrument::SoftSynth) {
programName = "";
AudioPluginInstance *plugin =
(*it)->getPlugin(Instrument::SYNTH_PLUGIN_POSITION);
if (plugin) {
// we don't translate any plugin program names or other texts
programName = strtoqstr(plugin->getDisplayName());
connectedIcon = (plugin->getIdentifier() != "");
}
} else if ((*it)->getType() == Instrument::Audio) {
connectedIcon = true;
} else {
QString conn = RosegardenSequencer::getInstance()->
getConnection(devId);
connectedIcon = (conn != "");
}
// These two are for selecting the correct icon to display.
bool instrUsedByMe = false;
bool instrUsedByAnyone = false;
if (thisTrackInstr && thisTrackInstr->getId() == (*it)->getId()) {
instrUsedByMe = true;
instrUsedByAnyone = true;
}
// If we have switched to a new device, we'll create a new submenu
if (devId != (DeviceId)(currentDevId)) {
currentDevId = int(devId);
// For selecting the correct icon to display.
bool deviceUsedByAnyone = false;
if (instrUsedByMe)
deviceUsedByAnyone = true;
else {
for (Composition::trackcontainer::iterator tit =
comp.getTracks().begin();
tit != comp.getTracks().end(); ++tit) {
if (tit->second->getInstrument() == (*it)->getId()) {
instrUsedByAnyone = true;
deviceUsedByAnyone = true;
break;
}
Instrument *instr =
studio.getInstrumentById(tit->second->getInstrument());
if (instr && (instr->getDevice()->getId() == devId)) {
deviceUsedByAnyone = true;
}
}
}
QIcon icon
(connectedIcon ?
(deviceUsedByAnyone ?
connectedUsedPixmap : connectedPixmap) :
(deviceUsedByAnyone ?
unconnectedUsedPixmap : unconnectedPixmap));
// Create a submenu for this device
QMenu *subMenu = new QMenu(instrumentPopup);
subMenu->setMouseTracking(true);
subMenu->setIcon(icon);
// Not needed so long as AA_DontShowIconsInMenus is false.
//subMenu->menuAction()->setIconVisibleInMenu(true);
// Menu title
QString deviceName = QObject::tr(device->getName().c_str());
subMenu->setTitle(deviceName);
// QObject name
subMenu->setObjectName(deviceName);
// Add the submenu to the popup menu
instrumentPopup->addMenu(subMenu);
// Connect the submenu to slotInstrumentSelected()
connect(subMenu, SIGNAL(triggered(QAction*)),
this, SLOT(slotInstrumentSelected(QAction*)));
currentSubMenu = subMenu;
} else if (!instrUsedByMe) {
// Search the tracks to see if anyone else is using this
// instrument
for (Composition::trackcontainer::iterator tit =
comp.getTracks().begin();
tit != comp.getTracks().end(); ++tit) {
if (tit->second->getInstrument() == (*it)->getId()) {
instrUsedByAnyone = true;
break;
}
}
}
QIcon icon
(connectedIcon ?
(instrUsedByAnyone ?
instrUsedByMe ?
connectedSelectedPixmap :
connectedUsedPixmap : connectedPixmap) :
(instrUsedByAnyone ?
instrUsedByMe ?
unconnectedSelectedPixmap :
unconnectedUsedPixmap : unconnectedPixmap));
// Create an action for this instrument
QAction* action = new QAction(instrumentPopup);
action->setIcon(icon);
// Not needed so long as AA_DontShowIconsInMenus is false.
//action->setIconVisibleInMenu(true);
// Action text
if (programName != "") iname += " (" + programName + ")";
action->setText(iname);
// Item index used to find the proper instrument once the user makes
// a selection from the menu.
action->setData(QVariant(count));
// QObject object name.
action->setObjectName(iname + QString(count));
// Add the action to the current submenu
if (currentSubMenu)
currentSubMenu->addAction(action);
// Next item index
count++;
}
}
void
TrackButtons::slotInstrumentSelected(QAction* action)
{
// The action data field has the instrument index.
slotInstrumentSelected(action->data().toInt());
}
void
TrackButtons::selectInstrument(Track *track, Instrument *instrument)
{
// Inform the rest of the system of the instrument change.
// ??? This routine needs to go for two reasons:
//
// 1. TrackParameterBox calls this. UI to UI connections should be
// avoided. It would be better to copy/paste this over to TPB
// to avoid the connection. But then we have double-maintenance.
// See reason 2.
//
// 2. The UI shouldn't know so much about the other objects in the
// system. The following updates should be done by their
// respective objects.
//
// A "TrackStaticSignals::instrumentChanged(Track *, Instrument *)"
// notification is probably the best way to get rid of this routine.
// It could be emitted from Track::setInstrument(). Normally emitting
// from setters is bad, but in this case, it is necessary. We need
// to know about every single change when it occurs.
// Then ControlBlockSignalHandler (new class to avoid deriving
// ControlBlock from QObject), InstrumentSignalHandler (new class to
// handle signals for all Instrument instances), and
// SequenceManager (already derives from QObject, might want to
// consider a new SequenceManagerSignalHandler to avoid additional
// dependency on QObject) can connect and do what needs to be done in
// response. Rationale for this over doc modified is that we
// can't simply refresh everything (Instrument::sendChannelSetup()<|fim▁hole|> // changed (we would have to cache the Track->Instrument mapping and
// check it for changes).
const TrackId trackId = track->getId();
// *** ControlBlock
ControlBlock::getInstance()->
setInstrumentForTrack(trackId, instrument->getId());
// *** Send out BS/PC
// Make sure the Device is in sync with the Instrument's settings.
instrument->sendChannelSetup();
// *** SequenceManager
// In case the sequencer is currently playing, we need to regenerate
// all the events with the new channel number.
Composition &comp = m_doc->getComposition();
SequenceManager *sequenceManager = m_doc->getSequenceManager();
// For each segment in the composition
for (Composition::iterator i = comp.begin();
i != comp.end();
++i) {
Segment *segment = (*i);
// If this Segment is on this Track, let SequenceManager know
// that the Instrument has changed.
// Segments on this track are now playing on a new
// instrument, so they're no longer ready (making them
// ready is done just-in-time elsewhere), nor is thru
// channel ready.
if (segment->getTrack() == trackId)
sequenceManager->segmentInstrumentChanged(segment);
}
}
void
TrackButtons::slotInstrumentSelected(int instrumentIndex)
{
//RG_DEBUG << "slotInstrumentSelected(): instrumentIndex =" << instrumentIndex;
Instrument *instrument =
m_doc->getStudio().getInstrumentFromList(instrumentIndex);
//RG_DEBUG << "slotInstrumentSelected(): instrument " << inst;
if (!instrument) {
RG_WARNING << "slotInstrumentSelected(): WARNING: Can't find Instrument";
return;
}
Composition &comp = m_doc->getComposition();
Track *track = comp.getTrackByPosition(m_popupTrackPos);
if (!track) {
RG_WARNING << "slotInstrumentSelected(): WARNING: Can't find Track";
return;
}
// No change? Bail.
if (instrument->getId() == track->getInstrument())
return;
// Select the new instrument for the track.
// ??? This sends a trackChanged() notification. It shouldn't. We should
// send one here.
track->setInstrument(instrument->getId());
// ??? This is what we should do.
//comp.notifyTrackChanged(track);
m_doc->slotDocumentModified();
// Notify IPB, ControlBlock, and SequenceManager.
selectInstrument(track, instrument);
}
void
TrackButtons::changeLabelDisplayMode(TrackLabel::DisplayMode mode)
{
// Set new mode
m_labelDisplayMode = mode;
// For each track, set the display mode and update.
for (int i = 0; i < m_tracks; i++) {
m_trackLabels[i]->setDisplayMode(mode);
m_trackLabels[i]->updateLabel();
}
}
void
TrackButtons::slotSynchroniseWithComposition()
{
//RG_DEBUG << "slotSynchroniseWithComposition()";
Composition &comp = m_doc->getComposition();
for (int i = 0; i < m_tracks; i++) {
updateUI(comp.getTrackByPosition(i));
}
}
#if 0
void
TrackButtons::slotLabelSelected(int position)
{
Track *track =
m_doc->getComposition().getTrackByPosition(position);
if (track) {
emit trackSelected(track->getId());
}
}
#endif
void
TrackButtons::slotTPBInstrumentSelected(TrackId trackId, int instrumentIndex)
{
//RG_DEBUG << "TrackButtons::slotTPBInstrumentSelected( trackId =" << trackId << ", instrumentIndex =" << instrumentIndex << ")";
// Set the position for slotInstrumentSelected().
// ??? This isn't good. Should have a selectTrack() that takes the
// track position and the instrument index. slotInstrumentSelected()
// could call it.
m_popupTrackPos =
m_doc->getComposition().getTrackById(trackId)->getPosition();
slotInstrumentSelected(instrumentIndex);
}
int
TrackButtons::labelWidth()
{
return m_trackLabelWidth -
((m_cellSize - m_buttonGap) * 2 + m_vuSpacing * 2 + m_vuWidth);
}
int
TrackButtons::trackHeight(TrackId trackId)
{
int multiple = m_doc->
getComposition().getMaxContemporaneousSegmentsOnTrack(trackId);
if (multiple == 0)
multiple = 1;
return m_cellSize * multiple - m_borderGap;
}
QFrame*
TrackButtons::makeButton(Track *track)
{
if (track == nullptr) return nullptr;
TrackId trackId = track->getId();
// *** Horizontal Box ***
QFrame *trackHBox = new QFrame(this);
QHBoxLayout *hblayout = new QHBoxLayout(trackHBox);
trackHBox->setLayout(hblayout);
hblayout->setMargin(0);
hblayout->setSpacing(0);
trackHBox->setMinimumSize(labelWidth(), trackHeight(trackId));
trackHBox->setFixedHeight(trackHeight(trackId));
trackHBox->setFrameShape(QFrame::StyledPanel);
trackHBox->setFrameShadow(QFrame::Raised);
// We will be changing the background color, so turn on auto-fill.
trackHBox->setAutoFillBackground(true);
// Insert a little gap
hblayout->addSpacing(m_vuSpacing);
// *** VU Meter ***
TrackVUMeter *vuMeter = new TrackVUMeter(trackHBox,
VUMeter::PeakHold,
m_vuWidth,
m_buttonGap,
track->getPosition());
m_trackMeters.push_back(vuMeter);
hblayout->addWidget(vuMeter);
// Insert a little gap
hblayout->addSpacing(m_vuSpacing);
// *** Mute LED ***
LedButton *mute = new LedButton(
GUIPalette::getColour(GUIPalette::MuteTrackLED), trackHBox);
mute->setToolTip(tr("Mute track"));
hblayout->addWidget(mute);
connect(mute, SIGNAL(stateChanged(bool)),
m_muteSigMapper, SLOT(map()));
m_muteSigMapper->setMapping(mute, track->getPosition());
m_muteLeds.push_back(mute);
mute->setFixedSize(m_cellSize - m_buttonGap, m_cellSize - m_buttonGap);
// *** Record LED ***
Rosegarden::Instrument *ins =
m_doc->getStudio().getInstrumentById(track->getInstrument());
LedButton *record = new LedButton(getRecordLedColour(ins), trackHBox);
record->setToolTip(tr("Record on this track"));
hblayout->addWidget(record);
connect(record, SIGNAL(stateChanged(bool)),
m_recordSigMapper, SLOT(map()));
m_recordSigMapper->setMapping(record, track->getPosition());
m_recordLeds.push_back(record);
record->setFixedSize(m_cellSize - m_buttonGap, m_cellSize - m_buttonGap);
// *** Solo LED ***
LedButton *solo = new LedButton(
GUIPalette::getColour(GUIPalette::SoloTrackLED), trackHBox);
solo->setToolTip(tr("Solo track"));
hblayout->addWidget(solo);
connect(solo, SIGNAL(stateChanged(bool)),
m_soloSigMapper, SLOT(map()));
m_soloSigMapper->setMapping(solo, track->getPosition());
m_soloLeds.push_back(solo);
solo->setFixedSize(m_cellSize - m_buttonGap, m_cellSize - m_buttonGap);
// *** Track Label ***
TrackLabel *trackLabel =
new TrackLabel(trackId, track->getPosition(), trackHBox);
hblayout->addWidget(trackLabel);
hblayout->addSpacing(m_vuSpacing);
trackLabel->setDisplayMode(m_labelDisplayMode);
trackLabel->setFixedSize(labelWidth(), m_cellSize - m_buttonGap);
trackLabel->setFixedHeight(m_cellSize - m_buttonGap);
trackLabel->setIndent(7);
connect(trackLabel, &TrackLabel::renameTrack,
this, &TrackButtons::slotRenameTrack);
m_trackLabels.push_back(trackLabel);
// Connect it
setButtonMapping(trackLabel, trackId);
connect(trackLabel, SIGNAL(changeToInstrumentList()),
m_instListSigMapper, SLOT(map()));
connect(trackLabel, SIGNAL(clicked()),
m_clickedSigMapper, SLOT(map()));
return trackHBox;
}
QColor
TrackButtons::getRecordLedColour(Instrument *ins)
{
if (!ins) return Qt::white;
switch (ins->getType()) {
case Instrument::Audio:
return GUIPalette::getColour(GUIPalette::RecordAudioTrackLED);
case Instrument::SoftSynth:
return GUIPalette::getColour(GUIPalette::RecordSoftSynthTrackLED);
case Instrument::Midi:
return GUIPalette::getColour(GUIPalette::RecordMIDITrackLED);
case Instrument::InvalidInstrument:
default:
RG_DEBUG << "TrackButtons::slotUpdateTracks() - invalid instrument type, this is probably a BUG!";
return Qt::green;
}
}
void
TrackButtons::tracksAdded(const Composition *, std::vector<TrackId> &/*trackIds*/)
{
//RG_DEBUG << "TrackButtons::tracksAdded()";
// ??? This is a bit heavy-handed as it just adds a track button, then
// recreates all the track buttons. We might be able to just add the
// one that is needed.
slotUpdateTracks();
}
void
TrackButtons::trackChanged(const Composition *, Track* track)
{
//RG_DEBUG << "trackChanged()";
//RG_DEBUG << " Position:" << track->getPosition();
//RG_DEBUG << " Armed:" << track->isArmed();
updateUI(track);
}
void
TrackButtons::tracksDeleted(const Composition *, std::vector<TrackId> &/*trackIds*/)
{
//RG_DEBUG << "TrackButtons::tracksDeleted()";
// ??? This is a bit heavy-handed as it just deletes a track button,
// then recreates all the track buttons. We might be able to just
// delete the one that is going away.
slotUpdateTracks();
}
void
TrackButtons::trackSelectionChanged(const Composition *, TrackId trackId)
{
//RG_DEBUG << "TrackButtons::trackSelectionChanged()" << trackId;
Track *track = m_doc->getComposition().getTrackById(trackId);
selectTrack(track->getPosition());
}
void
TrackButtons::segmentRemoved(const Composition *, Segment *)
{
// If recording causes the track heights to change, this makes sure
// they go back if needed when recording stops.
slotUpdateTracks();
}
void
TrackButtons::slotTrackSelected(int trackId)
{
// Select the track.
m_doc->getComposition().setSelectedTrack(trackId);
// Old notification mechanism
// ??? This should be replaced with emitDocumentModified() below.
m_doc->getComposition().notifyTrackSelectionChanged(trackId);
// Older mechanism. Keeping this until we can completely replace it
// with emitDocumentModified() below.
emit trackSelected(trackId);
// New notification mechanism.
// This should replace all others.
m_doc->emitDocumentModified();
}
void
TrackButtons::slotDocumentModified(bool)
{
// Full and immediate update.
// ??? Note that updates probably happen elsewhere. This will result
// in duplicate updates. All other updates should be removed and
// this should be the only update.
slotUpdateTracks();
}
}<|fim▁end|> | // sends out data), and it is expensive to detect what has actually |
<|file_name|>extensions.py<|end_file_name|><|fim▁begin|>from django.contrib.auth.models import Permission
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from cms.api import create_page
from cms.constants import PUBLISHER_STATE_DIRTY
from cms.models import Page
from cms.test_utils.project.extensionapp.models import MyPageExtension, MyTitleExtension
from cms.test_utils.testcases import SettingsOverrideTestCase as TestCase
from cms.extensions import extension_pool
from cms.extensions import TitleExtension
from cms.extensions import PageExtension
from cms.tests import AdminTestsBase
from cms.compat import get_user_model
class ExtensionsTestCase(TestCase):
def test_register_extension(self):
initial_extension_count = len(extension_pool.page_extensions)
# --- None extension registering -----------------------------
from cms.exceptions import SubClassNeededError
none_extension = self.get_none_extension_class()
self.assertRaises(SubClassNeededError, extension_pool.register, none_extension)
self.assertEqual(len(extension_pool.page_extensions), initial_extension_count)
self.assertEqual(len(extension_pool.title_extensions), initial_extension_count)
# --- Page registering ---------------------------------------
page_extension = self.get_page_extension_class()
# register first time
extension_pool.register(page_extension)
self.assertEqual(len(extension_pool.page_extensions), initial_extension_count+1)
# register second time
extension_pool.register(page_extension)
self.assertEqual(len(extension_pool.page_extensions), initial_extension_count+1)
self.assertIs(extension_pool.signaling_activated, True)
# --- Title registering --------------------------------------
title_extension = self.get_title_extension_class()
# register first time
extension_pool.register(title_extension)
self.assertEqual(len(extension_pool.title_extensions), initial_extension_count+1)
# register second time
extension_pool.register(title_extension)
self.assertEqual(len(extension_pool.title_extensions), initial_extension_count+1)
self.assertIs(extension_pool.signaling_activated, True)
# --- Unregister ---------------------------------------------
extension_pool.unregister(page_extension)
self.assertEqual(len(extension_pool.page_extensions), initial_extension_count)
extension_pool.unregister(title_extension)
self.assertEqual(len(extension_pool.title_extensions), initial_extension_count)
# Unregister an object that is not registered yet
extension_pool.unregister(page_extension)
extension_pool.unregister(title_extension)
def get_page_extension_class(self):
from django.db import models
class TestPageExtension(PageExtension):
content = models.CharField('Content', max_length=50)
return TestPageExtension
def get_title_extension_class(self):
from django.db import models
class TestTitleExtension(TitleExtension):
content = models.CharField('Content', max_length=50)
return TestTitleExtension
def get_none_extension_class(self):
class TestNoneExtension(object):
pass
return TestNoneExtension
def test_publish_page_extension(self):
page = create_page('Test Page Extension', "nav_playground.html", "en")
page_extension = MyPageExtension(extended_object=page, extra='page extension 1')
page_extension.save()
page.mypageextension = page_extension
# publish first time
page.publish('en')
self.assertEqual(page_extension.extra, page.publisher_public.mypageextension.extra)
self.assertEqual(page.get_publisher_state('en'), 0)
# change and publish again
page = Page.objects.get(pk=page.pk)
page_extension = page.mypageextension
page_extension.extra = 'page extension 1 - changed'
page_extension.save()
self.assertEqual(page.get_publisher_state('en', True), PUBLISHER_STATE_DIRTY)
page.publish('en')
self.assertEqual(page.get_publisher_state('en', True), 0)
# delete
page_extension.delete()
self.assertFalse(MyPageExtension.objects.filter(pk=page_extension.pk).exists())
self.assertEqual(page.get_publisher_state('en', True), PUBLISHER_STATE_DIRTY)
def test_publish_title_extension(self):
page = create_page('Test Title Extension', "nav_playground.html", "en")
title = page.get_title_obj()
title_extension = MyTitleExtension(extended_object=title, extra_title='title extension 1')
title_extension.save()
page.mytitleextension = title_extension
# publish first time
page.publish('en')
# import ipdb; ipdb.set_trace()
self.assertEqual(page.get_publisher_state('en'), 0)
self.assertEqual(title_extension.extra_title, page.publisher_public.get_title_obj().mytitleextension.extra_title)
# change and publish again
page = Page.objects.get(pk=page.pk)
title = page.get_title_obj()
title_extension = title.mytitleextension
title_extension.extra_title = 'title extension 1 - changed'
title_extension.save()
self.assertEqual(page.get_publisher_state('en', True), PUBLISHER_STATE_DIRTY)
page.publish('en')
self.assertEqual(page.get_publisher_state('en', True), 0)
# delete
title_extension.delete()
self.assertFalse(MyTitleExtension.objects.filter(pk=title_extension.pk).exists())
class ExtensionAdminTestCase(AdminTestsBase):
def setUp(self):
User = get_user_model()
self.admin, self.normal_guy = self._get_guys()
if get_user_model().USERNAME_FIELD == 'email':
self.no_page_permission_user = User.objects.create_user('no_page_permission', '[email protected]', '[email protected]')
else:
self.no_page_permission_user = User.objects.create_user('no_page_permission', '[email protected]', 'no_page_permission')
self.no_page_permission_user.is_staff = True
self.no_page_permission_user.is_active = True
self.no_page_permission_user.save()
[self.no_page_permission_user.user_permissions.add(p) for p in Permission.objects.filter(
codename__in=[
'change_mypageextension', 'change_mytitleextension',
'add_mypageextension', 'add_mytitleextension',
'delete_mypageextension', 'delete_mytitleextension',
]
)]
self.site = Site.objects.get(pk=1)
self.page = create_page(
'My Extension Page', 'nav_playground.html', 'en',
site=self.site, created_by=self.admin)
self.page_title = self.page.get_title_obj()<|fim▁hole|> self.page_extension = MyPageExtension.objects.create(
extended_object=self.page,
extra="page extension text")
self.title_extension = MyTitleExtension.objects.create(
extended_object=self.page.get_title_obj(),
extra_title="title extension text")
self.page_without_extension = create_page(
'A Page', 'nav_playground.html', 'en',
site=self.site, created_by=self.admin)
self.page_title_without_extension = self.page_without_extension.get_title_obj()
def test_admin_page_extension(self):
with self.login_user_context(self.admin):
# add a new extension
response = self.client.get(
reverse('admin:extensionapp_mypageextension_add') + '?extended_object=%s' % self.page_without_extension.pk
)
self.assertEqual(response.status_code, 200)
# make sure there is no extension yet
self.assertFalse(MyPageExtension.objects.filter(extended_object=self.page_without_extension).exists())
post_data = {
'extra': 'my extra'
}
response = self.client.post(
reverse('admin:extensionapp_mypageextension_add') + '?extended_object=%s' % self.page_without_extension.pk,
post_data, follow=True
)
created_page_extension = MyPageExtension.objects.get(extended_object=self.page_without_extension)
# can delete extension
response = self.client.post(
reverse('admin:extensionapp_mypageextension_delete', args=(created_page_extension.pk,)),
{'post': 'yes'}, follow=True
)
self.assertFalse(MyPageExtension.objects.filter(extended_object=self.page_without_extension).exists())
# accessing the add view on a page that already has an extension should redirect
response = self.client.get(
reverse('admin:extensionapp_mypageextension_add') + '?extended_object=%s' % self.page.pk
)
self.assertRedirects(response, reverse('admin:extensionapp_mypageextension_change', args=(self.page_extension.pk,)))
# saving an extension should work without the GET parameter
post_data = {
'extra': 'my extra text'
}
self.client.post(
reverse('admin:extensionapp_mypageextension_change', args=(self.page_extension.pk,)),
post_data, follow=True
)
self.assertTrue(MyPageExtension.objects.filter(extra='my extra text', pk=self.page_extension.pk).exists())
with self.login_user_context(self.no_page_permission_user):
# can't save if user does not have permissions to change the page
post_data = {
'extra': 'try to change extra text'
}
response = self.client.post(
reverse('admin:extensionapp_mypageextension_change', args=(self.page_extension.pk,)),
post_data, follow=True
)
self.assertEqual(response.status_code, 403)
# can't delete without page permission
response = self.client.post(
reverse('admin:extensionapp_mypageextension_delete', args=(self.page_extension.pk,)),
{'post': 'yes'}, follow=True
)
self.assertEqual(response.status_code, 403)
self.assertTrue(MyPageExtension.objects.filter(extended_object=self.page).exists())
def test_admin_title_extension(self):
with self.login_user_context(self.admin):
# add a new extension
response = self.client.get(
reverse('admin:extensionapp_mytitleextension_add') + '?extended_object=%s' % self.page_title_without_extension.pk
)
self.assertEqual(response.status_code, 200)
# make sure there is no extension yet
self.assertFalse(MyTitleExtension.objects.filter(extended_object=self.page_title_without_extension).exists())
post_data = {
'extra_title': 'my extra title'
}
self.client.post(
reverse('admin:extensionapp_mytitleextension_add') + '?extended_object=%s' % self.page_title_without_extension.pk,
post_data, follow=True
)
created_title_extension = MyTitleExtension.objects.get(extended_object=self.page_title_without_extension)
# can delete extension
self.client.post(
reverse('admin:extensionapp_mytitleextension_delete', args=(created_title_extension.pk,)),
{'post': 'yes'}, follow=True
)
self.assertFalse(MyTitleExtension.objects.filter(extended_object=self.page_title_without_extension).exists())
# accessing the add view on a page that already has an extension should redirect
response = self.client.get(
reverse('admin:extensionapp_mytitleextension_add') + '?extended_object=%s' % self.page_title.pk
)
self.assertRedirects(response, reverse('admin:extensionapp_mytitleextension_change', args=(self.title_extension.pk,)))
# saving an extension should work without the GET parameter
post_data = {
'extra_title': 'my extra text'
}
self.client.post(
reverse('admin:extensionapp_mytitleextension_change', args=(self.title_extension.pk,)),
post_data, follow=True
)
self.assertTrue(MyTitleExtension.objects.filter(extra_title='my extra text', pk=self.title_extension.pk).exists())
with self.login_user_context(self.no_page_permission_user):
# can't save if user does not have permissions to change the page
post_data = {
'extra_title': 'try to change extra text'
}
response = self.client.post(
reverse('admin:extensionapp_mytitleextension_change', args=(self.title_extension.pk,)),
post_data, follow=True
)
self.assertEqual(response.status_code, 403)
# can't delete without page permission
response = self.client.post(
reverse('admin:extensionapp_mytitleextension_delete', args=(self.title_extension.pk,)),
{'post': 'yes'}, follow=True
)
self.assertEqual(response.status_code, 403)
self.assertTrue(MyTitleExtension.objects.filter(extended_object=self.page_title).exists())<|fim▁end|> | |
<|file_name|>discriminative_reranking_task.py<|end_file_name|><|fim▁begin|># Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass, field
import itertools
import logging
import os
import numpy as np
import torch
from fairseq import metrics
from fairseq.data import (
ConcatDataset,
ConcatSentencesDataset,
data_utils,
Dictionary,
IdDataset,
indexed_dataset,
NestedDictionaryDataset,
NumSamplesDataset,
NumelDataset,
PrependTokenDataset,
RawLabelDataset,
RightPadDataset,
SortDataset,
TruncateDataset,
TokenBlockDataset,
)
from fairseq.dataclass import ChoiceEnum, FairseqDataclass
from fairseq.tasks import FairseqTask, register_task
from omegaconf import II, MISSING
EVAL_BLEU_ORDER = 4
TARGET_METRIC_CHOICES = ChoiceEnum(["bleu", "ter"])
logger = logging.getLogger(__name__)
@dataclass
class DiscriminativeRerankingNMTConfig(FairseqDataclass):
data: str = field(default=MISSING, metadata={"help": "path to data directory"})
num_data_splits: int = field(
default=1, metadata={"help": "total number of data splits"}
)
no_shuffle: bool = field(
default=False, metadata={"help": "do not shuffle training data"}
)
max_positions: int = field(
default=512, metadata={"help": "number of positional embeddings to learn"}
)
include_src: bool = field(
default=False, metadata={"help": "include source sentence"}
)
mt_beam: int = field(default=50, metadata={"help": "beam size of input hypotheses"})
eval_target_metric: bool = field(
default=False,
metadata={"help": "evaluation with the target metric during validation"},
)
target_metric: TARGET_METRIC_CHOICES = field(
default="bleu", metadata={"help": "name of the target metric to optimize for"}
)
train_subset: str = field(
default=II("dataset.train_subset"),
metadata={"help": "data subset to use for training (e.g. train, valid, test)"},
)
seed: int = field(
default=II("common.seed"),
metadata={"help": "pseudo random number generator seed"},
)
class RerankerScorer(object):
"""Scores the target for a given (source (optional), target) input."""
def __init__(self, args, mt_beam):
self.mt_beam = mt_beam
@torch.no_grad()
def generate(self, models, sample, **kwargs):
"""Score a batch of translations."""
net_input = sample["net_input"]
assert len(models) == 1, "does not support model ensemble"
model = models[0]
bs = net_input["src_tokens"].shape[0]
assert (
model.joint_classification == "none" or bs % self.mt_beam == 0
), f"invalid batch size ({bs}) for joint classification with beam size ({self.mt_beam})"
model.eval()
logits = model(**net_input)
batch_out = model.sentence_forward(logits, net_input["src_tokens"])
if model.joint_classification == "sent":
batch_out = model.joint_forward(
batch_out.view(self.mt_beam, bs // self.mt_beam, -1)
)
scores = model.classification_forward(
batch_out.view(bs, 1, -1)
) # input: B x T x C
return scores
@register_task(
"discriminative_reranking_nmt", dataclass=DiscriminativeRerankingNMTConfig
)
class DiscriminativeRerankingNMTTask(FairseqTask):
"""
Translation rerank task.
The input can be either (src, tgt) sentence pairs or tgt sentence only.
"""
cfg: DiscriminativeRerankingNMTConfig
def __init__(self, cfg: DiscriminativeRerankingNMTConfig, data_dictionary=None):
super().__init__(cfg)
self.dictionary = data_dictionary
self._max_positions = cfg.max_positions
# args.tokens_per_sample = self._max_positions
# self.num_classes = 1 # for model
@classmethod
def load_dictionary(cls, cfg, filename):
"""Load the dictionary from the filename"""
dictionary = Dictionary.load(filename)
dictionary.add_symbol("<mask>") # for loading pretrained XLMR model
return dictionary
@classmethod
def setup_task(cls, cfg: DiscriminativeRerankingNMTConfig, **kwargs):
# load data dictionary (assume joint dictionary)
data_path = cfg.data
data_dict = cls.load_dictionary(
cfg, os.path.join(data_path, "input_src/dict.txt")
)
logger.info("[input] src dictionary: {} types".format(len(data_dict)))
return DiscriminativeRerankingNMTTask(cfg, data_dict)
def load_dataset(self, split, epoch=0, combine=False, **kwargs):
"""Load a given dataset split (e.g., train, valid, test)."""
if self.cfg.data.endswith("1"):
data_shard = (epoch - 1) % self.cfg.num_data_splits + 1
data_path = self.cfg.data[:-1] + str(data_shard)
else:
data_path = self.cfg.data
def get_path(type, data_split):
return os.path.join(data_path, str(type), data_split)
def make_dataset(type, dictionary, data_split, combine):
split_path = get_path(type, data_split)
dataset = data_utils.load_indexed_dataset(
split_path,
dictionary,
combine=combine,
)
return dataset
def load_split(data_split, metric):
input_src = None
if self.cfg.include_src:
input_src = make_dataset(
"input_src", self.dictionary, data_split, combine=False
)
assert input_src is not None, "could not find dataset: {}".format(
get_path("input_src", data_split)
)
input_tgt = make_dataset(
"input_tgt", self.dictionary, data_split, combine=False
)
assert input_tgt is not None, "could not find dataset: {}".format(
get_path("input_tgt", data_split)
)
label_path = f"{get_path(metric, data_split)}.{metric}"
assert os.path.exists(label_path), f"could not find dataset: {label_path}"
np_labels = np.loadtxt(label_path)
if self.cfg.target_metric == "ter":
np_labels = -np_labels
label = RawLabelDataset(np_labels)
return input_src, input_tgt, label
src_datasets = []
tgt_datasets = []
label_datasets = []
if split == self.cfg.train_subset:
for k in itertools.count():
split_k = "train" + (str(k) if k > 0 else "")
prefix = os.path.join(data_path, "input_tgt", split_k)
if not indexed_dataset.dataset_exists(prefix, impl=None):
if k > 0:
break
else:
raise FileNotFoundError(f"Dataset not found: {prefix}")
input_src, input_tgt, label = load_split(
split_k, self.cfg.target_metric
)
src_datasets.append(input_src)
tgt_datasets.append(input_tgt)
label_datasets.append(label)
else:
input_src, input_tgt, label = load_split(split, self.cfg.target_metric)
src_datasets.append(input_src)
tgt_datasets.append(input_tgt)
label_datasets.append(label)
if len(tgt_datasets) == 1:
input_tgt, label = tgt_datasets[0], label_datasets[0]
if self.cfg.include_src:
input_src = src_datasets[0]
else:
input_tgt = ConcatDataset(tgt_datasets)
label = ConcatDataset(label_datasets)
if self.cfg.include_src:
input_src = ConcatDataset(src_datasets)
input_tgt = TruncateDataset(input_tgt, self.cfg.max_positions)
if self.cfg.include_src:
input_src = PrependTokenDataset(input_src, self.dictionary.bos())
input_src = TruncateDataset(input_src, self.cfg.max_positions)
src_lengths = NumelDataset(input_src, reduce=False)
src_tokens = ConcatSentencesDataset(input_src, input_tgt)
else:
src_tokens = PrependTokenDataset(input_tgt, self.dictionary.bos())
src_lengths = NumelDataset(src_tokens, reduce=False)
dataset = {
"id": IdDataset(),
"net_input": {
"src_tokens": RightPadDataset(
src_tokens,
pad_idx=self.source_dictionary.pad(),
),
"src_lengths": src_lengths,
},
"nsentences": NumSamplesDataset(),
"ntokens": NumelDataset(src_tokens, reduce=True),
"target": label,
}
dataset = NestedDictionaryDataset(
dataset,
sizes=[src_tokens.sizes],
)
assert (
len(dataset) % self.cfg.mt_beam == 0
), "dataset size (%d) is not a multiple of beam size (%d)" % (
len(dataset),
self.cfg.mt_beam,
)
# no need to shuffle valid/test sets
if not self.cfg.no_shuffle and split == self.cfg.train_subset:
# need to keep all hypothese together
start_idx = np.arange(0, len(dataset), self.cfg.mt_beam)
with data_utils.numpy_seed(self.cfg.seed + epoch):
np.random.shuffle(start_idx)
idx = np.arange(0, self.cfg.mt_beam)
shuffle = np.tile(idx, (len(start_idx), 1)).reshape(-1) + np.tile(
start_idx, (self.cfg.mt_beam, 1)
).transpose().reshape(-1)
dataset = SortDataset(
dataset,
sort_order=[shuffle],
)
logger.info(f"Loaded {split} with #samples: {len(dataset)}")
self.datasets[split] = dataset
return self.datasets[split]
def build_dataset_for_inference(self, src_tokens, src_lengths, **kwargs):
assert not self.cfg.include_src or len(src_tokens[0]) == 2
input_src = None
if self.cfg.include_src:
input_src = TokenBlockDataset(
[t[0] for t in src_tokens],
[l[0] for l in src_lengths],
block_size=None, # ignored for "eos" break mode
pad=self.source_dictionary.pad(),
eos=self.source_dictionary.eos(),
break_mode="eos",
)
input_src = PrependTokenDataset(input_src, self.dictionary.bos())
input_src = TruncateDataset(input_src, self.cfg.max_positions)
input_tgt = TokenBlockDataset(
[t[-1] for t in src_tokens],
[l[-1] for l in src_lengths],
block_size=None, # ignored for "eos" break mode
pad=self.source_dictionary.pad(),
eos=self.source_dictionary.eos(),
break_mode="eos",
)
input_tgt = TruncateDataset(input_tgt, self.cfg.max_positions)
if self.cfg.include_src:
src_tokens = ConcatSentencesDataset(input_src, input_tgt)
src_lengths = NumelDataset(input_src, reduce=False)
else:
input_tgt = PrependTokenDataset(input_tgt, self.dictionary.bos())
src_tokens = input_tgt
src_lengths = NumelDataset(src_tokens, reduce=False)
dataset = {
"id": IdDataset(),
"net_input": {
"src_tokens": RightPadDataset(
src_tokens,
pad_idx=self.source_dictionary.pad(),
),
"src_lengths": src_lengths,
},
"nsentences": NumSamplesDataset(),
"ntokens": NumelDataset(src_tokens, reduce=True),
}
return NestedDictionaryDataset(
dataset,
sizes=[src_tokens.sizes],
)
def build_model(self, cfg: FairseqDataclass, from_checkpoint: bool = False):
return super().build_model(cfg)
def build_generator(self, args):
return RerankerScorer(args, mt_beam=self.cfg.mt_beam)
def max_positions(self):
return self._max_positions
@property
def source_dictionary(self):
return self.dictionary
@property
def target_dictionary(self):
return self.dictionary
def create_dummy_batch(self, device):
dummy_target = (
torch.zeros(self.cfg.mt_beam, EVAL_BLEU_ORDER * 2 + 3).long().to(device)
if not self.cfg.eval_ter
else torch.zeros(self.cfg.mt_beam, 3).long().to(device)
)
return {
"id": torch.zeros(self.cfg.mt_beam, 1).long().to(device),
"net_input": {
"src_tokens": torch.zeros(self.cfg.mt_beam, 4).long().to(device),
"src_lengths": torch.ones(self.cfg.mt_beam, 1).long().to(device),
},
"nsentences": 0,
"ntokens": 0,
"target": dummy_target,
}
def train_step(
self, sample, model, criterion, optimizer, update_num, ignore_grad=False
):
if ignore_grad and sample is None:
sample = self.create_dummy_batch(model.device)
return super().train_step(
sample, model, criterion, optimizer, update_num, ignore_grad
)
def valid_step(self, sample, model, criterion):
if sample is None:
sample = self.create_dummy_batch(model.device)
loss, sample_size, logging_output = super().valid_step(sample, model, criterion)
if not self.cfg.eval_target_metric:
return loss, sample_size, logging_output
scores = logging_output["scores"]
if self.cfg.target_metric == "bleu":
assert sample["target"].shape[1] == EVAL_BLEU_ORDER * 2 + 3, (
"target does not contain enough information ("
+ str(sample["target"].shape[1])
+ "for evaluating BLEU"
)
max_id = torch.argmax(scores, dim=1)
select_id = max_id + torch.arange(
0, sample_size * self.cfg.mt_beam, self.cfg.mt_beam
).to(max_id.device)
bleu_data = sample["target"][select_id, 1:].sum(0).data
logging_output["_bleu_sys_len"] = bleu_data[0]
logging_output["_bleu_ref_len"] = bleu_data[1]
for i in range(EVAL_BLEU_ORDER):
logging_output["_bleu_counts_" + str(i)] = bleu_data[2 + i]
logging_output["_bleu_totals_" + str(i)] = bleu_data[
2 + EVAL_BLEU_ORDER + i
]
elif self.cfg.target_metric == "ter":
assert sample["target"].shape[1] == 3, (
"target does not contain enough information ("
+ str(sample["target"].shape[1])
+ "for evaluating TER"
)
max_id = torch.argmax(scores, dim=1)
select_id = max_id + torch.arange(
0, sample_size * self.cfg.mt_beam, self.cfg.mt_beam
).to(max_id.device)
ter_data = sample["target"][select_id, 1:].sum(0).data
logging_output["_ter_num_edits"] = -ter_data[0]
logging_output["_ter_ref_len"] = -ter_data[1]
return loss, sample_size, logging_output
def reduce_metrics(self, logging_outputs, criterion):
super().reduce_metrics(logging_outputs, criterion)
if not self.cfg.eval_target_metric:
return
def sum_logs(key):
return sum(log.get(key, 0) for log in logging_outputs)
if self.cfg.target_metric == "bleu":
counts, totals = [], []
for i in range(EVAL_BLEU_ORDER):
counts.append(sum_logs("_bleu_counts_" + str(i)))
totals.append(sum_logs("_bleu_totals_" + str(i)))
if max(totals) > 0:
# log counts as numpy arrays -- log_scalar will sum them correctly
metrics.log_scalar("_bleu_counts", np.array(counts))
metrics.log_scalar("_bleu_totals", np.array(totals))
metrics.log_scalar("_bleu_sys_len", sum_logs("_bleu_sys_len"))
metrics.log_scalar("_bleu_ref_len", sum_logs("_bleu_ref_len"))
def compute_bleu(meters):
import inspect
import sacrebleu
fn_sig = inspect.getfullargspec(sacrebleu.compute_bleu)[0]
if "smooth_method" in fn_sig:
smooth = {"smooth_method": "exp"}
else:
smooth = {"smooth": "exp"}
bleu = sacrebleu.compute_bleu(
correct=meters["_bleu_counts"].sum,
total=meters["_bleu_totals"].sum,<|fim▁hole|> sys_len=meters["_bleu_sys_len"].sum,
ref_len=meters["_bleu_ref_len"].sum,
**smooth,
)
return round(bleu.score, 2)
metrics.log_derived("bleu", compute_bleu)
elif self.cfg.target_metric == "ter":
num_edits = sum_logs("_ter_num_edits")
ref_len = sum_logs("_ter_ref_len")
if ref_len > 0:
metrics.log_scalar("_ter_num_edits", num_edits)
metrics.log_scalar("_ter_ref_len", ref_len)
def compute_ter(meters):
score = meters["_ter_num_edits"].sum / meters["_ter_ref_len"].sum
return round(score.item(), 2)
metrics.log_derived("ter", compute_ter)<|fim▁end|> | |
<|file_name|>font_face.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The [`@font-face`][ff] at-rule.
//!
//! [ff]: https://drafts.csswg.org/css-fonts/#at-font-face-rule
#![deny(missing_docs)]
#[cfg(feature = "gecko")]
use computed_values::{font_stretch, font_style, font_weight};
use cssparser::{AtRuleParser, DeclarationListParser, DeclarationParser, Parser};
use cssparser::{SourceLocation, CowRcStr};
use error_reporting::{ContextualParseError, ParseErrorReporter};
#[cfg(feature = "gecko")] use gecko_bindings::structs::CSSFontFaceDescriptors;
#[cfg(feature = "gecko")] use cssparser::UnicodeRange;
use parser::{ParserContext, ParserErrorContext, Parse};
#[cfg(feature = "gecko")]
use properties::longhands::font_language_override;
use selectors::parser::SelectorParseErrorKind;
use shared_lock::{SharedRwLockReadGuard, ToCssWithGuard};
use std::fmt::{self, Write};
use str::CssStringWriter;
use style_traits::{Comma, CssWriter, OneOrMoreSeparated, ParseError};
use style_traits::{StyleParseErrorKind, ToCss};
use values::computed::font::FamilyName;
#[cfg(feature = "gecko")]
use values::specified::font::{SpecifiedFontFeatureSettings, SpecifiedFontVariationSettings};
use values::specified::url::SpecifiedUrl;
/// A source for a font-face rule.
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Debug, Eq, PartialEq, ToCss)]
pub enum Source {
/// A `url()` source.
Url(UrlSource),
/// A `local()` source.
#[css(function)]
Local(FamilyName),
}
impl OneOrMoreSeparated for Source {
type S = Comma;
}
/// A `UrlSource` represents a font-face source that has been specified with a
/// `url()` function.
///
/// <https://drafts.csswg.org/css-fonts/#src-desc>
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Debug, Eq, PartialEq, ToCss)]
pub struct UrlSource {
/// The specified url.
pub url: SpecifiedUrl,
/// The format hints specified with the `format()` function.
#[css(skip)]
pub format_hints: Vec<String>,
}
/// A font-display value for a @font-face rule.
/// The font-display descriptor determines how a font face is displayed based
/// on whether and when it is downloaded and ready to use.
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq)]
#[derive(ToComputedValue, ToCss)]
pub enum FontDisplay {
Auto,
Block,
Swap,
Fallback,
Optional,
}
/// A font-weight value for a @font-face rule.
/// The font-weight CSS property specifies the weight or boldness of the font.
#[cfg(feature = "gecko")]
#[derive(Clone, Debug, Eq, PartialEq, ToCss)]
pub enum FontWeight {
/// Numeric font weights for fonts that provide more than just normal and bold.
Weight(font_weight::T),
/// Normal font weight. Same as 400.
Normal,
/// Bold font weight. Same as 700.
Bold,
}
#[cfg(feature = "gecko")]
impl Parse for FontWeight {
fn parse<'i, 't>(_: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<FontWeight, ParseError<'i>> {
let result = input.try(|input| {
let ident = input.expect_ident().map_err(|_| ())?;
match_ignore_ascii_case! { &ident,
"normal" => Ok(FontWeight::Normal),
"bold" => Ok(FontWeight::Bold),
_ => Err(())
}
});
result.or_else(|_| {
font_weight::T::from_int(input.expect_integer()?)
.map(FontWeight::Weight)
.map_err(|()| input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
})
}
}
/// Parse the block inside a `@font-face` rule.
///
/// Note that the prelude parsing code lives in the `stylesheets` module.
pub fn parse_font_face_block<R>(context: &ParserContext,
error_context: &ParserErrorContext<R>,
input: &mut Parser,
location: SourceLocation)
-> FontFaceRuleData
where R: ParseErrorReporter
{
let mut rule = FontFaceRuleData::empty(location);
{
let parser = FontFaceRuleParser {
context: context,
rule: &mut rule,
};
let mut iter = DeclarationListParser::new(input, parser);
while let Some(declaration) = iter.next() {
if let Err((error, slice)) = declaration {
let location = error.location;
let error = ContextualParseError::UnsupportedFontFaceDescriptor(slice, error);
context.log_css_error(error_context, location, error)
}
}
}
rule
}
/// A @font-face rule that is known to have font-family and src declarations.
#[cfg(feature = "servo")]
pub struct FontFace<'a>(&'a FontFaceRuleData);
/// A list of effective sources that we send over through IPC to the font cache.
#[cfg(feature = "servo")]
#[derive(Clone, Debug)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub struct EffectiveSources(Vec<Source>);
#[cfg(feature = "servo")]
impl<'a> FontFace<'a> {
/// Returns the list of effective sources for that font-face, that is the
/// sources which don't list any format hint, or the ones which list at
/// least "truetype" or "opentype".
pub fn effective_sources(&self) -> EffectiveSources {
EffectiveSources(self.sources().iter().rev().filter(|source| {
if let Source::Url(ref url_source) = **source {
let hints = &url_source.format_hints;
// We support only opentype fonts and truetype is an alias for
// that format. Sources without format hints need to be
// downloaded in case we support them.
hints.is_empty() || hints.iter().any(|hint| {
hint == "truetype" || hint == "opentype" || hint == "woff"
})
} else {
true
}
}).cloned().collect())
}
}
#[cfg(feature = "servo")]
impl Iterator for EffectiveSources {
type Item = Source;
fn next(&mut self) -> Option<Source> {
self.0.pop()
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.0.len(), Some(self.0.len()))
}
}
struct FontFaceRuleParser<'a, 'b: 'a> {
context: &'a ParserContext<'b>,
rule: &'a mut FontFaceRuleData,
}
/// Default methods reject all at rules.
impl<'a, 'b, 'i> AtRuleParser<'i> for FontFaceRuleParser<'a, 'b> {
type PreludeNoBlock = ();
type PreludeBlock = ();
type AtRule = ();
type Error = StyleParseErrorKind<'i>;
}
impl Parse for Source {
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Source, ParseError<'i>> {
if input.try(|input| input.expect_function_matching("local")).is_ok() {
return input.parse_nested_block(|input| {
FamilyName::parse(context, input)
}).map(Source::Local)
}
let url = SpecifiedUrl::parse(context, input)?;
// Parsing optional format()
let format_hints = if input.try(|input| input.expect_function_matching("format")).is_ok() {
input.parse_nested_block(|input| {
input.parse_comma_separated(|input| {
Ok(input.expect_string()?.as_ref().to_owned())
})
})?
} else {
vec![]
};
Ok(Source::Url(UrlSource {
url: url,
format_hints: format_hints,
}))
}
}
macro_rules! is_descriptor_enabled {
("font-display") => {
unsafe {
use gecko_bindings::structs::mozilla;
mozilla::StylePrefs_sFontDisplayEnabled
}
};
("font-variation-settings") => {
unsafe {
use gecko_bindings::structs::mozilla;
mozilla::StylePrefs_sFontVariationsEnabled
}
};
($name: tt) => { true }
}
macro_rules! font_face_descriptors_common {
(
$( #[$doc: meta] $name: tt $ident: ident / $gecko_ident: ident: $ty: ty, )*
) => {
/// Data inside a `@font-face` rule.
///
/// <https://drafts.csswg.org/css-fonts/#font-face-rule>
#[derive(Clone, Debug, PartialEq)]
pub struct FontFaceRuleData {
$(
#[$doc]
pub $ident: Option<$ty>,
)*
/// Line and column of the @font-face rule source code.
pub source_location: SourceLocation,
}
impl FontFaceRuleData {
fn empty(location: SourceLocation) -> Self {
FontFaceRuleData {
$(
$ident: None,
)*
source_location: location,<|fim▁hole|> }
}
/// Convert to Gecko types
#[cfg(feature = "gecko")]
pub fn set_descriptors(self, descriptors: &mut CSSFontFaceDescriptors) {
$(
if let Some(value) = self.$ident {
descriptors.$gecko_ident.set_from(value)
}
)*
// Leave unset descriptors to eCSSUnit_Null,
// FontFaceSet::FindOrCreateUserFontEntryFromFontFace does the defaulting
// to initial values.
}
}
impl ToCssWithGuard for FontFaceRuleData {
// Serialization of FontFaceRule is not specced.
fn to_css(&self, _guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
dest.write_str("@font-face {\n")?;
$(
if let Some(ref value) = self.$ident {
dest.write_str(concat!(" ", $name, ": "))?;
ToCss::to_css(value, &mut CssWriter::new(dest))?;
dest.write_str(";\n")?;
}
)*
dest.write_str("}")
}
}
impl<'a, 'b, 'i> DeclarationParser<'i> for FontFaceRuleParser<'a, 'b> {
type Declaration = ();
type Error = StyleParseErrorKind<'i>;
fn parse_value<'t>(&mut self, name: CowRcStr<'i>, input: &mut Parser<'i, 't>)
-> Result<(), ParseError<'i>> {
match_ignore_ascii_case! { &*name,
$(
$name if is_descriptor_enabled!($name) => {
// DeclarationParser also calls parse_entirely
// so we’d normally not need to,
// but in this case we do because we set the value as a side effect
// rather than returning it.
let value = input.parse_entirely(|i| Parse::parse(self.context, i))?;
self.rule.$ident = Some(value)
}
)*
_ => return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(name.clone())))
}
Ok(())
}
}
}
}
macro_rules! font_face_descriptors {
(
mandatory descriptors = [
$( #[$m_doc: meta] $m_name: tt $m_ident: ident / $m_gecko_ident: ident: $m_ty: ty, )*
]
optional descriptors = [
$( #[$o_doc: meta] $o_name: tt $o_ident: ident / $o_gecko_ident: ident: $o_ty: ty, )*
]
) => {
font_face_descriptors_common! {
$( #[$m_doc] $m_name $m_ident / $m_gecko_ident: $m_ty, )*
$( #[$o_doc] $o_name $o_ident / $o_gecko_ident: $o_ty, )*
}
impl FontFaceRuleData {
/// Per https://github.com/w3c/csswg-drafts/issues/1133 an @font-face rule
/// is valid as far as the CSS parser is concerned even if it doesn’t have
/// a font-family or src declaration.
///
/// However both are required for the rule to represent an actual font face.
#[cfg(feature = "servo")]
pub fn font_face(&self) -> Option<FontFace> {
if $( self.$m_ident.is_some() )&&* {
Some(FontFace(self))
} else {
None
}
}
}
#[cfg(feature = "servo")]
impl<'a> FontFace<'a> {
$(
#[$m_doc]
pub fn $m_ident(&self) -> &$m_ty {
self.0 .$m_ident.as_ref().unwrap()
}
)*
}
}
}
/// css-name rust_identifier: Type,
#[cfg(feature = "gecko")]
font_face_descriptors! {
mandatory descriptors = [
/// The name of this font face
"font-family" family / mFamily: FamilyName,
/// The alternative sources for this font face.
"src" sources / mSrc: Vec<Source>,
]
optional descriptors = [
/// The style of this font face
"font-style" style / mStyle: font_style::T,
/// The weight of this font face
"font-weight" weight / mWeight: FontWeight,
/// The stretch of this font face
"font-stretch" stretch / mStretch: font_stretch::T,
/// The display of this font face
"font-display" display / mDisplay: FontDisplay,
/// The ranges of code points outside of which this font face should not be used.
"unicode-range" unicode_range / mUnicodeRange: Vec<UnicodeRange>,
/// The feature settings of this font face.
"font-feature-settings" feature_settings / mFontFeatureSettings: SpecifiedFontFeatureSettings,
/// The variation settings of this font face.
"font-variation-settings" variation_settings / mFontVariationSettings: SpecifiedFontVariationSettings,
/// The language override of this font face.
"font-language-override" language_override / mFontLanguageOverride: font_language_override::SpecifiedValue,
]
}
#[cfg(feature = "servo")]
font_face_descriptors! {
mandatory descriptors = [
/// The name of this font face
"font-family" family / mFamily: FamilyName,
/// The alternative sources for this font face.
"src" sources / mSrc: Vec<Source>,
]
optional descriptors = [
]
}<|fim▁end|> | |
<|file_name|>Exports.js<|end_file_name|><|fim▁begin|>/********************************************************************<|fim▁hole|>vs.util.extend (exports, {
Animation: Animation,
Trajectory: Trajectory,
Vector1D: Vector1D,
Vector2D: Vector2D,
Circular2D: Circular2D,
Pace: Pace,
Chronometer: Chronometer,
generateCubicBezierFunction: generateCubicBezierFunction,
createTransition: createTransition,
freeTransition: freeTransition,
animateTransitionBis: animateTransitionBis,
attachTransition: attachTransition,
removeTransition: removeTransition
});<|fim▁end|> | Export
*********************************************************************/
/** @private */ |
<|file_name|>nf.rs<|end_file_name|><|fim▁begin|>use e2d2::headers::*;
use e2d2::operators::*;
#[inline]<|fim▁hole|>fn lat() {
unsafe {
asm!("nop"
:
:
:
: "volatile");
}
}
#[inline]
fn delay_loop(delay: u64) {
let mut d = 0;
while d < delay {
lat();
d += 1;
}
}
pub fn delay<T: 'static + Batch<Header = NullHeader>>(parent: T,
delay: u64)
-> TransformBatch<MacHeader, ParsedBatch<MacHeader, T>> {
parent.parse::<MacHeader>()
.transform(box move |pkt| {
assert!(pkt.refcnt() == 1);
let mut hdr = pkt.get_mut_header();
hdr.swap_addresses();
delay_loop(delay);
})
}<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | from test_methods import TestBaseFeedlyClass |
<|file_name|>passwords.py<|end_file_name|><|fim▁begin|># This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
<|fim▁hole|>
class BCryptPassword(object):
def __init__(self, hash_):
self.hash = str(hash_)
def __eq__(self, value):
if not self.hash or not value:
# For security reasons we never consider an empty password/hash valid
return False
if isinstance(value, unicode):
value = value.encode('utf-8')
return bcrypt.checkpw(value, self.hash)
def __ne__(self, other):
return not (self == other)
def __hash__(self): # pragma: no cover
return hash(self.hash)
def __repr__(self):
return '<BCryptPassword({})>'.format(self.hash)
@staticmethod
def hash(value):
if isinstance(value, unicode):
value = value.encode('utf-8')
return bcrypt.hashpw(value, bcrypt.gensalt())
class PasswordProperty(object):
"""Defines a hashed password property.
When reading this property, it will return an object which will
let you use the ``==`` operator to compare the password against
a plaintext password. When assigning a value to it, it will be
hashed and stored in :attr:`attr` of the containing object.
:param attr: The attribute of the containing object where the
password hash is stored.
:param backend: The password backend that handles hashing/checking
passwords.
"""
def __init__(self, attr, backend=BCryptPassword):
self.attr = attr
self.backend = backend
def __get__(self, instance, owner):
return self.backend(getattr(instance, self.attr, None)) if instance is not None else self
def __set__(self, instance, value):
if not value:
raise ValueError('Password may not be empty')
setattr(instance, self.attr, self.backend.hash(value))
def __delete__(self, instance):
setattr(instance, self.attr, None)<|fim▁end|> | import bcrypt |
<|file_name|>v1.js<|end_file_name|><|fim▁begin|>/**
* Copyright 2014 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.
*/
/* jshint maxlen: false */
'use strict';
var createAPIRequest = require('../../lib/apirequest');
/**
* Cloud Storage API
*
* @classdesc Lets you store and retrieve potentially-large, immutable data objects.
* @namespace storage
* @version v1
* @variation v1
* @this Storage
* @param {object=} options Options for Storage
*/
function Storage(options) {
var self = this;
this._options = options || {};
this.bucketAccessControls = {
/**
* storage.bucketAccessControls.delete
*
* @desc Permanently deletes the ACL entry for the specified entity on the specified bucket.
*
* @alias storage.bucketAccessControls.delete
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl/{entity}',
method: 'DELETE'
},
params: params,
requiredParams: ['bucket', 'entity'],
pathParams: ['bucket', 'entity'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.bucketAccessControls.get
*
* @desc Returns the ACL entry for the specified entity on the specified bucket.
*
* @alias storage.bucketAccessControls.get
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl/{entity}',
method: 'GET'
},
params: params,
requiredParams: ['bucket', 'entity'],
pathParams: ['bucket', 'entity'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.bucketAccessControls.insert
*
* @desc Creates a new ACL entry on the specified bucket.
*
* @alias storage.bucketAccessControls.insert
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
insert: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl',
method: 'POST'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.bucketAccessControls.list
*
* @desc Retrieves ACL entries on the specified bucket.
*
* @alias storage.bucketAccessControls.list
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl',
method: 'GET'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.bucketAccessControls.patch
*
* @desc Updates an ACL entry on the specified bucket. This method supports patch semantics.
*
* @alias storage.bucketAccessControls.patch
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
patch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl/{entity}',
method: 'PATCH'
},
params: params,
requiredParams: ['bucket', 'entity'],
pathParams: ['bucket', 'entity'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.bucketAccessControls.update
*
* @desc Updates an ACL entry on the specified bucket.
*
* @alias storage.bucketAccessControls.update
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
update: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl/{entity}',
method: 'PUT'
},
params: params,
requiredParams: ['bucket', 'entity'],
pathParams: ['bucket', 'entity'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
this.buckets = {
/**
* storage.buckets.delete
*
* @desc Permanently deletes an empty bucket.
*
* @alias storage.buckets.delete
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string=} params.ifMetagenerationMatch - If set, only deletes the bucket if its metageneration matches this value.
* @param {string=} params.ifMetagenerationNotMatch - If set, only deletes the bucket if its metageneration does not match this value.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}',
method: 'DELETE'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.buckets.get
*
* @desc Returns metadata for the specified bucket.
*
* @alias storage.buckets.get
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string=} params.ifMetagenerationMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value.
* @param {string=} params.ifMetagenerationNotMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value.
* @param {string=} params.projection - Set of properties to return. Defaults to noAcl.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}',
method: 'GET'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.buckets.insert
*
* @desc Creates a new bucket.
*
* @alias storage.buckets.insert
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this bucket.
* @param {string=} params.predefinedDefaultObjectAcl - Apply a predefined set of default object access controls to this bucket.
* @param {string} params.project - A valid API project identifier.
* @param {string=} params.projection - Set of properties to return. Defaults to noAcl, unless the bucket resource specifies acl or defaultObjectAcl properties, when it defaults to full.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
insert: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b',
method: 'POST'
},
params: params,
requiredParams: ['project'],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.buckets.list
*
* @desc Retrieves a list of buckets for a given project.
*
* @alias storage.buckets.list
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {integer=} params.maxResults - Maximum number of buckets to return.
* @param {string=} params.pageToken - A previously-returned page token representing part of the larger set of results to view.
* @param {string=} params.prefix - Filter results to buckets whose names begin with this prefix.
* @param {string} params.project - A valid API project identifier.
* @param {string=} params.projection - Set of properties to return. Defaults to noAcl.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b',
method: 'GET'
},
params: params,
requiredParams: ['project'],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.buckets.patch
*
* @desc Updates a bucket. This method supports patch semantics.
*
* @alias storage.buckets.patch
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string=} params.ifMetagenerationMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value.
* @param {string=} params.ifMetagenerationNotMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value.
* @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this bucket.
* @param {string=} params.predefinedDefaultObjectAcl - Apply a predefined set of default object access controls to this bucket.
* @param {string=} params.projection - Set of properties to return. Defaults to full.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
patch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}',
method: 'PATCH'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.buckets.update
*
* @desc Updates a bucket.
*
* @alias storage.buckets.update
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string=} params.ifMetagenerationMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value.
* @param {string=} params.ifMetagenerationNotMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value.
* @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this bucket.
* @param {string=} params.predefinedDefaultObjectAcl - Apply a predefined set of default object access controls to this bucket.
* @param {string=} params.projection - Set of properties to return. Defaults to full.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
update: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}',
method: 'PUT'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
}
};<|fim▁hole|> /**
* storage.channels.stop
*
* @desc Stop watching resources through this channel
*
* @alias storage.channels.stop
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
stop: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/channels/stop',
method: 'POST'
},
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
}
};
this.defaultObjectAccessControls = {
/**
* storage.defaultObjectAccessControls.delete
*
* @desc Permanently deletes the default object ACL entry for the specified entity on the specified bucket.
*
* @alias storage.defaultObjectAccessControls.delete
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl/{entity}',
method: 'DELETE'
},
params: params,
requiredParams: ['bucket', 'entity'],
pathParams: ['bucket', 'entity'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.defaultObjectAccessControls.get
*
* @desc Returns the default object ACL entry for the specified entity on the specified bucket.
*
* @alias storage.defaultObjectAccessControls.get
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl/{entity}',
method: 'GET'
},
params: params,
requiredParams: ['bucket', 'entity'],
pathParams: ['bucket', 'entity'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.defaultObjectAccessControls.insert
*
* @desc Creates a new default object ACL entry on the specified bucket.
*
* @alias storage.defaultObjectAccessControls.insert
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
insert: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl',
method: 'POST'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.defaultObjectAccessControls.list
*
* @desc Retrieves default object ACL entries on the specified bucket.
*
* @alias storage.defaultObjectAccessControls.list
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string=} params.ifMetagenerationMatch - If present, only return default ACL listing if the bucket's current metageneration matches this value.
* @param {string=} params.ifMetagenerationNotMatch - If present, only return default ACL listing if the bucket's current metageneration does not match the given value.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl',
method: 'GET'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.defaultObjectAccessControls.patch
*
* @desc Updates a default object ACL entry on the specified bucket. This method supports patch semantics.
*
* @alias storage.defaultObjectAccessControls.patch
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
patch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl/{entity}',
method: 'PATCH'
},
params: params,
requiredParams: ['bucket', 'entity'],
pathParams: ['bucket', 'entity'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.defaultObjectAccessControls.update
*
* @desc Updates a default object ACL entry on the specified bucket.
*
* @alias storage.defaultObjectAccessControls.update
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
update: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl/{entity}',
method: 'PUT'
},
params: params,
requiredParams: ['bucket', 'entity'],
pathParams: ['bucket', 'entity'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
this.objectAccessControls = {
/**
* storage.objectAccessControls.delete
*
* @desc Permanently deletes the ACL entry for the specified entity on the specified object.
*
* @alias storage.objectAccessControls.delete
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default).
* @param {string} params.object - Name of the object.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl/{entity}',
method: 'DELETE'
},
params: params,
requiredParams: ['bucket', 'object', 'entity'],
pathParams: ['bucket', 'entity', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objectAccessControls.get
*
* @desc Returns the ACL entry for the specified entity on the specified object.
*
* @alias storage.objectAccessControls.get
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default).
* @param {string} params.object - Name of the object.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl/{entity}',
method: 'GET'
},
params: params,
requiredParams: ['bucket', 'object', 'entity'],
pathParams: ['bucket', 'entity', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objectAccessControls.insert
*
* @desc Creates a new ACL entry on the specified object.
*
* @alias storage.objectAccessControls.insert
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default).
* @param {string} params.object - Name of the object.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
insert: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl',
method: 'POST'
},
params: params,
requiredParams: ['bucket', 'object'],
pathParams: ['bucket', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objectAccessControls.list
*
* @desc Retrieves ACL entries on the specified object.
*
* @alias storage.objectAccessControls.list
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default).
* @param {string} params.object - Name of the object.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl',
method: 'GET'
},
params: params,
requiredParams: ['bucket', 'object'],
pathParams: ['bucket', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objectAccessControls.patch
*
* @desc Updates an ACL entry on the specified object. This method supports patch semantics.
*
* @alias storage.objectAccessControls.patch
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default).
* @param {string} params.object - Name of the object.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
patch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl/{entity}',
method: 'PATCH'
},
params: params,
requiredParams: ['bucket', 'object', 'entity'],
pathParams: ['bucket', 'entity', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objectAccessControls.update
*
* @desc Updates an ACL entry on the specified object.
*
* @alias storage.objectAccessControls.update
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default).
* @param {string} params.object - Name of the object.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
update: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl/{entity}',
method: 'PUT'
},
params: params,
requiredParams: ['bucket', 'object', 'entity'],
pathParams: ['bucket', 'entity', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
this.objects = {
/**
* storage.objects.compose
*
* @desc Concatenates a list of existing objects into a new object in the same bucket.
*
* @alias storage.objects.compose
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.destinationBucket - Name of the bucket in which to store the new object.
* @param {string} params.destinationObject - Name of the new object.
* @param {string=} params.destinationPredefinedAcl - Apply a predefined set of access controls to the destination object.
* @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value.
* @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
compose: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{destinationBucket}/o/{destinationObject}/compose',
method: 'POST'
},
params: params,
requiredParams: ['destinationBucket', 'destinationObject'],
pathParams: ['destinationBucket', 'destinationObject'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objects.copy
*
* @desc Copies an object to a specified location. Optionally overrides metadata.
*
* @alias storage.objects.copy
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.destinationBucket - Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.
* @param {string} params.destinationObject - Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any.
* @param {string=} params.destinationPredefinedAcl - Apply a predefined set of access controls to the destination object.
* @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the destination object's current generation matches the given value.
* @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the destination object's current generation does not match the given value.
* @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the destination object's current metageneration matches the given value.
* @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the destination object's current metageneration does not match the given value.
* @param {string=} params.ifSourceGenerationMatch - Makes the operation conditional on whether the source object's generation matches the given value.
* @param {string=} params.ifSourceGenerationNotMatch - Makes the operation conditional on whether the source object's generation does not match the given value.
* @param {string=} params.ifSourceMetagenerationMatch - Makes the operation conditional on whether the source object's current metageneration matches the given value.
* @param {string=} params.ifSourceMetagenerationNotMatch - Makes the operation conditional on whether the source object's current metageneration does not match the given value.
* @param {string=} params.projection - Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full.
* @param {string} params.sourceBucket - Name of the bucket in which to find the source object.
* @param {string=} params.sourceGeneration - If present, selects a specific revision of the source object (as opposed to the latest version, the default).
* @param {string} params.sourceObject - Name of the source object.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
copy: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{sourceBucket}/o/{sourceObject}/copyTo/b/{destinationBucket}/o/{destinationObject}',
method: 'POST'
},
params: params,
requiredParams: ['sourceBucket', 'sourceObject', 'destinationBucket', 'destinationObject'],
pathParams: ['destinationBucket', 'destinationObject', 'sourceBucket', 'sourceObject'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objects.delete
*
* @desc Deletes an object and its metadata. Deletions are permanent if versioning is not enabled for the bucket, or if the generation parameter is used.
*
* @alias storage.objects.delete
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of the bucket in which the object resides.
* @param {string=} params.generation - If present, permanently deletes a specific revision of this object (as opposed to the latest version, the default).
* @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value.
* @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value.
* @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value.
* @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value.
* @param {string} params.object - Name of the object.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}',
method: 'DELETE'
},
params: params,
requiredParams: ['bucket', 'object'],
pathParams: ['bucket', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objects.get
*
* @desc Retrieves an object or its metadata.
*
* @alias storage.objects.get
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of the bucket in which the object resides.
* @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default).
* @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's generation matches the given value.
* @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's generation does not match the given value.
* @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value.
* @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value.
* @param {string} params.object - Name of the object.
* @param {string=} params.projection - Set of properties to return. Defaults to noAcl.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}',
method: 'GET'
},
params: params,
requiredParams: ['bucket', 'object'],
pathParams: ['bucket', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objects.insert
*
* @desc Stores a new object and metadata.
*
* @alias storage.objects.insert
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.
* @param {string=} params.contentEncoding - If set, sets the contentEncoding property of the final object to this value. Setting this parameter is equivalent to setting the contentEncoding metadata property. This can be useful when uploading an object with uploadType=media to indicate the encoding of the content being uploaded.
* @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value.
* @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value.
* @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value.
* @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value.
* @param {string=} params.name - Name of the object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any.
* @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this object.
* @param {string=} params.projection - Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full.
* @param {object} params.resource - Media resource metadata
* @param {object} params.media - Media object
* @param {string} params.media.mimeType - Media mime-type
* @param {string|object} params.media.body - Media body contents
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
insert: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o',
method: 'POST'
},
params: params,
mediaUrl: 'https://www.googleapis.com/upload/storage/v1/b/{bucket}/o',
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objects.list
*
* @desc Retrieves a list of objects matching the criteria.
*
* @alias storage.objects.list
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of the bucket in which to look for objects.
* @param {string=} params.delimiter - Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted.
* @param {integer=} params.maxResults - Maximum number of items plus prefixes to return. As duplicate prefixes are omitted, fewer total results may be returned than requested.
* @param {string=} params.pageToken - A previously-returned page token representing part of the larger set of results to view.
* @param {string=} params.prefix - Filter results to objects whose names begin with this prefix.
* @param {string=} params.projection - Set of properties to return. Defaults to noAcl.
* @param {boolean=} params.versions - If true, lists all versions of a file as distinct results.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o',
method: 'GET'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objects.patch
*
* @desc Updates an object's metadata. This method supports patch semantics.
*
* @alias storage.objects.patch
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of the bucket in which the object resides.
* @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default).
* @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value.
* @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value.
* @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value.
* @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value.
* @param {string} params.object - Name of the object.
* @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this object.
* @param {string=} params.projection - Set of properties to return. Defaults to full.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
patch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}',
method: 'PATCH'
},
params: params,
requiredParams: ['bucket', 'object'],
pathParams: ['bucket', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objects.update
*
* @desc Updates an object's metadata.
*
* @alias storage.objects.update
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of the bucket in which the object resides.
* @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default).
* @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value.
* @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value.
* @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value.
* @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value.
* @param {string} params.object - Name of the object.
* @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this object.
* @param {string=} params.projection - Set of properties to return. Defaults to full.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
update: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}',
method: 'PUT'
},
params: params,
requiredParams: ['bucket', 'object'],
pathParams: ['bucket', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objects.watchAll
*
* @desc Watch for changes on all objects in a bucket.
*
* @alias storage.objects.watchAll
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of the bucket in which to look for objects.
* @param {string=} params.delimiter - Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted.
* @param {integer=} params.maxResults - Maximum number of items plus prefixes to return. As duplicate prefixes are omitted, fewer total results may be returned than requested.
* @param {string=} params.pageToken - A previously-returned page token representing part of the larger set of results to view.
* @param {string=} params.prefix - Filter results to objects whose names begin with this prefix.
* @param {string=} params.projection - Set of properties to return. Defaults to noAcl.
* @param {boolean=} params.versions - If true, lists all versions of a file as distinct results.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
watchAll: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/watch',
method: 'POST'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
}
/**
* Exports Storage object
* @type Storage
*/
module.exports = Storage;<|fim▁end|> |
this.channels = {
|
<|file_name|>fields.py<|end_file_name|><|fim▁begin|>from select_multiple_field.models import SelectMultipleField
class CommaSeparatedCharField(SelectMultipleField):
<|fim▁hole|>
We just set our custom get_FIELD_display(),
which returns a comma-separated list of displays.
"""
super(CommaSeparatedCharField, self).contribute_to_class(cls, name,
**kwargs)
def _get_FIELD_display(instance):
choices = dict(self.choices)
values = getattr(instance, self.attname)
return ", ".join(unicode(choices.get(c, c)) for c in values if c)
setattr(cls, 'get_%s_display' % self.name, _get_FIELD_display)<|fim▁end|> | def contribute_to_class(self, cls, name, **kwargs):
"""Contribute to the Model subclass. |
<|file_name|>BenchmarkPointStorage.cpp<|end_file_name|><|fim▁begin|>/* This file is part of the KDE project
Copyright 2007 Stefan Nikolaus <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include <quuid.h>
#include "kspread_limits.h"
#include "PointStorage.h"
#include "BenchmarkPointStorage.h"
using namespace KSpread;
void PointStorageBenchmark::testInsertionPerformance_loadingLike()
{
PointStorage<int> storage;
int col = 1;
int row = 1;
int cols = 100;
int rows = 10000;
QBENCHMARK {
for (int r = row; r <= rows; ++r) {
for (int c = col; c <= cols; c += 1) {
storage.insert(c, r, c);
}
}
}
}
void PointStorageBenchmark::testInsertionPerformance_singular()
{
PointStorage<int> storage;
QBENCHMARK {
int col = 1 + rand() % 1000;
int row = 1 + rand() % 1000;
int cols = col + 1;
int rows = row + 1;
for (int r = row; r <= rows; ++r) {
for (int c = col; c <= cols; c += 1) {
storage.insert(c, r, c);
}
}
}
}
void PointStorageBenchmark::testLookupPerformance_data()
{
QTest::addColumn<int>("maxrow");
QTest::addColumn<int>("maxcol");
QTest::newRow("very small") << 5 << 5;
QTest::newRow("fit to screen") << 30 << 20;
QTest::newRow("medium") << 100 << 100;
QTest::newRow("large") << 1000 << 1000;
QTest::newRow("typical data: more rows") << 10000 << 100;
QTest::newRow("20 times larger") << 10000 << 2000;
QTest::newRow("not really typical: more columns") << 100 << 10000;
QTest::newRow("hopelessly large") << 8000 << 8000;
QTest::newRow("some complete columns; KS_colMax-10, because of max lookup range of width 10 below") << 10 << 32757;
QTest::newRow("some complete rows; KS_rowMax-10, because of max lookup range of height 10 below") << 32757 << 10;
}
void PointStorageBenchmark::testLookupPerformance()
{
PointStorage<int> storage;
QFETCH(int, maxrow);
QFETCH(int, maxcol);
for (int r = 0; r < maxrow; ++r) {
for (int c = 0; c < maxcol; ++c) {
storage.m_data << c;
storage.m_cols << (c + 1);
}
storage.m_rows << r*maxcol;
}
// qDebug() << endl << qPrintable( storage.dump() );
int v;
int col = 0;
int row = 0;
int cols = 0;
int rows = 0;
QBENCHMARK {
col = 1 + rand() % maxcol;
row = 1 + rand() % maxrow;
cols = col + 1 * (rand() % 10);
rows = row + rand() % 10;
for (int r = row; r <= rows; ++r) {
for (int c = col; c <= cols; c += 1) {
v = storage.lookup(c, r);
}
}
}<|fim▁hole|> PointStorage<int> storage;
for (int c = 0; c < KS_colMax; ++c) {
storage.m_data << 1;
storage.m_cols << 1;
}
storage.m_rows << 0;
QBENCHMARK {
storage.insertColumns(42, 3);
}
}
void PointStorageBenchmark::testDeleteColumnsPerformance()
{
PointStorage<int> storage;
for (int c = 0; c < KS_colMax; ++c) {
storage.m_data << 1;
storage.m_cols << 1;
}
storage.m_rows << 0;
QBENCHMARK {
storage.removeColumns(42, 3);
}
}
void PointStorageBenchmark::testInsertRowsPerformance()
{
PointStorage<int> storage;
for (int r = 0; r < KS_rowMax; ++r) {
storage.m_data << 1;
storage.m_cols << 1;
storage.m_rows << r;
}
QBENCHMARK {
storage.insertRows(42, 3);
}
}
void PointStorageBenchmark::testDeleteRowsPerformance()
{
PointStorage<int> storage;
for (int r = 0; r < KS_rowMax; ++r) {
storage.m_data << 1;
storage.m_cols << 1;
storage.m_rows << r;
}
QBENCHMARK {
storage.removeRows(42, 3);
}
}
void PointStorageBenchmark::testShiftLeftPerformance()
{
PointStorage<int> storage;
for (int c = 0; c < KS_colMax; ++c) {
storage.m_data << 1;
storage.m_cols << 1;
}
storage.m_rows << 0;
QBENCHMARK {
storage.removeShiftLeft(QRect(42, 1, 3, 1));
}
}
void PointStorageBenchmark::testShiftRightPerformance()
{
PointStorage<int> storage;
for (int c = 0; c < KS_colMax; ++c) {
storage.m_data << 1;
storage.m_cols << 1;
}
storage.m_rows << 0;
QBENCHMARK {
storage.insertShiftRight(QRect(42, 1, 3, 1));
}
}
void PointStorageBenchmark::testShiftUpPerformance()
{
PointStorage<int> storage;
for (int r = 0; r < KS_rowMax; ++r) {
storage.m_data << 1;
storage.m_cols << 1;
storage.m_rows << r;
}
QBENCHMARK {
storage.removeShiftUp(QRect(1, 42, 1, 3));
}
}
void PointStorageBenchmark::testShiftDownPerformance()
{
PointStorage<int> storage;
for (int r = 0; r < KS_rowMax; ++r) {
storage.m_data << 1;
storage.m_cols << 1;
storage.m_rows << r;
}
storage.m_rows << 0;
QBENCHMARK {
storage.insertShiftDown(QRect(1, 42, 1, 3));
}
}
void PointStorageBenchmark::testIterationPerformance_data()
{
QTest::addColumn<int>("maxrow");
QTest::addColumn<int>("maxcol");
QTest::newRow("very small") << 5 << 5;
QTest::newRow("fit to screen") << 30 << 20;
QTest::newRow("medium") << 100 << 100;
QTest::newRow("large") << 1000 << 1000;
QTest::newRow("typical data: more rows") << 10000 << 100;
QTest::newRow("20 times larger") << 10000 << 2000;
QTest::newRow("not really typical: more columns") << 100 << 10000;
QTest::newRow("hopelessly large") << 8000 << 8000;
#if 0
QTest::newRow("some complete columns; KS_colMax-10, because of max lookup range of width 10 below") << 10 << 32757;
QTest::newRow("some complete rows; KS_rowMax-10, because of max lookup range of height 10 below") << 32757 << 10;
#endif
}
void PointStorageBenchmark::testIterationPerformance()
{
PointStorage<int> storage;
QFETCH(int, maxrow);
QFETCH(int, maxcol);
storage.clear();
for (int r = 0; r < maxrow; ++r) {
for (int c = 0; c < maxcol; ++c) {
storage.m_data << c;
storage.m_cols << (c + 1);
}
storage.m_rows << r*maxcol;
}
// qDebug() << endl << qPrintable( storage.dump() );
QString prefix = QString("%1 x %2").arg(maxrow).arg(maxcol);
QBENCHMARK {
int v;
for (int i = 0; i < storage.count(); ++i) {
v = storage.data(i);
}
}
}
QTEST_MAIN(PointStorageBenchmark)
#include "BenchmarkPointStorage.moc"<|fim▁end|> | }
void PointStorageBenchmark::testInsertColumnsPerformance()
{ |
<|file_name|>p079.rs<|end_file_name|><|fim▁begin|>//! [Problem 79](https://projecteuler.net/problem=79) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate topological_sort as tsort;
use std::fs::File;
use std::io::{self, BufReader};
use std::io::prelude::*;
use tsort::TopologicalSort;
fn solve(file: File) -> io::Result<String> {
let mut ts = TopologicalSort::new();
for line in BufReader::new(file).lines() {
let line = try!(line);
let ds = line.trim().chars();
for (prec, succ) in ds.clone().zip(ds.skip(1)) {
ts.add_dependency(prec, succ);<|fim▁hole|> }
}
let s = ts.map(|d| d.to_string()).collect::<Vec<String>>().concat();
Ok(s)
}
problem!("73162890", "p079_keylog.txt", solve);<|fim▁end|> | |
<|file_name|>wunderground-slash-command.py<|end_file_name|><|fim▁begin|>from http.server import BaseHTTPRequestHandler, HTTPServer
import requests
import urllib.parse
import json
# Define server address and port, use localhost if you are running this on your Mattermost server.
HOSTNAME = ''
PORT = 7800
# guarantee unicode string
_u = lambda t: t.decode('UTF-8', 'replace') if isinstance(t, str) else t
#Handles mattermost slash command get request
class PostHandler(BaseHTTPRequestHandler):
def do_GET(self):
length = int(self.headers['Content-Length'])
data = urllib.parse.parse_qs(self.rfile.read(length).decode('utf-8'))
response_url = ""
text = ""
token = ""
channel_id = ""
team_id = ""
command = ""
team_domain = ""
user_name = ""
channel_name = ""
# Get POST data and initialize MattermostRequest object<|fim▁hole|> text = data[key]
elif key == 'token':
token = data[key]
elif key == 'channel_id':
channel_id = data[key]
elif key == 'team_id':
team_id = data[key]
elif key == 'command':
command = data[key]
elif key == 'team_domain':
team_domain = data[key]
elif key == 'user_name':
user_name = data[key]
elif key == 'channel_name':
channel_name = data[key]
responsetext = ''
print("Found command %s" % token)
if token[0] == u'<your-slash-command-token>':
if len(text) > 0:
responsetext = getweather(text[0])
else:
responsetext = getweather()
if responsetext:
res = {}
res['response_type'] = 'in_channel'
res['text'] = responsetext
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(res).encode("utf-8"))
return
#The command search in wunderground for the specified city and return weather info
def getweather(city="Rovereto, Italy"):
print("Searching cities containing %s" % city)
r = requests.get("http://autocomplete.wunderground.com/aq?query=%s" % urllib.parse.quote_plus(city))
cities = r.json()
if "RESULTS" not in cities or len(cities["RESULTS"]) == 0:
print("No result")
return u"**No city found**"
elif len(cities["RESULTS"]) > 1:
print("Found more than 1 city")
res = u"**Available cities**:\r\n"
for c in cities["RESULTS"]:
res = u"%s* %s\r\n" % (res, c["name"])
return res
else:
print("Requesting weather info from wunderground")
res = ""
c = cities["RESULTS"][0]
r = requests.get('http://api.wunderground.com/api/<your-wunderground-api-here>/geolookup/conditions%s.json' % c["l"])
data = r.json()
co = data['current_observation']
res = u'#### Weather conditions in **%s**:\n\n' % data['location']['city']
res += u"\n\n" % (co['weather'], co['icon_url'])
res += u"| Field | Value |\n"
res += u'| :---- | :----: |\n'
res += u'| Temperature : | %s °C |\n' % str(co['temp_c'])
res += u'| Feelslike : | %s °C |\n' % str(co['feelslike_c'])
res += u'| Wind : | %s |\n' % str(co['wind_string'])
res += u'| Wind direction : | %s |\n' % str(co['wind_dir'])
res += u'| Wind speed : | %s kn |\n' % str(round(co['wind_kph']*1/1.852, 1))
res += u'| Wind gust : | %s kn |\n' % str(round(float(co['wind_gust_kph'])*1/1.852, 1))
return res
#Start the app listening on specified port for http GET requests incoming from mattermost slash command
if __name__ == '__main__':
server = HTTPServer((HOSTNAME, PORT), PostHandler)
print('Starting matterslash server, use <Ctrl-C> to stop')
server.serve_forever()<|fim▁end|> | for key in data:
if key == 'response_url':
response_url = data[key]
elif key == 'text': |
<|file_name|>create-folders.js<|end_file_name|><|fim▁begin|>var mkdirp = require('mkdirp');
var path = require('canonical-path');
module.exports = {
create: function(config) {
var currentVersion = config.get('currentVersion');
var docsBase = path.join(config.get('basePath'), config.get('rendering.outputFolder'), 'docs');
var versionDir = path.join(docsBase, currentVersion);
// create the folders for the current version<|fim▁hole|> }
};<|fim▁end|> | mkdirp.sync(versionDir); |
<|file_name|>wxform.cpp<|end_file_name|><|fim▁begin|>/**
*
* wxform.cpp
*
* - implementation for main wx-based form
*
**/
#include "wxform.hpp"
#include <wx/aboutdlg.h>
#include "../res/apps.xpm"
#include "../res/exit.xpm"<|fim▁hole|>#define MACRO_WXBMP(bmp) wxBitmap(bmp##_xpm)
#define MACRO_WXICO(bmp) wxIcon(bmp##_xpm)
#define MESSAGE_WELCOME "Welcome to MY1TERMW\n"
#define DEFAULT_PROMPT "my1term> "
#define CONS_WIDTH 640
#define CONS_HEIGHT 480
my1Form::my1Form(const wxString &title)
: wxFrame( NULL, MY1ID_MAIN, title, wxDefaultPosition,
wxDefaultSize, wxDEFAULT_FRAME_STYLE)
{
// initialize stuffs
mTerm = new my1Term(this,wxID_ANY);
// setup image
wxIcon mIconApps = MACRO_WXICO(apps);
this->SetIcon(mIconApps);
// create tool bar
wxToolBar* mainTool = this->CreateToolBar(wxBORDER_NONE|wxTB_HORIZONTAL|
wxTB_FLAT,MY1ID_MAIN_TOOL,wxT("mainTool"));
mainTool->SetToolBitmapSize(wxSize(16,16));
wxBitmap mIconExit = MACRO_WXBMP(exit);
mainTool->AddTool(MY1ID_EXIT,wxT(""),mIconExit,wxT("Exit my1termw"));
mainTool->AddSeparator();
wxBitmap mIconAbout = MACRO_WXBMP(quest);
mainTool->AddTool(MY1ID_ABOUT, wxT(""), mIconAbout,wxT("About my1termw"));
mainTool->Realize();
// main box-sizer
//wxBoxSizer *pSizerMain = new wxBoxSizer(wxVERTICAL);
//pSizerMain->Add(mTerm,1,wxEXPAND);
//this->SetSizerAndFit(pSizerMain);
// duh!
this->SetClientSize(wxSize(CONS_WIDTH,CONS_HEIGHT));
// actions & events
this->Connect(MY1ID_EXIT,wxEVT_COMMAND_TOOL_CLICKED,
wxCommandEventHandler(my1Form::OnExit));
this->Connect(MY1ID_ABOUT,wxEVT_COMMAND_TOOL_CLICKED,
wxCommandEventHandler(my1Form::OnAbout));
// write welcome message
mTerm->WriteConsole(MESSAGE_WELCOME);
mTerm->SetPrompt(DEFAULT_PROMPT);
// position this!
this->Centre();
}
my1Form::~my1Form()
{
// nothing to do
}
void my1Form::OnExit(wxCommandEvent& event)
{
this->Close();
}
void my1Form::OnAbout(wxCommandEvent& event)
{
wxAboutDialogInfo cAboutInfo;
wxString cDescription = wxString::Format("%s",
"\nGUI for my1termu (Serial Port Interface)!\n");
cAboutInfo.SetName(MY1APP_PROGNAME);
cAboutInfo.SetVersion(MY1APP_PROGVERS);
cAboutInfo.SetDescription(cDescription);
cAboutInfo.SetCopyright("Copyright (C) "MY1APP_LICENSE_);
cAboutInfo.SetWebSite("http://www.my1matrix.org");
cAboutInfo.AddDeveloper("Azman M. Yusof <[email protected]>");
wxAboutBox(cAboutInfo,this);
}<|fim▁end|> | #include "../res/quest.xpm"
|
<|file_name|>conftest.py<|end_file_name|><|fim▁begin|>"""
pytest hooks and fixtures used for our unittests.
Please note that there should not be any Django/Olympia related imports
on module-level, they should instead be added to hooks or fixtures directly.
"""
import os
import uuid
import warnings
import pytest
import responses
import six
@pytest.fixture(autouse=True)
def unpin_db(request):
"""Unpin the database from master in the current DB.
The `multidb` middleware pins the current thread to master for 15 seconds
after any POST request, which can lead to unexpected results for tests
of DB slave functionality."""
from multidb import pinning
request.addfinalizer(pinning.unpin_this_thread)
@pytest.fixture(autouse=True)
def mock_elasticsearch():
"""Mock ElasticSearch in tests by default.
Tests that do need ES should inherit from ESTestCase, which will stop the
mock at setup time."""
from olympia.amo.tests import start_es_mocks, stop_es_mocks
start_es_mocks()
yield
stop_es_mocks()
@pytest.fixture(autouse=True)
def start_responses_mocking(request):
"""Enable ``responses`` this enforcing us to explicitly mark tests
that require internet usage.
"""
marker = request.node.get_closest_marker('allow_external_http_requests')
if not marker:
responses.start()
yield
try:
if not marker:
responses.stop()
responses.reset()
except RuntimeError:
# responses patcher was already uninstalled
pass
@pytest.fixture(autouse=True)
def mock_basket(settings):
"""Mock Basket in tests by default.
Tests that do need basket to work should disable `responses`
and add a passthrough.
"""
USER_TOKEN = u'13f64f64-1de7-42f6-8c7f-a19e2fae5021'
responses.add(
responses.GET,
settings.BASKET_URL + '/news/lookup-user/',
json={'status': 'ok', 'newsletters': [], 'token': USER_TOKEN})
responses.add(
responses.POST,
settings.BASKET_URL + '/news/subscribe/',
json={'status': 'ok', 'token': USER_TOKEN})
responses.add(
responses.POST,
settings.BASKET_URL + '/news/unsubscribe/{}/'.format(USER_TOKEN),
json={'status': 'ok', 'token': USER_TOKEN})
def pytest_configure(config):
import django
# Forcefully call `django.setup`, pytest-django tries to be very lazy
# and doesn't call it if it has already been setup.
# That is problematic for us since we overwrite our logging config
# in settings_test and it can happen that django get's initialized
# with the wrong configuration. So let's forcefully re-initialize
# to setup the correct logging config since at this point
# DJANGO_SETTINGS_MODULE should be `settings_test` every time.
django.setup()
from olympia.amo.tests import prefix_indexes
prefix_indexes(config)
@pytest.fixture(autouse=True, scope='session')
def instrument_jinja():
"""Make sure the "templates" list in a response is properly updated, even
though we're using Jinja2 and not the default django template engine."""
import jinja2
from django import test
old_render = jinja2.Template.render
def instrumented_render(self, *args, **kwargs):
context = dict(*args, **kwargs)
test.signals.template_rendered.send(
sender=self, template=self, context=context)
return old_render(self, *args, **kwargs)
jinja2.Template.render = instrumented_render
def default_prefixer(settings):
"""Make sure each test starts with a default URL prefixer."""
from django import http
from olympia import amo
request = http.HttpRequest()
request.META['SCRIPT_NAME'] = ''
prefixer = amo.urlresolvers.Prefixer(request)
prefixer.app = settings.DEFAULT_APP
prefixer.locale = settings.LANGUAGE_CODE
amo.urlresolvers.set_url_prefix(prefixer)
@pytest.yield_fixture(autouse=True)
def test_pre_setup(request, tmpdir, settings):
from django.core.cache import caches
from django.utils import translation
from olympia import amo, core
from olympia.translations.hold import clean_translations
from waffle.utils import get_cache as waffle_get_cache
from waffle import models as waffle_models
# Ignore ResourceWarning for now. It's a Python 3 thing so it's done<|fim▁hole|> if six.PY3:
warnings.filterwarnings('ignore', category=ResourceWarning) # noqa
# Clear all cache-instances. They'll be re-initialized by Django
# This will make sure that our random `KEY_PREFIX` is applied
# appropriately.
# This is done by Django too whenever `settings` is changed
# directly but because we're using the `settings` fixture
# here this is not detected correctly.
caches._caches.caches = {}
# Randomize the cache key prefix to keep
# tests isolated from each other.
prefix = uuid.uuid4().hex
settings.CACHES['default']['KEY_PREFIX'] = 'amo:{0}:'.format(prefix)
# Reset global django-waffle cache instance to make sure it's properly
# using our new key prefix
waffle_models.cache = waffle_get_cache()
translation.trans_real.deactivate()
# Django fails to clear this cache.
translation.trans_real._translations = {}
translation.trans_real.activate(settings.LANGUAGE_CODE)
def _path(*args):
path = str(os.path.join(*args))
if not os.path.exists(path):
os.makedirs(path)
return path
settings.STORAGE_ROOT = storage_root = _path(str(tmpdir.mkdir('storage')))
settings.SHARED_STORAGE = shared_storage = _path(
storage_root, 'shared_storage')
settings.ADDONS_PATH = _path(storage_root, 'files')
settings.GUARDED_ADDONS_PATH = _path(storage_root, 'guarded-addons')
settings.GIT_FILE_STORAGE_PATH = _path(storage_root, 'git-storage')
settings.MEDIA_ROOT = _path(shared_storage, 'uploads')
settings.TMP_PATH = _path(shared_storage, 'tmp')
# Reset the prefixer and urlconf after updating media root
default_prefixer(settings)
from django.urls import clear_url_caches, set_urlconf
def _clear_urlconf():
clear_url_caches()
set_urlconf(None)
_clear_urlconf()
request.addfinalizer(_clear_urlconf)
yield
core.set_user(None)
clean_translations(None) # Make sure queued translations are removed.
# Make sure we revert everything we might have changed to prefixers.
amo.urlresolvers.clean_url_prefixes()
@pytest.fixture
def admin_group(db):
"""Create the Admins group."""
from olympia.access.models import Group
return Group.objects.create(name='Admins', rules='*:*')
@pytest.fixture
def mozilla_user(admin_group, settings):
"""Create a "Mozilla User"."""
from olympia.access.models import GroupUser
from olympia.users.models import UserProfile
user = UserProfile.objects.create(pk=settings.TASK_USER_ID,
email='[email protected]',
username='admin')
user.save()
GroupUser.objects.create(user=user, group=admin_group)
return user<|fim▁end|> | # dynamically here. |
<|file_name|>defaults.py<|end_file_name|><|fim▁begin|>"""
This file holds the default values for the various programs.
"""
import sys
__all__ = ['defaults']<|fim▁hole|> # filenames
'cache_file' : 'bin/cache.bin',
'log_file' : sys.stderr,
# values
'num_threads' : 16,
# flags
'debug' : False,
'https' : False,
'offline' : False,
'quiet' : False
}<|fim▁end|> |
defaults = { |
<|file_name|>ByteSizeUnit.java<|end_file_name|><|fim▁begin|>package org.nbone.core.util;
/**
*
* @author thinking
* @version 1.0
* @since 2019-07-20
* org.elasticsearch.common.unit.ByteSizeUnit
*/
public enum ByteSizeUnit {
BYTES {
@Override
public long toBytes(long size) {
return size;
}
@Override
public long toKB(long size) {
return size / (C1 / C0);
}
@Override
public long toMB(long size) {
return size / (C2 / C0);
}
@Override
public long toGB(long size) {
return size / (C3 / C0);
}<|fim▁hole|>
@Override
public long toTB(long size) {
return size / (C4 / C0);
}
@Override
public long toPB(long size) {
return size / (C5 / C0);
}
},
KB {
@Override
public long toBytes(long size) {
return x(size, C1 / C0, MAX / (C1 / C0));
}
@Override
public long toKB(long size) {
return size;
}
@Override
public long toMB(long size) {
return size / (C2 / C1);
}
@Override
public long toGB(long size) {
return size / (C3 / C1);
}
@Override
public long toTB(long size) {
return size / (C4 / C1);
}
@Override
public long toPB(long size) {
return size / (C5 / C1);
}
},
MB {
@Override
public long toBytes(long size) {
return x(size, C2 / C0, MAX / (C2 / C0));
}
@Override
public long toKB(long size) {
return x(size, C2 / C1, MAX / (C2 / C1));
}
@Override
public long toMB(long size) {
return size;
}
@Override
public long toGB(long size) {
return size / (C3 / C2);
}
@Override
public long toTB(long size) {
return size / (C4 / C2);
}
@Override
public long toPB(long size) {
return size / (C5 / C2);
}
},
GB {
@Override
public long toBytes(long size) {
return x(size, C3 / C0, MAX / (C3 / C0));
}
@Override
public long toKB(long size) {
return x(size, C3 / C1, MAX / (C3 / C1));
}
@Override
public long toMB(long size) {
return x(size, C3 / C2, MAX / (C3 / C2));
}
@Override
public long toGB(long size) {
return size;
}
@Override
public long toTB(long size) {
return size / (C4 / C3);
}
@Override
public long toPB(long size) {
return size / (C5 / C3);
}
},
TB {
@Override
public long toBytes(long size) {
return x(size, C4 / C0, MAX / (C4 / C0));
}
@Override
public long toKB(long size) {
return x(size, C4 / C1, MAX / (C4 / C1));
}
@Override
public long toMB(long size) {
return x(size, C4 / C2, MAX / (C4 / C2));
}
@Override
public long toGB(long size) {
return x(size, C4 / C3, MAX / (C4 / C3));
}
@Override
public long toTB(long size) {
return size;
}
@Override
public long toPB(long size) {
return size / (C5 / C4);
}
},
PB {
@Override
public long toBytes(long size) {
return x(size, C5 / C0, MAX / (C5 / C0));
}
@Override
public long toKB(long size) {
return x(size, C5 / C1, MAX / (C5 / C1));
}
@Override
public long toMB(long size) {
return x(size, C5 / C2, MAX / (C5 / C2));
}
@Override
public long toGB(long size) {
return x(size, C5 / C3, MAX / (C5 / C3));
}
@Override
public long toTB(long size) {
return x(size, C5 / C4, MAX / (C5 / C4));
}
@Override
public long toPB(long size) {
return size;
}
};
static final long C0 = 1L;
static final long C1 = C0 * 1024L;
static final long C2 = C1 * 1024L;
static final long C3 = C2 * 1024L;
static final long C4 = C3 * 1024L;
static final long C5 = C4 * 1024L;
static final long MAX = Long.MAX_VALUE;
/**
* Scale d by m, checking for overflow.
* This has a short name to make above code more readable.
*/
static long x(long d, long m, long over) {
if (d > over) return Long.MAX_VALUE;
if (d < -over) return Long.MIN_VALUE;
return d * m;
}
public abstract long toBytes(long size);
public abstract long toKB(long size);
public abstract long toMB(long size);
public abstract long toGB(long size);
public abstract long toTB(long size);
public abstract long toPB(long size);
}<|fim▁end|> | |
<|file_name|>dropck_tarena_unsound_drop.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that a arena (TypedArena) cannot carry elements whose drop
// methods might access borrowed data of lifetime that does not
// strictly outlive the arena itself.
//
// Compare against run-pass/dropck_tarena_sound_drop.rs, which shows a
// similar setup, but loosens `f` so that the struct `C<'a>` can be
// fed a lifetime longer than that of the arena.
//
// (Also compare against dropck_tarena_cycle_checked.rs, from which
// this was reduced to better understand its error message.)
#![allow(unstable)]
#![feature(unsafe_destructor)]
extern crate arena;
use arena::TypedArena;
trait HasId { fn count(&self) -> usize; }
struct CheckId<T:HasId> { v: T }
// In the code below, the impl of HasId for `&'a usize` does not
// actually access the borrowed data, but the point is that the
// interface to CheckId does not (and cannot) know that, and therefore
// when encountering the a value V of type CheckId<S>, we must
// conservatively force the type S to strictly outlive V.
#[unsafe_destructor]
impl<T:HasId> Drop for CheckId<T> {
fn drop(&mut self) {
assert!(self.v.count() > 0);
}
}
struct C<'a> { v: CheckId<&'a usize>, }
impl<'a> HasId for &'a usize { fn count(&self) -> usize { 1 } }<|fim▁hole|>fn main() {
let arena: TypedArena<C> = TypedArena::new();
f(&arena); //~ ERROR `arena` does not live long enough
}<|fim▁end|> |
fn f<'a>(_arena: &'a TypedArena<C<'a>>) {}
|
<|file_name|>ZipWrapper.java<|end_file_name|><|fim▁begin|>package com.greenlemonmobile.app.ebook.books.parser;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
public interface ZipWrapper {
ZipEntry getEntry(String entryName);
<|fim▁hole|> InputStream getInputStream(ZipEntry entry) throws IOException;
Enumeration<? extends ZipEntry> entries();
void close() throws IOException;
}<|fim▁end|> | |
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|>from datetime import datetime
from api.utils import api_response
<|fim▁hole|> if not request.user.is_authenticated():
return api_response({"error": "not authenticated"}, status=401)
request.user.last_action=datetime.now().replace(tzinfo=None)
request.user.save()
return fn(self, request, *args, **kwargs)
return wrapped
def payload_required(fn):
def wrapped(self, request, *args, **kwargs):
if not request.body:
return api_response({"error": "payload required"}, status=403)
return fn(self, request, *args, **kwargs)
return wrapped<|fim▁end|> | def auth_required(fn):
def wrapped(self, request, *args, **kwargs): |
<|file_name|>ContentAssistProvider.java<|end_file_name|><|fim▁begin|>/*
* CLiC, Framework for Command Line Interpretation in Eclipse
*
* Copyright (C) 2013 Worldline or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.worldline.clic.internal.assist;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
/**
* This class allows to deal with autocompletion for all commands.
*
* @author mvanbesien
* @since 1.0
* @version 1.0
*/
public class ContentAssistProvider {
private final StyledText text;
private final IProcessor[] processors;
private final Map<String, Object> properties = new HashMap<String, Object>();
private IStructuredContentProvider assistContentProvider;
private Listener textKeyListener;
private Listener assistTablePopulationListener;
private Listener onSelectionListener;
private Listener onEscapeListener;
private IDoubleClickListener tableDoubleClickListener;
private Listener focusOutListener;
private Listener vanishListener;
private Table table;
private TableViewer viewer;
private Shell popupShell;
public ContentAssistProvider(final StyledText text,
final IProcessor... processors) {
this.text = text;
this.processors = processors;
build();
}
public void setProperty(final String key, final Object value) {
properties.put(key, value);
}
private void build() {
// Creation of graphical elements
final Display display = text.getDisplay();
popupShell = new Shell(display, SWT.ON_TOP);
popupShell.setLayout(new FillLayout());
table = new Table(popupShell, SWT.SINGLE);
viewer = new TableViewer(table);
assistContentProvider = newAssistContentProvider();
textKeyListener = newTextKeyListener();
assistTablePopulationListener = newAssistTablePopulationListener();<|fim▁hole|> focusOutListener = newFocusOutListener();
vanishListener = newVanishListener();
viewer.setContentProvider(assistContentProvider);
text.addListener(SWT.KeyDown, textKeyListener);
text.addListener(SWT.Modify, assistTablePopulationListener);
table.addListener(SWT.DefaultSelection, onSelectionListener);
table.addListener(SWT.KeyDown, onEscapeListener);
viewer.addDoubleClickListener(tableDoubleClickListener);
table.addListener(SWT.FocusOut, focusOutListener);
text.addListener(SWT.FocusOut, focusOutListener);
text.getShell().addListener(SWT.Move, vanishListener);
text.addDisposeListener(newDisposeListener());
}
private DisposeListener newDisposeListener() {
return new DisposeListener() {
@Override
public void widgetDisposed(final DisposeEvent e) {
text.removeListener(SWT.KeyDown, textKeyListener);
text.removeListener(SWT.Modify, assistTablePopulationListener);
table.removeListener(SWT.DefaultSelection, onSelectionListener);
table.removeListener(SWT.KeyDown, onEscapeListener);
viewer.removeDoubleClickListener(tableDoubleClickListener);
table.removeListener(SWT.FocusOut, focusOutListener);
text.removeListener(SWT.FocusOut, focusOutListener);
text.getShell().removeListener(SWT.Move, vanishListener);
table.dispose();
popupShell.dispose();
}
};
}
private IStructuredContentProvider newAssistContentProvider() {
return new IStructuredContentProvider() {
@Override
public void inputChanged(final Viewer viewer,
final Object oldInput, final Object newInput) {
}
@Override
public void dispose() {
}
@Override
public Object[] getElements(final Object inputElement) {
final Collection<String> results = new ArrayList<String>();
if (inputElement instanceof String) {
final String input = (String) inputElement;
final ProcessorContext pc = new ProcessorContext(input,
text.getCaretOffset(), properties);
for (final IProcessor processor : processors)
results.addAll(processor.getProposals(pc));
}
return results.toArray();
}
};
}
private Listener newAssistTablePopulationListener() {
return new Listener() {
@Override
public void handleEvent(final Event event) {
if (event.widget instanceof Text) {
final Text text = (Text) event.widget;
final String string = text.getText();
if (string.length() == 0)
// if (popupShell.isVisible())
popupShell.setVisible(false);
else {
viewer.setInput(string);
final Rectangle textBounds = text.getDisplay().map(
text.getParent(), null, text.getBounds());
popupShell.setBounds(textBounds.x, textBounds.y
+ textBounds.height, textBounds.width, 80);
// if (!popupShell.isVisible())
popupShell.setVisible(true);
}
}
}
};
}
private Listener newVanishListener() {
return new Listener() {
@Override
public void handleEvent(final Event event) {
popupShell.setVisible(false);
}
};
}
private Listener newTextKeyListener() {
return new Listener() {
@Override
public void handleEvent(final Event event) {
switch (event.keyCode) {
case SWT.ARROW_DOWN:
int index = (table.getSelectionIndex() + 1)
% table.getItemCount();
table.setSelection(index);
event.doit = false;
break;
case SWT.ARROW_UP:
index = table.getSelectionIndex() - 1;
if (index < 0)
index = table.getItemCount() - 1;
table.setSelection(index);
event.doit = false;
break;
case SWT.ARROW_RIGHT:
if (popupShell.isVisible()
&& table.getSelectionIndex() != -1) {
text.setText(table.getSelection()[0].getText());
text.setSelection(text.getText().length());
popupShell.setVisible(false);
}
break;
case SWT.ESC:
popupShell.setVisible(false);
break;
}
}
};
}
private IDoubleClickListener newDoubleClickListener() {
return new IDoubleClickListener() {
@Override
public void doubleClick(final DoubleClickEvent event) {
if (popupShell.isVisible() && table.getSelectionIndex() != -1) {
text.setText(table.getSelection()[0].getText());
text.setSelection(text.getText().length());
popupShell.setVisible(false);
}
}
};
}
private Listener newOnSelectionListener() {
return new Listener() {
@Override
public void handleEvent(final Event event) {
if (event.widget instanceof Text) {
final Text text = (Text) event.widget;
final ISelection selection = viewer.getSelection();
if (selection instanceof IStructuredSelection) {
text.setText(((IStructuredSelection) selection)
.getFirstElement().toString());
text.setSelection(text.getText().length() - 1);
}
popupShell.setVisible(false);
}
}
};
}
private Listener newOnEscapeListener() {
return new Listener() {
@Override
public void handleEvent(final Event event) {
if (event.keyCode == SWT.ESC)
popupShell.setVisible(false);
}
};
}
private Listener newFocusOutListener() {
return new Listener() {
@Override
public void handleEvent(final Event event) {
popupShell.setVisible(false);
}
};
}
}<|fim▁end|> | onSelectionListener = newOnSelectionListener();
onEscapeListener = newOnEscapeListener();
tableDoubleClickListener = newDoubleClickListener(); |
<|file_name|>gameboy.rs<|end_file_name|><|fim▁begin|>// This file is part of Mooneye GB.
// Copyright (C) 2014-2020 Joonas Javanainen <[email protected]>
//
// Mooneye GB 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.
//
// Mooneye GB 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 Mooneye GB. If not, see <http://www.gnu.org/licenses/>.
pub type HiramData = [u8; HIRAM_SIZE];
pub type ScreenBuffer = [Color; SCREEN_PIXELS];
#[derive(Debug, PartialEq, Clone, Copy)]
#[repr(u8)]
pub enum Color {
Off = 0,
Light = 1,
Dark = 2,
On = 3,
}
impl Color {
#[inline]
pub fn from_u8(value: u8) -> Color {
use self::Color::*;
match value {
1 => Light,
2 => Dark,<|fim▁hole|> }
}
}
impl Into<u8> for Color {
fn into(self) -> u8 {
match self {
Color::Off => 0,
Color::Light => 1,
Color::Dark => 2,
Color::On => 3,
}
}
}
pub const CPU_SPEED_HZ: usize = 4_194_304;
pub const HIRAM_SIZE: usize = 0x80;
pub const HIRAM_EMPTY: HiramData = [0; HIRAM_SIZE];
pub const ROM_BANK_SIZE: usize = 0x4000;
pub const RAM_BANK_SIZE: usize = 0x2000;
pub const SCREEN_WIDTH: usize = 160;
pub const SCREEN_HEIGHT: usize = 144;
pub const SCREEN_PIXELS: usize = SCREEN_WIDTH * SCREEN_HEIGHT;
pub const SCREEN_EMPTY: ScreenBuffer = [Color::Off; SCREEN_PIXELS];<|fim▁end|> | 3 => On,
_ => Off, |
<|file_name|>wkf_expr.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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<|fim▁hole|># You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import sys
import openerp.netsvc as netsvc
import openerp.osv as base
import openerp.pooler as pooler
from openerp.tools.safe_eval import safe_eval as eval
class Env(dict):
def __init__(self, cr, uid, model, ids):
self.cr = cr
self.uid = uid
self.model = model
self.ids = ids
self.obj = pooler.get_pool(cr.dbname).get(model)
self.columns = self.obj._columns.keys() + self.obj._inherit_fields.keys()
def __getitem__(self, key):
if (key in self.columns) or (key in dir(self.obj)):
res = self.obj.browse(self.cr, self.uid, self.ids[0])
return res[key]
else:
return super(Env, self).__getitem__(key)
def _eval_expr(cr, ident, workitem, action):
ret=False
assert action, 'You used a NULL action in a workflow, use dummy node instead.'
for line in action.split('\n'):
line = line.strip()
uid=ident[0]
model=ident[1]
ids=[ident[2]]
if line =='True':
ret=True
elif line =='False':
ret=False
else:
env = Env(cr, uid, model, ids)
ret = eval(line, env, nocopy=True)
return ret
def execute_action(cr, ident, workitem, activity):
obj = pooler.get_pool(cr.dbname).get('ir.actions.server')
ctx = {'active_model':ident[1], 'active_id':ident[2], 'active_ids':[ident[2]]}
result = obj.run(cr, ident[0], [activity['action_id']], ctx)
return result
def execute(cr, ident, workitem, activity):
return _eval_expr(cr, ident, workitem, activity['action'])
def check(cr, workitem, ident, transition, signal):
if transition['signal'] and signal != transition['signal']:
return False
uid = ident[0]
if transition['group_id'] and uid != 1:
pool = pooler.get_pool(cr.dbname)
user_groups = pool.get('res.users').read(cr, uid, [uid], ['groups_id'])[0]['groups_id']
if not transition['group_id'] in user_groups:
return False
return _eval_expr(cr, ident, workitem, transition['condition'])
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:<|fim▁end|> | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# |
<|file_name|>nodept.rs<|end_file_name|><|fim▁begin|>pub type Node = usize;
#[derive(Debug, Copy, Clone)]<|fim▁hole|>pub struct NodePt {
pub id: Node,
pub x: f64,
pub y: f64,
}
impl NodePt {
pub fn new(node_id: Node, x: f64, y: f64) -> NodePt {
NodePt {
id: node_id,
x: x,
y: y,
}
}
pub fn distance_to(self, other: NodePt) -> f64 {
let xx = (self.x - other.x) * (self.x - other.x);
let yy = (self.y - other.y) * (self.y - other.y);
(xx + yy).sqrt().round()
}
}
impl PartialEq for NodePt {
fn eq(&self, other: &NodePt) -> bool {
self.id == other.id
}
fn ne(&self, other: &NodePt) -> bool {
self.id != other.id
}
}<|fim▁end|> | |
<|file_name|>models.py<|end_file_name|><|fim▁begin|><|fim▁hole|>
class Stuff (db.Model):
owner = db.UserProperty(required=True, auto_current_user=True)
pulp = db.BlobProperty()
class Greeting(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
avatar = db.BlobProperty()
date = db.DateTimeProperty(auto_now_add=True)
class Placebo(db.Model):
developer = db.StringProperty()
OID = db.StringProperty()
concept = db.StringProperty()
category = db.StringProperty()
taxonomy = db.StringProperty()
taxonomy_version = db.StringProperty()
code = db.StringProperty()
descriptor = db.StringProperty()<|fim▁end|> | from google.appengine.ext import db |
<|file_name|>storage.js<|end_file_name|><|fim▁begin|>/**
* Central storage with in-memory cache
*/
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const app = process.type === 'renderer'
? require('electron').remote.app
: require('electron').app;
const _defaultDir = path.join(app.getPath('userData'), 'data');
const _storage = {};
function getPath(options) {
if(options.prefix) {
return path.join(_defaultDir, options.prefix, options.fileName);
}
return path.join(_defaultDir, options.fileName);
}
function ensureDirectoryExists(dir) {
if (!fs.existsSync(dir)){
mkdirp.sync(dir);
}
}
function ensurePrefixExists(prefix) {
ensureDirectoryExists(path.join(_defaultDir, prefix));
}
ensureDirectoryExists(_defaultDir);
const Storage = {};
Storage.set = function(options, callback) {
if(options.prefix) {
ensurePrefixExists(options.prefix);
}
const file = getPath(options);
_storage[file] = options.value;
fs.writeFile(file, options.value, callback);
};
Storage.get = function(options, callback) {
const file = getPath(options);
if(file in _storage) {<|fim▁hole|>
fs.readFile(file, callback);
};
Storage.append = function(options, callback) {
if(options.prefix) {
ensurePrefixExists(options.prefix);
}
const file = getPath(options);
if(!(file in _storage)) {
_storage[file] = [];
}
_storage[file].push(options.value);
fs.appendFile(file, options.value, callback);
};
Storage.delete = function(options, callback) {
const file = getPath(options);
delete _storage[file];
fs.unlink(file, callback);
};
module.exports = Storage;<|fim▁end|> | callback(null, _storage[file]);
return;
} |
<|file_name|>resource_thread.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A thread that takes a URL and streams back the binary data.
use about_loader;
use blob_loader;
use chrome_loader;
use connector::{Connector, create_http_connector};
use content_blocker::BLOCKED_CONTENT_RULES;
use cookie;
use cookie_rs;
use cookie_storage::CookieStorage;
use data_loader;
use devtools_traits::DevtoolsControlMsg;
use fetch::methods::{FetchContext, fetch};
use file_loader;
use filemanager_thread::{FileManager, TFDProvider};
use hsts::HstsList;
use http_loader::{self, HttpState};
use hyper::client::pool::Pool;
use hyper::header::{ContentType, Header, SetCookie};
use hyper::mime::{Mime, SubLevel, TopLevel};
use hyper_serde::Serde;
use ipc_channel::ipc::{self, IpcReceiver, IpcReceiverSet, IpcSender};
use mime_classifier::{ApacheBugFlag, MimeClassifier, NoSniffFlag};
use net_traits::{CookieSource, CoreResourceThread, Metadata, ProgressMsg};
use net_traits::{CoreResourceMsg, FetchResponseMsg, FetchTaskTarget, LoadConsumer};
use net_traits::{CustomResponseMediator, LoadData, LoadResponse, NetworkError, ResourceId};
use net_traits::{ResourceThreads, WebSocketCommunicate, WebSocketConnectData};
use net_traits::LoadContext;
use net_traits::ProgressMsg::Done;
use net_traits::request::{Request, RequestInit};
use net_traits::storage_thread::StorageThreadMsg;
use profile_traits::time::ProfilerChan;
use rustc_serialize::{Decodable, Encodable};
use rustc_serialize::json;
use servo_url::ServoUrl;
use std::borrow::{Cow, ToOwned};
use std::boxed::FnBox;
use std::cell::Cell;
use std::collections::HashMap;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::{Arc, RwLock};
use std::sync::mpsc::{Receiver, Sender, channel};
use storage_thread::StorageThreadFactory;
use util::prefs::PREFS;
use util::thread::spawn_named;
use websocket_loader;
const TFD_PROVIDER: &'static TFDProvider = &TFDProvider;
pub enum ProgressSender {
Channel(IpcSender<ProgressMsg>),
}
#[derive(Clone)]
pub struct ResourceGroup {
cookie_jar: Arc<RwLock<CookieStorage>>,
auth_cache: Arc<RwLock<AuthCache>>,
hsts_list: Arc<RwLock<HstsList>>,
connector: Arc<Pool<Connector>>,
}
impl ProgressSender {
//XXXjdm return actual error
pub fn send(&self, msg: ProgressMsg) -> Result<(), ()> {
match *self {
ProgressSender::Channel(ref c) => c.send(msg).map_err(|_| ()),
}
}
}
pub fn send_error(url: ServoUrl, err: NetworkError, start_chan: LoadConsumer) {
let mut metadata: Metadata = Metadata::default(url);
metadata.status = None;
if let Ok(p) = start_sending_opt(start_chan, metadata) {
p.send(Done(Err(err))).unwrap();
}
}
/// For use by loaders in responding to a Load message that allows content sniffing.
pub fn start_sending_sniffed_opt(start_chan: LoadConsumer, mut metadata: Metadata,
classifier: Arc<MimeClassifier>, partial_body: &[u8],
context: LoadContext)
-> Result<ProgressSender, ()> {
if PREFS.get("network.mime.sniff").as_boolean().unwrap_or(false) {
// TODO: should be calculated in the resource loader, from pull requeset #4094
let mut no_sniff = NoSniffFlag::Off;
let mut check_for_apache_bug = ApacheBugFlag::Off;
if let Some(ref headers) = metadata.headers {
if let Some(ref content_type) = headers.get_raw("content-type").and_then(|c| c.last()) {
check_for_apache_bug = ApacheBugFlag::from_content_type(content_type)
}
if let Some(ref raw_content_type_options) = headers.get_raw("X-content-type-options") {
if raw_content_type_options.iter().any(|ref opt| *opt == b"nosniff") {
no_sniff = NoSniffFlag::On
}
}
}
let supplied_type =
metadata.content_type.as_ref().map(|&Serde(ContentType(Mime(ref toplevel, ref sublevel, _)))| {
(toplevel.to_owned(), format!("{}", sublevel))
});
let (toplevel, sublevel) = classifier.classify(context,
no_sniff,
check_for_apache_bug,
&supplied_type,
&partial_body);
let mime_tp: TopLevel = toplevel.into();
let mime_sb: SubLevel = sublevel.parse().unwrap();
metadata.content_type =
Some(Serde(ContentType(Mime(mime_tp, mime_sb, vec![]))));
}
start_sending_opt(start_chan, metadata)
}
/// For use by loaders in responding to a Load message.
/// It takes an optional NetworkError, so that we can extract the SSL Validation errors
/// and take it to the HTML parser
fn start_sending_opt(start_chan: LoadConsumer, metadata: Metadata) -> Result<ProgressSender, ()> {
match start_chan {
LoadConsumer::Channel(start_chan) => {
let (progress_chan, progress_port) = ipc::channel().unwrap();
let result = start_chan.send(LoadResponse {
metadata: metadata,
progress_port: progress_port,
});
match result {
Ok(_) => Ok(ProgressSender::Channel(progress_chan)),
Err(_) => Err(())
}
}
}
}
/// Returns a tuple of (public, private) senders to the new threads.
pub fn new_resource_threads(user_agent: Cow<'static, str>,
devtools_chan: Option<Sender<DevtoolsControlMsg>>,
profiler_chan: ProfilerChan,
config_dir: Option<PathBuf>)
-> (ResourceThreads, ResourceThreads) {
let (public_core, private_core) = new_core_resource_thread(
user_agent,
devtools_chan,
profiler_chan,
config_dir.clone());
let storage: IpcSender<StorageThreadMsg> = StorageThreadFactory::new(config_dir);
(ResourceThreads::new(public_core, storage.clone()),
ResourceThreads::new(private_core, storage))
}
/// Create a CoreResourceThread
pub fn new_core_resource_thread(user_agent: Cow<'static, str>,
devtools_chan: Option<Sender<DevtoolsControlMsg>>,
profiler_chan: ProfilerChan,
config_dir: Option<PathBuf>)
-> (CoreResourceThread, CoreResourceThread) {
let (public_setup_chan, public_setup_port) = ipc::channel().unwrap();
let (private_setup_chan, private_setup_port) = ipc::channel().unwrap();
let public_setup_chan_clone = public_setup_chan.clone();
let private_setup_chan_clone = private_setup_chan.clone();
spawn_named("ResourceManager".to_owned(), move || {
let resource_manager = CoreResourceManager::new(
user_agent, devtools_chan, profiler_chan
);
let mut channel_manager = ResourceChannelManager {
resource_manager: resource_manager,
config_dir: config_dir,
};
channel_manager.start(public_setup_chan_clone,
private_setup_chan_clone,
public_setup_port,
private_setup_port);
});
(public_setup_chan, private_setup_chan)
}
struct ResourceChannelManager {
resource_manager: CoreResourceManager,
config_dir: Option<PathBuf>,
}
fn create_resource_groups(config_dir: Option<&Path>)
-> (ResourceGroup, ResourceGroup) {
let mut hsts_list = HstsList::from_servo_preload();
let mut auth_cache = AuthCache::new();
let mut cookie_jar = CookieStorage::new();
if let Some(config_dir) = config_dir {
read_json_from_file(&mut auth_cache, config_dir, "auth_cache.json");
read_json_from_file(&mut hsts_list, config_dir, "hsts_list.json");
read_json_from_file(&mut cookie_jar, config_dir, "cookie_jar.json");
}
let resource_group = ResourceGroup {
cookie_jar: Arc::new(RwLock::new(cookie_jar)),
auth_cache: Arc::new(RwLock::new(auth_cache)),
hsts_list: Arc::new(RwLock::new(hsts_list.clone())),
connector: create_http_connector(),
};
let private_resource_group = ResourceGroup {
cookie_jar: Arc::new(RwLock::new(CookieStorage::new())),
auth_cache: Arc::new(RwLock::new(AuthCache::new())),
hsts_list: Arc::new(RwLock::new(HstsList::new())),
connector: create_http_connector(),
};
(resource_group, private_resource_group)
}
impl ResourceChannelManager {
#[allow(unsafe_code)]
fn start(&mut self,
public_control_sender: CoreResourceThread,
private_control_sender: CoreResourceThread,
public_receiver: IpcReceiver<CoreResourceMsg>,
private_receiver: IpcReceiver<CoreResourceMsg>) {
let (public_resource_group, private_resource_group) =
create_resource_groups(self.config_dir.as_ref().map(Deref::deref));
let mut rx_set = IpcReceiverSet::new().unwrap();
let private_id = rx_set.add(private_receiver).unwrap();
let public_id = rx_set.add(public_receiver).unwrap();
loop {
for (id, data) in rx_set.select().unwrap().into_iter().map(|m| m.unwrap()) {
let (group, sender) = if id == private_id {
(&private_resource_group, &private_control_sender)
} else {
assert_eq!(id, public_id);
(&public_resource_group, &public_control_sender)
};
if let Ok(msg) = data.to() {
if !self.process_msg(msg, group, &sender) {
break;
}
}
}
}
}
/// Returns false if the thread should exit.
fn process_msg(&mut self,
msg: CoreResourceMsg,
group: &ResourceGroup,
control_sender: &CoreResourceThread) -> bool {
match msg {
CoreResourceMsg::Load(load_data, consumer, id_sender) =>
self.resource_manager.load(load_data, consumer, id_sender, control_sender.clone(), group),
CoreResourceMsg::Fetch(init, sender) =>
self.resource_manager.fetch(init, sender, group),
CoreResourceMsg::WebsocketConnect(connect, connect_data) =>
self.resource_manager.websocket_connect(connect, connect_data, group),
CoreResourceMsg::SetCookiesForUrl(request, cookie_list, source) =>
self.resource_manager.set_cookies_for_url(request, cookie_list, source, group),
CoreResourceMsg::SetCookiesForUrlWithData(request, cookie, source) =>
self.resource_manager.set_cookies_for_url_with_data(request, cookie, source, group),
CoreResourceMsg::GetCookiesForUrl(url, consumer, source) => {
let mut cookie_jar = group.cookie_jar.write().unwrap();
consumer.send(cookie_jar.cookies_for_url(&url, source)).unwrap();
}
CoreResourceMsg::NetworkMediator(mediator_chan) => {
self.resource_manager.swmanager_chan = Some(mediator_chan)
}
CoreResourceMsg::GetCookiesDataForUrl(url, consumer, source) => {
let mut cookie_jar = group.cookie_jar.write().unwrap();
let cookies = cookie_jar.cookies_data_for_url(&url, source).map(Serde).collect();
consumer.send(cookies).unwrap();
}
CoreResourceMsg::Cancel(res_id) => {
if let Some(cancel_sender) = self.resource_manager.cancel_load_map.get(&res_id) {
let _ = cancel_sender.send(());
}
self.resource_manager.cancel_load_map.remove(&res_id);
}
CoreResourceMsg::Synchronize(sender) => {
let _ = sender.send(());
}
CoreResourceMsg::ToFileManager(msg) => self.resource_manager.filemanager.handle(msg, None, TFD_PROVIDER),
CoreResourceMsg::Exit(sender) => {
if let Some(ref config_dir) = self.config_dir {
match group.auth_cache.read() {
Ok(auth_cache) => write_json_to_file(&*auth_cache, config_dir, "auth_cache.json"),
Err(_) => warn!("Error writing auth cache to disk"),
}
match group.cookie_jar.read() {
Ok(jar) => write_json_to_file(&*jar, config_dir, "cookie_jar.json"),
Err(_) => warn!("Error writing cookie jar to disk"),
}
match group.hsts_list.read() {
Ok(hsts) => write_json_to_file(&*hsts, config_dir, "hsts_list.json"),
Err(_) => warn!("Error writing hsts list to disk"),
}
}
let _ = sender.send(());
return false;
}
}
true
}
}
pub fn read_json_from_file<T>(data: &mut T, config_dir: &Path, filename: &str)
where T: Decodable
{
let path = config_dir.join(filename);
let display = path.display();
let mut file = match File::open(&path) {
Err(why) => {
warn!("couldn't open {}: {}", display, Error::description(&why));
return;
},
Ok(file) => file,
};
let mut string_buffer: String = String::new();
match file.read_to_string(&mut string_buffer) {
Err(why) => {
panic!("couldn't read from {}: {}", display,
Error::description(&why))
},
Ok(_) => println!("successfully read from {}", display),
}
match json::decode(&string_buffer) {
Ok(decoded_buffer) => *data = decoded_buffer,
Err(why) => warn!("Could not decode buffer{}", why),
}
}
pub fn write_json_to_file<T>(data: &T, config_dir: &Path, filename: &str)
where T: Encodable
{
let json_encoded: String;
match json::encode(&data) {
Ok(d) => json_encoded = d,
Err(_) => return,
}
let path = config_dir.join(filename);
let display = path.display();
let mut file = match File::create(&path) {
Err(why) => panic!("couldn't create {}: {}",
display,
Error::description(&why)),
Ok(file) => file,
};
match file.write_all(json_encoded.as_bytes()) {
Err(why) => {
panic!("couldn't write to {}: {}", display,
Error::description(&why))
},
Ok(_) => println!("successfully wrote to {}", display),
}
}
/// The optional resources required by the `CancellationListener`
pub struct CancellableResource {
/// The receiver which receives a message on load cancellation
cancel_receiver: Receiver<()>,
/// The `CancellationListener` is unique to this `ResourceId`
resource_id: ResourceId,
/// If we haven't initiated any cancel requests, then the loaders ask
/// the listener to remove the `ResourceId` in the `HashMap` of
/// `CoreResourceManager` once they finish loading
resource_thread: CoreResourceThread,
}
impl CancellableResource {
pub fn new(receiver: Receiver<()>, res_id: ResourceId, res_thread: CoreResourceThread) -> CancellableResource {
CancellableResource {
cancel_receiver: receiver,
resource_id: res_id,
resource_thread: res_thread,
}
}
}
/// A listener which is basically a wrapped optional receiver which looks
/// for the load cancellation message. Some of the loading processes always keep
/// an eye out for this message and stop loading stuff once they receive it.
pub struct CancellationListener {
/// We'll be needing the resources only if we plan to cancel it
cancel_resource: Option<CancellableResource>,
/// This lets us know whether the request has already been cancelled
cancel_status: Cell<bool>,
}
impl CancellationListener {
pub fn new(resources: Option<CancellableResource>) -> CancellationListener {
CancellationListener {
cancel_resource: resources,
cancel_status: Cell::new(false),
}
}
pub fn is_cancelled(&self) -> bool {
let resource = match self.cancel_resource {
Some(ref resource) => resource,
None => return false, // channel doesn't exist!
};
if resource.cancel_receiver.try_recv().is_ok() {
self.cancel_status.set(true);
true
} else {
self.cancel_status.get()
}
}
}
impl Drop for CancellationListener {
fn drop(&mut self) {
if let Some(ref resource) = self.cancel_resource {
// Ensure that the resource manager stops tracking this request now that it's terminated.
let _ = resource.resource_thread.send(CoreResourceMsg::Cancel(resource.resource_id));
}
}
}
#[derive(RustcDecodable, RustcEncodable, Clone)]
pub struct AuthCacheEntry {
pub user_name: String,
pub password: String,
}
impl AuthCache {
pub fn new() -> AuthCache {
AuthCache {
version: 1,
entries: HashMap::new()
}
}
}
#[derive(RustcDecodable, RustcEncodable, Clone)]
pub struct AuthCache {
pub version: u32,
pub entries: HashMap<String, AuthCacheEntry>,
}
pub struct CoreResourceManager {
user_agent: Cow<'static, str>,
mime_classifier: Arc<MimeClassifier>,
devtools_chan: Option<Sender<DevtoolsControlMsg>>,
swmanager_chan: Option<IpcSender<CustomResponseMediator>>,
profiler_chan: ProfilerChan,
filemanager: FileManager,
cancel_load_map: HashMap<ResourceId, Sender<()>>,
next_resource_id: ResourceId,
}
impl CoreResourceManager {
pub fn new(user_agent: Cow<'static, str>,
devtools_channel: Option<Sender<DevtoolsControlMsg>>,
profiler_chan: ProfilerChan) -> CoreResourceManager {
CoreResourceManager {
user_agent: user_agent,
mime_classifier: Arc::new(MimeClassifier::new()),
devtools_chan: devtools_channel,
swmanager_chan: None,
profiler_chan: profiler_chan,
filemanager: FileManager::new(),
cancel_load_map: HashMap::new(),
next_resource_id: ResourceId(0),
}
}
fn set_cookies_for_url(&mut self,
request: ServoUrl,
cookie_list: String,
source: CookieSource,
resource_group: &ResourceGroup) {
let header = Header::parse_header(&[cookie_list.into_bytes()]);
if let Ok(SetCookie(cookies)) = header {
for bare_cookie in cookies {
if let Some(cookie) = cookie::Cookie::new_wrapped(bare_cookie, &request, source) {
let mut cookie_jar = resource_group.cookie_jar.write().unwrap();
cookie_jar.push(cookie, source);
}
}
}
}
fn set_cookies_for_url_with_data(&mut self, request: ServoUrl, cookie: cookie_rs::Cookie, source: CookieSource,
resource_group: &ResourceGroup) {
if let Some(cookie) = cookie::Cookie::new_wrapped(cookie, &request, source) {
let mut cookie_jar = resource_group.cookie_jar.write().unwrap();
cookie_jar.push(cookie, source)
}
}
fn load(&mut self,
load_data: LoadData,
consumer: LoadConsumer,
id_sender: Option<IpcSender<ResourceId>>,
resource_thread: CoreResourceThread,
resource_grp: &ResourceGroup) {
fn from_factory(factory: fn(LoadData, LoadConsumer, Arc<MimeClassifier>, CancellationListener))
-> Box<FnBox(LoadData,
LoadConsumer,
Arc<MimeClassifier>,
CancellationListener) + Send> {
box move |load_data, senders, classifier, cancel_listener| {
factory(load_data, senders, classifier, cancel_listener)
}
}
let cancel_resource = id_sender.map(|sender| {
let current_res_id = self.next_resource_id;
let _ = sender.send(current_res_id);
let (cancel_sender, cancel_receiver) = channel();
self.cancel_load_map.insert(current_res_id, cancel_sender);
self.next_resource_id.0 += 1;
CancellableResource::new(cancel_receiver, current_res_id, resource_thread)
});
let cancel_listener = CancellationListener::new(cancel_resource);
let loader = match load_data.url.scheme() {
"chrome" => from_factory(chrome_loader::factory),
"file" => from_factory(file_loader::factory),
"http" | "https" | "view-source" => {
let http_state = HttpState {
blocked_content: BLOCKED_CONTENT_RULES.clone(),
hsts_list: resource_grp.hsts_list.clone(),
cookie_jar: resource_grp.cookie_jar.clone(),
auth_cache: resource_grp.auth_cache.clone()
};
http_loader::factory(self.user_agent.clone(),
http_state,
self.devtools_chan.clone(),
self.profiler_chan.clone(),
self.swmanager_chan.clone(),
resource_grp.connector.clone())
},
"data" => from_factory(data_loader::factory),
"about" => from_factory(about_loader::factory),
"blob" => blob_loader::factory(self.filemanager.clone()),
_ => {
debug!("resource_thread: no loader for scheme {}", load_data.url.scheme());
send_error(load_data.url, NetworkError::Internal("no loader for scheme".to_owned()), consumer);
return
}
};
debug!("loading url: {}", load_data.url);
loader.call_box((load_data,
consumer,<|fim▁hole|> }
fn fetch(&self,
init: RequestInit,
sender: IpcSender<FetchResponseMsg>,
group: &ResourceGroup) {
let http_state = HttpState {
hsts_list: group.hsts_list.clone(),
cookie_jar: group.cookie_jar.clone(),
auth_cache: group.auth_cache.clone(),
blocked_content: BLOCKED_CONTENT_RULES.clone(),
};
let ua = self.user_agent.clone();
let dc = self.devtools_chan.clone();
let filemanager = self.filemanager.clone();
spawn_named(format!("fetch thread for {}", init.url), move || {
let request = Request::from_init(init);
// XXXManishearth: Check origin against pipeline id (also ensure that the mode is allowed)
// todo load context / mimesniff in fetch
// todo referrer policy?
// todo service worker stuff
let mut target = Some(Box::new(sender) as Box<FetchTaskTarget + Send + 'static>);
let context = FetchContext {
state: http_state,
user_agent: ua,
devtools_chan: dc,
filemanager: filemanager,
};
fetch(Rc::new(request), &mut target, &context);
})
}
fn websocket_connect(&self,
connect: WebSocketCommunicate,
connect_data: WebSocketConnectData,
resource_grp: &ResourceGroup) {
websocket_loader::init(connect, connect_data, resource_grp.cookie_jar.clone());
}
}<|fim▁end|> | self.mime_classifier.clone(),
cancel_listener)); |
<|file_name|>authorizationDialog.component.ts<|end_file_name|><|fim▁begin|>import {Component} from '@angular/core';
import {ModalDialog} from './modalDialog';
import {NgbActiveModal} from '@ng-bootstrap/ng-bootstrap';
type ButtonStyle = 'btn-primary' | 'btn-danger';<|fim▁hole|>export interface IAuthModel
{
title:string;
text:string;
buttonText: string;
buttonIcon: string;
buttonStyle: ButtonStyle;
}
@Component({
template: `
<div class="modal-body">
<button type="button" class="close" aria-label="Close" (click)="onCancel()">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">AUTH OR NOT</h4>
<p class="card-text">AUTH OR NOT</p>
<button type="button" (click)="onSubmit()" class="btn btn-md">
Auth
</button>
<button type="button" (click)="onCancel()" class="btn btn-secondary btn-md">
Cancel
</button>
</div>`
})
export class AuthorizationDialogComponent extends ModalDialog<IAuthModel>
{
constructor(activeModal: NgbActiveModal)
{
super(activeModal);
}
showConfirmation = (confirmation:IAuthModel) => this.model = confirmation;
model: IAuthModel = null;
}<|fim▁end|> | |
<|file_name|>ccallback.rs<|end_file_name|><|fim▁begin|>macro_rules! check_useful_c_callback {
($x:ident, $e:expr) => {
let $x = match $x {<|fim▁hole|> };
}
}<|fim▁end|> | Some($x) => $x,
None => return $e |
<|file_name|>httpheader.rs<|end_file_name|><|fim▁begin|>// Copyright (c) 2014 Nathan Sizemore
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
/*
* Module representing the HTTP Header Request/Response
* To conform to RFC - 6455 up to the point of allowing
* Text/Binary messaging. Covering all websocket connection
* types is outside the intent of this module.
*
* http://tools.ietf.org/html/rfc6455
*/
use super::rust_crypto::digest::Digest;
use super::rust_crypto::sha1::Sha1;
use super::rustc_serialize::base64::{ToBase64, STANDARD};
/*
* Struct representing a websocket connection request
*/
pub struct RequestHeader {
pub upgrade: String,
pub connection: String,
pub host: String,
pub origin: String,
pub pragma: String,
pub cache_control: String,
pub sec_websocket_key: String,
pub sec_websocket_version: String,
pub sec_websocket_extensions: String,
pub user_agent: String
}
/*
* Struct representing the websocket accept header
*/
pub struct ReturnHeader {
pub heading: String,
pub upgrade: String,
pub connection: String,
pub sec_websocket_accept: String
}
impl RequestHeader {
// Constructs a new RequestHeader struct
pub fn new(header: &str) -> RequestHeader {
// Build a default header
let mut request_header = RequestHeader {
upgrade: String::from_str(""),
connection: String::from_str(""),
host: String::from_str(""),
origin: String::from_str(""),
pragma: String::from_str(""),
cache_control: String::from_str(""),
sec_websocket_key: String::from_str(""),
sec_websocket_version: String::from_str(""),
sec_websocket_extensions: String::from_str(""),
user_agent:String::from_str("")
};
// TODO - Parse and get the values correctly
//
// This is all fucked up because it delimits off spaces
// All the fields we really care about work with this method, but
// it would be nice to make it actually find and parse correctly
for line in header.split_str("\r\n") {
let key_value: Vec<&str> = line.split(' ').collect();
match key_value[0] {
"Upgrade:" => request_header.upgrade = String::from_str(key_value[1]),
"Connection:" => request_header.connection = String::from_str(key_value[1]),
"Host:" => request_header.host = String::from_str(key_value[1]),
"Origin:" => request_header.origin = String::from_str(key_value[1]),
"Pragma:" => request_header.pragma = String::from_str(key_value[1]),
"Cache-Control:" => request_header.cache_control = String::from_str(key_value[1]),
"Sec-WebSocket-Key:" => request_header.sec_websocket_key = String::from_str(key_value[1]),
"Sec-WebSocket-Version:" => request_header.sec_websocket_version = String::from_str(key_value[1]),
"Sec-WebSocket-Extensions:" => request_header.sec_websocket_extensions = String::from_str(key_value[1]),
"User-Agent:" => request_header.user_agent = String::from_str(key_value[1]),
_ => { /* Do nothing */ }
}
}
return request_header;
}
// TODO - Create real logic that will actually verifiy this
pub fn is_valid(&self) -> bool {
if self.sec_websocket_key.as_slice() != "" {
return true;
}
return false;
}
}
impl ReturnHeader {
/*
* Returns the WebSocket Protocol Accept Header
*
* Accept Header:
* HTTP/.1 101 Switching Protocols
* Upgrade: websocket
* Connection: Upgrade
* Sec-WebSocket-Accept: COMPUTED_VALUE
*
* Steps to create the Sec-WebSocket-Accept Key:
* 1.) Append "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" to passed key
* 2.) SHA-1 Hash that value
* 3.) Base64 encode the hashed bytes, not string
* 4.) Return Base64 encoded bytes, not string
*/
pub fn new(key: &str) -> ReturnHeader {
// Combine key and WebSocket Key API thing
let mut pre_hash = String::from_str(key);
pre_hash.push_str("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
// Get the SHA-1 Hash as bytes
let mut out = [0u8; 20];
ReturnHeader::sha1_hash(pre_hash.as_slice(), &mut out);
// Base64 encode the buffer
let config = STANDARD;
let encoded = out.to_base64(config);
ReturnHeader {
heading: String::from_str("HTTP/1.1 101 Switching Protocols\r\n"),
upgrade: String::from_str("Upgrade: websocket\r\n"),
connection: String::from_str("Connection: Upgrade\r\n"),
sec_websocket_accept: encoded
}
}
// Returns a string version of the header
pub fn to_string(&self) -> String {
let mut stringified = String::new();
stringified.push_str(self.heading.as_slice());
stringified.push_str(self.upgrade.as_slice());
stringified.push_str(self.connection.as_slice());<|fim▁hole|> stringified.push_str(self.sec_websocket_accept.as_slice());
stringified.push_str("\r\n\r\n");
return stringified;
}
/*
* SHA-1 Hash performed on passed value
* Bytes placed in passed out buffer
*/
fn sha1_hash(value: &str, out: &mut [u8]) {
let mut sha = box Sha1::new();
(*sha).input_str(value);
sha.result(out);
}
}<|fim▁end|> | stringified.push_str("Sec-Websocket-Accept: "); |
<|file_name|>ClusterPolicyCRUDCommandTest.java<|end_file_name|><|fim▁begin|>package org.ovirt.engine.core.bll.scheduling.commands;<|fim▁hole|>import org.junit.Rule;
import org.junit.Test;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.scheduling.ClusterPolicy;
import org.ovirt.engine.core.common.scheduling.parameters.ClusterPolicyCRUDParameters;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.utils.MockConfigRule;
public class ClusterPolicyCRUDCommandTest {
@Rule
public MockConfigRule mockConfigRule =
new MockConfigRule((MockConfigRule.mockConfig(ConfigValues.EnableVdsLoadBalancing, false)),
(MockConfigRule.mockConfig(ConfigValues.EnableVdsHaReservation, false)));
@Test
public void testCheckAddEditValidations() {
Guid clusterPolicyId = new Guid("e754440b-76a6-4099-8235-4565ab4b5521");
ClusterPolicy clusterPolicy = new ClusterPolicy();
clusterPolicy.setId(clusterPolicyId);
ClusterPolicyCRUDCommand command =
new ClusterPolicyCRUDCommand(new ClusterPolicyCRUDParameters(clusterPolicyId,
clusterPolicy)) {
@Override
protected void executeCommand() {
}
};
Assert.assertTrue(command.checkAddEditValidations());
}
@Test
public void testCheckAddEditValidationsFailOnParameters() {
Guid clusterPolicyId = new Guid("e754440b-76a6-4099-8235-4565ab4b5521");
ClusterPolicy clusterPolicy = new ClusterPolicy();
clusterPolicy.setId(clusterPolicyId);
HashMap<String, String> parameterMap = new HashMap<String, String>();
parameterMap.put("fail?", "sure, fail!");
clusterPolicy.setParameterMap(parameterMap);
ClusterPolicyCRUDCommand command =
new ClusterPolicyCRUDCommand(new ClusterPolicyCRUDParameters(clusterPolicyId,
clusterPolicy)) {
@Override
protected void executeCommand() {
}
};
Assert.assertFalse(command.checkAddEditValidations());
}
}<|fim▁end|> |
import java.util.HashMap;
import org.junit.Assert; |
<|file_name|>MediaSessionManager.java<|end_file_name|><|fim▁begin|>package com.simplecity.amp_library.playback;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.RemoteControlClient;
import android.os.Bundle;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.text.TextUtils;
import android.util.Log;
import com.annimon.stream.Stream;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.cantrowitz.rxbroadcast.RxBroadcast;
import com.simplecity.amp_library.R;
import com.simplecity.amp_library.ShuttleApplication;
import com.simplecity.amp_library.androidauto.CarHelper;
import com.simplecity.amp_library.androidauto.MediaIdHelper;
import com.simplecity.amp_library.data.Repository;
import com.simplecity.amp_library.model.Song;
import com.simplecity.amp_library.playback.constants.InternalIntents;
import com.simplecity.amp_library.ui.screens.queue.QueueItem;
import com.simplecity.amp_library.ui.screens.queue.QueueItemKt;
import com.simplecity.amp_library.utils.LogUtils;
import com.simplecity.amp_library.utils.MediaButtonIntentReceiver;
import com.simplecity.amp_library.utils.SettingsManager;
import io.reactivex.Completable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import java.util.List;
import kotlin.Unit;
class MediaSessionManager {
<|fim▁hole|> private MediaSessionCompat mediaSession;
private QueueManager queueManager;
private PlaybackManager playbackManager;
private PlaybackSettingsManager playbackSettingsManager;
private SettingsManager settingsManager;
private CompositeDisposable disposables = new CompositeDisposable();
private MediaIdHelper mediaIdHelper;
private static String SHUFFLE_ACTION = "ACTION_SHUFFLE";
MediaSessionManager(
Context context,
QueueManager queueManager,
PlaybackManager playbackManager,
PlaybackSettingsManager playbackSettingsManager,
SettingsManager settingsManager,
Repository.SongsRepository songsRepository,
Repository.AlbumsRepository albumsRepository,
Repository.AlbumArtistsRepository albumArtistsRepository,
Repository.GenresRepository genresRepository,
Repository.PlaylistsRepository playlistsRepository
) {
this.context = context.getApplicationContext();
this.queueManager = queueManager;
this.playbackManager = playbackManager;
this.settingsManager = settingsManager;
this.playbackSettingsManager = playbackSettingsManager;
mediaIdHelper = new MediaIdHelper((ShuttleApplication) context.getApplicationContext(), songsRepository, albumsRepository, albumArtistsRepository, genresRepository, playlistsRepository);
ComponentName mediaButtonReceiverComponent = new ComponentName(context.getPackageName(), MediaButtonIntentReceiver.class.getName());
mediaSession = new MediaSessionCompat(context, "Shuttle", mediaButtonReceiverComponent, null);
mediaSession.setCallback(new MediaSessionCompat.Callback() {
@Override
public void onPause() {
playbackManager.pause(true);
}
@Override
public void onPlay() {
playbackManager.play();
}
@Override
public void onSeekTo(long pos) {
playbackManager.seekTo(pos);
}
@Override
public void onSkipToNext() {
playbackManager.next(true);
}
@Override
public void onSkipToPrevious() {
playbackManager.previous(false);
}
@Override
public void onSkipToQueueItem(long id) {
List<QueueItem> queueItems = queueManager.getCurrentPlaylist();
QueueItem queueItem = Stream.of(queueItems)
.filter(aQueueItem -> (long) aQueueItem.hashCode() == id)
.findFirst()
.orElse(null);
if (queueItem != null) {
playbackManager.setQueuePosition(queueItems.indexOf(queueItem));
}
}
@Override
public void onStop() {
playbackManager.stop(true);
}
@Override
public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
Log.e("MediaButtonReceiver", "OnMediaButtonEvent called");
MediaButtonIntentReceiver.handleIntent(context, mediaButtonEvent, playbackSettingsManager);
return true;
}
@Override
public void onPlayFromMediaId(String mediaId, Bundle extras) {
mediaIdHelper.getSongListForMediaId(mediaId, (songs, position) -> {
playbackManager.load((List<Song>) songs, position, true, 0);
return Unit.INSTANCE;
});
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@SuppressLint("CheckResult")
@Override
public void onPlayFromSearch(String query, Bundle extras) {
if (TextUtils.isEmpty(query)) {
playbackManager.play();
} else {
mediaIdHelper.handlePlayFromSearch(query, extras)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
pair -> {
if (!pair.getFirst().isEmpty()) {
playbackManager.load(pair.getFirst(), pair.getSecond(), true, 0);
} else {
playbackManager.pause(false);
}
},
error -> LogUtils.logException(TAG, "Failed to gather songs from search. Query: " + query, error)
);
}
}
@Override
public void onCustomAction(String action, Bundle extras) {
if (action.equals(SHUFFLE_ACTION)) {
queueManager.setShuffleMode(queueManager.shuffleMode == QueueManager.ShuffleMode.ON ? QueueManager.ShuffleMode.OFF : QueueManager.ShuffleMode.ON);
}
updateMediaSession(action);
}
});
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS | MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
//For some reason, MediaSessionCompat doesn't seem to pass all of the available 'actions' on as
//transport control flags for the RCC, so we do that manually
RemoteControlClient remoteControlClient = (RemoteControlClient) mediaSession.getRemoteControlClient();
if (remoteControlClient != null) {
remoteControlClient.setTransportControlFlags(
RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
| RemoteControlClient.FLAG_KEY_MEDIA_PLAY
| RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
| RemoteControlClient.FLAG_KEY_MEDIA_NEXT
| RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
| RemoteControlClient.FLAG_KEY_MEDIA_STOP);
}
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(InternalIntents.QUEUE_CHANGED);
intentFilter.addAction(InternalIntents.META_CHANGED);
intentFilter.addAction(InternalIntents.PLAY_STATE_CHANGED);
intentFilter.addAction(InternalIntents.POSITION_CHANGED);
disposables.add(RxBroadcast.fromBroadcast(context, intentFilter).subscribe(intent -> {
String action = intent.getAction();
if (action != null) {
updateMediaSession(intent.getAction());
}
}));
}
private void updateMediaSession(final String action) {
int playState = playbackManager.isPlaying() ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED;
long playbackActions = getMediaSessionActions();
QueueItem currentQueueItem = queueManager.getCurrentQueueItem();
PlaybackStateCompat.Builder builder = new PlaybackStateCompat.Builder();
builder.setActions(playbackActions);
switch (queueManager.shuffleMode) {
case QueueManager.ShuffleMode.OFF:
builder.addCustomAction(
new PlaybackStateCompat.CustomAction.Builder(SHUFFLE_ACTION, context.getString(R.string.btn_shuffle_on), R.drawable.ic_shuffle_off_circled).build());
break;
case QueueManager.ShuffleMode.ON:
builder.addCustomAction(
new PlaybackStateCompat.CustomAction.Builder(SHUFFLE_ACTION, context.getString(R.string.btn_shuffle_off), R.drawable.ic_shuffle_on_circled).build());
break;
}
builder.setState(playState, playbackManager.getSeekPosition(), 1.0f);
if (currentQueueItem != null) {
builder.setActiveQueueItemId((long) currentQueueItem.hashCode());
}
PlaybackStateCompat playbackState = builder.build();
if (action.equals(InternalIntents.PLAY_STATE_CHANGED) || action.equals(InternalIntents.POSITION_CHANGED) || action.equals(SHUFFLE_ACTION)) {
mediaSession.setPlaybackState(playbackState);
} else if (action.equals(InternalIntents.META_CHANGED) || action.equals(InternalIntents.QUEUE_CHANGED)) {
if (currentQueueItem != null) {
MediaMetadataCompat.Builder metaData = new MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, String.valueOf(currentQueueItem.getSong().id))
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, currentQueueItem.getSong().artistName)
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, currentQueueItem.getSong().albumArtistName)
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, currentQueueItem.getSong().albumName)
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, currentQueueItem.getSong().name)
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, currentQueueItem.getSong().duration)
.putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, (long) (queueManager.queuePosition + 1))
//Getting the genre is expensive.. let's not bother for now.
//.putString(MediaMetadataCompat.METADATA_KEY_GENRE, getGenreName())
.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, null)
.putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, (long) (queueManager.getCurrentPlaylist().size()));
// If we're in car mode, don't wait for the artwork to load before setting session metadata.
if (CarHelper.isCarUiMode(context)) {
mediaSession.setMetadata(metaData.build());
}
mediaSession.setPlaybackState(playbackState);
mediaSession.setQueue(QueueItemKt.toMediaSessionQueueItems(queueManager.getCurrentPlaylist()));
mediaSession.setQueueTitle(context.getString(R.string.menu_queue));
if (settingsManager.showLockscreenArtwork() || CarHelper.isCarUiMode(context)) {
updateMediaSessionArtwork(metaData);
} else {
mediaSession.setMetadata(metaData.build());
}
}
}
}
private void updateMediaSessionArtwork(MediaMetadataCompat.Builder metaData) {
QueueItem currentQueueItem = queueManager.getCurrentQueueItem();
if (currentQueueItem != null) {
disposables.add(Completable.defer(() -> Completable.fromAction(() ->
Glide.with(context)
.load(currentQueueItem.getSong().getAlbum())
.asBitmap()
.override(1024, 1024)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
if (bitmap != null) {
metaData.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, bitmap);
}
try {
mediaSession.setMetadata(metaData.build());
} catch (NullPointerException e) {
metaData.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, null);
mediaSession.setMetadata(metaData.build());
}
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
super.onLoadFailed(e, errorDrawable);
mediaSession.setMetadata(metaData.build());
}
})
))
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe()
);
}
}
private long getMediaSessionActions() {
return PlaybackStateCompat.ACTION_PLAY
| PlaybackStateCompat.ACTION_PAUSE
| PlaybackStateCompat.ACTION_PLAY_PAUSE
| PlaybackStateCompat.ACTION_SKIP_TO_NEXT
| PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
| PlaybackStateCompat.ACTION_STOP
| PlaybackStateCompat.ACTION_SEEK_TO
| PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID
| PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH
| PlaybackStateCompat.ACTION_SKIP_TO_QUEUE_ITEM;
}
MediaSessionCompat.Token getSessionToken() {
return mediaSession.getSessionToken();
}
void setActive(boolean active) {
mediaSession.setActive(active);
}
void destroy() {
disposables.clear();
mediaSession.release();
}
}<|fim▁end|> | private static final String TAG = "MediaSessionManager";
private Context context;
|
<|file_name|>gatefilter.py<|end_file_name|><|fim▁begin|>"""
gatefilter.py
Driver function that creates an ARTView display and initiates Gatefilter.
"""
import os
import sys
from ..core import Variable, QtGui, QtCore
from ..components import RadarDisplay, Menu
from ._common import _add_all_advanced_tools, _parse_dir, _parse_field
from ..plugins import GateFilter
def run(DirIn=None, filename=None, field=None):
"""
artview execution for filtering gates radar display
"""
DirIn = _parse_dir(DirIn)
app = QtGui.QApplication(sys.argv)
# start Menu and initiate Vradar<|fim▁hole|>
field = _parse_field(Vradar.value, field)
# start Displays
Vtilt = Variable(0)
plot1 = RadarDisplay(Vradar, Variable(field), Vtilt, name="Display",
parent=menu)
filt = GateFilter(Vradar=Vradar, Vgatefilter=plot1.Vgatefilter,
name="GateFilter", parent=None)
# plot1._gatefilter_toggle_on()
menu.addLayoutWidget(filt)
# add graphical starts
_add_all_advanced_tools(menu)
menu.setGeometry(0, 0, 500, 300)
# start program
app.exec_()<|fim▁end|> | menu = Menu(DirIn, filename, mode=("Radar",), name="Menu")
Vradar = menu.Vradar |
<|file_name|>throttle.spec.js<|end_file_name|><|fim▁begin|>describe('ngThrottleSpec', function() {
var $animate, body, $rootElement, $throttle, $timeout;
beforeEach(module('material.services.throttle', 'material.animations'));
beforeEach(inject(function(_$throttle_, _$timeout_, _$animate_, _$rootElement_, $document ){
$throttle = _$throttle_;
$timeout = _$timeout_;
$animate = _$animate_;
$rootElement = _$rootElement_;
body = angular.element($document[0].body);
body.append($rootElement);
}));
describe('use $throttle with no configurations', function() {
var finished, started, ended;
var done = function() { finished = true; };
beforeEach( function() { finished = started = ended = false; });
it("should start and end without configuration",function() {
var process = $throttle()( done );
$timeout.flush();
expect(finished).toBe(true);
});
it("should run process function without throttle configuration",function() {
var process = $throttle()( done );
process("a");
$timeout.flush();
expect(finished).toBe(true);
});
it("should start and end with `done` callbacks",function() {
var startFn = function(done){ started = true; done(); };
var process = $throttle({start:startFn})( done );
expect(process).toBeDefined();
expect(started).toBe(false);
$timeout.flush(); // flush start()
expect(started).toBe(true);
expect(finished).toBe(true);
});
it("should start and end withOUT `done` callbacks",function() {
var startFn = function(){ started = true; };
var endFn = function(){ ended = true; };
var process = $throttle({start:startFn, end:endFn})( done );
$timeout.flush(); // throttle()
expect(started).toBe(true);
expect(ended).toBe(true);
expect(finished).toBe(true);
});
it("should start without throttle or end calls specified",function() {
var startFn = function(){ started = true; };
var throttledFn = $throttle({start:startFn})();
$timeout.flush();
expect(started).toBe(true);
});
it("should start but NOT end if throttle does not complete",function() {
var startFn = function(){ started = true;},
endFn = function(){ ended = true;};
lockFn = function(done){ ; }, // do not callback for completion
$throttle({start:startFn, throttle:lockFn, end:endFn})();
$timeout.flush();
expect(started).toBe(true);
expect(ended).toBe(false);
});
});
describe('use $throttle with synchronous processing', function() {
it("should process n-times correctly",function() {
var wanted="The Hulk";
var sCount=0, title="",
startFn = function(){
sCount++;
},
processFn = function(text, done){
title += text;
if ( title == wanted ) {
// Conditional termination of throttle phase
done();
}
};
concat = $throttle({start:startFn, throttle:processFn})( );
concat("The ");
concat("Hulk");
$timeout.flush();
expect(title).toBe(wanted);
});
it("should properly process with report callbacks",function() {
var pCount= 10, total, callCount= 0,
processFn = function(count, done){
pCount -= count;
if ( pCount == 5 ) {
// Conditional termination of throttle phase
// report total value in callback
done(pCount);
}
},
/**
* only called when ALL processing is done
*/
reportFn = function(count){ total = count; callCount +=1;},
subtract = $throttle({throttle:processFn})( );
subtract(2, reportFn );
subtract(3, reportFn );
$timeout.flush();
expect(total).toBe(5);
expect(callCount).toBe(1);
});
it("should restart if already finished",function() {
var total= 0, started = 0,
startFn = function(){
started += 1;
},
processFn = function(count, done){
total += count;
done(); // !!finish throttling
},
add = $throttle({start:startFn, throttle:processFn})();
add(1); $timeout.flush(); // proceed to end()
add(1); $timeout.flush(); // proceed to end()
add(1); $timeout.flush(); // proceed to end()
expect(total).toBe(3);
expect(started).toBe(3); // restarted 1x
});
});
describe('use $throttle with exceptions', function() {
it("should report error within start()", function() {
var started = false;
var error = "";
var fn = $throttle({start:function(done){
started = true;
throw new Error("fault_with_start");
}})(null, function(fault){
error = fault;
});
$timeout.flush();
expect(started).toBe(true);
expect(error).toNotBe("");
});
it("should report error within end()", function() {
var ended = false, error = "";
var config = { end : function(done){
ended = true;
throw new Error("fault_with_end");
}};
var captureError = function(fault) { error = fault; };
$throttle(config)(null, captureError );
$timeout.flush();
expect(ended).toBe(true);
expect(error).toNotBe("");
});
it("should report error within throttle()", function() {
var count = 0, error = "";
var config = { throttle : function(done){
count += 1;
switch(count)
{
case 1 : break;
case 2 : throw new Error("fault_with_throttle"); break;
case 3 : done(); break;
}
}};
var captureError = function(fault) { error = fault; };
var fn = $throttle(config)(null, captureError );
$timeout.flush();
fn( 1 );
fn( 2 );
fn( 3 );
expect(count).toBe(2);
expect(error).toNotBe("");
});
});
describe('use $throttle with async processing', function() {
var finished = false;
var done = function() { finished = true; };
beforeEach( function() { finished = false; });
it("should pass with async start()",function() {
var sCount=0,
startFn = function(){
return $timeout(function(){
sCount++;
},100)
},
concat = $throttle({start:startFn})( done );
concat("The ");
concat("Hulk");
$timeout.flush();
expect(sCount).toBe(1);
});
it("should pass with async start(done)",function() {
var sCount=0,
startFn = function(done){
return $timeout(function(){
sCount++;
done();
},100)
},
concat = $throttle({start:startFn})( done );
concat("The ");
concat("Hulk");
$timeout.flush(); // flush to begin 1st deferred start()
expect(sCount).toBe(1);
});
it("should pass with async start(done) and end(done)",function() {
var sCount=3, eCount= 0,
startFn = function(done){
return $timeout(function(){
sCount--;
done();
},100)
},
endFn = function(done){
return $timeout(function(){
eCount++;
done();
},100)
};
$throttle({start:startFn, end:endFn})( done );
$timeout.flush(); // flush to begin 1st deferred start()
$timeout.flush(); // start()
$timeout.flush(); // end()
expect(sCount).toBe(2);
expect(eCount).toBe(1);
expect(finished).toBe(true);
});
it("should pass with async start(done) and process(done)",function() {
var title="",
startFn = function(){
return $timeout(function(){
done();
},200);
},
processFn = function(data, done){
$timeout(function(){
title += data;
},400);
},
concat = $throttle({start:startFn, throttle:processFn})( done );
$timeout.flush(); // start()
concat("The "); $timeout.flush(); // throttle(1)
concat("Hulk"); $timeout.flush(); // throttle(2)
expect(title).toBe("The Hulk");
});
it("should pass with async process(done) and restart with cancellable end",function() {
var content="", numStarts= 0, numEnds = 0,
startFn = function(done){
numStarts++;
done("start-done");
},
throttleFn = function(data, done){
$timeout(function(){
content += data;
if ( data == "e" ) {
done("throttle-done");
}
},400);
},
endFn = function(done){
numEnds++;
var procID = $timeout(function(){
done("end-done");
},500,false);
return function() {
$timeout.cancel( procID );
};
},
concat = $throttle({ start:startFn, throttle:throttleFn, end:endFn })( done );
$timeout.flush(); // flush to begin 1st start()
concat("a"); // Build string...
concat("b");
concat("c");
concat("d");
concat("e"); // forces end()
$timeout.flush(); // flush to throttle( 5x )
$timeout(function(){
concat("a"); // forces restart()
concat("e"); // forces end()
},400,false);
$timeout.flush(); // flush() 278
$timeout.flush(); // flush to throttle( 2x )
expect(content).toBe("abcdeae");
expect(numStarts).toBe(2);
expect(numEnds).toBe(2);
});
});
describe('use $throttle with inkRipple', function(){
var finished, started, ended;
var done = function() { finished = true; };
beforeEach( function() { finished = started = ended = false; });
function setup() {
var el;
var tmpl = '' +
'<div style="width:50px; height:50px;">'+
'<canvas class="material-ink-ripple" ></canvas>' +
'</div>';
<|fim▁hole|> $rootScope.$apply();
});
return el;
}
it('should start, animate, and end.', inject(function($compile, $rootScope, $materialEffects) {
var cntr = setup(),
canvas = cntr.find('canvas'),
rippler, makeRipple, throttled = 0,
config = {
start : function() {
rippler = rippler || $materialEffects.inkRipple( canvas[0] );
cntr.on('mousedown', makeRipple);
started = true;
},
throttle : function(e, done) {
throttled += 1;
switch(e.type)
{
case 'mousedown' :
rippler.createAt( {x:25,y:25} );
rippler.draw( done );
break;
default:
break;
}
}
}
// prepare rippler wave function...
makeRipple = $throttle(config)(done);
$timeout.flush();
expect(started).toBe(true);
// trigger wave animation...
cntr.triggerHandler("mousedown");
// Allow animation to finish...
$timeout(function(){
expect(throttled).toBe(1);
expect(ended).toBe(true);
expect(finished).toBe(true);
},10);
// Remove from $rootElement
cntr.remove();
}));
});
});<|fim▁end|> | inject(function($compile, $rootScope) {
el = $compile(tmpl)($rootScope);
$rootElement.append( el ); |
<|file_name|>test_touchup.py<|end_file_name|><|fim▁begin|>import logging
from sanic.signals import RESERVED_NAMESPACES
from sanic.touchup import TouchUp
<|fim▁hole|> assert len(TouchUp._registry) == 9
async def test_ode_removes_dispatch_events(app, caplog):
with caplog.at_level(logging.DEBUG, logger="sanic.root"):
await app._startup()
logs = caplog.record_tuples
for signal in RESERVED_NAMESPACES["http"]:
assert (
"sanic.root",
logging.DEBUG,
f"Disabling event: {signal}",
) in logs<|fim▁end|> |
def test_touchup_methods(app): |
<|file_name|>detail.py<|end_file_name|><|fim▁begin|>############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core business involves the administration of students, teachers,
# courses, programs and so on.
#
# Copyright (C) 2015-2018 Université catholique de Louvain (http://www.uclouvain.be)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 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 General Public License for more details.
#
# A copy of this license - GNU General Public License - is available
# at the root of the source code of this program. If not,
# see http://www.gnu.org/licenses/.
#
############################################################################
from django.contrib.auth.decorators import login_required<|fim▁hole|>from base.models.person import Person
from base.views.learning_units.common import get_learning_unit_identification_context
@login_required
def learning_unit_identification(request, learning_unit_year_id):
person = get_object_or_404(Person, user=request.user)
context = get_learning_unit_identification_context(learning_unit_year_id, person)
learning_unit_year = context['learning_unit_year']
if learning_unit_year.is_external():
template = "learning_unit/external/read.html"
permission = 'base.can_access_externallearningunityear'
else:
template = "learning_unit/identification.html"
permission = 'base.can_access_learningunit'
if not person.user.has_perm(permission):
raise PermissionDenied
return render(request, template, context)<|fim▁end|> | from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404, render
|
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>import Component from '@glimmer/component';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';
import type WindowService from 'emberclear/services/window';
export default class Install extends Component {
@service window!: WindowService;
@action<|fim▁hole|> install() {
return this.window.promptInstall();
}
}<|fim▁end|> | |
<|file_name|>packrepository.py<|end_file_name|><|fim▁begin|># Copyright (C) 2008 Canonical Ltd<|fim▁hole|># it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
from __future__ import absolute_import
"""Server-side pack repository related request implmentations."""
from bzrlib.smart.request import (
FailedSmartServerResponse,
SuccessfulSmartServerResponse,
)
from bzrlib.smart.repository import (
SmartServerRepositoryRequest,
)
class SmartServerPackRepositoryAutopack(SmartServerRepositoryRequest):
def do_repository_request(self, repository):
pack_collection = getattr(repository, '_pack_collection', None)
if pack_collection is None:
# This is a not a pack repo, so asking for an autopack is just a
# no-op.
return SuccessfulSmartServerResponse(('ok',))
repository.lock_write()
try:
repository._pack_collection.autopack()
finally:
repository.unlock()
return SuccessfulSmartServerResponse(('ok',))<|fim▁end|> | #
# This program is free software; you can redistribute it and/or modify |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>"""srt URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')<|fim▁hole|> 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include("cut_link.urls", namespace='cut')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)<|fim▁end|> | Class-based views
1. Add an import: from other_app.views import Home |
<|file_name|>create.go<|end_file_name|><|fim▁begin|>// Copyright (C) 2015 The GoHBase Authors. All rights reserved.
// This file is part of GoHBase.
// Use of this source code is governed by the Apache License 2.0
// that can be found in the COPYING file.
package hrpc
import (
"context"
"github.com/golang/protobuf/proto"
"github.com/tsuna/gohbase/pb"
)
// CreateTable represents a CreateTable HBase call
type CreateTable struct {
base
families map[string]map[string]string
splitKeys [][]byte
}
var defaultAttributes = map[string]string{
"BLOOMFILTER": "ROW",
"VERSIONS": "3",
"IN_MEMORY": "false",
"KEEP_DELETED_CELLS": "false",
"DATA_BLOCK_ENCODING": "FAST_DIFF",
"TTL": "2147483647",
"COMPRESSION": "NONE",
"MIN_VERSIONS": "0",
"BLOCKCACHE": "true",
"BLOCKSIZE": "65536",
"REPLICATION_SCOPE": "0",
}
// NewCreateTable creates a new CreateTable request that will create the given
// table in HBase. 'families' is a map of column family name to its attributes.
// For use by the admin client.
func NewCreateTable(ctx context.Context, table []byte,
families map[string]map[string]string,
options ...func(*CreateTable)) *CreateTable {
ct := &CreateTable{
base: base{
table: table,
ctx: ctx,
resultch: make(chan RPCResult, 1),
},
families: make(map[string]map[string]string, len(families)),
}
for _, option := range options {
option(ct)
}
for family, attrs := range families {
ct.families[family] = make(map[string]string, len(defaultAttributes))
for k, dv := range defaultAttributes {
if v, ok := attrs[k]; ok {
ct.families[family][k] = v
} else {
ct.families[family][k] = dv
}
}
}
return ct
}
// SplitKeys will return an option that will set the split keys for the created table<|fim▁hole|> return func(ct *CreateTable) {
ct.splitKeys = sk
}
}
// Name returns the name of this RPC call.
func (ct *CreateTable) Name() string {
return "CreateTable"
}
// ToProto converts the RPC into a protobuf message
func (ct *CreateTable) ToProto() proto.Message {
pbFamilies := make([]*pb.ColumnFamilySchema, 0, len(ct.families))
for family, attrs := range ct.families {
f := &pb.ColumnFamilySchema{
Name: []byte(family),
Attributes: make([]*pb.BytesBytesPair, 0, len(attrs)),
}
for k, v := range attrs {
f.Attributes = append(f.Attributes, &pb.BytesBytesPair{
First: []byte(k),
Second: []byte(v),
})
}
pbFamilies = append(pbFamilies, f)
}
return &pb.CreateTableRequest{
TableSchema: &pb.TableSchema{
TableName: &pb.TableName{
// TODO: handle namespaces
Namespace: []byte("default"),
Qualifier: ct.table,
},
ColumnFamilies: pbFamilies,
},
SplitKeys: ct.splitKeys,
}
}
// NewResponse creates an empty protobuf message to read the response of this
// RPC.
func (ct *CreateTable) NewResponse() proto.Message {
return &pb.CreateTableResponse{}
}<|fim▁end|> | func SplitKeys(sk [][]byte) func(*CreateTable) { |
<|file_name|>DevTools.js<|end_file_name|><|fim▁begin|>import React from 'react'
import { createDevTools } from 'redux-devtools'
import LogMonitor from 'redux-devtools-log-monitor'
import DockMonitor from 'redux-devtools-dock-monitor'
export default createDevTools(
<DockMonitor
toggleVisibilityKey="H"
changePositionKey="Q"
>
<LogMonitor /><|fim▁hole|><|fim▁end|> | </DockMonitor>
) |
<|file_name|>lasoverlapPro.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
***************************************************************************
lasoverlapPro.py
---------------------
Date : October 2014
Copyright : (C) 2014 by Martin Isenburg
Email : martin near rapidlasso point com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Martin Isenburg'
__date__ = 'October 2014'
__copyright__ = '(C) 2014, Martin Isenburg'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
from LAStoolsUtils import LAStoolsUtils
from LAStoolsAlgorithm import LAStoolsAlgorithm
from processing.core.parameters import ParameterBoolean
from processing.core.parameters import ParameterNumber
from processing.core.parameters import ParameterSelection
class lasoverlapPro(LAStoolsAlgorithm):
CHECK_STEP = "CHECK_STEP"
ATTRIBUTE = "ATTRIBUTE"
OPERATION = "OPERATION"
ATTRIBUTES = ["elevation", "intensity", "number_of_returns", "scan_angle_abs", "density"]
OPERATIONS = ["lowest", "highest", "average"]
CREATE_OVERLAP_RASTER = "CREATE_OVERLAP_RASTER"
CREATE_DIFFERENCE_RASTER = "CREATE_DIFFERENCE_RASTER"
def defineCharacteristics(self):
self.name = "lasoverlapPro"
self.group = "LAStools Production"
self.addParametersPointInputFolderGUI()
self.addParametersFilesAreFlightlinesGUI()
self.addParametersFilter1ReturnClassFlagsGUI()
self.addParameter(ParameterNumber(lasoverlapPro.CHECK_STEP,
self.tr("size of grid used for overlap check"), 0, None, 2.0))
self.addParameter(ParameterSelection(lasoverlapPro.ATTRIBUTE,
self.tr("attribute to check"), lasoverlapPro.ATTRIBUTES, 0))
self.addParameter(ParameterSelection(lasoverlapPro.OPERATION,
self.tr("operation on attribute per cell"), lasoverlapPro.OPERATIONS, 0))
self.addParameter(ParameterBoolean(lasoverlapPro.CREATE_OVERLAP_RASTER,
self.tr("create overlap raster"), True))
self.addParameter(ParameterBoolean(lasoverlapPro.CREATE_DIFFERENCE_RASTER,
self.tr("create difference raster"), True))
self.addParametersOutputDirectoryGUI()
self.addParametersOutputAppendixGUI()
self.addParametersRasterOutputFormatGUI()
self.addParametersRasterOutputGUI()
self.addParametersAdditionalGUI()
self.addParametersCoresGUI()
self.addParametersVerboseGUI()
def processAlgorithm(self, progress):
commands = [os.path.join(LAStoolsUtils.LAStoolsPath(), "bin", "lasoverlap")]
self.addParametersVerboseCommands(commands)
self.addParametersPointInputFolderCommands(commands)
self.addParametersFilesAreFlightlinesCommands(commands)
self.addParametersFilter1ReturnClassFlagsCommands(commands)
step = self.getParameterValue(lasoverlapPro.CHECK_STEP)
if step != 0.0:<|fim▁hole|> commands.append(str(step))
commands.append("-values")
attribute = self.getParameterValue(lasoverlapPro.ATTRIBUTE)
if attribute != 0:
commands.append("-" + lasoverlapPro.ATTRIBUTES[attribute])
operation = self.getParameterValue(lasoverlapPro.OPERATION)
if operation != 0:
commands.append("-" + lasoverlapPro.OPERATIONS[operation])
if not self.getParameterValue(lasoverlapPro.CREATE_OVERLAP_RASTER):
commands.append("-no_over")
if not self.getParameterValue(lasoverlapPro.CREATE_DIFFERENCE_RASTER):
commands.append("-no_diff")
self.addParametersOutputDirectoryCommands(commands)
self.addParametersOutputAppendixCommands(commands)
self.addParametersRasterOutputFormatCommands(commands)
self.addParametersRasterOutputCommands(commands)
self.addParametersAdditionalCommands(commands)
self.addParametersCoresCommands(commands)
LAStoolsUtils.runLAStools(commands, progress)<|fim▁end|> | commands.append("-step") |
<|file_name|>SameFancyPet.java<|end_file_name|><|fim▁begin|>/*
*
* Copyright 2017 the original author or 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.
*
*
*/<|fim▁hole|>public class SameFancyPet extends SamePet {
private SameCategory extendedCategory;
public SameCategory getExtendedCategory() {
return extendedCategory;
}
public void setExtendedCategory(SameCategory extendedCategories) {
this.extendedCategory = extendedCategories;
}
}<|fim▁end|> |
package springfox.test.contract.swagger.models;
|
<|file_name|>infinite-tag-type-recursion.rs<|end_file_name|><|fim▁begin|>// -*- rust -*-
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your<|fim▁hole|>// option. This file may not be copied, modified, or distributed
// except according to those terms.
// error-pattern: illegal recursive enum type; wrap the inner value in a box
enum mlist { cons(int, mlist), nil, }
fn main() { let a = cons(10, cons(11, nil)); }<|fim▁end|> | |
<|file_name|>jinja_template.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Renders one or more template files using the Jinja template engine."""
import codecs
import argparse
import os
import sys
from util import build_utils
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))
from pylib.constants import host_paths
# Import jinja2 from third_party/jinja2
sys.path.append(os.path.join(host_paths.DIR_SOURCE_ROOT, 'third_party'))
import jinja2 # pylint: disable=F0401
class _RecordingFileSystemLoader(jinja2.FileSystemLoader):
def __init__(self, searchpath):
jinja2.FileSystemLoader.__init__(self, searchpath)
self.loaded_templates = set()
def get_source(self, environment, template):
contents, filename, uptodate = jinja2.FileSystemLoader.get_source(
self, environment, template)
self.loaded_templates.add(os.path.relpath(filename))
return contents, filename, uptodate
class JinjaProcessor(object):
"""Allows easy rendering of jinja templates with input file tracking."""
def __init__(self, loader_base_dir, variables=None):
self.loader_base_dir = loader_base_dir
self.variables = variables or {}
self.loader = _RecordingFileSystemLoader(loader_base_dir)
self.env = jinja2.Environment(loader=self.loader)
self.env.undefined = jinja2.StrictUndefined
self.env.line_comment_prefix = '##'
self.env.trim_blocks = True
self.env.lstrip_blocks = True
self._template_cache = {} # Map of path -> Template
def Render(self, input_filename, variables=None):
input_rel_path = os.path.relpath(input_filename, self.loader_base_dir)
template = self._template_cache.get(input_rel_path)
if not template:
template = self.env.get_template(input_rel_path)
self._template_cache[input_rel_path] = template
return template.render(variables or self.variables)
def GetLoadedTemplates(self):
return list(self.loader.loaded_templates)
def _ProcessFile(processor, input_filename, output_filename):
output = processor.Render(input_filename)
with codecs.open(output_filename, 'w', 'utf-8') as output_file:
output_file.write(output)
def _ProcessFiles(processor, input_filenames, inputs_base_dir, outputs_zip):
with build_utils.TempDir() as temp_dir:
for input_filename in input_filenames:
relpath = os.path.relpath(os.path.abspath(input_filename),
os.path.abspath(inputs_base_dir))
if relpath.startswith(os.pardir):
raise Exception('input file %s is not contained in inputs base dir %s'
% (input_filename, inputs_base_dir))
output_filename = os.path.join(temp_dir, relpath)
parent_dir = os.path.dirname(output_filename)
build_utils.MakeDirectory(parent_dir)
_ProcessFile(processor, input_filename, output_filename)
build_utils.ZipDir(outputs_zip, temp_dir)
def _ParseVariables(variables_arg, error_func):
variables = {}
for v in build_utils.ParseGnList(variables_arg):
if '=' not in v:
error_func('--variables argument must contain "=": ' + v)
name, _, value = v.partition('=')
variables[name] = value
return variables
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--inputs', required=True,
help='The template files to process.')
parser.add_argument('--output', help='The output file to generate. Valid '
'only if there is a single input.')
parser.add_argument('--outputs-zip', help='A zip file for the processed '
'templates. Required if there are multiple inputs.')
parser.add_argument('--inputs-base-dir', help='A common ancestor directory '
'of the inputs. Each output\'s path in the output zip '
'will match the relative path from INPUTS_BASE_DIR to '
'the input. Required if --output-zip is given.')
parser.add_argument('--loader-base-dir', help='Base path used by the '
'template loader. Must be a common ancestor directory of '<|fim▁hole|> 'the template processing environment, as a GYP list '
'(e.g. --variables "channel=beta mstone=39")', default='')
build_utils.AddDepfileOption(parser)
options = parser.parse_args()
inputs = build_utils.ParseGnList(options.inputs)
if (options.output is None) == (options.outputs_zip is None):
parser.error('Exactly one of --output and --output-zip must be given')
if options.output and len(inputs) != 1:
parser.error('--output cannot be used with multiple inputs')
if options.outputs_zip and not options.inputs_base_dir:
parser.error('--inputs-base-dir must be given when --output-zip is used')
variables = _ParseVariables(options.variables, parser.error)
processor = JinjaProcessor(options.loader_base_dir, variables=variables)
if options.output:
_ProcessFile(processor, inputs[0], options.output)
else:
_ProcessFiles(processor, inputs, options.inputs_base_dir,
options.outputs_zip)
if options.depfile:
output = options.output or options.outputs_zip
deps = processor.GetLoadedTemplates()
build_utils.WriteDepfile(options.depfile, output, deps)
if __name__ == '__main__':
main()<|fim▁end|> | 'the inputs. Defaults to DIR_SOURCE_ROOT.',
default=host_paths.DIR_SOURCE_ROOT)
parser.add_argument('--variables', help='Variables to be made available in ' |
<|file_name|>aws_rds_endpoint_port_from_instance_name.py<|end_file_name|><|fim▁begin|># (c) 2015, Jon Hadfield <[email protected]>
"""
Description: This lookup takes an AWS region and an RDS instance
name and returns the endpoint port.
Example Usage:
{{ lookup('aws_rds_endpoint_port_from_instance_name', ('eu-west-1', 'mydb')) }}
"""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import *
from ansible.plugins.lookup import LookupBase
try:
import boto3
import botocore
except ImportError:
raise AnsibleError("aws_rds_endpoint_port_from_instance_name lookup cannot be run without boto installed")
class LookupModule(LookupBase):
def run(self, terms, variables=None, **kwargs):
region = terms[0][0]
instance_name = terms[0][1]
session=boto3.session.Session(region_name=region)
<|fim▁hole|> rds_client=session.client('rds')
except botocore.exceptions.NoRegionError:
raise AnsibleError("AWS region not specified.")
result=rds_client.describe_db_instances(DBInstanceIdentifier=instance_name)
if result and result.get('DBInstances'):
return [result.get('DBInstances')[0].get('Endpoint').get('Port').encode('utf-8')]
return None<|fim▁end|> | try: |
<|file_name|>GeoGigDataStore.java<|end_file_name|><|fim▁begin|>/* Copyright (c) 2013-2014 Boundless and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/edl-v10.html
*
* Contributors:
* Gabriel Roldan (Boundless) - initial implementation
*/
package org.locationtech.geogig.geotools.data;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import org.eclipse.jdt.annotation.Nullable;
import org.geotools.data.DataStore;
import org.geotools.data.Transaction;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.store.ContentDataStore;
import org.geotools.data.store.ContentEntry;
import org.geotools.data.store.ContentState;
import org.geotools.feature.NameImpl;
import org.locationtech.geogig.data.FindFeatureTypeTrees;
import org.locationtech.geogig.model.ObjectId;
import org.locationtech.geogig.model.Ref;
import org.locationtech.geogig.model.RevObject.TYPE;
import org.locationtech.geogig.model.RevTree;
import org.locationtech.geogig.model.SymRef;
import org.locationtech.geogig.plumbing.ForEachRef;
import org.locationtech.geogig.plumbing.RefParse;
import org.locationtech.geogig.plumbing.RevParse;
import org.locationtech.geogig.plumbing.TransactionBegin;
import org.locationtech.geogig.porcelain.AddOp;
import org.locationtech.geogig.porcelain.CheckoutOp;
import org.locationtech.geogig.porcelain.CommitOp;
import org.locationtech.geogig.repository.Context;
import org.locationtech.geogig.repository.GeogigTransaction;
import org.locationtech.geogig.repository.NodeRef;
import org.locationtech.geogig.repository.Repository;
import org.locationtech.geogig.repository.WorkingTree;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.Name;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
/**
* A GeoTools {@link DataStore} that serves and edits {@link SimpleFeature}s in a geogig repository.
* <p>
* Multiple instances of this kind of data store may be created against the same repository,
* possibly working against different {@link #setHead(String) heads}.
* <p>
* A head is any commit in GeoGig. If a head has a branch pointing at it then the store allows
* transactions, otherwise no data modifications may be made.
*
* A branch in Geogig is a separate line of history that may or may not share a common ancestor with
* another branch. In the later case the branch is called "orphan" and by convention the default
* branch is called "master", which is created when the geogig repo is first initialized, but does
* not necessarily exist.
* <p>
* Every read operation (like in {@link #getFeatureSource(Name)}) reads committed features out of
* the configured "head" branch. Write operations are only supported if a {@link Transaction} is
* set, in which case a {@link GeogigTransaction} is tied to the geotools transaction by means of a
* {@link GeogigTransactionState}. During the transaction, read operations will read from the
* transaction's {@link WorkingTree} in order to "see" features that haven't been committed yet.
* <p>
* When the transaction is committed, the changes made inside that transaction are merged onto the
* actual repository. If any other change was made to the repository meanwhile, a rebase will be
* attempted, and the transaction commit will fail if the rebase operation finds any conflict. This
* provides for optimistic locking and reduces thread contention.
*
*/
public class GeoGigDataStore extends ContentDataStore implements DataStore {
private final Repository geogig;
/** @see #setHead(String) */
private String refspec;
/** When the configured head is not a branch, we disallow transactions */
private boolean allowTransactions = true;
public GeoGigDataStore(Repository geogig) {
super();
Preconditions.checkNotNull(geogig);
this.geogig = geogig;
}
@Override
public void dispose() {
super.dispose();
geogig.close();
}
/**
* Instructs the datastore to operate against the specified refspec, or against the checked out
* branch, whatever it is, if the argument is {@code null}.
*
* Editing capabilities are disabled if the refspec is not a local branch.
*
* @param refspec the name of the branch to work against, or {@code null} to default to the
* currently checked out branch
* @see #getConfiguredBranch()
* @see #getOrFigureOutHead()
* @throws IllegalArgumentException if {@code refspec} is not null and no such commit exists in
* the repository
*/
public void setHead(@Nullable final String refspec) throws IllegalArgumentException {
if (refspec == null) {
allowTransactions = true; // when no branch name is set we assume we should make
// transactions against the current HEAD
} else {
final Context context = getCommandLocator(null);
Optional<ObjectId> rev = context.command(RevParse.class).setRefSpec(refspec).call();
if (!rev.isPresent()) {
throw new IllegalArgumentException("Bad ref spec: " + refspec);
}
Optional<Ref> branchRef = context.command(RefParse.class).setName(refspec).call();
if (branchRef.isPresent()) {
Ref ref = branchRef.get();
if (ref instanceof SymRef) {
ref = context.command(RefParse.class).setName(((SymRef) ref).getTarget()).call()
.orNull();
}
Preconditions.checkArgument(ref != null, "refSpec is a dead symref: " + refspec);
if (ref.getName().startsWith(Ref.HEADS_PREFIX)) {
allowTransactions = true;
} else {
allowTransactions = false;
}
} else {
allowTransactions = false;
}
}
this.refspec = refspec;
}
public String getOrFigureOutHead() {
String branch = getConfiguredHead();
if (branch != null) {
return branch;
}
return getCheckedOutBranch();
}
public Repository getGeogig() {
return geogig;
}
/**
* @return the configured refspec of the commit this datastore works against, or {@code null} if
* no head in particular has been set, meaning the data store works against whatever the
* currently checked out branch is.
*/
@Nullable
public String getConfiguredHead() {
return this.refspec;
}
/**
* @return whether or not we can support transactions against the configured head
*/
public boolean isAllowTransactions() {
return this.allowTransactions;
}
/**
* @return the name of the currently checked out branch in the repository, not necessarily equal
* to {@link #getConfiguredBranch()}, or {@code null} in the (improbable) case HEAD is
* on a dettached state (i.e. no local branch is currently checked out)
*/
@Nullable
public String getCheckedOutBranch() {
Optional<Ref> head = getCommandLocator(null).command(RefParse.class).setName(Ref.HEAD)
.call();
if (!head.isPresent()) {
return null;
}
Ref headRef = head.get();
if (!(headRef instanceof SymRef)) {
return null;
}
String refName = ((SymRef) headRef).getTarget();
Preconditions.checkState(refName.startsWith(Ref.HEADS_PREFIX));
String branchName = refName.substring(Ref.HEADS_PREFIX.length());
return branchName;
}
public ImmutableList<String> getAvailableBranches() {
ImmutableSet<Ref> heads = getCommandLocator(null).command(ForEachRef.class)
.setPrefixFilter(Ref.HEADS_PREFIX).call();
List<String> list = Lists.newArrayList(Collections2.transform(heads, (ref) -> {
String branchName = ref.getName().substring(Ref.HEADS_PREFIX.length());
return branchName;<|fim▁hole|>
}));
Collections.sort(list);
return ImmutableList.copyOf(list);
}
public Context getCommandLocator(@Nullable Transaction transaction) {
Context commandLocator = null;
if (transaction != null && !Transaction.AUTO_COMMIT.equals(transaction)) {
GeogigTransactionState state;
state = (GeogigTransactionState) transaction.getState(GeogigTransactionState.class);
Optional<GeogigTransaction> geogigTransaction = state.getGeogigTransaction();
if (geogigTransaction.isPresent()) {
commandLocator = geogigTransaction.get();
}
}
if (commandLocator == null) {
commandLocator = geogig.context();
}
return commandLocator;
}
public Name getDescriptorName(NodeRef treeRef) {
Preconditions.checkNotNull(treeRef);
Preconditions.checkArgument(TYPE.TREE.equals(treeRef.getType()));
Preconditions.checkArgument(!treeRef.getMetadataId().isNull(),
"NodeRef '%s' is not a feature type reference", treeRef.path());
return new NameImpl(getNamespaceURI(), NodeRef.nodeFromPath(treeRef.path()));
}
public NodeRef findTypeRef(Name typeName, @Nullable Transaction tx) {
Preconditions.checkNotNull(typeName);
final String localName = typeName.getLocalPart();
final List<NodeRef> typeRefs = findTypeRefs(tx);
Collection<NodeRef> matches = Collections2.filter(typeRefs, new Predicate<NodeRef>() {
@Override
public boolean apply(NodeRef input) {
return NodeRef.nodeFromPath(input.path()).equals(localName);
}
});
switch (matches.size()) {
case 0:
throw new NoSuchElementException(
String.format("No tree ref matched the name: %s", localName));
case 1:
return matches.iterator().next();
default:
throw new IllegalArgumentException(String
.format("More than one tree ref matches the name %s: %s", localName, matches));
}
}
@Override
protected ContentState createContentState(ContentEntry entry) {
return new ContentState(entry);
}
@Override
protected ImmutableList<Name> createTypeNames() throws IOException {
List<NodeRef> typeTrees = findTypeRefs(Transaction.AUTO_COMMIT);
return ImmutableList
.copyOf(Collections2.transform(typeTrees, (ref) -> getDescriptorName(ref)));
}
private List<NodeRef> findTypeRefs(@Nullable Transaction tx) {
final String rootRef = getRootRef(tx);
Context commandLocator = getCommandLocator(tx);
List<NodeRef> typeTrees = commandLocator.command(FindFeatureTypeTrees.class)
.setRootTreeRef(rootRef).call();
return typeTrees;
}
String getRootRef(@Nullable Transaction tx) {
final String rootRef;
if (null == tx || Transaction.AUTO_COMMIT.equals(tx)) {
rootRef = getOrFigureOutHead();
} else {
rootRef = Ref.WORK_HEAD;
}
return rootRef;
}
@Override
protected GeogigFeatureStore createFeatureSource(ContentEntry entry) throws IOException {
return new GeogigFeatureStore(entry);
}
/**
* Creates a new feature type tree on the {@link #getOrFigureOutHead() current branch}.
* <p>
* Implementation detail: the operation is the homologous to starting a transaction, checking
* out the current/configured branch, creating the type tree inside the transaction, issueing a
* geogig commit, and committing the transaction for the created tree to be merged onto the
* configured branch.
*/
@Override
public void createSchema(SimpleFeatureType featureType) throws IOException {
if (!allowTransactions) {
throw new IllegalStateException("Configured head " + refspec
+ " is not a branch; transactions are not supported.");
}
GeogigTransaction tx = getCommandLocator(null).command(TransactionBegin.class).call();
boolean abort = false;
try {
String treePath = featureType.getName().getLocalPart();
// check out the datastore branch on the transaction space
final String branch = getOrFigureOutHead();
tx.command(CheckoutOp.class).setForce(true).setSource(branch).call();
// now we can use the transaction working tree with the correct branch checked out
WorkingTree workingTree = tx.workingTree();
workingTree.createTypeTree(treePath, featureType);
tx.command(AddOp.class).addPattern(treePath).call();
tx.command(CommitOp.class).setMessage("Created feature type tree " + treePath).call();
tx.commit();
} catch (IllegalArgumentException alreadyExists) {
abort = true;
throw new IOException(alreadyExists.getMessage(), alreadyExists);
} catch (Exception e) {
abort = true;
throw Throwables.propagate(e);
} finally {
if (abort) {
tx.abort();
}
}
}
// Deliberately leaving the @Override annotation commented out so that the class builds
// both against GeoTools 10.x and 11.x (as the method was added to DataStore in 11.x)
// @Override
public void removeSchema(Name name) throws IOException {
throw new UnsupportedOperationException(
"removeSchema not yet supported by geogig DataStore");
}
// Deliberately leaving the @Override annotation commented out so that the class builds
// both against GeoTools 10.x and 11.x (as the method was added to DataStore in 11.x)
// @Override
public void removeSchema(String name) throws IOException {
throw new UnsupportedOperationException(
"removeSchema not yet supported by geogig DataStore");
}
public static enum ChangeType {
ADDED, REMOVED, CHANGED_NEW, CHANGED_OLD;
}
/**
* Builds a FeatureSource (read-only) that fetches features out of the differences between two
* root trees: a provided tree-ish as the left side of the comparison, and the datastore's
* configured HEAD as the right side of the comparison.
* <p>
* E.g., to get all features of a given feature type that were removed between a given commit
* and its parent:
*
* <pre>
* <code>
* String commitId = ...
* GeoGigDataStore store = new GeoGigDataStore(geogig);
* store.setHead(commitId);
* FeatureSource removed = store.getDiffFeatureSource("roads", commitId + "~1", ChangeType.REMOVED);
* </code>
* </pre>
*
* @param typeName the feature type name to look up a type tree for in the datastore's current
* {@link #getOrFigureOutHead() HEAD}
* @param oldRoot a tree-ish string that resolves to the ROOT tree to be used as the left side
* of the diff
* @param changeType the type of change between {@code oldRoot} and {@link #getOrFigureOutHead()
* head} to pick as the features to return.
* @return a feature source whose features are computed out of the diff between the feature type
* diffs between the given {@code oldRoot} and the datastore's
* {@link #getOrFigureOutHead() HEAD}.
*/
public SimpleFeatureSource getDiffFeatureSource(final String typeName, final String oldRoot,
final ChangeType changeType) throws IOException {
Preconditions.checkNotNull(typeName, "typeName");
Preconditions.checkNotNull(oldRoot, "oldRoot");
Preconditions.checkNotNull(changeType, "changeType");
final Name name = name(typeName);
final ContentEntry entry = ensureEntry(name);
GeogigFeatureSource featureSource = new GeogigFeatureSource(entry);
featureSource.setTransaction(Transaction.AUTO_COMMIT);
featureSource.setChangeType(changeType);
if (ObjectId.NULL.toString().equals(oldRoot)
|| RevTree.EMPTY_TREE_ID.toString().equals(oldRoot)) {
featureSource.setOldRoot(null);
} else {
featureSource.setOldRoot(oldRoot);
}
return featureSource;
}
}<|fim▁end|> | |
<|file_name|>alu8.rs<|end_file_name|><|fim▁begin|>/// Module for 8 bit arithmetic (ALU instructions)
use jeebie::core::cpu::CPU;
use jeebie::core::registers::Register8::*;
use jeebie::core::registers::Register16::*;
// 'ADD A,A' 87 4
pub fn ADD_a_a(cpu: &mut CPU) -> i32 {
cpu.compute_add(A, A);
4
}
// 'ADD A,B' 80 4
pub fn ADD_a_b(cpu: &mut CPU) -> i32 {
cpu.compute_add(A, B);
4
}
// 'ADD A,C' 81 4
pub fn ADD_a_c(cpu: &mut CPU) -> i32 {
cpu.compute_add(A, C);
4
}
// 'ADD A,D' 82 4
pub fn ADD_a_d(cpu: &mut CPU) -> i32 {
cpu.compute_add(A, D);
4
}
// 'ADD A,E' 83 4
pub fn ADD_a_e(cpu: &mut CPU) -> i32 {
cpu.compute_add(A, E);
4
}
// 'ADD A,H' 84 4
pub fn ADD_a_h(cpu: &mut CPU) -> i32 {
cpu.compute_add(A, H);
4
}
// 'ADD A,L' 85 4
pub fn ADD_a_l(cpu: &mut CPU) -> i32 {
cpu.compute_add(A, L);
4
}
// 'ADD A,(HL)' 86 8
pub fn ADD_a_hlm(cpu: &mut CPU) -> i32 {
cpu.compute_add(A, RegisterAddress(HL));
8
}
// 'ADD A,*' C6 8
pub fn ADD_a_n(cpu: &mut CPU) -> i32 {
cpu.compute_add(A, N);
8
}
// 'ADC A,A' 8F 4
pub fn ADC_a_a(cpu: &mut CPU) -> i32 {
cpu.compute_adc(A, A);
4
}
// 'ADC A,B' 88 4
pub fn ADC_a_b(cpu: &mut CPU) -> i32 {
cpu.compute_adc(A, B);
4
}
// 'ADC A,C' 89 4
pub fn ADC_a_c(cpu: &mut CPU) -> i32 {
cpu.compute_adc(A, C);
4
}
// 'ADC A,D' 8A 4
pub fn ADC_a_d(cpu: &mut CPU) -> i32 {
cpu.compute_adc(A, D);
4
}
// 'ADC A,E' 8B 4
pub fn ADC_a_e(cpu: &mut CPU) -> i32 {
cpu.compute_adc(A, E);
4
}
// 'ADC A,H' 8C 4
pub fn ADC_a_h(cpu: &mut CPU) -> i32 {
cpu.compute_adc(A, H);
4
}
// 'ADC A,L' 8D 4
pub fn ADC_a_l(cpu: &mut CPU) -> i32 {
cpu.compute_adc(A, L);
4
}
// 'ADC A,(HL)' 8E 8
pub fn ADC_a_hlm(cpu: &mut CPU) -> i32 {
cpu.compute_adc(A, RegisterAddress(HL));
8
}
// 'ADC A,*' CE 8
pub fn ADC_a_n(cpu: &mut CPU) -> i32 {
cpu.compute_adc(A, N);
8
}
// 'SUB A' 97 4
pub fn SUB_a_A(cpu: &mut CPU) -> i32 {
cpu.compute_sub(A);
4
}
// 'SUB B' 90 4
pub fn SUB_a_B(cpu: &mut CPU) -> i32 {
cpu.compute_sub(B);
4
}
// 'SUB C' 91 4
pub fn SUB_a_C(cpu: &mut CPU) -> i32 {
cpu.compute_sub(C);
4
}
// 'SUB D' 92 4
pub fn SUB_a_D(cpu: &mut CPU) -> i32 {
cpu.compute_sub(D);
4
}
// 'SUB E' 93 4
pub fn SUB_a_E(cpu: &mut CPU) -> i32 {
cpu.compute_sub(E);
4
}
// 'SUB H' 94 4
pub fn SUB_a_H(cpu: &mut CPU) -> i32 {
cpu.compute_sub(H);
4
}
// 'SUB L' 95 4
pub fn SUB_a_L(cpu: &mut CPU) -> i32 {
cpu.compute_sub(L);
4
}
// 'SUB (HL)' 96 8
pub fn SUB_a_hlm(cpu: &mut CPU) -> i32 {
cpu.compute_sub(RegisterAddress(HL));
8
}
// 'SUB *' D6 8
pub fn SUB_a_n(cpu: &mut CPU) -> i32 {
cpu.compute_sub(N);
8
}
// 'SBC A,A' 9F 4
pub fn SBC_a_a(cpu: &mut CPU) -> i32 {
cpu.compute_sbc(A);
4
}
// 'SBC A,B' 98 4
pub fn SBC_a_b(cpu: &mut CPU) -> i32 {
cpu.compute_sbc(B);
4
}
// 'SBC A,C' 99 4
pub fn SBC_a_c(cpu: &mut CPU) -> i32 {
cpu.compute_sbc(C);
4
}
// 'SBC A,D' 9A 4
pub fn SBC_a_d(cpu: &mut CPU) -> i32 {
cpu.compute_sbc(D);
4
}
// 'SBC A,E' 9B 4
pub fn SBC_a_e(cpu: &mut CPU) -> i32 {
cpu.compute_sbc(E);
4
}
// 'SBC A,H' 9C 4
pub fn SBC_a_h(cpu: &mut CPU) -> i32 {
cpu.compute_sbc(H);
4
}
// 'SBC A,L' 9D 4
pub fn SBC_a_l(cpu: &mut CPU) -> i32 {
cpu.compute_sbc(L);
4
}
// 'SBC A,(HL)' 9E 8
pub fn SBC_a_hlm(cpu: &mut CPU) -> i32 {
cpu.compute_sbc(RegisterAddress(HL));
8
}
// 'SBC A,*' DE 8
pub fn SBC_a_n(cpu: &mut CPU) -> i32 {
cpu.compute_sbc(N);
0
}
// 'AND A' A7 4
pub fn AND_a(cpu: &mut CPU) -> i32 {
cpu.compute_and(A);
4
}
// 'AND B' A0 4
pub fn AND_b(cpu: &mut CPU) -> i32 {
cpu.compute_and(B);
4
}
// 'AND C' A1 4
pub fn AND_c(cpu: &mut CPU) -> i32 {
cpu.compute_and(C);
4
}
// 'AND D' A2 4
pub fn AND_d(cpu: &mut CPU) -> i32 {
cpu.compute_and(D);
4
}
// 'AND E' A3 4
pub fn AND_e(cpu: &mut CPU) -> i32 {
cpu.compute_and(E);
4
}
// 'AND H' A4 4
pub fn AND_h(cpu: &mut CPU) -> i32 {
cpu.compute_and(H);
4
}
// 'AND L' A5 4
pub fn AND_l(cpu: &mut CPU) -> i32 {
cpu.compute_and(L);
4
}
// 'AND (HL)' A6 8
pub fn AND_hlm(cpu: &mut CPU) -> i32 {
cpu.compute_and(RegisterAddress(HL));
8
}
// 'AND *' E6 8
pub fn AND_n(cpu: &mut CPU) -> i32 {
cpu.compute_and(N);
8
}
// 'OR A' B7 4
pub fn OR_a(cpu: &mut CPU) -> i32 {
cpu.compute_or(A);
4
}
// 'OR B' B0 4
pub fn OR_b(cpu: &mut CPU) -> i32 {
cpu.compute_or(B);
4
}
// 'OR C' B1 4
pub fn OR_c(cpu: &mut CPU) -> i32 {
cpu.compute_or(C);
4
}
// 'OR D' B2 4
pub fn OR_d(cpu: &mut CPU) -> i32 {
cpu.compute_or(D);
4
}
// 'OR E' B3 4
pub fn OR_e(cpu: &mut CPU) -> i32 {
cpu.compute_or(E);
4
}
// 'OR H' B4 4
pub fn OR_h(cpu: &mut CPU) -> i32 {
cpu.compute_or(H);
4
}
// 'OR L' B5 4
pub fn OR_l(cpu: &mut CPU) -> i32 {
cpu.compute_or(L);
4
}
// 'OR (HL)' B6 8
pub fn OR_hlm(cpu: &mut CPU) -> i32 {
cpu.compute_or(RegisterAddress(HL));
8
}
// 'OR *' F6 8
pub fn OR_n(cpu: &mut CPU) -> i32 {
cpu.compute_or(N);
8
}
// 'XOR A' AF 4
pub fn XOR_a(cpu: &mut CPU) -> i32 {
cpu.compute_xor(A);
4
}
// 'XOR B' A8 4
pub fn XOR_b(cpu: &mut CPU) -> i32 {
cpu.compute_xor(B);
4
}
// 'XOR C' A9 4
pub fn XOR_c(cpu: &mut CPU) -> i32 {
cpu.compute_xor(C);
4
}
// 'XOR D' AA 4
pub fn XOR_d(cpu: &mut CPU) -> i32 {
cpu.compute_xor(D);
4
}
// 'XOR E' AB 4
pub fn XOR_e(cpu: &mut CPU) -> i32 {
cpu.compute_xor(E);
4
}
// 'XOR H' AC 4
pub fn XOR_h(cpu: &mut CPU) -> i32 {
cpu.compute_xor(H);
4
}
// 'XOR L' AD 4
pub fn XOR_l(cpu: &mut CPU) -> i32 {
cpu.compute_xor(L);
4
}
// 'XOR (HL)' AE 8
pub fn XOR_hlm(cpu: &mut CPU) -> i32 {
cpu.compute_xor(RegisterAddress(HL));
8
}
// 'XOR *' EE 8
pub fn XOR_n(cpu: &mut CPU) -> i32 {
cpu.compute_xor(N);
8
}
// 'CP A' BF 4
pub fn CP_a(cpu: &mut CPU) -> i32 {
cpu.compute_cp(A);
4
}
// 'CP B' B8 4
pub fn CP_b(cpu: &mut CPU) -> i32 {
cpu.compute_cp(B);
4
}
// 'CP C' B9 4
pub fn CP_c(cpu: &mut CPU) -> i32 {
cpu.compute_cp(C);
4
}
// 'CP D' BA 4
pub fn CP_d(cpu: &mut CPU) -> i32 {
cpu.compute_cp(D);
4
}
// 'CP E' BB 4
pub fn CP_e(cpu: &mut CPU) -> i32 {
cpu.compute_cp(E);
4
}
// 'CP H' BC 4
pub fn CP_h(cpu: &mut CPU) -> i32 {
cpu.compute_cp(H);
4<|fim▁hole|>// 'CP L' BD 4
pub fn CP_l(cpu: &mut CPU) -> i32 {
cpu.compute_cp(L);
4
}
// 'CP (HL)' BE 8
pub fn CP_hlm(cpu: &mut CPU) -> i32 {
cpu.compute_cp(RegisterAddress(HL));
8
}
// 'CP *' FE 8
pub fn CP_n(cpu: &mut CPU) -> i32 {
cpu.compute_cp(N);
8
}
// 'INC A' 3C 4
pub fn INC_a(cpu: &mut CPU) -> i32 {
cpu.compute_inc(A);
4
}
// 'INC B' 04 4
pub fn INC_b(cpu: &mut CPU) -> i32 {
cpu.compute_inc(B);
4
}
// 'INC C' 0C 4
pub fn INC_c(cpu: &mut CPU) -> i32 {
cpu.compute_inc(C);
4
}
// 'INC D' 14 4
pub fn INC_d(cpu: &mut CPU) -> i32 {
cpu.compute_inc(D);
4
}
// 'INC E' 1C 4
pub fn INC_e(cpu: &mut CPU) -> i32 {
cpu.compute_inc(E);
4
}
// 'INC H' 24 4
pub fn INC_h(cpu: &mut CPU) -> i32 {
cpu.compute_inc(H);
4
}
// 'INC L' 2C 4
pub fn INC_l(cpu: &mut CPU) -> i32 {
cpu.compute_inc(L);
4
}
// 'INC (HL)' 34 12
pub fn INC_hlm(cpu: &mut CPU) -> i32 {
cpu.compute_inc(RegisterAddress(HL));
12
}
// 'DEC A' 3D 4
pub fn DEC_a(cpu: &mut CPU) -> i32 {
cpu.compute_dec(A);
4
}
// 'DEC B' 05 4
pub fn DEC_b(cpu: &mut CPU) -> i32 {
cpu.compute_dec(B);
4
}
// 'DEC C' 0D 4
pub fn DEC_c(cpu: &mut CPU) -> i32 {
cpu.compute_dec(C);
4
}
// 'DEC D' 15 4
pub fn DEC_d(cpu: &mut CPU) -> i32 {
cpu.compute_dec(D);
4
}
// 'DEC E' 1D 4
pub fn DEC_e(cpu: &mut CPU) -> i32 {
cpu.compute_dec(E);
4
}
// 'DEC H' 25 4
pub fn DEC_h(cpu: &mut CPU) -> i32 {
cpu.compute_dec(H);
4
}
// 'DEC L' 2D 4
pub fn DEC_l(cpu: &mut CPU) -> i32 {
cpu.compute_dec(L);
4
}
// 'DEC (HL)' 35 12
pub fn DEC_hlm(cpu: &mut CPU) -> i32 {
cpu.compute_dec(RegisterAddress(HL));
12
}<|fim▁end|> | }
|
<|file_name|>pipeline.js<|end_file_name|><|fim▁begin|>/*
* Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
'use strict';
/* global createProcessedMediaStreamTrack */ // defined in main.js
/**
* Wrapper around createProcessedMediaStreamTrack to apply transform to a
* MediaStream.
* @param {!MediaStream} sourceStream the video stream to be transformed. The
* first video track will be used.
* @param {!FrameTransformFn} transform the transform to apply to the
* sourceStream.
* @param {!AbortSignal} signal can be used to stop processing
* @return {!MediaStream} holds a single video track of the transformed video
* frames
*/
function createProcessedMediaStream(sourceStream, transform, signal) {
// For this sample, we're only dealing with video tracks.
/** @type {!MediaStreamTrack} */
const sourceTrack = sourceStream.getVideoTracks()[0];
const processedTrack =
createProcessedMediaStreamTrack(sourceTrack, transform, signal);
// Create a new MediaStream to hold our processed track.
const processedStream = new MediaStream();
processedStream.addTrack(processedTrack);
return processedStream;
}
/**
* Interface implemented by all video sources the user can select. A common
* interface allows the user to choose a source independently of the transform
* and sink.
* @interface
*/
class MediaStreamSource { // eslint-disable-line no-unused-vars
/**
* Sets the path to this object from the debug global var.
* @param {string} path
*/
setDebugPath(path) {}
/**
* Indicates if the source video should be mirrored/displayed on the page. If
* false (the default), any element producing frames will not be a child of
* the document.
* @param {boolean} visible whether to add the raw source video to the page
*/
setVisibility(visible) {}
/**
* Initializes and returns the MediaStream for this source.
* @return {!Promise<!MediaStream>}
*/
async getMediaStream() {}
/** Frees any resources used by this object. */
destroy() {}
}
/**
* Interface implemented by all video transforms that the user can select. A
* common interface allows the user to choose a transform independently of the
* source and sink.
* @interface
*/
class FrameTransform { // eslint-disable-line no-unused-vars
/** Initializes state that is reused across frames. */
async init() {}
/**
* Applies the transform to frame. Queues the output frame (if any) using the
* controller.
* @param {!VideoFrame} frame the input frame
* @param {!TransformStreamDefaultController<!VideoFrame>} controller
*/
async transform(frame, controller) {}
/** Frees any resources used by this object. */
destroy() {}
}
/**
* Interface implemented by all video sinks that the user can select. A common
* interface allows the user to choose a sink independently of the source and<|fim▁hole|> /**
* @param {!MediaStream} stream
*/
async setMediaStream(stream) {}
/** Frees any resources used by this object. */
destroy() {}
}
/**
* Assembles a MediaStreamSource, FrameTransform, and MediaStreamSink together.
*/
class Pipeline { // eslint-disable-line no-unused-vars
constructor() {
/** @private {?MediaStreamSource} set by updateSource*/
this.source_ = null;
/** @private {?FrameTransform} set by updateTransform */
this.frameTransform_ = null;
/** @private {?MediaStreamSink} set by updateSink */
this.sink_ = null;
/** @private {!AbortController} may used to stop all processing */
this.abortController_ = new AbortController();
/**
* @private {?MediaStream} set in maybeStartPipeline_ after all of source_,
* frameTransform_, and sink_ are set
*/
this.processedStream_ = null;
}
/** @return {?MediaStreamSource} */
getSource() {
return this.source_;
}
/**
* Sets a new source for the pipeline.
* @param {!MediaStreamSource} mediaStreamSource
*/
async updateSource(mediaStreamSource) {
if (this.source_) {
this.abortController_.abort();
this.abortController_ = new AbortController();
this.source_.destroy();
this.processedStream_ = null;
}
this.source_ = mediaStreamSource;
this.source_.setDebugPath('debug.pipeline.source_');
console.log(
'[Pipeline] Updated source.',
'debug.pipeline.source_ = ', this.source_);
await this.maybeStartPipeline_();
}
/** @private */
async maybeStartPipeline_() {
if (this.processedStream_ || !this.source_ || !this.frameTransform_ ||
!this.sink_) {
return;
}
const sourceStream = await this.source_.getMediaStream();
await this.frameTransform_.init();
try {
this.processedStream_ = createProcessedMediaStream(
sourceStream, async (frame, controller) => {
if (this.frameTransform_) {
await this.frameTransform_.transform(frame, controller);
}
}, this.abortController_.signal);
} catch (e) {
this.destroy();
return;
}
await this.sink_.setMediaStream(this.processedStream_);
console.log(
'[Pipeline] Pipeline started.',
'debug.pipeline.abortController_ =', this.abortController_);
}
/**
* Sets a new transform for the pipeline.
* @param {!FrameTransform} frameTransform
*/
async updateTransform(frameTransform) {
if (this.frameTransform_) this.frameTransform_.destroy();
this.frameTransform_ = frameTransform;
console.log(
'[Pipeline] Updated frame transform.',
'debug.pipeline.frameTransform_ = ', this.frameTransform_);
if (this.processedStream_) {
await this.frameTransform_.init();
} else {
await this.maybeStartPipeline_();
}
}
/**
* Sets a new sink for the pipeline.
* @param {!MediaStreamSink} mediaStreamSink
*/
async updateSink(mediaStreamSink) {
if (this.sink_) this.sink_.destroy();
this.sink_ = mediaStreamSink;
console.log(
'[Pipeline] Updated sink.', 'debug.pipeline.sink_ = ', this.sink_);
if (this.processedStream_) {
await this.sink_.setMediaStream(this.processedStream_);
} else {
await this.maybeStartPipeline_();
}
}
/** Frees any resources used by this object. */
destroy() {
console.log('[Pipeline] Destroying Pipeline');
this.abortController_.abort();
if (this.source_) this.source_.destroy();
if (this.frameTransform_) this.frameTransform_.destroy();
if (this.sink_) this.sink_.destroy();
}
}<|fim▁end|> | * transform.
* @interface
*/
class MediaStreamSink { // eslint-disable-line no-unused-vars |
<|file_name|>test_hermite_e.py<|end_file_name|><|fim▁begin|>"""Tests for hermite_e module.
"""
from __future__ import division, absolute_import, print_function
import numpy as np
import numpy.polynomial.hermite_e as herme
from numpy.polynomial.polynomial import polyval
from numpy.testing import (
TestCase, assert_almost_equal, assert_raises,
assert_equal, assert_, run_module_suite)
He0 = np.array([1])
He1 = np.array([0, 1])
He2 = np.array([-1, 0, 1])
He3 = np.array([0, -3, 0, 1])
He4 = np.array([3, 0, -6, 0, 1])
He5 = np.array([0, 15, 0, -10, 0, 1])
He6 = np.array([-15, 0, 45, 0, -15, 0, 1])
He7 = np.array([0, -105, 0, 105, 0, -21, 0, 1])
He8 = np.array([105, 0, -420, 0, 210, 0, -28, 0, 1])
He9 = np.array([0, 945, 0, -1260, 0, 378, 0, -36, 0, 1])
Helist = [He0, He1, He2, He3, He4, He5, He6, He7, He8, He9]
def trim(x):
return herme.hermetrim(x, tol=1e-6)
class TestConstants(TestCase):
def test_hermedomain(self):
assert_equal(herme.hermedomain, [-1, 1])
def test_hermezero(self):
assert_equal(herme.hermezero, [0])
def test_hermeone(self):
assert_equal(herme.hermeone, [1])
def test_hermex(self):
assert_equal(herme.hermex, [0, 1])
class TestArithmetic(TestCase):
x = np.linspace(-3, 3, 100)
def test_hermeadd(self):
for i in range(5):
for j in range(5):
msg = "At i=%d, j=%d" % (i, j)
tgt = np.zeros(max(i, j) + 1)
tgt[i] += 1
tgt[j] += 1
res = herme.hermeadd([0] * i + [1], [0] * j + [1])
assert_equal(trim(res), trim(tgt), err_msg=msg)
def test_hermesub(self):
for i in range(5):
for j in range(5):
msg = "At i=%d, j=%d" % (i, j)
tgt = np.zeros(max(i, j) + 1)
tgt[i] += 1
tgt[j] -= 1
res = herme.hermesub([0] * i + [1], [0] * j + [1])
assert_equal(trim(res), trim(tgt), err_msg=msg)
def test_hermemulx(self):
assert_equal(herme.hermemulx([0]), [0])
assert_equal(herme.hermemulx([1]), [0, 1])
for i in range(1, 5):
ser = [0] * i + [1]
tgt = [0] * (i - 1) + [i, 0, 1]
assert_equal(herme.hermemulx(ser), tgt)
def test_hermemul(self):
# check values of result
for i in range(5):
pol1 = [0] * i + [1]
val1 = herme.hermeval(self.x, pol1)
for j in range(5):
msg = "At i=%d, j=%d" % (i, j)
pol2 = [0] * j + [1]
val2 = herme.hermeval(self.x, pol2)
pol3 = herme.hermemul(pol1, pol2)
val3 = herme.hermeval(self.x, pol3)
assert_(len(pol3) == i + j + 1, msg)
assert_almost_equal(val3, val1 * val2, err_msg=msg)
def test_hermediv(self):
for i in range(5):
for j in range(5):
msg = "At i=%d, j=%d" % (i, j)
ci = [0] * i + [1]
cj = [0] * j + [1]
tgt = herme.hermeadd(ci, cj)
quo, rem = herme.hermediv(tgt, ci)
res = herme.hermeadd(herme.hermemul(quo, ci), rem)
assert_equal(trim(res), trim(tgt), err_msg=msg)
class TestEvaluation(TestCase):
# coefficients of 1 + 2*x + 3*x**2
c1d = np.array([4., 2., 3.])
c2d = np.einsum('i,j->ij', c1d, c1d)
c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)
# some random values in [-1, 1)
x = np.random.random((3, 5)) * 2 - 1
y = polyval(x, [1., 2., 3.])
def test_hermeval(self):
# check empty input
assert_equal(herme.hermeval([], [1]).size, 0)
# check normal input)
x = np.linspace(-1, 1)
y = [polyval(x, c) for c in Helist]
for i in range(10):
msg = "At i=%d" % i
tgt = y[i]
res = herme.hermeval(x, [0] * i + [1])
assert_almost_equal(res, tgt, err_msg=msg)
# check that shape is preserved
for i in range(3):
dims = [2] * i
x = np.zeros(dims)
assert_equal(herme.hermeval(x, [1]).shape, dims)
assert_equal(herme.hermeval(x, [1, 0]).shape, dims)
assert_equal(herme.hermeval(x, [1, 0, 0]).shape, dims)
def test_hermeval2d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
# test exceptions
assert_raises(ValueError, herme.hermeval2d, x1, x2[:2], self.c2d)
# test values
tgt = y1 * y2
res = herme.hermeval2d(x1, x2, self.c2d)
assert_almost_equal(res, tgt)
# test shape
z = np.ones((2, 3))
res = herme.hermeval2d(z, z, self.c2d)
assert_(res.shape == (2, 3))
def test_hermeval3d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
# test exceptions
assert_raises(ValueError, herme.hermeval3d, x1, x2, x3[:2], self.c3d)
# test values
tgt = y1 * y2 * y3
res = herme.hermeval3d(x1, x2, x3, self.c3d)
assert_almost_equal(res, tgt)
# test shape
z = np.ones((2, 3))
res = herme.hermeval3d(z, z, z, self.c3d)
assert_(res.shape == (2, 3))
def test_hermegrid2d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
# test values
tgt = np.einsum('i,j->ij', y1, y2)
res = herme.hermegrid2d(x1, x2, self.c2d)
assert_almost_equal(res, tgt)
# test shape
z = np.ones((2, 3))
res = herme.hermegrid2d(z, z, self.c2d)
assert_(res.shape == (2, 3) * 2)
def test_hermegrid3d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
# test values
tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
res = herme.hermegrid3d(x1, x2, x3, self.c3d)
assert_almost_equal(res, tgt)
# test shape
z = np.ones((2, 3))
res = herme.hermegrid3d(z, z, z, self.c3d)
assert_(res.shape == (2, 3) * 3)
class TestIntegral(TestCase):
def test_hermeint(self):
# check exceptions
assert_raises(ValueError, herme.hermeint, [0], .5)
assert_raises(ValueError, herme.hermeint, [0], -1)
assert_raises(ValueError, herme.hermeint, [0], 1, [0, 0])
# test integration of zero polynomial
for i in range(2, 5):
k = [0] * (i - 2) + [1]
res = herme.hermeint([0], m=i, k=k)
assert_almost_equal(res, [0, 1])
# check single integration with integration constant
for i in range(5):
scl = i + 1
pol = [0] * i + [1]
tgt = [i] + [0] * i + [1 / scl]
hermepol = herme.poly2herme(pol)
hermeint = herme.hermeint(hermepol, m=1, k=[i])
res = herme.herme2poly(hermeint)
assert_almost_equal(trim(res), trim(tgt))
# check single integration with integration constant and lbnd
for i in range(5):
scl = i + 1
pol = [0] * i + [1]
hermepol = herme.poly2herme(pol)
hermeint = herme.hermeint(hermepol, m=1, k=[i], lbnd=-1)
assert_almost_equal(herme.hermeval(-1, hermeint), i)
# check single integration with integration constant and scaling
for i in range(5):
scl = i + 1
pol = [0] * i + [1]
tgt = [i] + [0] * i + [2 / scl]
hermepol = herme.poly2herme(pol)
hermeint = herme.hermeint(hermepol, m=1, k=[i], scl=2)
res = herme.herme2poly(hermeint)
assert_almost_equal(trim(res), trim(tgt))
# check multiple integrations with default k
for i in range(5):
for j in range(2, 5):
pol = [0] * i + [1]
tgt = pol[:]
for k in range(j):
tgt = herme.hermeint(tgt, m=1)
res = herme.hermeint(pol, m=j)
assert_almost_equal(trim(res), trim(tgt))
# check multiple integrations with defined k
for i in range(5):
for j in range(2, 5):
pol = [0] * i + [1]
tgt = pol[:]
for k in range(j):
tgt = herme.hermeint(tgt, m=1, k=[k])
res = herme.hermeint(pol, m=j, k=list(range(j)))
assert_almost_equal(trim(res), trim(tgt))
# check multiple integrations with lbnd
for i in range(5):
for j in range(2, 5):
pol = [0] * i + [1]
tgt = pol[:]
for k in range(j):
tgt = herme.hermeint(tgt, m=1, k=[k], lbnd=-1)
res = herme.hermeint(pol, m=j, k=list(range(j)), lbnd=-1)
assert_almost_equal(trim(res), trim(tgt))
# check multiple integrations with scaling
for i in range(5):
for j in range(2, 5):
pol = [0] * i + [1]
tgt = pol[:]
for k in range(j):
tgt = herme.hermeint(tgt, m=1, k=[k], scl=2)
res = herme.hermeint(pol, m=j, k=list(range(j)), scl=2)
assert_almost_equal(trim(res), trim(tgt))
def test_hermeint_axis(self):
# check that axis keyword works
c2d = np.random.random((3, 4))
tgt = np.vstack([herme.hermeint(c) for c in c2d.T]).T
res = herme.hermeint(c2d, axis=0)
assert_almost_equal(res, tgt)
tgt = np.vstack([herme.hermeint(c) for c in c2d])
res = herme.hermeint(c2d, axis=1)
assert_almost_equal(res, tgt)
tgt = np.vstack([herme.hermeint(c, k=3) for c in c2d])
res = herme.hermeint(c2d, k=3, axis=1)
assert_almost_equal(res, tgt)
class TestDerivative(TestCase):
def test_hermeder(self):
# check exceptions
assert_raises(ValueError, herme.hermeder, [0], .5)
assert_raises(ValueError, herme.hermeder, [0], -1)
# check that zeroth derivative does nothing
for i in range(5):
tgt = [0] * i + [1]
res = herme.hermeder(tgt, m=0)
assert_equal(trim(res), trim(tgt))
# check that derivation is the inverse of integration
for i in range(5):
for j in range(2, 5):
tgt = [0] * i + [1]
res = herme.hermeder(herme.hermeint(tgt, m=j), m=j)
assert_almost_equal(trim(res), trim(tgt))
# check derivation with scaling
for i in range(5):
for j in range(2, 5):
tgt = [0] * i + [1]
res = herme.hermeder(
herme.hermeint(tgt, m=j, scl=2), m=j, scl=.5)
assert_almost_equal(trim(res), trim(tgt))
def test_hermeder_axis(self):
# check that axis keyword works
c2d = np.random.random((3, 4))
tgt = np.vstack([herme.hermeder(c) for c in c2d.T]).T
res = herme.hermeder(c2d, axis=0)
assert_almost_equal(res, tgt)
tgt = np.vstack([herme.hermeder(c) for c in c2d])
res = herme.hermeder(c2d, axis=1)
assert_almost_equal(res, tgt)
class TestVander(TestCase):
# some random values in [-1, 1)
x = np.random.random((3, 5)) * 2 - 1
def test_hermevander(self):
# check for 1d x
x = np.arange(3)
v = herme.hermevander(x, 3)
assert_(v.shape == (3, 4))
for i in range(4):
coef = [0] * i + [1]
assert_almost_equal(v[..., i], herme.hermeval(x, coef))
# check for 2d x
x = np.array([[1, 2], [3, 4], [5, 6]])
v = herme.hermevander(x, 3)
assert_(v.shape == (3, 2, 4))
for i in range(4):
coef = [0] * i + [1]
assert_almost_equal(v[..., i], herme.hermeval(x, coef))
def test_hermevander2d(self):
# also tests hermeval2d for non-square coefficient array
x1, x2, x3 = self.x
c = np.random.random((2, 3))
van = herme.hermevander2d(x1, x2, [1, 2])
tgt = herme.hermeval2d(x1, x2, c)
res = np.dot(van, c.flat)
assert_almost_equal(res, tgt)
# check shape
van = herme.hermevander2d([x1], [x2], [1, 2])
assert_(van.shape == (1, 5, 6))
def test_hermevander3d(self):
# also tests hermeval3d for non-square coefficient array
x1, x2, x3 = self.x
c = np.random.random((2, 3, 4))
van = herme.hermevander3d(x1, x2, x3, [1, 2, 3])
tgt = herme.hermeval3d(x1, x2, x3, c)
res = np.dot(van, c.flat)
assert_almost_equal(res, tgt)
# check shape
van = herme.hermevander3d([x1], [x2], [x3], [1, 2, 3])
assert_(van.shape == (1, 5, 24))
class TestFitting(TestCase):
def test_hermefit(self):
def f(x):
return x * (x - 1) * (x - 2)
def f2(x):
return x ** 4 + x ** 2 + 1
# Test exceptions
assert_raises(ValueError, herme.hermefit, [1], [1], -1)
assert_raises(TypeError, herme.hermefit, [[1]], [1], 0)
assert_raises(TypeError, herme.hermefit, [], [1], 0)
assert_raises(TypeError, herme.hermefit, [1], [[[1]]], 0)
assert_raises(TypeError, herme.hermefit, [1, 2], [1], 0)
assert_raises(TypeError, herme.hermefit, [1], [1, 2], 0)
assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[[1]])
assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[1, 1])
assert_raises(ValueError, herme.hermefit, [1], [1], [-1, ])
assert_raises(ValueError, herme.hermefit, [1], [1], [2, -1, 6])
assert_raises(TypeError, herme.hermefit, [1], [1], [])
# Test fit
x = np.linspace(0, 2)
y = f(x)
#
coef3 = herme.hermefit(x, y, 3)
assert_equal(len(coef3), 4)
assert_almost_equal(herme.hermeval(x, coef3), y)
coef3 = herme.hermefit(x, y, [0, 1, 2, 3])
assert_equal(len(coef3), 4)
assert_almost_equal(herme.hermeval(x, coef3), y)
#
coef4 = herme.hermefit(x, y, 4)
assert_equal(len(coef4), 5)
assert_almost_equal(herme.hermeval(x, coef4), y)
coef4 = herme.hermefit(x, y, [0, 1, 2, 3, 4])
assert_equal(len(coef4), 5)
assert_almost_equal(herme.hermeval(x, coef4), y)
# check things still work if deg is not in strict increasing
coef4 = herme.hermefit(x, y, [2, 3, 4, 1, 0])
assert_equal(len(coef4), 5)
assert_almost_equal(herme.hermeval(x, coef4), y)
#
coef2d = herme.hermefit(x, np.array([y, y]).T, 3)
assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
coef2d = herme.hermefit(x, np.array([y, y]).T, [0, 1, 2, 3])
assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
# test weighting
w = np.zeros_like(x)
yw = y.copy()
w[1::2] = 1
y[0::2] = 0
wcoef3 = herme.hermefit(x, yw, 3, w=w)
assert_almost_equal(wcoef3, coef3)
wcoef3 = herme.hermefit(x, yw, [0, 1, 2, 3], w=w)
assert_almost_equal(wcoef3, coef3)
#
wcoef2d = herme.hermefit(x, np.array([yw, yw]).T, 3, w=w)
assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
wcoef2d = herme.hermefit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)
assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
# test scaling with complex values x points whose square
# is zero when summed.
x = [1, 1j, -1, -1j]
assert_almost_equal(herme.hermefit(x, x, 1), [0, 1])
assert_almost_equal(herme.hermefit(x, x, [0, 1]), [0, 1])
# test fitting only even Legendre polynomials
x = np.linspace(-1, 1)
y = f2(x)
coef1 = herme.hermefit(x, y, 4)
assert_almost_equal(herme.hermeval(x, coef1), y)
coef2 = herme.hermefit(x, y, [0, 2, 4])
assert_almost_equal(herme.hermeval(x, coef2), y)
assert_almost_equal(coef1, coef2)
class TestCompanion(TestCase):
def test_raises(self):
assert_raises(ValueError, herme.hermecompanion, [])
assert_raises(ValueError, herme.hermecompanion, [1])
def test_dimensions(self):
for i in range(1, 5):
coef = [0] * i + [1]
assert_(herme.hermecompanion(coef).shape == (i, i))
def test_linear_root(self):
assert_(herme.hermecompanion([1, 2])[0, 0] == -.5)
class TestGauss(TestCase):
def test_100(self):
x, w = herme.hermegauss(100)
# test orthogonality. Note that the results need to be normalized,
# otherwise the huge values that can arise from fast growing
# functions like Laguerre can be very confusing.
v = herme.hermevander(x, 99)
vv = np.dot(v.T * w, v)
vd = 1 / np.sqrt(vv.diagonal())
vv = vd[:, None] * vv * vd
assert_almost_equal(vv, np.eye(100))
# check that the integral of 1 is correct
tgt = np.sqrt(2 * np.pi)
assert_almost_equal(w.sum(), tgt)
<|fim▁hole|> assert_almost_equal(trim(res), [1])
for i in range(1, 5):
roots = np.cos(np.linspace(-np.pi, 0, 2 * i + 1)[1::2])
pol = herme.hermefromroots(roots)
res = herme.hermeval(roots, pol)
tgt = 0
assert_(len(pol) == i + 1)
assert_almost_equal(herme.herme2poly(pol)[-1], 1)
assert_almost_equal(res, tgt)
def test_hermeroots(self):
assert_almost_equal(herme.hermeroots([1]), [])
assert_almost_equal(herme.hermeroots([1, 1]), [-1])
for i in range(2, 5):
tgt = np.linspace(-1, 1, i)
res = herme.hermeroots(herme.hermefromroots(tgt))
assert_almost_equal(trim(res), trim(tgt))
def test_hermetrim(self):
coef = [2, -1, 1, 0]
# Test exceptions
assert_raises(ValueError, herme.hermetrim, coef, -1)
# Test results
assert_equal(herme.hermetrim(coef), coef[:-1])
assert_equal(herme.hermetrim(coef, 1), coef[:-3])
assert_equal(herme.hermetrim(coef, 2), [0])
def test_hermeline(self):
assert_equal(herme.hermeline(3, 4), [3, 4])
def test_herme2poly(self):
for i in range(10):
assert_almost_equal(herme.herme2poly([0] * i + [1]), Helist[i])
def test_poly2herme(self):
for i in range(10):
assert_almost_equal(herme.poly2herme(Helist[i]), [0] * i + [1])
def test_weight(self):
x = np.linspace(-5, 5, 11)
tgt = np.exp(-.5 * x ** 2)
res = herme.hermeweight(x)
assert_almost_equal(res, tgt)
if __name__ == "__main__":
run_module_suite()<|fim▁end|> | class TestMisc(TestCase):
def test_hermefromroots(self):
res = herme.hermefromroots([]) |
<|file_name|>run_list_handling.py<|end_file_name|><|fim▁begin|>from sqlalchemy import and_
from DBtransfer import *
from zlib import *
#retrun compressed
def generateFromDB(DBSession, InternData, tmp_name) :
run_list=[]
user_data = DBSession.query(InternData).filter(InternData.timestamp == tmp_name)
for data in user_data :
if not data.run in run_list :
run_list.append(data.run)
return compressList(run_list)
def getknown_runsAndrun_list(DBSession, Mass_specData, InternData, tmp_name) : #CR: rename to splitKnownAndTodo
#~ knownRuns = [] # devide runs from upload into known runs (in DB) ...
#~ runList = [] #...and the usual run_list, to get data from these runs
#CR:
runs_in_upload = decompressList(generateFromDB(DBSession, InternData, tmp_name))
#~ known_runs = [x for x in DBSession.query(Mass_specData.filename).all() if x in runs_in_upload]
known_runs = [x.filename for x in DBSession.query(Mass_specData).filter(Mass_specData.filename.in_(runs_in_upload))]
run_list = [x for x in runs_in_upload if x not in known_runs]
#~ allRuns = getAllRuns_Filename(DBSession, Mass_specData)# in DB saved runs
#~ decomruns_in_upload = decompressList(runs_in_upload)
#~ for run in decomruns_in_upload :
#~ if run in allRuns :
#~ knownRuns.append(run)
#~ else :
#~ runList.append(run)
return (known_runs, run_list)
#input compressed
#output not compressed
def usedRuns(run_list, params) :
list_of_used_runs = []
runs = decompressList(run_list)
for i in range(0, len(runs)) :
if runs[i] in params :
list_of_used_runs.append(runs[i])
return list_of_used_runs
# input not compressed
# output InternData objects
def rowsToFill(DBSession, InternData, tmp_name, used_runs) :
users_rows = getUserRows(DBSession, InternData, tmp_name)
rows = []
for row in users_rows :
if row.run in used_runs :
rows.append(row)
return rows
#input compressed, not compressed
def throughOutUsedRuns(run_list, used_runs) : # not compressed
rl = decompressList(run_list)
for run in used_runs :
rl.pop(rl.index(run))<|fim▁hole|> return []
#
def compressList(list) :
return compress('$$'.join(list))
#input compressed
def decompressList(run_list) :
return decompress(run_list).split('$$')<|fim▁end|> | if len(rl) > 0 :
return compressList(rl)
else : |
<|file_name|>initials.py<|end_file_name|><|fim▁begin|><|fim▁hole|>def get_initials(fullname):
fullname = fullname.split(' ')
initials = ''
# accumulator pattern
for eachName in fullname:
initials = initials + eachName[0].upper()
return initials
def main():
inputName = input("What is your full name?\n")
print(get_initials(inputName))
if __name__ == '__main__':
main()
# test stub
## uncomment to validate code
#from testEqual import testEqual
### test: "First Last"
#testEqual.testEqual(get_initials("Ozzie Smith"), "OS")
### test: "first last"
#testEqual.testEqual(get_initials("bonnie blair"), "BB")
### test: "First Middle Last"
#testEqual.testEqual(get_initials("Daniel Day Lewis"), "DDL")<|fim▁end|> | #### initials.py ####
#
# Given a person's name, return the person's initials (uppercase)
# |
<|file_name|>util_tests.py<|end_file_name|><|fim▁begin|>import tempfile
from git import InvalidGitRepositoryError
try:
from unittest2 import TestCase
from mock import patch, Mock
except ImportError:
from unittest import TestCase
from mock import patch, Mock
import textwrap
from datetime import datetime
from botocore.exceptions import ClientError
from dateutil.tz import tzutc
from cfn_sphere import util, CloudFormationStack
from cfn_sphere.exceptions import CfnSphereException, CfnSphereBotoError
from cfn_sphere.template import CloudFormationTemplate
class UtilTests(TestCase):
def test_convert_yaml_to_json_string_returns_valid_json_string(self):
data = textwrap.dedent("""
foo:
foo: baa
""")
self.assertEqual('{\n "foo": {\n "foo": "baa"\n }\n}', util.convert_yaml_to_json_string(data))
def test_convert_yaml_to_json_string_returns_valid_json_string_on_empty_string_input(self):
data = ""
self.assertEqual('{}', util.convert_yaml_to_json_string(data))
def test_convert_json_to_yaml_string_returns_valid_yaml_string(self):
data = textwrap.dedent("""
{
"foo": {
"foo": "baa"
}
}
""")
self.assertEqual('foo:\n foo: baa\n', util.convert_json_to_yaml_string(data))
def test_convert_json_to_yaml_string_returns_empty_string_on_empty_json_input(self):
data = {}
self.assertEqual('', util.convert_json_to_yaml_string(data))
@patch("cfn_sphere.util.urllib2.urlopen")
def test_get_cfn_api_server_time_returns_gmt_datetime(self, urlopen_mock):
urlopen_mock.return_value.info.return_value.get.return_value = "Mon, 21 Sep 2015 17:17:26 GMT"
expected_timestamp = datetime(year=2015, month=9, day=21, hour=17, minute=17, second=26, tzinfo=tzutc())
self.assertEqual(expected_timestamp, util.get_cfn_api_server_time())
@patch("cfn_sphere.util.urllib2.urlopen")
def test_get_cfn_api_server_time_raises_exception_on_empty_date_header(self, urlopen_mock):
urlopen_mock.return_value.info.return_value.get.return_value = ""
with self.assertRaises(CfnSphereException):
util.get_cfn_api_server_time()
def test_with_boto_retry_retries_method_call_for_throttling_exception(self):
count_func = Mock()
@util.with_boto_retry(max_retries=1, pause_time_multiplier=1)
def my_retried_method(count_func):
count_func()
exception = CfnSphereBotoError(
ClientError(error_response={"Error": {"Code": "Throttling", "Message": "Rate exceeded"}},
operation_name="DescribeStacks"))
raise exception
with self.assertRaises(CfnSphereBotoError):
my_retried_method(count_func)
self.assertEqual(2, count_func.call_count)
def test_with_boto_retry_does_not_retry_for_simple_exception(self):
count_func = Mock()
@util.with_boto_retry(max_retries=1, pause_time_multiplier=1)
def my_retried_method(count_func):
count_func()
raise Exception
with self.assertRaises(Exception):
my_retried_method(count_func)
self.assertEqual(1, count_func.call_count)
def test_with_boto_retry_does_not_retry_for_another_boto_client_error(self):
count_func = Mock()
@util.with_boto_retry(max_retries=1, pause_time_multiplier=1)
def my_retried_method(count_func):
count_func()
exception = ClientError(error_response={"Error": {"Code": "Another Error", "Message": "Foo"}},
operation_name="DescribeStacks")
raise exception
with self.assertRaises(ClientError):
my_retried_method(count_func)
self.assertEqual(1, count_func.call_count)
def test_with_boto_retry_does_not_retry_without_exception(self):
count_func = Mock()
@util.with_boto_retry(max_retries=1, pause_time_multiplier=1)
def my_retried_method(count_func):
count_func()
return "foo"
self.assertEqual("foo", my_retried_method(count_func))
self.assertEqual(1, count_func.call_count)
def test_get_pretty_parameters_string(self):
template_body = {
'Parameters': {
'myParameter1': {
'Type': 'String',
'NoEcho': True
},
'myParameter2': {
'Type': 'String'
},
'myParameter3': {
'Type': 'Number',
'NoEcho': 'true'
},
'myParameter4': {
'Type': 'Number',
'NoEcho': 'false'
},
'myParameter5': {
'Type': 'Number',
'NoEcho': False
}
}
}
parameters = {
'myParameter1': 'super-secret',
'myParameter2': 'not-that-secret',
'myParameter3': 'also-super-secret',
'myParameter4': 'could-be-public',
'myParameter5': 'also-ok'
}
template = CloudFormationTemplate(template_body, 'just-another-template')
stack = CloudFormationStack(template, parameters, 'just-another-stack', 'eu-west-1')
expected_string = """+--------------+-----------------+
| Parameter | Value |
+--------------+-----------------+
| myParameter1 | *** |
| myParameter2 | not-that-secret |
| myParameter3 | *** |
| myParameter4 | could-be-public |
| myParameter5 | also-ok |
+--------------+-----------------+"""
self.assertEqual(expected_string, util.get_pretty_parameters_string(stack))
def test_get_pretty_stack_outputs_returns_proper_table(self):
outputs = [
{
'OutputKey': 'key1',
'OutputValue': 'value1',
'Description': 'desc1'
}, {
'OutputKey': 'key2',
'OutputValue': 'value2',
'Description': 'desc2'
}, {
'OutputKey': 'key3',
'OutputValue': 'value3',
'Description': 'desc3'
}
]
expected = """+--------+--------+
| Output | Value |
+--------+--------+
| key1 | value1 |
| key2 | value2 |
| key3 | value3 |
+--------+--------+"""
result = util.get_pretty_stack_outputs(outputs)
self.assertEqual(expected, result)
def test_strip_string_strips_string(self):
s = "sfsdklgashgslkadghkafhgaknkbndkjfbnwurtqwhgsdnkshGLSAKGKLDJFHGSKDLGFLDFGKSDFLGKHAsdjdghskjdhsdcxbvwerA323"
result = util.strip_string(s)
self.assertEqual(
"sfsdklgashgslkadghkafhgaknkbndkjfbnwurtqwhgsdnkshGLSAKGKLDJFHGSKDLGFLDFGKSDFLGKHAsdjdghskjdhsdcxbvwe...",
result)
<|fim▁hole|> self.assertEqual("my-short-string...", result)
@patch("cfn_sphere.util.Repo")
def test_get_git_repository_remote_url_returns_none_if_no_repository_present(self, repo_mock):
repo_mock.side_effect = InvalidGitRepositoryError
self.assertEqual(None, util.get_git_repository_remote_url(tempfile.mkdtemp()))
@patch("cfn_sphere.util.Repo")
def test_get_git_repository_remote_url_returns_repo_url(self, repo_mock):
url = "http://config.repo.git"
repo_mock.return_value.remotes.origin.url = url
self.assertEqual(url, util.get_git_repository_remote_url(tempfile.mkdtemp()))
@patch("cfn_sphere.util.Repo")
def test_get_git_repository_remote_url_returns_repo_url_from_parent_dir(self, repo_mock):
url = "http://config.repo.git"
repo_object_mock = Mock()
repo_object_mock.remotes.origin.url = url
repo_mock.side_effect = [InvalidGitRepositoryError, repo_object_mock]
self.assertEqual(url, util.get_git_repository_remote_url(tempfile.mkdtemp()))
def test_get_git_repository_remote_url_returns_none_for_none_working_dir(self):
self.assertEqual(None, util.get_git_repository_remote_url(None))
def test_get_git_repository_remote_url_returns_none_for_empty_string_working_dir(self):
self.assertEqual(None, util.get_git_repository_remote_url(""))
def test_kv_list_to_dict_returns_empty_dict_for_empty_list(self):
result = util.kv_list_to_dict([])
self.assertEqual({}, result)
def test_kv_list_to_dict(self):
result = util.kv_list_to_dict(["k1=v1", "k2=v2"])
self.assertEqual({"k1": "v1", "k2": "v2"}, result)
def test_kv_list_to_dict_raises_exception_on_syntax_error(self):
with self.assertRaises(CfnSphereException):
util.kv_list_to_dict(["k1=v1", "k2:v2"])<|fim▁end|> | def test_strip_string_doesnt_strip_short_strings(self):
s = "my-short-string"
result = util.strip_string(s) |
<|file_name|>vtEngine.py<|end_file_name|><|fim▁begin|># encoding: UTF-8
from eventEngine import *
from ctpGateway import CtpGateway
########################################################################
class MainEngine(object):
"""主引擎"""
#----------------------------------------------------------------------<|fim▁hole|> """Constructor"""
# 创建事件引擎
self.eventEngine = EventEngine()
self.eventEngine.start()
# 用来保存接口对象的字典
self.gatewayDict = {}
# 创建我们想要接入的接口对象
self.addGateway(CtpGateway, 'CTP')
#----------------------------------------------------------------------
def addGateway(self, gateway, gatewayName=None):
"""创建接口"""
self.gatewayDict[gatewayName] = gateway(self.eventEngine, gatewayName)
#----------------------------------------------------------------------
def connect(self, gatewayName):
"""连接特定名称的接口"""
gateway = self.gatewayDict[gatewayName]
gateway.connect()
#----------------------------------------------------------------------
def subscribe(self, subscribeReq, gatewayName):
"""订阅特定接口的行情"""
gateway = self.gatewayDict[gatewayName]
gateway.subscribe(subscribeReq)
#----------------------------------------------------------------------
def sendOrder(self, orderReq, gatewayName):
"""对特定接口发单"""
gateway = self.gatewayDict[gatewayName]
return gateway.sendOrder(orderReq)
#----------------------------------------------------------------------
def cancelOrder(self, cancelOrderReq, gatewayName):
"""对特定接口撤单"""
gateway = self.gatewayDict[gatewayName]
gateway.cancelOrder(cancelOrderReq)
#----------------------------------------------------------------------
def getAccont(self, gatewayName):
"""查询特定接口的账户"""
gateway = self.gatewayDict[gatewayName]
gateway.getAccount()
#----------------------------------------------------------------------
def getPosition(self, gatewayName):
"""查询特定接口的持仓"""
gateway = self.gatewayDict[gatewayName]
gateway.getPosition()
#----------------------------------------------------------------------
def exit(self):
"""退出程序前调用,保证正常退出"""
# 停止事件引擎
self.eventEngine.stop()
# 安全关闭所有接口
for gateway in self.gatewayDict.values():
gateway.close()<|fim▁end|> | def __init__(self): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.