prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>types.py<|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.
from typing import Optional
from typing import Callable
from typing import Union
from typing import cast
from enum import Enum
if False:
# Work around for MYPY for cyclic import problem
from libcloud.compute.base import BaseDriver
__all__ = [
"Type",
"LibcloudError",
"MalformedResponseError",
"ProviderError",
"InvalidCredsError",
"InvalidCredsException",<|fim▁hole|>class Type(str, Enum):
@classmethod
def tostring(cls, value):
# type: (Union[Enum, str]) -> str
"""Return the string representation of the state object attribute
:param str value: the state object to turn into string
:return: the uppercase string that represents the state object
:rtype: str
"""
value = cast(Enum, value)
return str(value._value_).upper()
@classmethod
def fromstring(cls, value):
# type: (str) -> str
"""Return the state object attribute that matches the string
:param str value: the string to look up
:return: the state object attribute that matches the string
:rtype: str
"""
return getattr(cls, value.upper(), None)
"""
NOTE: These methods are here for backward compatibility reasons where
Type values were simple strings and Type didn't inherit from Enum.
"""
def __eq__(self, other):
if isinstance(other, Type):
return other.value == self.value
elif isinstance(other, str):
return self.value == other
return super(Type, self).__eq__(other)
def upper(self):
return self.value.upper() # pylint: disable=no-member
def lower(self):
return self.value.lower() # pylint: disable=no-member
def __ne__(self, other):
return not self.__eq__(other)
def __str__(self):
return str(self.value)
def __repr__(self):
return self.value
def __hash__(self):
return id(self)
class LibcloudError(Exception):
"""The base class for other libcloud exceptions"""
def __init__(self, value, driver=None):
# type: (str, BaseDriver) -> None
super(LibcloudError, self).__init__(value)
self.value = value
self.driver = driver
def __str__(self):
return self.__repr__()
def __repr__(self):
return ("<LibcloudError in " +
repr(self.driver) +
" " +
repr(self.value) + ">")
class MalformedResponseError(LibcloudError):
"""Exception for the cases when a provider returns a malformed
response, e.g. you request JSON and provider returns
'<h3>something</h3>' due to some error on their side."""
def __init__(self, value, body=None, driver=None):
# type: (str, Optional[str], Optional[BaseDriver]) -> None
self.value = value
self.driver = driver
self.body = body
def __str__(self):
return self.__repr__()
def __repr__(self):
return ("<MalformedResponseException in " +
repr(self.driver) +
" " +
repr(self.value) +
">: " +
repr(self.body))
class ProviderError(LibcloudError):
"""
Exception used when provider gives back
error response (HTTP 4xx, 5xx) for a request.
Specific sub types can be derived for errors like
HTTP 401 : InvalidCredsError
HTTP 404 : NodeNotFoundError, ContainerDoesNotExistError
"""
def __init__(self, value, http_code, driver=None):
# type: (str, int, Optional[BaseDriver]) -> None
super(ProviderError, self).__init__(value=value, driver=driver)
self.http_code = http_code
def __str__(self):
return self.__repr__()
def __repr__(self):
return repr(self.value)
class InvalidCredsError(ProviderError):
"""Exception used when invalid credentials are used on a provider."""
def __init__(self, value='Invalid credentials with the provider',
driver=None):
# type: (str, Optional[BaseDriver]) -> None
# NOTE: We don't use http.client constants here since that adds ~20ms
# import time overhead
super(InvalidCredsError, self).__init__(value,
http_code=401,
driver=driver)
# Deprecated alias of :class:`InvalidCredsError`
InvalidCredsException = InvalidCredsError
class ServiceUnavailableError(ProviderError):
"""Exception used when a provider returns 503 Service Unavailable."""
def __init__(self, value='Service unavailable at provider', driver=None):
# type: (str, Optional[BaseDriver]) -> None
# NOTE: We don't use http.client constants here since that adds ~20ms
# import time overhead
super(ServiceUnavailableError, self).__init__(
value,
http_code=503,
driver=driver
)
class LazyList(object):
def __init__(self, get_more, value_dict=None):
# type: (Callable, Optional[dict]) -> None
self._data = [] # type: list
self._last_key = None
self._exhausted = False
self._all_loaded = False
self._get_more = get_more
self._value_dict = value_dict or {}
def __iter__(self):
if not self._all_loaded:
self._load_all()
data = self._data
for i in data:
yield i
def __getitem__(self, index):
if index >= len(self._data) and not self._all_loaded:
self._load_all()
return self._data[index]
def __len__(self):
self._load_all()
return len(self._data)
def __repr__(self):
self._load_all()
repr_string = ', ' .join([repr(item) for item in self._data])
repr_string = '[%s]' % (repr_string)
return repr_string
def _load_all(self):
while not self._exhausted:
newdata, self._last_key, self._exhausted = \
self._get_more(last_key=self._last_key,
value_dict=self._value_dict)
self._data.extend(newdata)
self._all_loaded = True<|fim▁end|>
|
"LazyList"
]
|
<|file_name|>transform.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/. */
//! Specified types for CSS values that are related to transformations.
use crate::parser::{Parse, ParserContext};
use crate::values::computed::{Context, LengthPercentage as ComputedLengthPercentage};
use crate::values::computed::{Percentage as ComputedPercentage, ToComputedValue};
use crate::values::generics::transform as generic;
use crate::values::generics::transform::{Matrix, Matrix3D};
use crate::values::specified::position::{Side, X, Y};
use crate::values::specified::{self, Angle, Integer, Length, LengthPercentage, Number};
use crate::Zero;
use cssparser::Parser;
use style_traits::{ParseError, StyleParseErrorKind};
pub use crate::values::generics::transform::TransformStyle;
/// A single operation in a specified CSS `transform`
pub type TransformOperation =
generic::TransformOperation<Angle, Number, Length, Integer, LengthPercentage>;
/// A specified CSS `transform`
pub type Transform = generic::Transform<TransformOperation>;
/// The specified value of a CSS `<transform-origin>`
pub type TransformOrigin = generic::TransformOrigin<OriginComponent<X>, OriginComponent<Y>, Length>;
impl Transform {
/// Internal parse function for deciding if we wish to accept prefixed values or not
///
/// `transform` allows unitless zero angles as an exception, see:
/// https://github.com/w3c/csswg-drafts/issues/1162
fn parse_internal<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
use style_traits::{Separator, Space};
if input
.try(|input| input.expect_ident_matching("none"))
.is_ok()
{
return Ok(generic::Transform(Vec::new()));
}
Ok(generic::Transform(Space::parse(input, |input| {
let function = input.expect_function()?.clone();
input.parse_nested_block(|input| {
let location = input.current_source_location();
let result = match_ignore_ascii_case! { &function,
"matrix" => {
let a = Number::parse(context, input)?;
input.expect_comma()?;
let b = Number::parse(context, input)?;
input.expect_comma()?;
let c = Number::parse(context, input)?;
input.expect_comma()?;
let d = Number::parse(context, input)?;
input.expect_comma()?;
// Standard matrix parsing.
let e = Number::parse(context, input)?;
input.expect_comma()?;
let f = Number::parse(context, input)?;
Ok(generic::TransformOperation::Matrix(Matrix { a, b, c, d, e, f }))
},
"matrix3d" => {
let m11 = Number::parse(context, input)?;
input.expect_comma()?;
let m12 = Number::parse(context, input)?;
input.expect_comma()?;
let m13 = Number::parse(context, input)?;
input.expect_comma()?;
let m14 = Number::parse(context, input)?;
input.expect_comma()?;
let m21 = Number::parse(context, input)?;
input.expect_comma()?;
let m22 = Number::parse(context, input)?;
input.expect_comma()?;
let m23 = Number::parse(context, input)?;
input.expect_comma()?;
let m24 = Number::parse(context, input)?;
input.expect_comma()?;
let m31 = Number::parse(context, input)?;
input.expect_comma()?;
let m32 = Number::parse(context, input)?;
input.expect_comma()?;
let m33 = Number::parse(context, input)?;
input.expect_comma()?;
let m34 = Number::parse(context, input)?;
input.expect_comma()?;
// Standard matrix3d parsing.
let m41 = Number::parse(context, input)?;
input.expect_comma()?;
let m42 = Number::parse(context, input)?;
input.expect_comma()?;
let m43 = Number::parse(context, input)?;
input.expect_comma()?;
let m44 = Number::parse(context, input)?;
Ok(generic::TransformOperation::Matrix3D(Matrix3D {
m11, m12, m13, m14,
m21, m22, m23, m24,
m31, m32, m33, m34,
m41, m42, m43, m44,
}))
},
"translate" => {
let sx = specified::LengthPercentage::parse(context, input)?;
if input.try(|input| input.expect_comma()).is_ok() {
let sy = specified::LengthPercentage::parse(context, input)?;
Ok(generic::TransformOperation::Translate(sx, sy))
} else {
Ok(generic::TransformOperation::Translate(sx, Zero::zero()))
}
},
"translatex" => {
let tx = specified::LengthPercentage::parse(context, input)?;
Ok(generic::TransformOperation::TranslateX(tx))
},
"translatey" => {
let ty = specified::LengthPercentage::parse(context, input)?;
Ok(generic::TransformOperation::TranslateY(ty))
},
"translatez" => {
let tz = specified::Length::parse(context, input)?;
Ok(generic::TransformOperation::TranslateZ(tz))
},
"translate3d" => {
let tx = specified::LengthPercentage::parse(context, input)?;
input.expect_comma()?;
let ty = specified::LengthPercentage::parse(context, input)?;
input.expect_comma()?;
let tz = specified::Length::parse(context, input)?;
Ok(generic::TransformOperation::Translate3D(tx, ty, tz))
},
"scale" => {
let sx = Number::parse(context, input)?;
if input.try(|input| input.expect_comma()).is_ok() {
let sy = Number::parse(context, input)?;
Ok(generic::TransformOperation::Scale(sx, sy))
} else {
Ok(generic::TransformOperation::Scale(sx, sx))
}
},
"scalex" => {
let sx = Number::parse(context, input)?;
Ok(generic::TransformOperation::ScaleX(sx))
},
"scaley" => {
let sy = Number::parse(context, input)?;<|fim▁hole|> Ok(generic::TransformOperation::ScaleY(sy))
},
"scalez" => {
let sz = Number::parse(context, input)?;
Ok(generic::TransformOperation::ScaleZ(sz))
},
"scale3d" => {
let sx = Number::parse(context, input)?;
input.expect_comma()?;
let sy = Number::parse(context, input)?;
input.expect_comma()?;
let sz = Number::parse(context, input)?;
Ok(generic::TransformOperation::Scale3D(sx, sy, sz))
},
"rotate" => {
let theta = specified::Angle::parse_with_unitless(context, input)?;
Ok(generic::TransformOperation::Rotate(theta))
},
"rotatex" => {
let theta = specified::Angle::parse_with_unitless(context, input)?;
Ok(generic::TransformOperation::RotateX(theta))
},
"rotatey" => {
let theta = specified::Angle::parse_with_unitless(context, input)?;
Ok(generic::TransformOperation::RotateY(theta))
},
"rotatez" => {
let theta = specified::Angle::parse_with_unitless(context, input)?;
Ok(generic::TransformOperation::RotateZ(theta))
},
"rotate3d" => {
let ax = Number::parse(context, input)?;
input.expect_comma()?;
let ay = Number::parse(context, input)?;
input.expect_comma()?;
let az = Number::parse(context, input)?;
input.expect_comma()?;
let theta = specified::Angle::parse_with_unitless(context, input)?;
// TODO(gw): Check that the axis can be normalized.
Ok(generic::TransformOperation::Rotate3D(ax, ay, az, theta))
},
"skew" => {
let ax = specified::Angle::parse_with_unitless(context, input)?;
if input.try(|input| input.expect_comma()).is_ok() {
let ay = specified::Angle::parse_with_unitless(context, input)?;
Ok(generic::TransformOperation::Skew(ax, ay))
} else {
Ok(generic::TransformOperation::Skew(ax, Zero::zero()))
}
},
"skewx" => {
let theta = specified::Angle::parse_with_unitless(context, input)?;
Ok(generic::TransformOperation::SkewX(theta))
},
"skewy" => {
let theta = specified::Angle::parse_with_unitless(context, input)?;
Ok(generic::TransformOperation::SkewY(theta))
},
"perspective" => {
let d = specified::Length::parse_non_negative(context, input)?;
Ok(generic::TransformOperation::Perspective(d))
},
_ => Err(()),
};
result.map_err(|()| {
location
.new_custom_error(StyleParseErrorKind::UnexpectedFunction(function.clone()))
})
})
})?))
}
}
impl Parse for Transform {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Transform::parse_internal(context, input)
}
}
/// The specified value of a component of a CSS `<transform-origin>`.
#[derive(Clone, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss)]
pub enum OriginComponent<S> {
/// `center`
Center,
/// `<length-percentage>`
Length(LengthPercentage),
/// `<side>`
Side(S),
}
impl Parse for TransformOrigin {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
let parse_depth = |input: &mut Parser| {
input
.try(|i| Length::parse(context, i))
.unwrap_or(Length::from_px(0.))
};
match input.try(|i| OriginComponent::parse(context, i)) {
Ok(x_origin @ OriginComponent::Center) => {
if let Ok(y_origin) = input.try(|i| OriginComponent::parse(context, i)) {
let depth = parse_depth(input);
return Ok(Self::new(x_origin, y_origin, depth));
}
let y_origin = OriginComponent::Center;
if let Ok(x_keyword) = input.try(X::parse) {
let x_origin = OriginComponent::Side(x_keyword);
let depth = parse_depth(input);
return Ok(Self::new(x_origin, y_origin, depth));
}
let depth = Length::from_px(0.);
return Ok(Self::new(x_origin, y_origin, depth));
},
Ok(x_origin) => {
if let Ok(y_origin) = input.try(|i| OriginComponent::parse(context, i)) {
let depth = parse_depth(input);
return Ok(Self::new(x_origin, y_origin, depth));
}
let y_origin = OriginComponent::Center;
let depth = Length::from_px(0.);
return Ok(Self::new(x_origin, y_origin, depth));
},
Err(_) => {},
}
let y_keyword = Y::parse(input)?;
let y_origin = OriginComponent::Side(y_keyword);
if let Ok(x_keyword) = input.try(X::parse) {
let x_origin = OriginComponent::Side(x_keyword);
let depth = parse_depth(input);
return Ok(Self::new(x_origin, y_origin, depth));
}
if input.try(|i| i.expect_ident_matching("center")).is_ok() {
let x_origin = OriginComponent::Center;
let depth = parse_depth(input);
return Ok(Self::new(x_origin, y_origin, depth));
}
let x_origin = OriginComponent::Center;
let depth = Length::from_px(0.);
Ok(Self::new(x_origin, y_origin, depth))
}
}
impl<S> ToComputedValue for OriginComponent<S>
where
S: Side,
{
type ComputedValue = ComputedLengthPercentage;
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
match *self {
OriginComponent::Center => {
ComputedLengthPercentage::new_percent(ComputedPercentage(0.5))
},
OriginComponent::Length(ref length) => length.to_computed_value(context),
OriginComponent::Side(ref keyword) => {
let p = ComputedPercentage(if keyword.is_start() { 0. } else { 1. });
ComputedLengthPercentage::new_percent(p)
},
}
}
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
OriginComponent::Length(ToComputedValue::from_computed_value(computed))
}
}
impl<S> OriginComponent<S> {
/// `0%`
pub fn zero() -> Self {
OriginComponent::Length(LengthPercentage::Percentage(ComputedPercentage::zero()))
}
}
/// A specified CSS `rotate`
pub type Rotate = generic::Rotate<Number, Angle>;
impl Parse for Rotate {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
if input.try(|i| i.expect_ident_matching("none")).is_ok() {
return Ok(generic::Rotate::None);
}
// Parse <angle> or [ x | y | z | <number>{3} ] && <angle>.
//
// The rotate axis and angle could be in any order, so we parse angle twice to cover
// two cases. i.e. `<number>{3} <angle>` or `<angle> <number>{3}`
let angle = input.try(|i| specified::Angle::parse(context, i)).ok();
let axis = input
.try(|i| {
Ok(try_match_ident_ignore_ascii_case! { i,
"x" => (Number::new(1.), Number::new(0.), Number::new(0.)),
"y" => (Number::new(0.), Number::new(1.), Number::new(0.)),
"z" => (Number::new(0.), Number::new(0.), Number::new(1.)),
})
})
.or_else(|_: ParseError| -> Result<_, ParseError> {
input.try(|i| {
Ok((
Number::parse(context, i)?,
Number::parse(context, i)?,
Number::parse(context, i)?,
))
})
})
.ok();
let angle = match angle {
Some(a) => a,
None => specified::Angle::parse(context, input)?,
};
Ok(match axis {
Some((x, y, z)) => generic::Rotate::Rotate3D(x, y, z, angle),
None => generic::Rotate::Rotate(angle),
})
}
}
/// A specified CSS `translate`
pub type Translate = generic::Translate<LengthPercentage, Length>;
impl Parse for Translate {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
if input.try(|i| i.expect_ident_matching("none")).is_ok() {
return Ok(generic::Translate::None);
}
let tx = specified::LengthPercentage::parse(context, input)?;
if let Ok(ty) = input.try(|i| specified::LengthPercentage::parse(context, i)) {
if let Ok(tz) = input.try(|i| specified::Length::parse(context, i)) {
// 'translate: <length-percentage> <length-percentage> <length>'
return Ok(generic::Translate::Translate3D(tx, ty, tz));
}
// translate: <length-percentage> <length-percentage>'
return Ok(generic::Translate::Translate(tx, ty));
}
// 'translate: <length-percentage> '
Ok(generic::Translate::Translate(
tx,
specified::LengthPercentage::zero(),
))
}
}
/// A specified CSS `scale`
pub type Scale = generic::Scale<Number>;
impl Parse for Scale {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
if input.try(|i| i.expect_ident_matching("none")).is_ok() {
return Ok(generic::Scale::None);
}
let sx = Number::parse(context, input)?;
if let Ok(sy) = input.try(|i| Number::parse(context, i)) {
if let Ok(sz) = input.try(|i| Number::parse(context, i)) {
// 'scale: <number> <number> <number>'
return Ok(generic::Scale::Scale3D(sx, sy, sz));
}
// 'scale: <number> <number>'
return Ok(generic::Scale::Scale(sx, sy));
}
// 'scale: <number>'
Ok(generic::Scale::Scale(sx, sx))
}
}<|fim▁end|>
| |
<|file_name|>jnr12_in.js<|end_file_name|><|fim▁begin|>function enter(pi) {
pi.warp(926110401, 0); //next
return(true);<|fim▁hole|><|fim▁end|>
|
}
|
<|file_name|>events.ts<|end_file_name|><|fim▁begin|><|fim▁hole|>import { Jogador } from '../../../../common/database/models/Jogador';
import { environment } from '../../../../common/environment';
import { BrazucasEventos } from '../../interfaces/brazucas-eventos';
import { VoiceChatProvider } from '../../providers/voice-chat.provider';
import { Rpg } from '../../rpg';
import { playerEvent } from '../functions/player';
export class Events {
protected brazucasServer: BrazucasServer;
constructor(brazucasServer: BrazucasServer) {
this.brazucasServer = brazucasServer;
}
public async [BrazucasEventos.AUTENTICAR_JOGADOR](player: PlayerMp, dados: DadosLogin) {
try {
const jogador: Jogador = await this.brazucasServer.autenticarJogador(player.name, dados.senha);
if (jogador) {
player.spawn(environment.posicaoLogin);
await Rpg.playerProvider.update(player, jogador.toJSON());
return {
eventoResposta: 'AutenticacaoResultado',
credenciaisInvalidas: false,
autenticado: true,
};
} else {
return {
eventoResposta: 'AutenticacaoResultado',
credenciaisInvalidas: true,
autenticado: false,
};
}
} catch (err) {
console.error(err.toString());
return {
eventoResposta: 'AutenticacaoResultado',
credenciaisInvalidas: false,
autenticado: false,
};
}
}
public async [BrazucasEventos.REGISTRAR_JOGADOR](player: PlayerMp, dados: DadosRegistro) {
try {
const jogador: Jogador = await this.brazucasServer.registrarJogador(player, dados);
if (jogador) {
player.spawn(environment.posicaoLogin);
playerEvent<RegistroResultado>(player, BrazucasEventos.REGISTRO_RESULTADO, {
erro: false,
jogador: jogador,
registrado: true,
});
} else {
playerEvent<RegistroResultado>(player, BrazucasEventos.REGISTRO_RESULTADO, {
registrado: false,
erro: true,
});
}
} catch (err) {
console.debug(`[REGISTRO] Um erro ocorreu ao criar o jogador ${player.name}`);
console.error(err.toString());
playerEvent<RegistroResultado>(player, BrazucasEventos.REGISTRO_RESULTADO, {
registrado: false,
erro: true,
mensagem: err.toString() || 'Erro interno ao cadastrar',
});
}
}
public async [BrazucasEventos.CRIAR_VEICULO](player: PlayerMp, dados: DadosVeiculo) {
try {
await this.brazucasServer.criarVeiculo(player, dados);
} catch (err) {
console.debug(`[VEÍCULOS] Um erro ocorreu ao criar o veículo`);
console.error(err.toString());
return false;
}
}
public async [BrazucasEventos.HABILITAR_VOICE_CHAT](player: PlayerMp, dados: any) {
console.log(`[VOICE CHAT] Ativando voice chat para ${player.name} com os dados: ${JSON.stringify(dados)}`);
const target = mp.players.at(dados.targetId);
if (!target) {
return {
erro: true,
mensagem: 'Jogador não encontrado',
};
}
VoiceChatProvider.habilitar(player, target);
}
public async [BrazucasEventos.DESABILITAR_VOICE_CHAT](player: PlayerMp, dados: any) {
console.log(`[VOICE CHAT] Desativando voice chat para ${player.name} com os dados: ${JSON.stringify(dados)}`);
const target = mp.players.at(dados.targetId);
if (!target) {
return {
erro: true,
mensagem: 'Jogador não encontrado',
};
}
VoiceChatProvider.desabilitar(player, target);
}
public async [BrazucasEventos.ANIMACAO_VOICE_CHAT](player: PlayerMp) {
console.log(`[VOICE CHAT] Aplicando animação para ${player.name}`);
player.playAnimation('special_ped@baygor@monologue_3@monologue_3e', 'trees_can_talk_4', 1, 0);
}
public async [BrazucasEventos.VISUALIZAR_ANIMACAO](player: PlayerMp, dados: {
pacote: string,
nome: string;
}) {
player.stopAnimation();
player.playAnimation(dados.pacote, dados.nome, 1, 0);
}
}<|fim▁end|>
|
import { DadosVeiculo } from '../../../../browser/src/app/services/veiculo.service';
import { DadosLogin, DadosRegistro, RegistroResultado } from '../../../../browser/src/interfaces/login.interface';
import { BrazucasServer } from '../../../../common/brazucas-server';
|
<|file_name|>sword.cc<|end_file_name|><|fim▁begin|>/*
* Xiphos Bible Study Tool
* sword.cc - glue
*
* Copyright (C) 2000-2020 Xiphos Developer Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library 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 St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <gtk/gtk.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <swmgr.h>
#include <swmodule.h>
#include <stringmgr.h>
#include <localemgr.h>
extern "C" {
#include "gui/bibletext.h"
#include "main/gtk_compat.h"
}
#include <ctype.h>
#include <time.h>
#include "gui/main_window.h"
#include "gui/font_dialog.h"
#include "gui/widgets.h"
#include "gui/commentary.h"
#include "gui/dialog.h"
#include "gui/parallel_dialog.h"
#include "gui/parallel_tab.h"
#include "gui/parallel_view.h"
#include "gui/tabbed_browser.h"
#include "gui/xiphos.h"
#include "gui/sidebar.h"
#include "gui/utilities.h"
#include "gui/cipher_key_dialog.h"
#include "gui/main_menu.h"
#include "main/biblesync_glue.h"
#include "main/display.hh"
#include "main/lists.h"
#include "main/navbar.h"
#include "main/navbar_book.h"
#include "main/search_sidebar.h"
#include "main/previewer.h"
#include "main/settings.h"
#include "main/sidebar.h"
#include "main/sword.h"
#include "main/url.hh"
#include "main/xml.h"
#include "main/parallel_view.h"
#include "main/modulecache.hh"
#include "backend/sword_main.hh"
#include "backend/gs_stringmgr.h"
#include "biblesync/biblesync.hh"
#include "gui/debug_glib_null.h"
#ifdef HAVE_DBUS
#include "gui/ipc.h"
#endif
extern BibleSync *biblesync;
using namespace sword;
char *sword_locale = NULL;
gboolean companion_activity = FALSE;
/* Unicode collation necessities. */
UCollator* collator;
UErrorCode collator_status;
extern gboolean valid_scripture_key;
// these track together. when one changes, so does the other.
static std::map<string, string> abbrev_name2abbrev, abbrev_abbrev2name;
typedef std::map<string, string>::iterator abbrev_iter;
/******************************************************************************
* Name
* main_add_abbreviation
*
* Synopsis
* #include "main/sword.h"
*
* void main_add_abbreviation(char *name, char *abbreviation)
*
* Description
* adds an element to each of the abbreviation maps.
*
* Return value
* void
*/
void main_add_abbreviation(const char *name, const char *abbreviation)
{
// let's not be stupid about abbreviations chosen, ok?
if (!strchr(abbreviation, '(')) {
abbrev_name2abbrev[name] = abbreviation;
abbrev_abbrev2name[abbreviation] = name;
}
}
/******************************************************************************
* Name
* main_get_abbreviation
*
* Synopsis
* #include "main/sword.h"
*
* const char * main_get_abbreviation(const char *name)
*
* Description
* gets abbreviation from real module, if available.
*
* Return value
* const char *
*/
const char *main_get_abbreviation(const char *name)
{
if (name == NULL)
return NULL;
abbrev_iter it = abbrev_name2abbrev.find(name);
if (it != abbrev_name2abbrev.end()) {
return it->second.c_str();
}
return NULL;
}
/******************************************************************************
* Name
* main_get_name
*
* Synopsis
* #include "main/sword.h"
*
* const char * main_get_name(const char *abbreviation)
*
* Description
* gets real module name from abbreviation, if available.
*
* Return value
* const char *
*/
const char *main_get_name(const char *abbreviation)
{
if (abbreviation == NULL)
return NULL;
abbrev_iter it = abbrev_abbrev2name.find(abbreviation);
if (it != abbrev_abbrev2name.end()) {
return it->second.c_str();
}
return NULL;
}
/******************************************************************************
* Name
* main_book_heading
*
* Synopsis
* #include "main/sword.h"
*
* void main_book_heading(char * mod_name)
*
* Description
*
*
* Return value
* void
*/
void main_book_heading(char *mod_name)
{
VerseKey *vkey;
SWMgr *mgr = backend->get_mgr();
backend->display_mod = mgr->Modules[mod_name];
vkey = (VerseKey *)(SWKey *)(*backend->display_mod);
vkey->setIntros(1);
vkey->setAutoNormalize(0);
vkey->setChapter(0);
vkey->setVerse(0);
backend->display_mod->display();
}
/******************************************************************************
* Name
* main_chapter_heading
*
* Synopsis
* #include "main/module_dialogs.h"
*
* void main_chapter_heading(char * mod_name)
*
* Description
*
*
* Return value
* void
*/
void main_chapter_heading(char *mod_name)
{
VerseKey *vkey;
SWMgr *mgr = backend->get_mgr();
backend->display_mod = mgr->Modules[mod_name];
backend->display_mod->setKey(settings.currentverse);
vkey = (VerseKey *)(SWKey *)(*backend->display_mod);
vkey->setIntros(1);
vkey->setAutoNormalize(0);
vkey->setVerse(0);
backend->display_mod->display();
}
/******************************************************************************
* Name
* main_save_note
*
* Synopsis
* #include "main/sword.h"
*
* void main_save_note(const gchar * module_name,
* const gchar * key_str ,
* const gchar * note_str )
*
* Description
*
*
* Return value
* void
*/
void main_save_note(const gchar *module_name,
const gchar *key_str,
const gchar *note_str)
{
// Massage encoded spaces ("%20") back to real spaces.
// This is a sick. unreliable hack that should be removed
// after the underlying problem is fixed in Sword.
gchar *rework;
for (rework = (char *)strstr(note_str, "%20");
rework;
rework = strstr(rework + 1, "%20")) {
*rework = ' ';
(void)strcpy(rework + 1, rework + 3);
}
XI_message(("note module %s\nnote key %s\nnote text%s",
module_name,
key_str,
note_str));
backend->save_note_entry(module_name, key_str, note_str);
main_display_commentary(module_name, settings.currentverse);
}
/******************************************************************************
* Name
* main_delete_note
*
* Synopsis
* #include "main/sword.h"
*
* void main_delete_note(DIALOG_DATA * d)
*
* Description
*
*
* Return value
* void
*/
void main_delete_note(const gchar *module_name,
const gchar *key_str)
{
backend->set_module_key(module_name, key_str);
XI_message(("note module %s\nnote key %s\n",
module_name,
key_str));
backend->delete_entry();
if ((!strcmp(settings.CommWindowModule, module_name)) &&
(!strcmp(settings.currentverse, key_str)))
main_display_commentary(module_name, key_str);
}
/******************************************************************************
* Name
* set_module_unlocked
*
* Synopsis
* #include "bibletext.h"
*
* void set_module_unlocked(char *mod_name, char *key)
*
* Description
* unlocks locked module -
*
* Return value
* void
*/
void main_set_module_unlocked(const char *mod_name, char *key)
{
SWMgr *mgr = backend->get_mgr();
mgr->setCipherKey(mod_name, key);
}
/******************************************************************************
* Name
* main_save_module_key
*
* Synopsis
* #include "main/configs.h"
*
* void main_save_module_key(gchar * mod_name, gchar * key)
*
* Description
* to unlock locked modules
*
* Return value
* void
*/
void main_save_module_key(const char *mod_name, char *key)
{
backend->save_module_key((char *)mod_name, key);
}
/******************************************************************************
* Name
* main_getText
*
* Synopsis
* #include "main/sword.h"
* void main_getText(gchar * key)
*
* Description
* get unabbreviated key
*
* Return value
* char *
*/
char *main_getText(char *key)
{
VerseKey vkey(key);
return strdup((char *)vkey.getText());
}
/******************************************************************************
* Name
* main_getShortText
*
* Synopsis
* #include "main/sword.h"
* void main_getShortText(gchar * key)
*
* Description
* get short-name key
*
* Return value
* char *
*/
char *main_getShortText(char *key)
{
VerseKey vkey(key);
return strdup((char *)vkey.getShortText());
}
/******************************************************************************
* Name
* main_update_nav_controls
*
* Synopsis
* #include "toolbar_nav.h"
*
* gchar *main_update_nav_controls(const gchar * key)
*
* Description
* updates the nav toolbar controls
*
* Return value
* gchar *
*/
gchar *main_update_nav_controls(const char *module_name, const gchar *key)
{
char *val_key = backend->get_valid_key(module_name, key);
// we got a valid key. but was it really a valid key within v11n?
// for future use in determining whether to show normal navbar content.
navbar_versekey.valid_key = main_is_Bible_key(module_name, key);
/*
* remember verse
*/
xml_set_value("Xiphos", "keys", "verse", val_key);
settings.currentverse = xml_get_value("keys", "verse");
settings.apply_change = FALSE;
navbar_versekey.module_name = g_string_assign(navbar_versekey.module_name, settings.MainWindowModule);
navbar_versekey.key = g_string_assign(navbar_versekey.key, val_key);
main_navbar_versekey_set(navbar_versekey, val_key);
settings.apply_change = TRUE;
#ifdef HAVE_DBUS
IpcObject *ipc = ipc_get_main_ipc();
if (ipc)
ipc_object_navigation_signal(ipc, (const gchar *)val_key, NULL);
#endif
return val_key;
}
/******************************************************************************
* Name
* get_module_key
*
* Synopsis
* #include "main/module.h"
*
* char *get_module_key(void)
*
* Description
* returns module key
*
* Return value
* char *
*/
char *main_get_active_pane_key(void)
{
if (settings.havebible) {
switch (settings.whichwindow) {
case MAIN_TEXT_WINDOW:
case COMMENTARY_WINDOW:
return (char *)settings.currentverse;
break;
case DICTIONARY_WINDOW:
return (char *)settings.dictkey;
break;
case parallel_WINDOW:
return (char *)settings.cvparallel;
break;
case BOOK_WINDOW:
return (char *)settings.book_key;
break;
}
}
return NULL;
}
/******************************************************************************
* Name
* get_module_name
*
* Synopsis
* #include "main/module.h"
*
* char *get_module_name(void)
*
* Description
* returns module name
*
* Return value
* char *
*/
char *main_get_active_pane_module(void)
{
if (settings.havebible) {
switch (settings.whichwindow) {
case MAIN_TEXT_WINDOW:
return (char *)xml_get_value("modules",
"bible");
break;
case COMMENTARY_WINDOW:
return (char *)xml_get_value("modules",
"comm");
break;
case DICTIONARY_WINDOW:
return (char *)settings.DictWindowModule;
break;
case BOOK_WINDOW:
return (char *)settings.book_mod;
break;
}
}
return NULL;
}
/******************************************************************************
* Name
* module_name_from_description
*
* Synopsis
* #include ".h"
*
* void module_name_from_description(gchar *mod_name, gchar *description)
*
* Description
*
*
* Return value
* void
*/
char *main_module_name_from_description(char *description)
{
return backend->module_name_from_description(description);
}
/******************************************************************************
* Name
* main_get_sword_version
*
* Synopsis
* #include "sword.h"
*
* const char *main_get_sword_version(void)
*
* Description
*
*
* Return value
* const char *
*/
const char *main_get_sword_version(void)
{
return backend->get_sword_version();
}
/******************************************************************************
* Name
* get_search_results_text
*
* Synopsis
* #include "sword.h"
*
* char *get_search_results_text(char * mod_name, char * key)
*
* Description
*
*
* Return value
* char *
*/
char *main_get_search_results_text(char *mod_name, char *key)
{
return backend->get_render_text((char *)mod_name, (char *)key);
}
/******************************************************************************
* Name
* main_get_path_to_mods
*
* Synopsis
* #include "sword.h"
*
* gchar *main_get_path_to_mods(void)
*
* Description
* returns the path to the sword modules
*
* Return value
* gchar *
*/
char *main_get_path_to_mods(void)
{
SWMgr *mgr = backend->get_mgr();
char *path = mgr->prefixPath;
return (path ? g_strdup(path) : NULL);
}
/******************************************************************************
* Name
* main_init_language_map
*
* Synopsis
* #include "sword.h"
*
* void main_init_language_map(void)
*
* Description
* initializes the hard-coded abbrev->name mapping.
*
* Return value
* void
*/
typedef std::map<SWBuf, SWBuf> ModLanguageMap;
ModLanguageMap languageMap;
void main_init_language_map()
{
gchar *language_file;
FILE *language;
gchar *s, *end, *abbrev, *name, *newline;
gchar *mapspace;
size_t length;
if ((language_file = gui_general_user_file("languages", FALSE)) == NULL) {
gui_generic_warning(_("Xiphos's file for language\nabbreviations is missing."));
return;
}
XI_message(("%s", language_file));
if ((language = g_fopen(language_file, "r")) == NULL) {
gui_generic_warning(_("Xiphos's language abbreviation\nfile cannot be opened."));
g_free(language_file);
return;
}
g_free(language_file);
(void)fseek(language, 0L, SEEK_END);
length = ftell(language);
rewind(language);
if ((length == 0) ||
(mapspace = (gchar *)g_malloc(length + 2)) == NULL) {
fclose(language);
gui_generic_warning(_("Xiphos cannot allocate space\nfor language abbreviations."));
return;
}
if (fread(mapspace, 1, length, language) != length) {
fclose(language);
g_free(mapspace);
gui_generic_warning(_("Xiphos cannot read the\nlanguage abbreviation file."));
return;
}
fclose(language);
end = length + mapspace;
*end = '\0';
for (s = mapspace; s < end; ++s) {
if ((newline = strchr(s, '\n')) == NULL) {
XI_message(("incomplete last line in languages"));
break;
}
*newline = '\0';
if ((*s == '#') || (s == newline)) {
s = newline; // comment or empty line.
continue;
}
abbrev = s;
if ((name = strchr(s, '\t')) == NULL) {
XI_message(("tab-less line in languages"));
break;
}
*(name++) = '\0'; // NUL-terminate abbrev, mark name.
languageMap[SWBuf(abbrev)] = SWBuf(name);
s = newline;
}
g_free(mapspace);
}
const char *main_get_language_map(const char *language)
{
if (language == NULL)
return "Unknown";
return languageMap[language].c_str();
}
char **main_get_module_language_list(void)
{
return backend->get_module_language_list();
}
/******************************************************************************
* Name
* set_sword_locale
*
* Synopsis
* #include "main/sword.h"
*
* char *set_sword_locale(const char *sys_locale)
*
* Description
* set sword's idea of the locale in which the user operates
*
* Return value
* char *
*/
char *set_sword_locale(const char *sys_locale)
{
if (sys_locale) {
SWBuf locale;
StringList localelist = LocaleMgr::getSystemLocaleMgr()->getAvailableLocales();
StringList::iterator it;
int ncmp[3] = {100, 5, 2}; // fixed data
// length-limited match
for (int i = 0; i < 3; ++i) {
for (it = localelist.begin(); it != localelist.end(); ++it) {
locale = *it;
if (!strncmp(sys_locale, locale.c_str(), ncmp[i])) {
LocaleMgr::getSystemLocaleMgr()->setDefaultLocaleName(locale.c_str());
return g_strdup(locale.c_str());
}
}
}
}
// either we were given a null sys_locale, or it didn't match anything.
char *err = g_strdup_printf(_("No matching locale found for `%s'.\n%s"),
sys_locale,
_("Book names and menus may not be translated."));
gui_generic_warning(err);
g_free(err);
return NULL;
}
/******************************************************************************
* Name
* backend_init
*
* Synopsis
* #include "main/sword.h"
*
* void main_init_backend(void)
*
* Description
* start sword
*
* Return value
* void
*/
void main_init_backend(void)
{
StringMgr::setSystemStringMgr(new GS_StringMgr());
const char *lang = getenv("LANG");
if (!lang)
lang = "C";
sword_locale = set_sword_locale(lang);
collator = ucol_open(sword_locale, &collator_status);
lang = LocaleMgr::getSystemLocaleMgr()->getDefaultLocaleName();
backend = new BackEnd();
backend->init_SWORD(0);
settings.path_to_mods = main_get_path_to_mods();
//#ifndef DEBUG
g_chdir(settings.path_to_mods);
//#else
// XI_warning(("no chdir(SWORD_PATH) => modmgr 'archive' may not work"));
//#endif
XI_print(("%s sword-%s\n", "Starting", backend->get_sword_version()));
XI_print(("%s\n", "Initiating SWORD"));
XI_print(("%s: %s\n", "path to sword", settings.path_to_mods));
XI_print(("%s %s\n", "SWORD locale is", lang));
XI_print(("%s\n", "Checking for SWORD Modules"));
settings.spell_language = strdup(lang);
main_init_lists();
//
// BibleSync backend startup. identify the user by name.
//
biblesync = new BibleSync("Xiphos", VERSION,
#ifdef WIN32
// in win32 glib, get_real_name and get_user_name are the same.
(string)g_get_real_name()
#else
(string)g_get_real_name() + " (" + g_get_user_name() + ")"
#endif
);
}
/******************************************************************************
* Name
* shutdown_sword
*
* Synopsis
* #include "sword.h"
*
* void shutdown_sword(void)
*
* Description
* close down sword by deleting backend;
*
* Return value
* void
*/
void main_shutdown_backend(void)
{
if (sword_locale)
free((char *)sword_locale);
sword_locale = NULL;
if (backend)
delete backend;
backend = NULL;
XI_print(("%s\n", "SWORD is shutdown"));
}
/******************************************************************************
* Name
* main_dictionary_entry_changed
*
* Synopsis
* #include "main/sword.h"
*
* void main_dictionary_entry_changed(char * mod_name)
*
* Description
* text in the dictionary entry has changed and the entry activated
*
* Return value
* void
*/
void main_dictionary_entry_changed(char *mod_name)
{
gchar *key = NULL;
if (!mod_name)
return;
if (strcmp(settings.DictWindowModule, mod_name)) {
xml_set_value("Xiphos", "modules", "dict", mod_name);
settings.DictWindowModule = xml_get_value("modules", "dict");
}
key = g_strdup((gchar *)gtk_entry_get_text(GTK_ENTRY(widgets.entry_dict)));
backend->set_module_key(mod_name, key);
g_free(key);
key = backend->get_module_key();
xml_set_value("Xiphos", "keys", "dictionary", key);
settings.dictkey = xml_get_value("keys", "dictionary");
main_check_unlock(mod_name, TRUE);
backend->set_module_key(mod_name, key);
backend->display_mod->display();
gtk_entry_set_text(GTK_ENTRY(widgets.entry_dict), key);
g_free(key);
}
static void dict_key_list_select(GtkMenuItem *menuitem, gpointer user_data)
{
gtk_entry_set_text(GTK_ENTRY(widgets.entry_dict), (gchar *)user_data);
gtk_widget_activate(widgets.entry_dict);
}
/******************************************************************************
* Name
*
*
* Synopsis
* #include "main/sword.h"
*
*
*
* Description
* text in the dictionary entry has changed and the entry activated
*
* Return value
* void
*/
GtkWidget *main_dictionary_drop_down_new(char *mod_name, char *old_key)
{
gint count = 9, i;
gchar *new_key;
gchar *key = NULL;
GtkWidget *menu;
menu = gtk_menu_new();
if (!settings.havedict || !mod_name)
return NULL;
if (strcmp(settings.DictWindowModule, mod_name)) {
xml_set_value("Xiphos", "modules", "dict",
mod_name);
settings.DictWindowModule = xml_get_value(
"modules", "dict");
}
key = g_strdup((gchar *)gtk_entry_get_text(GTK_ENTRY(widgets.entry_dict)));
XI_message(("\nold_key: %s\nkey: %s", old_key, key));
backend->set_module_key(mod_name, key);
g_free(key);
key = backend->get_module_key();
xml_set_value("Xiphos", "keys", "dictionary", key);
settings.dictkey = xml_get_value("keys", "dictionary");
main_check_unlock(mod_name, TRUE);
backend->set_module_key(mod_name, key);
backend->display_mod->display();
new_key = g_strdup((char *)backend->display_mod->getKeyText());
for (i = 0; i < (count / 2) + 1; i++) {
(*backend->display_mod)--;
}
for (i = 0; i < count; i++) {
free(new_key);
(*backend->display_mod)++;
new_key = g_strdup((char *)backend->display_mod->getKeyText());
/* add menu item */
GtkWidget *item =
gtk_menu_item_new_with_label((gchar *)new_key);
gtk_widget_show(item);
g_signal_connect(G_OBJECT(item), "activate",
G_CALLBACK(dict_key_list_select),
g_strdup(new_key));
gtk_container_add(GTK_CONTAINER(menu), item);
}
free(new_key);
g_free(key);
return menu;
}
/******************************************************************************
* Name
* main_dictionary_button_clicked
*
* Synopsis
* #include "main/sword.h"
*
* void main_dictionary_button_clicked(gint direction)
*
* Description
* The back or foward dictinary key button was clicked.
* the module key is set to the current dictkey.
* then the module is incremented or decremented.
* the new key is returned from the module and the dictionary entry is set
* to the new key. The entry is then activated.
*
* Return value
* void
*/
void main_dictionary_button_clicked(gint direction)
{
gchar *key = NULL;
if (!settings.havedict || !settings.DictWindowModule)
return;
backend->set_module_key(settings.DictWindowModule,
settings.dictkey);
if (direction == 0)
(*backend->display_mod)--;
else
(*backend->display_mod)++;
key = g_strdup((char *)backend->display_mod->getKeyText());
gtk_entry_set_text(GTK_ENTRY(widgets.entry_dict), key);
gtk_widget_activate(widgets.entry_dict);
g_free(key);
}
void main_display_book(const char *mod_name,
const char *key)
{
if (!settings.havebook || !mod_name)
return;
if (key == NULL)
key = "0";
XI_message(("main_display_book\nmod_name: %s\nkey: %s", mod_name, key));
if (!backend->is_module(mod_name))
return;
if (!settings.book_mod)
settings.book_mod = g_strdup((char *)mod_name);
if (strcmp(settings.book_mod, mod_name)) {
xml_set_value("Xiphos", "modules", "book", mod_name);
gui_reassign_strdup(&settings.book_mod, (gchar *)mod_name);
}
if (!isdigit(key[0])) {
xml_set_value("Xiphos", "keys", "book", key);
settings.book_key = xml_get_value("keys", "book");
backend->set_module(mod_name);
backend->set_treekey(0);
settings.book_offset = backend->treekey_set_key((char *)key);
} else {
settings.book_offset = atol(key);
if (settings.book_offset < 4)
settings.book_offset = 4;
xml_set_value("Xiphos", "keys", "book", key);
settings.book_key = xml_get_value("keys", "book");
xml_set_value("Xiphos", "keys", "offset", key);
backend->set_module(mod_name);
backend->set_treekey(settings.book_offset);
}
main_check_unlock(mod_name, TRUE);
backend->display_mod->display();
main_setup_navbar_book(settings.book_mod, settings.book_offset);
//if (settings.browsing)
gui_update_tab_struct(NULL,
NULL,
NULL,
mod_name,
NULL,
key,
FALSE,
settings.showtexts,
settings.showpreview,
settings.showcomms,
settings.showdicts);
}
void main_display_commentary(const char *mod_name,
const char *key)
{
if (!settings.havecomm || !settings.comm_showing)
return;
if (!mod_name)
mod_name = ((settings.browsing && (cur_passage_tab != NULL))
? g_strdup(cur_passage_tab->commentary_mod)
: xml_get_value("modules", "comm"));
if (!mod_name || !backend->is_module(mod_name))
return;
int modtype = backend->module_type(mod_name);
if ((modtype != COMMENTARY_TYPE) && (modtype != PERCOM_TYPE))
return; // what are we doing here?
if (!settings.CommWindowModule)
settings.CommWindowModule = g_strdup((gchar *)mod_name);
settings.comm_showing = TRUE;
settings.whichwindow = COMMENTARY_WINDOW;
if (strcmp(settings.CommWindowModule, mod_name)) {
xml_set_value("Xiphos", "modules", "comm", mod_name);
gui_reassign_strdup(&settings.CommWindowModule, (gchar *)mod_name);
// handle a conf directive "Companion=This,That,TheOther"
char *companion = main_get_mod_config_entry(mod_name, "Companion");
gchar **name_set = (companion ? g_strsplit(companion, ",", -1) : NULL);
if (companion &&
(!companion_activity) &&
name_set[0] &&
*name_set[0] &&
backend->is_module(name_set[0]) &&
((settings.MainWindowModule == NULL) ||
strcmp(name_set[0], settings.MainWindowModule))) {
companion_activity = TRUE;
gint name_length = g_strv_length(name_set);
char *companion_question =
g_strdup_printf(_("Module %s has companion modules:\n%s.\n"
"Would you like to open these as well?%s"),
mod_name, companion,
((name_length > 1)
? _("\n\nThe first will open in the main window\n"
"and others in separate windows.")
: ""));
if (gui_yes_no_dialog(companion_question, NULL)) {
main_display_bible(name_set[0], key);
for (int i = 1; i < name_length; i++) {
main_dialogs_open(name_set[i], key, FALSE);
}
}
g_free(companion_question);
companion_activity = FALSE;
}
if (name_set)
g_strfreev(name_set);
if (companion)<|fim▁hole|>
main_check_unlock(mod_name, TRUE);
valid_scripture_key = main_is_Bible_key(mod_name, key);
backend->set_module_key(mod_name, key);
backend->display_mod->display();
valid_scripture_key = TRUE; // leave nice for future use.
//if (settings.browsing)
gui_update_tab_struct(NULL,
mod_name,
NULL,
NULL,
NULL,
NULL,
TRUE,
settings.showtexts,
settings.showpreview,
settings.showcomms,
settings.showdicts);
}
void main_display_dictionary(const char *mod_name,
const char *key)
{
const gchar *old_key, *feature;
// for devotional use.
gchar buf[10];
if (!settings.havedict || !mod_name)
return;
XI_message(("main_display_dictionary\nmod_name: %s\nkey: %s", mod_name, key));
if (!backend->is_module(mod_name))
return;
if (!settings.DictWindowModule)
settings.DictWindowModule = g_strdup((gchar *)mod_name);
if (key == NULL)
key = (char *)"Grace";
feature = (char *)backend->get_mgr()->getModule(mod_name)->getConfigEntry("Feature");
// turn on "all strong's" iff we have that kind of dictionary.
if (feature && (!strcmp(feature, "HebrewDef") || !strcmp(feature, "GreekDef")))
gtk_widget_show(widgets.all_strongs);
else
gtk_widget_hide(widgets.all_strongs);
if (strcmp(settings.DictWindowModule, mod_name)) {
// new dict -- is it actually a devotional?
time_t curtime;
if (feature && !strcmp(feature, "DailyDevotion")) {
if ((strlen(key) != 5) || // blunt tests.
(key[0] < '0') || (key[0] > '9') ||
(key[1] < '0') || (key[1] > '9') ||
(key[2] != '.') ||
(key[3] < '0') || (key[3] > '9') ||
(key[4] < '0') || (key[4] > '9')) { // not MM.DD
struct tm *loctime;
curtime = time(NULL);
loctime = localtime(&curtime);
strftime(buf, 10, "%m.%d", loctime);
key = buf;
}
}
xml_set_value("Xiphos", "modules", "dict", mod_name);
gui_reassign_strdup(&settings.DictWindowModule, (gchar *)mod_name);
}
// old_key is uppercase
key = g_utf8_strup(key, -1);
old_key = gtk_entry_get_text(GTK_ENTRY(widgets.entry_dict));
if (!strcmp(old_key, key))
main_dictionary_entry_changed(settings.DictWindowModule);
else {
gtk_entry_set_text(GTK_ENTRY(widgets.entry_dict), key);
gtk_widget_activate(widgets.entry_dict);
}
//if (settings.browsing)
gui_update_tab_struct(NULL,
NULL,
mod_name,
NULL,
key,
NULL,
settings.comm_showing,
settings.showtexts,
settings.showpreview,
settings.showcomms,
settings.showdicts);
}
void main_display_bible(const char *mod_name,
const char *key)
{
gchar *bs_key = g_strdup(key); // avoid tab data corruption problem.
/* keeps us out of a crash causing loop */
extern guint scroll_adj_signal;
extern GtkAdjustment *adjustment;
if (adjustment)
g_signal_handler_block(adjustment, scroll_adj_signal);
if (!gtk_widget_get_realized(GTK_WIDGET(widgets.html_text)))
return;
if (!mod_name)
mod_name = ((settings.browsing && (cur_passage_tab != NULL))
? g_strdup(cur_passage_tab->text_mod)
: xml_get_value("modules", "bible"));
if (!settings.havebible || !mod_name)
return;
if (!backend->is_module(mod_name))
return;
int modtype = backend->module_type(mod_name);
if (modtype != TEXT_TYPE)
return; // what are we doing here?
if (!settings.MainWindowModule)
settings.MainWindowModule = g_strdup((gchar *)mod_name);
if (strcmp(settings.currentverse, key)) {
xml_set_value("Xiphos", "keys", "verse",
key);
settings.currentverse = xml_get_value(
"keys", "verse");
}
if (strcmp(settings.MainWindowModule, mod_name)) {
xml_set_value("Xiphos", "modules", "bible", mod_name);
gui_reassign_strdup(&settings.MainWindowModule, (gchar *)mod_name);
// handle a conf directive "Companion=This,That,TheOther"
char *companion = main_get_mod_config_entry(mod_name, "Companion");
gchar **name_set = (companion ? g_strsplit(companion, ",", -1) : NULL);
if (companion &&
(!companion_activity) &&
name_set[0] &&
*name_set[0] &&
backend->is_module(name_set[0]) &&
((settings.CommWindowModule == NULL) ||
strcmp(name_set[0], settings.CommWindowModule))) {
companion_activity = TRUE;
gint name_length = g_strv_length(name_set);
char *companion_question =
g_strdup_printf(_("Module %s has companion modules:\n%s.\n"
"Would you like to open these as well?%s"),
mod_name, companion,
((name_length > 1)
? _("\n\nThe first will open in the main window\n"
"and others in separate windows.")
: ""));
if (gui_yes_no_dialog(companion_question, NULL)) {
main_display_commentary(name_set[0], key);
for (int i = 1; i < name_length; i++) {
main_dialogs_open(name_set[i], key, FALSE);
}
}
g_free(companion_question);
companion_activity = FALSE;
}
if (name_set)
g_strfreev(name_set);
if (companion)
g_free(companion);
navbar_versekey.module_name = g_string_assign(navbar_versekey.module_name,
settings.MainWindowModule);
navbar_versekey.key = g_string_assign(navbar_versekey.key,
settings.currentverse);
main_search_sidebar_fill_bounds_combos();
}
settings.whichwindow = MAIN_TEXT_WINDOW;
main_check_unlock(mod_name, TRUE);
valid_scripture_key = main_is_Bible_key(mod_name, key);
if (backend->module_has_testament(mod_name,
backend->get_key_testament(mod_name, key))) {
backend->set_module_key(mod_name, key);
backend->display_mod->display();
} else {
gchar *val_key = NULL;
if (backend->get_key_testament(mod_name, key) == 1)
val_key = main_update_nav_controls(mod_name, "Matthew 1:1");
else
val_key = main_update_nav_controls(mod_name, "Genesis 1:1");
backend->set_module_key(mod_name, val_key);
backend->display_mod->display();
g_free(val_key);
}
valid_scripture_key = TRUE; // leave nice for future use.
XI_message(("mod_name = %s", mod_name));
//if (settings.browsing) {
gui_update_tab_struct(mod_name,
NULL,
NULL,
NULL,
NULL,
NULL,
settings.comm_showing,
settings.showtexts,
settings.showpreview,
settings.showcomms,
settings.showdicts);
gui_set_tab_label(settings.currentverse, FALSE);
//}
gui_change_window_title(settings.MainWindowModule);
// (called _after_ tab data updated so not overwritten with old tab)
/*
* change parallel verses
*/
if (settings.dockedInt)
main_update_parallel_page();
else {
if (settings.showparatab)
gui_keep_parallel_tab_in_sync();
else
gui_keep_parallel_dialog_in_sync();
}
// multicast now, iff user has not asked for keyboard-only xmit.
if (!settings.bs_keyboard)
biblesync_prep_and_xmit(mod_name, bs_key);
g_free(bs_key);
if (adjustment)
g_signal_handler_unblock(adjustment, scroll_adj_signal);
}
/******************************************************************************
* Name
* main_display_devotional
*
* Synopsis
* #include "main/sword.h"
*
* void main_display_devotional(void)
*
* Description
*
*
* Return value
* void
*/
void main_display_devotional(void)
{
gchar buf[10];
gchar *prettybuf;
time_t curtime;
struct tm *loctime;
gchar *text;
/*
* This makes sense only if you've installed & defined one.
*/
if (settings.devotionalmod == NULL) {
GList *glist = get_list(DEVOTION_LIST);
if (g_list_length(glist) != 0) {
xml_set_value("Xiphos", "modules", "devotional",
(char *)glist->data);
gui_reassign_strdup(&settings.devotionalmod, (gchar *)glist->data);
} else {
gui_generic_warning(_("Daily devotional was requested, but there are none installed."));
}
}
/*
* Get the current time, converted to local time.
*/
curtime = time(NULL);
loctime = localtime(&curtime);
strftime(buf, 10, "%m.%d", loctime);
prettybuf = g_strdup_printf("<b>%s %d</b>",
gettext(month_names[loctime->tm_mon]),
loctime->tm_mday);
text = backend->get_render_text(settings.devotionalmod, buf);
if (text) {
main_entry_display(settings.show_previewer_in_sidebar
? sidebar.html_viewer_widget
: widgets.html_previewer_text,
settings.devotionalmod, text, prettybuf, TRUE);
g_free(text);
}
g_free(prettybuf);
}
void main_setup_displays(void)
{
backend->textDisplay = new GTKChapDisp(widgets.html_text, backend);
backend->commDisplay = new GTKEntryDisp(widgets.html_comm, backend);
backend->bookDisplay = new GTKEntryDisp(widgets.html_book, backend);
backend->dictDisplay = new GTKEntryDisp(widgets.html_dict, backend);
}
const char *main_get_module_language(const char *module_name)
{
return backend->module_get_language(module_name);
}
/******************************************************************************
* Name
* main_check_for_option
*
* Synopsis
* #include ".h"
*
* gint main_check_for_option(const gchar * mod_name, const gchar * key, const gchar * option)
*
* Description
* get any option for a module
*
* Return value
* gint
*/
gint main_check_for_option(const gchar *mod_name, const gchar *key, const gchar *option)
{
return backend->has_option(mod_name, key, option);
}
/******************************************************************************
* Name
* main_check_for_global_option
*
* Synopsis
* #include ".h"
*
* gint main_check_for_global_option(const gchar * mod_name, const gchar * option)
*
* Description
* get global options for a module
*
* Return value
* gint
*/
gint main_check_for_global_option(const gchar *mod_name, const gchar *option)
{
return backend->has_global_option(mod_name, option);
}
/******************************************************************************
* Name
* main_is_module
*
* Synopsis
* #include "main/module.h"
*
* int main_is_module(char * mod_name)
*
* Description
* check for presents of a module by name
*
* Return value
* int
*/
int main_is_module(char *mod_name)
{
return backend->is_module(mod_name);
}
/******************************************************************************
* Name
* main_has_search_framework
*
* Synopsis
* #include "main/module.h"
*
* int main_has_search_framework(char * mod_name)
*
* Description
* tells us whether CLucene is available
*
* Return value
* int (boolean)
*/
int main_has_search_framework(char *mod_name)
{
SWMgr *mgr = backend->get_mgr();
SWModule *mod = mgr->getModule(mod_name);
return (mod && mod->hasSearchFramework());
}
/******************************************************************************
* Name
* main_optimal_search
*
* Synopsis
* #include "main/module.h"
*
* int main_optimal_search(char * mod_name)
*
* Description
* tells us whether a CLucene index exists
*
* Return value
* int (boolean)
*/
int main_optimal_search(char *mod_name)
{
SWMgr *mgr = backend->get_mgr();
SWModule *mod = mgr->Modules.find(mod_name)->second;
return mod->isSearchOptimallySupported("God", -4, 0, 0);
}
char *main_get_mod_config_entry(const char *module_name,
const char *entry)
{
return backend->get_config_entry((char *)module_name, (char *)entry);
}
char *main_get_mod_config_file(const char *module_name,
const char *moddir)
{
#ifdef SWORD_SHOULD_HAVE_A_WAY_TO_GET_A_CONF_FILENAME_FROM_A_MODNAME
return backend->get_config_file((char *)module_name, (char *)moddir);
#else
GDir *dir;
SWBuf name;
name = moddir;
name += "/mods.d";
if ((dir = g_dir_open(name, 0, NULL))) {
const gchar *ent;
g_dir_rewind(dir);
while ((ent = g_dir_read_name(dir))) {
name = moddir;
name += "/mods.d/";
name += ent;
SWConfig *config = new SWConfig(name.c_str());
if (config->getSections().find(module_name) !=
config->getSections().end()) {
gchar *ret_name = g_strdup(ent);
g_dir_close(dir);
delete config;
return ret_name;
} else
delete config;
}
g_dir_close(dir);
}
return NULL;
#endif
}
int main_is_mod_rtol(const char *module_name)
{
char *direction = backend->get_config_entry((char *)module_name, (char *)"Direction");
return (direction && !strcmp(direction, "RtoL"));
}
/******************************************************************************
* Name
* main_has_cipher_tag
*
* Synopsis
* #include "main/.h"
*
* int main_has_cipher_tag(char *mod_name)
*
* Description
*
*
* Return value
* int
*/
int main_has_cipher_tag(char *mod_name)
{
gchar *cipherkey = backend->get_config_entry(mod_name, (char *)"CipherKey");
int retval = (cipherkey != NULL);
g_free(cipherkey);
return retval;
}
#define CIPHER_INTRO \
_("<b>Locked Module.</b>\n\n<u>You are opening a module which requires a <i>key</i>.</u>\n\nThe module is locked, meaning that the content is encrypted by its publisher, and you must enter its key in order for the content to become useful. This key should have been received by you on the web page which confirmed your purchase, or perhaps sent via email after purchase.\n\nPlease enter the key in the dialog.")
/******************************************************************************
* Name
* main_check_unlock
*
* Synopsis
* #include "main/.h"
*
* int main_check_unlock(const char *mod_name)
*
* Description
*
*
* Return value
* int
*/
void main_check_unlock(const char *mod_name, gboolean conditional)
{
gchar *cipher_old = main_get_mod_config_entry(mod_name, "CipherKey");
/* if forced by the unlock menu item, or it's present but empty... */
if (!conditional ||
((cipher_old != NULL) && (*cipher_old == '\0'))) {
if (conditional) {
GtkWidget *dialog;
dialog = gtk_message_dialog_new_with_markup(NULL, /* no need for a parent window */
GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_INFO,
GTK_BUTTONS_OK,
CIPHER_INTRO);
g_signal_connect_swapped(dialog, "response",
G_CALLBACK(gtk_widget_destroy),
dialog);
gtk_widget_show(dialog);
}
gchar *cipher_key = gui_add_cipher_key(mod_name, cipher_old);
if (cipher_key) {
ModuleCacheErase(mod_name);
redisplay_to_realign();
g_free(cipher_key);
}
}
g_free(cipher_old);
}
/******************************************************************************
* Name
* main_get_striptext
*
* Synopsis
* #include "main/sword.h"
*
* char *main_get_striptext(char *module_name, char *key)
*
* Description
*
*
* Return value
* char *
*/
char *main_get_striptext(char *module_name, char *key)
{
return backend->get_strip_text(module_name, key);
}
/******************************************************************************
* Name
* main_get_rendered_text
*
* Synopsis
* #include "main/sword.h"
*
* char *main_get_rendered_text(char *module_name, char *key)
*
* Description
*
*
* Return value
* char *
*/
char *main_get_rendered_text(const char *module_name, const char *key)
{
return backend->get_render_text(module_name, key);
}
/******************************************************************************
* Name
* main_get_raw_text
*
* Synopsis
* #include "main/sword.h"
*
* char *main_get_raw_text(char *module_name, char *key)
*
* Description
*
*
* Return value
* char *
*/
char *main_get_raw_text(char *module_name, char *key)
{
return backend->get_raw_text(module_name, key);
}
/******************************************************************************
* Name
* main_get_mod_type
*
* Synopsis
* #include "main/module.h"
*
* int main_get_mod_type(char * mod_name)
*
* Description
*
*
* Return value
* int
*/
int main_get_mod_type(char *mod_name)
{
return backend->module_type(mod_name);
}
/******************************************************************************
* Name
* main_get_module_description
*
* Synopsis
* #include "main/module.h"
*
* gchar *main_get_module_description(gchar * module_name)
*
* Description
*
*
* Return value
* gchar *
*/
const char *main_get_module_description(const char *module_name)
{
return backend->module_description(module_name);
}
/******************************************************************************
* Name
* main_format_number
*
* Synopsis
* #include "main/sword.h"
* char *main_format_number(int x)
*
* Description
* returns a digit string in either "latinate arabic" (normal) or
* farsi characters.
* re_encode_digits is chosen at startup in settings.c.
* caller must free allocated string space when finished with it.
*
* Return value
* char *
*/
int re_encode_digits = FALSE;
char *
main_format_number(int x)
{
char *digits = g_strdup_printf("%d", x);
if (re_encode_digits) {
//
// "\333\260" is farsi "zero".
//
char *d, *f, *farsi = g_new(char, 2 * (strlen(digits) + 1));
// 2 "chars" per farsi-displayed digit + slop.
for (d = digits, f = farsi; *d; ++d) {
*(f++) = '\333';
*(f++) = '\260' + ((*d) - '0');
}
*f = '\0';
g_free(digits);
return farsi;
}
return digits;
}
/******************************************************************************
* Name
* main_flush_widgets_content
*
* Synopsis
* #include "main/sword.h"
* void main_flush_widgets_content()
*
* Description
* cleans content from all subwindow widgets.
*
* Return value
* int
*/
void main_flush_widgets_content(void)
{
GString *blank_html_content = g_string_new(NULL);
g_string_printf(blank_html_content,
"<html><head></head><body bgcolor=\"%s\" text=\"%s\"> </body></html>",
settings.bible_bg_color, settings.bible_text_color);
if (gtk_widget_get_realized(GTK_WIDGET(widgets.html_text)))
HtmlOutput(blank_html_content->str, widgets.html_text, NULL, NULL);
if (gtk_widget_get_realized(GTK_WIDGET(widgets.html_comm)))
HtmlOutput(blank_html_content->str, widgets.html_comm, NULL, NULL);
if (gtk_widget_get_realized(GTK_WIDGET(widgets.html_dict)))
HtmlOutput(blank_html_content->str, widgets.html_dict, NULL, NULL);
if (gtk_widget_get_realized(GTK_WIDGET(widgets.html_book)))
HtmlOutput(blank_html_content->str, widgets.html_book, NULL, NULL);
g_string_free(blank_html_content, TRUE);
}
/******************************************************************************
* Name
* main_is_Bible_key
*
* Synopsis
* #include "main/sword.h"
* void main_is_Bible_key()
*
* Description
* returns boolean status of whether input is a legit Bible key.
*
* Return value
* gboolean
*/
gboolean main_is_Bible_key(const gchar *name, const gchar *key)
{
return (gboolean)(backend->is_Bible_key(name, key, settings.currentverse) != 0);
}
/******************************************************************************
* Name
* main_get_osisref_from_key
*
* Synopsis
* #include "main/sword.h"
* void main_get_osisref_from_key()
*
* Description
* returns OSISRef-formatted key value.
*
* Return value
* const char *
*/
const char *
main_get_osisref_from_key(const char *module, const char *key)
{
return backend->get_osisref_from_key(module, key);
}<|fim▁end|>
|
g_free(companion);
}
|
<|file_name|>conf.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# eofs documentation build configuration file, created by
# sphinx-quickstart on Thu Jul 5 15:47:55 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
import time
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.append(os.path.abspath('sphinxext'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc',
'sphinx.ext.mathjax',
'sphinx.ext.viewcode',
'sphinx.ext.autosummary',
'sphinx.ext.intersphinx',
'sphinx.ext.extlinks',
'matplotlib.sphinxext.plot_directive',]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'eofs'
copyright = '2013-{} Andrew Dawson'.format(time.localtime().tm_year)
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
import eofs
version = eofs.__version__
# The full version, including alpha/beta/rc tags.
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
highlight_language = 'python'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- extlinks configuration ----------------------------------------------------
# Allow e.g. :issue:`42` and :pr:`42` roles:
extlinks = {'issue': ('https://github.com/ajdawson/eofs/issues/%s', '#'),
'pr': ('https://github.com/ajdawson/eofs/pull/%s', '#')}
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx13'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ['_themes']
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
html_sidebars = {'**': ['sidebar_toc.html',
'relations.html',
'sourcelink.html',
'searchbox.html']}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {'index': 'index.html'}
# If false, no module index is generated.
html_domain_indices = False
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'eofsdoc'
# Options for intersphinx.
intersphinx_mapping = {
'eof2': ('http://ajdawson.github.com/eof2', None),
'iris': ('http://scitools.org.uk/iris/docs/latest', None),
'numpy': ('http://docs.scipy.org/doc/numpy', None),
'xarray': ('http://xarray.pydata.org/en/stable', None),
'dask': ('https://docs.dask.org/en/latest', None),
}
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
'pointsize': '11pt',
# Additional stuff for the LaTeX preamble.
'preamble': """\\usepackage{amssymb}
\\usepackage{amsmath}""",
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('userguide/index', 'userguide.tex', 'eofs User Guide', 'Andrew Dawson',
'manual'),
('examples/index', 'examples.tex', 'eofs Examples', 'Andrew Dawson',
'manual'),
('api/index', 'api.tex', 'eofs API Reference', 'Andrew Dawson',
'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'eofs', 'eofs Documentation',
['Andrew Dawson'], 1)<|fim▁hole|>#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'eofs', 'eofs Documentation',
'Andrew Dawson', 'eofs', 'EOF analysis in Python.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# -- Autodoc settings -- #
autoclass_content = 'both'
autodoc_member_order = 'bysource'
autodoc_docstring_signature = True
autosummary_generate = True<|fim▁end|>
|
]
# If true, show URL addresses after external links.
|
<|file_name|>transifex.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Matt Layman
from ConfigParser import ConfigParser, NoOptionError, NoSectionError
import os
import sys
import requests
API_URL = 'https://www.transifex.com/api/2'
LANGUAGES = [<|fim▁hole|> 'it',
'nl',
]
def fetch_po_for(language, username, password):
print 'Downloading po file for {0} ...'.format(language)
po_api = '/project/tappy/resource/tappypot/translation/{0}/'.format(
language)
po_url = API_URL + po_api
params = {'file': '1'}
r = requests.get(po_url, auth=(username, password), params=params)
if r.status_code == 200:
r.encoding = 'utf-8'
output_file = os.path.join(
here, 'tap', 'locale', language, 'LC_MESSAGES', 'tappy.po')
with open(output_file, 'wb') as out:
out.write(r.text.encode('utf-8'))
else:
print('Something went wrong fetching the {0} po file.'.format(
language))
def get_auth_from_conf(here):
transifex_conf = os.path.join(here, '.transifex.ini')
config = ConfigParser()
try:
with open(transifex_conf, 'r') as conf:
config.readfp(conf)
except IOError as ex:
sys.exit('Failed to load authentication configuration file.\n'
'{0}'.format(ex))
try:
username = config.get('auth', 'username')
password = config.get('auth', 'password')
except (NoOptionError, NoSectionError) as ex:
sys.exit('Oops. Incomplete configuration file: {0}'.format(ex))
return username, password
if __name__ == '__main__':
here = os.path.abspath(os.path.dirname(__file__))
username, password = get_auth_from_conf(here)
for language in LANGUAGES:
fetch_po_for(language, username, password)<|fim▁end|>
|
'es',
'fr',
|
<|file_name|>basic.py<|end_file_name|><|fim▁begin|>a = a # e 4
a = 1 # 0 int
l = [a] # 0 [int]
d = {a:l} # 0 {int:[int]}
s = "abc"
c = ord(s[2].lower()[0]) # 0 int # 4 (str) -> int
l2 = [range(i) for i in d] # 0 [[int]]
y = [(a,b) for a,b in {1:'2'}.iteritems()] # 0 [(int,str)]
b = 1 # 0 int
if 0:
b = '' # 4 str
else:
b = str(b) # 4 str # 12 int
r = 0 # 0 int
if r: # 3 int
r = str(r) # 4 str # 12 int
r # 0 <int|str>
l = range(5) # 0 [int]
l2 = l[2:3] # 0 [int]
x = l2[1] # 0 int
k = 1() # 0 <unknown> # e 4
del k
k # e 0
l = [] # 0 [int]
x = 1 # 0 int
while x: # 6 int
l = [] # 4 [int]
l.append(1) # 0 [int] # 2 (int) -> None
l = [1, 2] # 0 [int]
l2 = [x for x in l] # 0 [<int|str>]
l2.append('') # 0 [<int|str>]
s = str() # 0 str
s2 = str(s) # 0 str
s3 = repr() # e 5 # 0 str
s4 = repr(s) # 0 str
x = 1 if [] else '' # 0 <int|str>
l = [1] # 0 [<int|str>]
l2 = [''] # 0 [str]
l[:] = l2 # 0 [<int|str>]
b = 1 < 2 < 3 # 0 bool
l = sorted(range(5), key=lambda x:-x) # 0 [int]
d = {} # 0 {<bool|int>:<int|str>}
d1 = {1:''} # 0 {int:str}
d.update(d1)
d[True] = 1
d # 0 {<bool|int>:<int|str>}
l = [] # 0 [int]
l1 = [] # 0 [<unknown>]
l.extend(l1)
l.append(2)
l = [] # 0 [<[str]|int>]
l1 = [[]] # 0 [[str]]
l.extend(l1)
l[0].append('') # e 0
l.append(1)
l = [] # 0 [[<int|str>]]
l2 = [1] # 0 [int]
l3 = [''] # 0 [str]
l.append(l2)
l.append(l3)
for i, s in enumerate("aoeu"): # 4 int # 7 str
pass
x = 1 # 0 int
y = x + 1.0 # 0 float
y << 1 # e 0
l = [1, 1.0] # 0 [float]
1.0 in [1] # e 0<|fim▁hole|>def f():
x = `1` # 4 str
d = dict(a=1) # 0 {str:int}
l = list() # 0 [<unknown>]
i = int(1) # 0 int
i = int(1.2) # 0 int
i = abs(1) # 0 int
i = abs(1.0) # 0 float
d = dict() # 0 {int:int}
d[1] = 2
d2 = dict(d) # 0 {<int|str>:<int|str>}
d2[''] = ''
d3 = dict([(1,2)]) # 0 {int:int}
d4 = dict(a=1) # 0 {str:int}<|fim▁end|>
|
x = `1` # 0 str
|
<|file_name|>QueryFormModel.js<|end_file_name|><|fim▁begin|>/*
* Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
*/
define([
'underscore',
'backbone',
'knockout',
"protocol",
'contrail-model',
'query-or-model',
'query-and-model',
'core-basedir/reports/qe/ui/js/common/qe.utils',
'contrail-list-model',
], function (_, Backbone, Knockout, protocolUtils, ContrailModel, QueryOrModel, QueryAndModel, qeUtils, ContrailListModel) {
var QueryFormModel = ContrailModel.extend({
defaultSelectFields: [],
disableSelectFields: [],
disableSubstringInSelectFields: ['CLASS('],
disableWhereFields: [],
constructor: function (modelData, queryReqConfig) {
var self = this, modelRemoteDataConfig,
defaultQueryReqConfig = {chunk: 1, autoSort: true, chunkSize: cowc.QE_RESULT_CHUNK_SIZE_10K, async: true};
var defaultSelectFields = this.defaultSelectFields,
disableFieldArray = [].concat(defaultSelectFields).concat(this.disableSelectFields),
disableSubstringArray = this.disableSubstringInSelectFields;
if (contrail.checkIfExist(modelData.table_name)) {
modelRemoteDataConfig = getTableSchemaConfig(self, modelData.table_name, disableFieldArray, disableSubstringArray, this.disableWhereFields);
}
if(contrail.checkIfExist(queryReqConfig)) {
defaultQueryReqConfig = $.extend(true, defaultQueryReqConfig, queryReqConfig);
}
this.defaultQueryReqConfig = defaultQueryReqConfig;
ContrailModel.prototype.constructor.call(this, modelData, modelRemoteDataConfig);
this.model().on("change:table_name", this.onChangeTable, this);
this.model().on('change:select change:table_name change:time_range change:where change:filter change:time_granularity change:time_granularity_unit', function () {
// TODO ContrailListModel should have reload function instead of whole model recreation just to get new data
self.refresh()
})
//TODO - Needs to be tested for Flow Pages
this.model().on("change:time_range change:from_time change:to_time change:table_type", this.onChangeTime, this);
return this;
},
onChangeTime: function() {
var self = this,
table_type = self.model().get('table_type')
if (table_type === cowc.QE_STAT_TABLE_TYPE
|| table_type === cowc.QE_OBJECT_TABLE_TYPE
|| table_type === cowc.QE_FLOW_TABLE_TYPE) {
var setTableValuesCallbackFn = function (self, resultArr){
var currentSelectedTable = self.model().attributes.table_name;
if (currentSelectedTable != null)
{
// If time_range is changed then Fetch active tables and check if selected table
// is present in the response; if not then reset, else don't reset
if (_.indexOf(resultArr, currentSelectedTable) == -1) {
// reset everything except time range
self.reset(self, null, false, true);
}
}
}
this.setTableValues(setTableValuesCallbackFn, table_type)
}
// use the timer trick to overcome a event firing sequence issue.
setTimeout(function() {
this.setTableFieldValues();
}.bind(this), 0);
},
setTableValues: function(setTableValuesCallbackFn, tabletype) {
var self = this,
contrailViewModel = this.model(),
timeRange = contrailViewModel.attributes.time_range;
function fetchTableValues(fromTimeUTC, toTimeUTC) {
var data = {
fromTimeUTC: fromTimeUTC,
toTimeUTC : toTimeUTC,
table_name : 'StatTable.FieldNames.fields',
select : ['name', 'fields.value'],
where : [[{"name": "name", "value": tabletype, "op": 7}]]
};
self.table_name_data_object({
status: cowc.DATA_REQUEST_STATE_FETCHING,
data: []
});
$.ajax({
url: '/api/qe/table/column/values',
type: "POST",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (resultJSON) {
var resultArr = [];
$.each(resultJSON.data, function(dataKey, dataValue) {
var nameOption = dataValue.name.split(':')[1];
resultArr.push(nameOption);
});
self.table_name_data_object({
status: cowc.DATA_REQUEST_STATE_SUCCESS_NOT_EMPTY,
data: resultArr
});
if(setTableValuesCallbackFn !== null){
setTableValuesCallbackFn(self, resultArr);
}
}).error(function(xhr) {
self.table_name_data_object({
status: cowc.DATA_REQUEST_STATE_ERROR,
error: xhr,
data: []
});
});
}
if (tabletype === cowc.QE_FLOW_TABLE_TYPE) {
var resultArr = [
cowc.FLOW_SERIES_TABLE,
cowc.FLOW_RECORD_TABLE
];
self.table_name_data_object({
status: cowc.DATA_REQUEST_STATE_SUCCESS_NOT_EMPTY,
data: resultArr
});
if(setTableValuesCallbackFn !== null){
setTableValuesCallbackFn(self, resultArr);
}
} else if (timeRange == -1) {
var fromTimeUTC = new Date(contrailViewModel.attributes.from_time).getTime(),
toTimeUTC = new Date(contrailViewModel.attributes.to_time).getTime();
fetchTableValues(fromTimeUTC, toTimeUTC);
} else {
qeUtils.fetchServerCurrentTime(function (serverCurrentTime) {
var fromTimeUTC = serverCurrentTime - (timeRange * 1000),
toTimeUTC = serverCurrentTime;
fetchTableValues(fromTimeUTC, toTimeUTC);
});
}
},
setTableFieldValues: function() {
var contrailViewModel = this.model(),
tableName = contrailViewModel.attributes.table_name,
timeRange = contrailViewModel.attributes.time_range;
if (contrail.checkIfExist(tableName)) {
qeUtils.fetchServerCurrentTime(function(serverCurrentTime) {
var fromTimeUTC = serverCurrentTime - (timeRange * 1000),
toTimeUTC = serverCurrentTime
if (timeRange == -1) {
fromTimeUTC = new Date(contrailViewModel.attributes.from_time).getTime();
toTimeUTC = new Date(contrailViewModel.attributes.to_time).getTime();
}
var data = {
fromTimeUTC: fromTimeUTC,
toTimeUTC: toTimeUTC,
table_name: 'StatTable.FieldNames.fields',
select: ['name', 'fields.value'],
where: [[{"name":"name","value":tableName,"op":7}]]
};
$.ajax({
url: '/api/qe/table/column/values',
type: "POST",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (resultJSON) {
var valueOptionList = {};
if (_.includes(["FlowSeriesTable", "FlowRecordTable"], tableName)) {
valueOptionList["protocol"] = [
"TCP", "UDP", "ICMP"
];
}
$.each(resultJSON.data, function(dataKey, dataValue) {
var nameOption = dataValue.name.split(':')[1];
if (!contrail.checkIfExist(valueOptionList[nameOption])) {
valueOptionList[nameOption] = [];
}
valueOptionList[nameOption].push(dataValue['fields.value']);
});
contrailViewModel.attributes.where_data_object['value_option_list'] = valueOptionList;
}).error(function(xhr) {
console.log(xhr);
});
});
}
},
onChangeTable: function() {
var self = this,
model = self.model();
if (self.table_type() == cowc.QE_OBJECT_TABLE_TYPE
|| self.table_type() == cowc.QE_STAT_TABLE_TYPE
|| self.table_type() === cowc.QE_FLOW_TABLE_TYPE) {
self.reset(this, null, false, false);
}
var tableName = model.attributes.table_name,
tableSchemeUrl = '/api/qe/table/schema/' + tableName,
ajaxConfig = {
url: tableSchemeUrl,
type: 'GET'
},
contrailViewModel = this.model(),
defaultSelectFields = this.defaultSelectFields,
disableFieldArray = [].concat(defaultSelectFields).concat(this.disableSelectFields),
disableSubstringArray = this.disableSubstringInSelectFields;
// qeUtils.adjustHeight4FormTextarea(model.attributes.query_prefix);
if(tableName != '') {
$.ajax(ajaxConfig).success(function(response) {
var selectFields = getSelectFields4Table(response, disableFieldArray, disableSubstringArray),
whereFields = getWhereFields4NameDropdown(response, tableName, self.disableWhereFields);
var selectFields_Aggtype = [];
self.select_data_object().requestState((selectFields.length > 0) ? cowc.DATA_REQUEST_STATE_SUCCESS_NOT_EMPTY : cowc.DATA_REQUEST_STATE_SUCCESS_EMPTY);
contrailViewModel.set({
'ui_added_parameters': {
'table_schema': response,
'table_schema_column_names_map' : getTableSchemaColumnMap(response)
}
});
setEnable4SelectFields(selectFields, self.select_data_object().enable_map());
setChecked4SelectFields(selectFields, self.select_data_object().checked_map());
self.select_data_object().select_fields(selectFields);
contrailViewModel.attributes.where_data_object['name_option_list'] = whereFields;
if (self.table_type() == cowc.QE_OBJECT_TABLE_TYPE
|| self.table_type() == cowc.QE_STAT_TABLE_TYPE
|| self.table_type() === cowc.QE_FLOW_TABLE_TYPE) {
self.setTableFieldValues();
}
}).error(function(xhr) {
console.log(xhr);
});
}
},
formatModelConfig: function(modelConfig) {
var whereOrClausesCollectionModel, filterAndClausesCollectionModel;
whereOrClausesCollectionModel = new Backbone.Collection([]);
modelConfig['where_or_clauses'] = whereOrClausesCollectionModel;
filterAndClausesCollectionModel = new Backbone.Collection([]);
modelConfig['filter_and_clauses'] = filterAndClausesCollectionModel;
return modelConfig;
},
saveSelect: function (callbackObj) {
try {
var checkedFields = qeUtils.getCheckedFields(this.select_data_object().checked_map());
if (contrail.checkIfFunction(callbackObj.init)) {
callbackObj.init();
}
this.select(checkedFields.join(", "));
if (contrail.checkIfFunction(callbackObj.success)) {
callbackObj.success();
}
} catch (error) {
if (contrail.checkIfFunction(callbackObj.error)) {
callbackObj.error(this.getFormErrorText(this.query_prefix()));
}
}
},
saveWhere: function (callbackObj) {
try {
if (contrail.checkIfFunction(callbackObj.init)) {
callbackObj.init();
}
this.where(qeUtils.parseWhereCollection2String(this));
if (contrail.checkIfFunction(callbackObj.success)) {
callbackObj.success();
}
} catch (error) {
if (contrail.checkIfFunction(callbackObj.error)) {
callbackObj.error(this.getFormErrorText(this.query_prefix()));
}
}
},
saveFilter: function (callbackObj) {
try {
if (contrail.checkIfFunction(callbackObj.init)) {
callbackObj.init();
}
this.filters(qeUtils.parseFilterCollection2String(this));
if (contrail.checkIfFunction(callbackObj.success)) {
callbackObj.success();
}
} catch (error) {
if (contrail.checkIfFunction(callbackObj.error)) {
callbackObj.error(this.getFormErrorText(this.query_prefix()));
}
}
},
isTimeRangeCustom: function() {
var self = this;
/*
TODO: time_range is somehow stored as string inside the dropdown, hence use ==
*/
return self.time_range() == -1;
},
isSelectTimeChecked: function() {
var self = this,
selectString = self.select(),
selectStringCheckedFields = (selectString !== null) ? selectString.split(', ') : [];
return selectStringCheckedFields.indexOf("T=") != -1;
},
toggleAdvancedFields: function() {
var showAdvancedOptions = this.model().get('show_advanced_options');
this.show_advanced_options(!showAdvancedOptions);
},
getAdvancedOptionsText: function() {
var showAdvancedOptions = this.show_advanced_options();
if (!showAdvancedOptions) {
return 'Show Advanced Options';
} else {
return 'Hide Advanced Options';
}
},
getSortByOptionList: function(viewModel) {
var validSortFields = qeUtils.getCheckedFields(this.select_data_object().checked_map()),
invalidSortFieldsArr = ["T=" , "UUID"],
resultSortFieldsDataArr = [];
for(var i=0; i< validSortFields.length; i++){
if(invalidSortFieldsArr.indexOf(validSortFields[i]) === -1) {
resultSortFieldsDataArr.push({id: validSortFields[i], text: validSortFields[i]});
}
}
return resultSortFieldsDataArr;
},
toJSON: function () {
var modelAttrs = this.model().attributes
var attrs4Server = {}
var ignoreKeyList = ['elementConfigMap', 'errors', 'locks', 'ui_added_parameters', 'where_or_clauses',
'select_data_object', 'where_data_object', 'filter_data_object', 'filter_and_clauses', 'sort_by',
'sort_order', 'log_category', 'log_type', 'is_request_in_progress', 'show_advanced_options',
'table_name_data_object']
for (var key in modelAttrs) {
if (modelAttrs.hasOwnProperty(key) && ignoreKeyList.indexOf(key) === -1) {
attrs4Server[key] = modelAttrs[key];
}
}
return attrs4Server;
},
getQueryRequestPostData: function (serverCurrentTime, customQueryReqObj, useOldTime) {
var self = this,
formModelAttrs = this.toJSON(),
queryReqObj = {};
/**
* Analytics only understand protocol code.
* So convert protocol name in where clause.
*/
if (formModelAttrs.where) {
var regex = /(protocol\s*=\s*)(UDP|TCP|ICMP)/g;
formModelAttrs.where = formModelAttrs.where.replace(regex,
function(match, leftValue, protocolName) {
return leftValue + protocolUtils.getProtocolCode(protocolName);
});
}
if(useOldTime != true) {
qeUtils.setUTCTimeObj(this.query_prefix(), formModelAttrs, serverCurrentTime);
}
self.from_time_utc(formModelAttrs.from_time_utc);
self.to_time_utc(formModelAttrs.to_time_utc);
queryReqObj['formModelAttrs'] = formModelAttrs;
queryReqObj.queryId = qeUtils.generateQueryUUID();
queryReqObj.engQueryStr = qeUtils.getEngQueryStr(formModelAttrs);
queryReqObj = $.extend(true, self.defaultQueryReqConfig, queryReqObj, customQueryReqObj)
return queryReqObj;
},
reset: function (data, event, resetTR, resetTable) {
if(resetTR) {
this.time_range(600);
}
if(resetTable) {
this.table_name('');
}
this.time_granularity(60);
this.time_granularity_unit('secs');
this.select('');
this.where('');
this.direction('1');
this.filters('');
this.select_data_object().reset(this);
this.model().get('where_or_clauses').reset();
this.model().get('filter_and_clauses').reset();
},
addNewOrClauses: function(orClauseObject) {
var self = this,
whereOrClauses = this.model().get('where_or_clauses'),
newOrClauses = [];
$.each(orClauseObject, function(orClauseKey, orClauseValue) {
newOrClauses.push(new QueryOrModel(self, orClauseValue));
});
whereOrClauses.add(newOrClauses);
},
addNewFilterAndClause: function(andClauseObject) {
var self = this,
filterObj = andClauseObject.filter,
limitObj = andClauseObject.limit,
sortByArr = andClauseObject.sort_fields,
sortOrderStr = andClauseObject.sort_order,
filterAndClauses = this.model().attributes.filter_and_clauses;
if(contrail.checkIfExist(filterObj)) {
$.each(filterObj, function(filterObjKey, filterObjValue) {
var modelDataObj = {
name : filterObjValue.name,
operator: filterObjValue.op,
value : filterObjValue.value
};
var newAndClause = new QueryAndModel(self.model().attributes, modelDataObj);
filterAndClauses.add(newAndClause);
});
}
if(contrail.checkIfExist(limitObj)) {
this.limit(limitObj);
}
if(contrail.checkIfExist(sortOrderStr)) {
this.sort_order(sortOrderStr);
}
if(contrail.checkIfExist(sortByArr) && sortByArr.length > 0) {
this.sort_by(sortByArr);
}
},
addFilterAndClause: function() {
var andClauses = this.model().get('filter_and_clauses'),<|fim▁hole|> isSuffixVisible: function(name) {
var whereDataObject = this.model().get('where_data_object');
name = contrail.checkIfFunction(name) ? name() : name;
return (qeUtils.getNameSuffixKey(name, whereDataObject['name_option_list']) != -1);
},
getTimeGranularityUnits: function() {
var self = this;
return Knockout.computed(function () {
var timeRange = self.time_range(),
fromTime = new Date(self.from_time()).getTime(),
toTime = new Date(self.to_time()).getTime(),
timeGranularityUnits = [];
timeGranularityUnits.push({id: "secs", text: "secs"});
if (timeRange == -1) {
timeRange = (toTime - fromTime) / 1000;
}
if (timeRange > 60) {
timeGranularityUnits.push({id: "mins", text: "mins"});
}
if (timeRange > 3600) {
timeGranularityUnits.push({id: "hrs", text: "hrs"});
}
if (timeRange > 86400) {
timeGranularityUnits.push({id: "days", text: "days"});
}
return timeGranularityUnits;
}, this);
},
validations: {
runQueryValidation: {
table_type: {
required: true,
msg: window.cowm.getRequiredMessage('table type'),
},
table_name: {
required: true,
msg: window.cowm.getRequiredMessage('table name'),
},
select: {
required: true,
msg: window.cowm.getRequiredMessage('select'),
},
from_time: function(value) {
var fromTime = new Date(value).getTime(),
toTime = new Date(this.attributes.to_time).getTime(),
timeRange = this.attributes.time_range;
if(fromTime > toTime && timeRange == -1) {
return window.cowm.FROM_TIME_SMALLER_THAN_TO_TIME;
}
},
to_time: function(value) {
var toTime = new Date(value).getTime(),
fromTime = new Date(this.attributes.from_time).getTime(),
timeRange = this.attributes.time_range;
if (toTime < fromTime && timeRange == -1) {
return window.cowm.TO_TIME_GREATER_THAN_FROM_TIME;
}
}
}
},
getDataModel: function (p) {
var self = this,
currQuery = JSON.stringify(this.toJSON()), // TOOD: modify this to use hashcode based on this.toJSON()
queryResultPostData = {};
// reset data model on query change
if (_.isUndefined(self.loader) || (currQuery !== self._lastQuery)) {
queryResultPostData = self.getQueryRequestPostData(+new Date);
// config changes to prevent query to be queued
delete queryResultPostData.queryId;
queryResultPostData.async = false;
self.loader = new ContrailListModel({
remote: {
ajaxConfig: {
url: "/api/qe/query",
type: "POST",
data: JSON.stringify(queryResultPostData),
dataFilter:function(data){
return data;
}
},
dataParser: function (response) {
return response.data;
},
},
});
self._lastQuery = currQuery;
}
return self.loader;
},
refresh: function () {
var self = this;
self.loader = undefined;
}
});
function getTableSchemaConfig(model, tableName, disableFieldArray, disableSubstringArray, disableWhereFields) {
var tableSchemeUrl = '/api/qe/table/schema/' + tableName,
modelRemoteDataConfig = {
remote: {
ajaxConfig: {
url: tableSchemeUrl,
type: 'GET'
},
setData2Model: function (contrailViewModel, response) {
var selectFields = getSelectFields4Table(response, disableFieldArray, disableSubstringArray),
whereFields = getWhereFields4NameDropdown(response, tableName, disableWhereFields);
model.select_data_object().requestState((selectFields.length > 0) ? cowc.DATA_REQUEST_STATE_SUCCESS_NOT_EMPTY : cowc.DATA_REQUEST_STATE_SUCCESS_EMPTY);
contrailViewModel.set({
'ui_added_parameters': {
'table_schema': response,
'table_schema_column_names_map' : getTableSchemaColumnMap(response)
}
});
setEnable4SelectFields(selectFields, model.select_data_object().enable_map());
setChecked4SelectFields(selectFields, model.select_data_object().checked_map());
model.select_data_object().select_fields(selectFields);
contrailViewModel.attributes.where_data_object['name_option_list'] = whereFields;
}
},
vlRemoteConfig: {
vlRemoteList: []
}
};
return modelRemoteDataConfig;
};
function getTableSchemaColumnMap (tableSchema) {
if (_.isEmpty(tableSchema)) {
return {};
}
var tableSchemaColumnMapObj = {},
cols = tableSchema.columns;
for(var i = 0; i < cols.length; i++) {
var colName = cols[i]["name"];
tableSchemaColumnMapObj[colName] = cols[i];
}
return tableSchemaColumnMapObj;
};
function getSelectFields4Table(tableSchema, disableFieldArray, disableSubstringArray) {
if (_.isEmpty(tableSchema)) {
return [];
}
var tableColumns = tableSchema['columns'],
filteredSelectFields = [];
$.each(tableColumns, function (k, v) {
if (contrail.checkIfExist(v) && showSelectField(v.name, disableFieldArray, disableSubstringArray)) {
filteredSelectFields.push(v);
}
});
_.sortBy(filteredSelectFields, 'name');
return filteredSelectFields;
};
function showSelectField(fieldName, disableFieldArray, disableSubstringArray) {
var showField = true;
for (var i = 0; i < disableSubstringArray.length; i++) {
if(fieldName.indexOf(disableSubstringArray[i]) != -1) {
showField = false;
break;
}
}
if(disableFieldArray.indexOf(fieldName) != -1) {
showField = false;
}
return showField;
};
function getWhereFields4NameDropdown(tableSchema, tableName, disableWhereFields) {
if (_.isEmpty(tableSchema)) {
return [];
}
var tableSchemaFormatted = [];
$.each(tableSchema.columns, function(schemaKey, schemaValue) {
if (schemaValue.index && disableWhereFields.indexOf(schemaValue.name) == -1){
if (tableName === 'FlowSeriesTable' || tableName === 'FlowRecordTable') {
if (schemaValue.name === 'protocol') {
schemaValue.suffixes = ['sport', 'dport'];
tableSchemaFormatted.push(schemaValue);
} else if (schemaValue.name === 'sourcevn') {
schemaValue.suffixes = ['sourceip'];
tableSchemaFormatted.push(schemaValue);
} else if (schemaValue.name === 'destvn') {
schemaValue.suffixes = ['destip'];
tableSchemaFormatted.push(schemaValue);
} else if (schemaValue.name === 'vrouter') {
tableSchemaFormatted.push(schemaValue);
} else {
schemaValue.index = false;
}
} else {
tableSchemaFormatted.push(schemaValue);
}
}
});
return tableSchemaFormatted
}
function setEnable4SelectFields(selectFields, isEnableMap) {
for (var key in isEnableMap) {
delete isEnableMap[key];
}
for (var i = 0; i < selectFields.length; i++) {
isEnableMap[selectFields[i]['name']] = ko.observable(true);
}
}
function setChecked4SelectFields(selectFields, checkedMap) {
var selectFieldsGroups = {};
_.each(cowc.SELECT_FIELDS_GROUPS, function(fieldGroupValue, fieldGroupKey) {
selectFieldsGroups[fieldGroupValue] = [];
});
for (var key in checkedMap) {
delete checkedMap[key];
}
_.each(selectFields, function(selectFieldValue, selectFieldKey) {
var key = selectFieldValue.name,
aggregateType = cowl.getFirstCharUpperCase(key.substring(0, key.indexOf('(')));
if(key == 'T' || key == 'T=' ){
selectFieldsGroups["Time Range"].push(key);
aggregateType = "Time Range";
} else if(aggregateType == ''){
selectFieldsGroups["Non Aggregate"].push(key);
aggregateType = "Non Aggregate";
} else {
selectFieldsGroups[aggregateType].push(key);
}
selectFieldValue['aggregate_type'] = cowl.getFirstCharUpperCase(aggregateType);
});
_.each(selectFieldsGroups, function(aggregateFields, aggregateKey) {
_.each(aggregateFields, function(fieldValue, fieldKey) {
checkedMap[fieldValue] = ko.observable(false);
});
});
}
return QueryFormModel;
});<|fim▁end|>
|
newAndClause = new QueryAndModel(this.model().attributes);
andClauses.add([newAndClause]);
},
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.<|fim▁hole|>mod bloom;
mod bloom_group;
mod group_position;
pub use self::bloom::Bloom;
pub use self::bloom_group::BloomGroup;
pub use self::group_position::GroupPosition;<|fim▁end|>
|
//! Bridge between bloomchain crate types and ethcore.
|
<|file_name|>SegmentHandler.java<|end_file_name|><|fim▁begin|>package com.cmput402w2016.t1.webapi.handler;
import com.cmput402w2016.t1.data.Segment;
import com.cmput402w2016.t1.webapi.Helper;
import com.cmput402w2016.t1.webapi.WebApi;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.util.Map;
/**
* Handler for the /segment webservice route
*/
public class SegmentHandler implements HttpHandler {
/**
* Handle the web request to the server
*
* @param httpExchange HttpExchange object containing the request
*/
@Override
public void handle(HttpExchange httpExchange) {
// Get & parse query<|fim▁hole|> String requestMethod = httpExchange.getRequestMethod();
if (requestMethod.equalsIgnoreCase("GET")) {
String query = httpExchange.getRequestURI().getRawQuery();
Map<String, String> stringStringMap = Helper.queryToMap(query);
if (stringStringMap.containsKey("geohash")) {
String geohash = stringStringMap.get("geohash");
String neighbors = Segment.getClosestSegmentFromGeohash(geohash, WebApi.get_segment_table());
Helper.requestResponse(httpExchange, 200, neighbors);
httpExchange.close();
return;
} else if (stringStringMap.containsKey("lat") && stringStringMap.containsKey("lon")) {
String lat = stringStringMap.get("lat");
String lon = stringStringMap.get("lon");
String neighbors = Segment.getClosestSegmentFromLatLon(lat, lon, WebApi.get_segment_table());
Helper.requestResponse(httpExchange, 200, neighbors);
httpExchange.close();
return;
}
}
Helper.malformedRequestResponse(httpExchange, 400, "Invalid query to the segment api");
httpExchange.close();
} catch (Exception e) {
// Wasn't returned earlier, something must be wrong
e.printStackTrace();
Helper.malformedRequestResponse(httpExchange, 400, e.getMessage());
httpExchange.close();
}
}
}<|fim▁end|>
|
try {
|
<|file_name|>user_context.go<|end_file_name|><|fim▁begin|>/*
Copyright 2015 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.
*/
package main
import (
"fmt"
"strings"
"time"
"github.com/coreos/go-oidc/jose"
"github.com/coreos/go-oidc/oidc"
)
// extractIdentity parse the jwt token and extracts the various elements is order to construct
func extractIdentity(token jose.JWT) (*userContext, error) {
claims, err := token.Claims()
if err != nil {
return nil, err
}
identity, err := oidc.IdentityFromClaims(claims)
if err != nil {
return nil, err
}
// step: ensure we have and can extract the preferred name of the user, if not, we set to the ID
preferredName, found, err := claims.StringClaim(claimPreferredName)
if err != nil || !found {
preferredName = identity.Email
}
audience, found, err := claims.StringClaim(claimAudience)
if err != nil || !found {
return nil, ErrNoTokenAudience
}
// step: extract the realm roles
var list []string
if realmRoles, found := claims[claimRealmAccess].(map[string]interface{}); found {
if roles, found := realmRoles[claimResourceRoles]; found {
for _, r := range roles.([]interface{}) {
list = append(list, fmt.Sprintf("%s", r))
}
}
}
// step: extract the client roles from the access token
if accesses, found := claims[claimResourceAccess].(map[string]interface{}); found {
for roleName, roleList := range accesses {
scopes := roleList.(map[string]interface{})
if roles, found := scopes[claimResourceRoles]; found {
for _, r := range roles.([]interface{}) {
list = append(list, fmt.Sprintf("%s:%s", roleName, r))
}
}
}
}
return &userContext{
id: identity.ID,
name: preferredName,
audience: audience,
preferredName: preferredName,
email: identity.Email,
expiresAt: identity.ExpiresAt,
roles: list,
token: token,
claims: claims,
}, nil
}
// isAudience checks the audience
func (r *userContext) isAudience(aud string) bool {
return r.audience == aud
}
// getRoles returns a list of roles
func (r *userContext) getRoles() string {
return strings.Join(r.roles, ",")
}
// isExpired checks if the token has expired
func (r *userContext) isExpired() bool {
return r.expiresAt.Before(time.Now())
}
// isBearer checks if the token
func (r *userContext) isBearer() bool {<|fim▁hole|> return r.bearerToken
}
// isCookie checks if it's by a cookie
func (r *userContext) isCookie() bool {
return !r.isBearer()
}
// String returns a string representation of the user context
func (r *userContext) String() string {
return fmt.Sprintf("user: %s, expires: %s, roles: %s", r.preferredName, r.expiresAt.String(), strings.Join(r.roles, ","))
}<|fim▁end|>
| |
<|file_name|>megacoin_zh_TW.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="zh_TW">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+26"/>
<source>Dialog</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+125"/>
<source>Information about program</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+91"/>
<source><b>Megacoin</b> version</source>
<translation><b>美卡幣</b>版本</translation>
</message>
<message>
<location line="+170"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>
這是一套實驗性的軟體.
此軟體是依據 MIT/X11 軟體授權條款散布, 詳情請見附帶的 COPYING 檔案, 或是以下網站: http://www.opensource.org/licenses/mit-license.php.
此產品也包含了由 OpenSSL Project 所開發的 OpenSSL Toolkit (http://www.openssl.org/) 軟體, 由 Eric Young ([email protected]) 撰寫的加解密軟體, 以及由 Thomas Bernard 所撰寫的 UPnP 軟體.</translation>
</message>
<message>
<location line="+105"/>
<source>OK</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+21"/>
<source>Copyright</source>
<translation>版權</translation>
</message>
<message>
<location line="+0"/>
<source>Dr. Kimoto Chan</source>
<translation>美卡幣開發人員</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+159"/>
<location line="+137"/>
<source>Address Book</source>
<translation>位址簿</translation>
</message>
<message>
<location line="+48"/>
<source>Double-click to edit address or label</source>
<translation>點兩下來修改位址或標記</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+74"/>
<source>&Copy Address</source>
<translation>複製位址</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+219"/>
<source>Show &QR Code</source>
<translation>顯示 &QR 條碼</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+4"/>
<source>Sign &Message</source>
<translation>訊息簽署</translation>
</message>
<message>
<location line="+1"/>
<source>&Verify Message</source>
<translation>訊息驗證</translation>
</message>
<message>
<location line="+1"/>
<source>&Delete</source>
<translation>刪除</translation>
</message>
<message>
<location line="-5"/>
<source>Copy &Label</source>
<translation>複製標記</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>編輯</translation>
</message>
<message>
<location line="-10"/>
<source>Adress for receiving Megacoins</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+272"/>
<source>Export Address Book Data</source>
<translation>匯出位址簿資料</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>逗號區隔資料檔 (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>匯出失敗</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>無法寫入檔案 %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+146"/>
<source>Label</source>
<translation>標記</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>位址</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(沒有標記)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>密碼對話視窗</translation>
</message>
<message>
<location line="+162"/>
<source>Change password</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+111"/>
<source>Enter passphrase</source>
<translation>輸入密碼</translation>
</message>
<message>
<location line="+27"/>
<source>New passphrase</source>
<translation>新的密碼</translation>
</message>
<message>
<location line="+27"/>
<source>Repeat new passphrase</source>
<translation>重複新密碼</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+38"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>輸入錢包的新密碼.<br/>請用<b>10個以上的字元</b>, 或是<b>8個以上的單字</b>.</translation>
</message>
<message>
<location line="+1"/>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>錢包加密</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>這個動作需要用你的錢包密碼來解鎖</translation>
</message>
<message>
<location line="+6"/>
<location line="+1"/>
<source>Unlock wallet</source>
<translation>錢包解鎖</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>這個動作需要用你的錢包密碼來解密</translation>
</message>
<message>
<location line="+6"/>
<location line="+1"/>
<source>Decrypt wallet</source>
<translation>錢包解密</translation>
</message>
<message>
<location line="+4"/>
<location line="+1"/>
<source>Change passphrase</source>
<translation>變更密碼</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>輸入錢包的新舊密碼.</translation>
</message>
<message>
<location line="+50"/>
<source>Confirm wallet encryption</source>
<translation>錢包加密確認</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR MEGACOINS</b>!</source>
<translation>警告: 如果將錢包加密後忘記密碼, 你會<b>失去其中所有的美卡幣</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>你確定要將錢包加密嗎?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>重要: 請改用新產生有加密的錢包檔, 來取代之前錢包檔的備份. 為了安全性的理由, 當你開始使用新的有加密的錢包時, 舊錢包的備份就不能再使用了.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>警告: 大寫字母鎖定作用中!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>錢包已加密</translation>
</message>
<message>
<location line="-56"/>
<source>Megacoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your megacoins from being stolen by malware infecting your computer.</source>
<translation>美卡幣現在要關閉以完成加密程序. 請記住, 加密錢包無法完全防止入侵電腦的惡意程式偷取你的美卡幣.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>錢包加密失敗</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>錢包加密因程式內部錯誤而失敗. 你的錢包還是沒有加密.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>提供的密碼不符.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>錢包解鎖失敗</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>用來解密錢包的密碼輸入錯誤.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>錢包解密失敗</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>錢包密碼變更成功.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>網路警報</translation>
</message>
<message>
<location line="+16"/>
<source>Incoming News</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+171"/>
<source>Edit record</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+89"/>
<source>&Label</source>
<translation>標記</translation>
</message>
<message>
<location line="+78"/>
<source>The label associated with this address book entry</source>
<translation>與這個位址簿項目關聯的標記</translation>
</message>
<message>
<location line="+14"/>
<source>&Address</source>
<translation>位址</translation>
</message>
<message>
<location line="+25"/>
<source>Paste from clipboard</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+24"/>
<source>Alt+A</source>
<translation type="unfinished">Alt+A</translation>
</message>
<message>
<location line="-122"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>與這個位址簿項目關聯的位址. 付款位址才能被更改.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+26"/>
<location line="+1"/>
<source>New receiving address</source>
<translation>新收款位址</translation>
</message>
<message>
<location line="+7"/>
<location line="+1"/>
<source>New sending address</source>
<translation>新增付款位址</translation>
</message>
<message>
<location line="+5"/>
<location line="+1"/>
<source>Edit receiving address</source>
<translation>編輯收款位址</translation>
</message>
<message>
<location line="+7"/>
<location line="+1"/>
<source>Edit sending address</source>
<translation>編輯付款位址</translation>
</message>
<message>
<location line="+81"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>輸入的位址"%1"已存在於位址簿中.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Megacoin address.</source>
<translation>輸入的位址 "%1" 並不是有效的美卡幣位址.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>無法將錢包解鎖.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>新密鑰產生失敗.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+442"/>
<location line="+12"/>
<source>Megacoin-Qt</source>
<translation>美卡幣-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>版本</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>用法:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>命令列選項</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>使用界面選項</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>設定語言, 比如說 "de_DE" (預設: 系統語系)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>啓動時最小化
</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>顯示啓動畫面 (預設: 1)</translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../forms/mainwindow.ui" line="+19"/>
<source>MainWindow</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+266"/>
<source>Messages from Megacoin</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+85"/>
<source>Megacoin</source>
<translation type="unfinished">美卡幣</translation>
</message>
<message>
<location line="+17"/>
<source>global wallet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+51"/>
<source>File</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+52"/>
<source>Operations</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+52"/>
<source>Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+156"/>
<source><html><head/><body><p>Welcome to Megacoin. This is your personal account</p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+62"/>
<source>Overview</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+110"/>
<source>Mining</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+53"/>
<source>Send Coins</source>
<translation type="unfinished">付錢</translation>
</message>
<message>
<location line="+47"/>
<source>Transactions</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+47"/>
<source>Sign Message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+47"/>
<source>Receive Coins</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+47"/>
<source>Address Book</source>
<translation type="unfinished">位址簿</translation>
</message>
<message>
<location line="+47"/>
<source>Verify Message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+200"/>
<source>Synchronization</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+45"/>
<source>10549874 blocks</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>MegacoinGUI</name>
<message>
<location filename="../megacoingui.cpp" line="+366"/>
<location line="+753"/>
<source>Sign &message...</source>
<translation>訊息簽署...</translation>
</message>
<message>
<location line="-487"/>
<source>Synchronizing with network...</source>
<translation>網路同步中...</translation>
</message>
<message>
<location line="-343"/>
<location line="+780"/>
<source>&Overview</source>
<translation>總覽</translation>
</message>
<message>
<location line="-779"/>
<source>Show general overview of wallet</source>
<translation>顯示錢包一般總覽</translation>
</message>
<message>
<location line="+20"/>
<location line="+804"/>
<source>&Transactions</source>
<translation>交易</translation>
</message>
<message>
<location line="-803"/>
<source>Browse transaction history</source>
<translation>瀏覽交易紀錄</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>編輯位址與標記的儲存列表</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>顯示收款位址的列表</translation>
</message>
<message>
<location line="-8"/>
<source>&Send coins</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<source>&Receive coins</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+14"/>
<location line="+798"/>
<source>&Address Book</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-778"/>
<location line="+735"/>
<source>E&xit</source>
<translation>結束</translation>
</message>
<message>
<location line="-734"/>
<source>Quit application</source>
<translation>結束應用程式</translation>
</message>
<message>
<location line="+7"/>
<source>Show information about Megacoin</source>
<translation>顯示美卡幣相關資訊</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>關於 &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>顯示有關於 Qt 的資訊</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>選項...</translation>
</message>
<message>
<location line="+9"/>
<location line="+757"/>
<source>&Encrypt Wallet...</source>
<translation>錢包加密...</translation>
</message>
<message>
<location line="-754"/>
<source>&Backup Wallet...</source>
<translation>錢包備份...</translation>
</message>
<message>
<location line="+2"/>
<location line="+754"/>
<source>&Change Passphrase...</source>
<translation>密碼變更...</translation>
</message>
<message>
<location line="-747"/>
<location line="+700"/>
<source>&Export...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-699"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished">將目前分頁的資料匯出存成檔案</translation>
</message>
<message>
<location line="+59"/>
<source>Actions toolbar</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+204"/>
<source>Importing blocks from disk...</source>
<translation>從磁碟匯入區塊中...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>重建磁碟區塊索引中...</translation>
</message>
<message>
<location line="-341"/>
<source>Send coins to a Megacoin address</source>
<translation>付錢到美卡幣位址</translation>
</message>
<message>
<location line="+54"/>
<source>Modify configuration options for Megacoin</source>
<translation>修改美卡幣的設定選項</translation>
</message>
<message>
<location line="+12"/>
<source>Backup wallet to another location</source>
<translation>將錢包備份到其它地方</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>變更錢包加密用的密碼</translation>
</message>
<message>
<location line="+9"/>
<location line="+800"/>
<source>&Debug window</source>
<translation>除錯視窗</translation>
</message>
<message>
<location line="-799"/>
<source>Open debugging and diagnostic console</source>
<translation>開啓除錯與診斷主控台</translation>
</message>
<message>
<location line="-7"/>
<location line="+752"/>
<source>&Verify message...</source>
<translation>驗證訊息...</translation>
</message>
<message>
<location line="-1014"/>
<location line="+6"/>
<location line="+619"/>
<source>Megacoin</source>
<translation>美卡幣</translation>
</message>
<message>
<location line="-625"/>
<location line="+6"/>
<source>Wallet</source>
<translation>錢包</translation>
</message>
<message>
<location line="+230"/>
<location line="+2"/>
<location line="+831"/>
<source>&About Megacoin</source>
<translation>關於美卡幣</translation>
</message>
<message>
<location line="-821"/>
<location line="+2"/>
<source>&Show / Hide</source>
<translation>顯示或隱藏</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>顯示或隱藏主視窗</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>將屬於你的錢包的密鑰加密</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Megacoin addresses to prove you own them</source>
<translation>用美卡幣位址簽署訊息來證明那是你的</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Megacoin addresses</source>
<translation>驗證訊息來確認是用指定的美卡幣位址簽署的</translation>
</message>
<message>
<location line="+31"/>
<source>&File</source>
<translation>檔案</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>設定</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>求助</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>分頁工具列</translation>
</message>
<message>
<location line="-311"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+385"/>
<source>Megacoin client</source>
<translation>美卡幣客戶端軟體</translation>
</message>
<message numerus="yes">
<location line="+109"/>
<source>%n active connection(s) to Megacoin network</source>
<translation>
<numerusform>與美卡幣網路有 %n 個連線在使用中</numerusform>
</translation>
</message>
<message>
<location line="+57"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>已處理了 %1 個區塊的交易紀錄.</translation>
</message>
<message>
<location line="+77"/>
<source>Error</source>
<translation>錯誤</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>警告</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>資訊</translation>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>這筆交易的資料大小超過限制了. 你還是可以付出 %1 的費用來傳送, 這筆費用會付給處理你的交易的節點, 並幫助維持整個網路. 你願意支付這項費用嗎?</translation>
</message>
<message>
<location line="-121"/>
<source>Up to date</source>
<translation>最新狀態</translation>
</message>
<message numerus="yes">
<location line="-47"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished">
<numerusform></numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n blocks</source>
<translation type="unfinished">
<numerusform></numerusform>
</translation>
</message>
<message>
<location line="+3"/>
<source>Processed %1 of %2 blocks of transaction history (%3% done).</source>
<translation type="unfinished"></translation>
</message>
<message numerus="yes">
<location line="+22"/>
<source>%n second(s) ago</source>
<translation type="unfinished">
<numerusform></numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s) ago</source>
<translation type="unfinished">
<numerusform></numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished">
<numerusform></numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation type="unfinished">
<numerusform></numerusform>
</translation>
</message>
<message>
<location line="+13"/>
<source>Catching up...</source>
<translation>進度追趕中...</translation>
</message>
<message>
<location line="+16"/>
<source>Last received block was generated %1.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+102"/>
<source>Confirm transaction fee</source>
<translation>確認交易手續費</translation>
</message>
<message>
<location line="+38"/>
<source>Sent transaction</source>
<translation>付款交易</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>收款交易</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>日期: %1
金額: %2
類別: %3
位址: %4</translation>
</message>
<message>
<location line="+123"/>
<location line="+80"/>
<source>URI handling</source>
<translation>URI 處理</translation>
</message>
<message>
<location line="-80"/>
<location line="+80"/>
<source>URI can not be parsed! This can be caused by an invalid Megacoin address or malformed URI parameters.</source>
<translation>無法解析 URI! 也許美卡幣位址無效或 URI 參數有誤.</translation>
</message>
<message>
<location line="+8"/>
<source>Service messages</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+42"/>
<source>Send Megacoins</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Receive Megacoins</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+4"/>
<source>Mining</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+56"/>
<source>Common, Network</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+38"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>錢包<b>已加密</b>並且正<b>解鎖中</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>錢包<b>已加密</b>並且正<b>上鎖中</b></translation>
</message>
<message>
<location line="+23"/>
<source>Backup Wallet</source>
<translation type="unfinished">錢包備份</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished">錢包資料檔 (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished">備份失敗</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished">儲存錢包資料到新的地方失敗</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished">備份成功</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished">錢包的資料已經成功儲存到新的地方了.</translation>
</message>
<message>
<location filename="../megacoin.cpp" line="+109"/>
<source>A fatal error occurred. Megacoin can no longer continue safely and will quit.</source>
<translation>發生了致命的錯誤. 美卡幣程式無法再繼續安全執行, 只好結束.</translation>
</message>
</context>
<context>
<name>MessageBoxDialog</name>
<message>
<location filename="../forms/message_box_dialog.ui" line="+374"/>
<source>OK</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+82"/>
<source>Yes</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+51"/>
<source>No</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+76"/>
<source>Don't show again</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>MiningPage</name>
<message>
<location filename="../forms/miningpage.ui" line="+159"/>
<source>Form</source>
<translation type="unfinished">表單</translation>
</message>
<message>
<location line="+107"/>
<source>Mining coins</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+378"/>
<source>Stop</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+38"/>
<source>Start</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../miningpage.cpp" line="+66"/>
<source>Mining coins started!</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Used threads %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Mining coins stopped!</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+46"/>
<source>Running mining coins...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<source>Start error!</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+11"/>
<source>Stop mining coins...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<source>Stop error!</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>選項</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>主要</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation>非必要的交易手續費, 以 kB 為計費單位, 且有助於縮短你的交易處理時間. 大部份交易資料的大小是 1 kB.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>付交易手續費</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Megacoin after logging in to the system.</source>
<translation>在登入系統後自動啓動美卡幣.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Megacoin on system login</source>
<translation>系統登入時啟動美卡幣</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>回復所有客戶端軟體選項成預設值.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>選項回復</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>網路</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Megacoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>自動在路由器上開啟 Megacoin 的客戶端通訊埠. 只有在你的路由器支援 UPnP 且開啟時才有作用.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>用 &UPnP 設定通訊埠對應</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Megacoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>透過 SOCKS 代理伺服器連線至美卡幣網路 (比如說要透過 Tor 連線).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>透過 SOCKS 代理伺服器連線:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>代理伺服器位址:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>代理伺服器的網際網路位址 (比如說 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>通訊埠:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>代理伺服器的通訊埠 (比如說 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS 協定版本:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>代理伺服器的 SOCKS 協定版本 (比如說 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>視窗</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>最小化視窗後只在通知區域顯示圖示</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>最小化至通知區域而非工作列</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>當視窗關閉時將其最小化, 而非結束應用程式. 當勾選這個選項時, 應用程式只能用選單中的結束來停止執行.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>關閉時最小化</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>顯示</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>使用界面語言</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Megacoin.</source>
<translation>可以在這裡設定使用者介面的語言. 這個設定在美卡幣程式重啓後才會生效.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>金額顯示單位:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>選擇操作界面與付錢時預設顯示的細分單位.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Megacoin addresses in the transaction list or not.</source>
<translation>是否要在交易列表中顯示美卡幣位址.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>在交易列表顯示位址</translation>
</message>
<message>
<location line="+21"/>
<source>Mining</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+9"/>
<source>&Start mining Megacoins on application start</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>好</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>取消</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>套用</translation>
</message>
<message>
<location filename="../optionspage.cpp" line="+56"/>
<source>default</source>
<translation>預設</translation>
</message>
<message>
<location line="+43"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Fee 0.01 recommended.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+112"/>
<source>Confirm options reset</source>
<translation>確認回復選項</translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>有些設定可能需要重新啓動客戶端軟體才會生效.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>你想要就做下去嗎?</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>警告</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Megacoin.</source>
<translation>這個設定會在美卡幣程式重啓後生效.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>提供的代理伺服器位址無效</translation>
</message>
</context>
<context>
<name>OptionsPage</name>
<message>
<location filename="../forms/optionspage.ui" line="+159"/>
<source>Form</source>
<translation type="unfinished">表單</translation>
</message>
<message>
<location line="+110"/>
<source>Common settings, Network</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+103"/>
<source>Common</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+29"/>
<source>Automatically start Megacoin after logging in to the system.</source>
<translation type="unfinished">在登入系統後自動啓動美卡幣.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Megacoin on system login</source>
<translation type="unfinished">系統登入時啟動美卡幣</translation>
</message>
<message>
<location line="+17"/>
<source>&Start mining megacoins on start application</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+14"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished">最小化視窗後只在通知區域顯示圖示</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished">最小化至通知區域而非工作列</translation>
</message>
<message>
<location line="+14"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished">當視窗關閉時將其最小化, 而非結束應用程式. 當勾選這個選項時, 應用程式只能用選單中的結束來停止執行.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished">關閉時最小化</translation>
</message>
<message>
<location line="+17"/>
<source>&Allow sounds</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+20"/>
<source>&Check updates at startup</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+36"/>
<source>Display</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+60"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished">金額顯示單位:</translation>
</message>
<message>
<location line="+18"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished">選擇操作界面與付錢時預設顯示的細分單位.</translation>
</message>
<message>
<location line="+45"/>
<source>User Interface &language:</source>
<translation type="unfinished">使用界面語言</translation>
</message>
<message>
<location line="+31"/>
<source>The user interface language can be set here. This setting will take effect after restarting Megacoin.</source>
<translation type="unfinished">可以在這裡設定使用者介面的語言. 這個設定在美卡幣程式重啓後才會生效.</translation>
</message>
<message>
<location line="+17"/>
<source>Whether to show Megacoin addresses in the transaction list or not.</source>
<translation type="unfinished">是否要在交易列表中顯示美卡幣位址.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished">在交易列表顯示位址</translation>
</message>
<message>
<location line="+59"/>
<source>Pay transaction fee</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+56"/>
<source>Network</source>
<translation type="unfinished">網路</translation>
</message>
<message>
<location line="+32"/>
<source>Automatically open the Megacoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished">自動在路由器上開啟 Megacoin 的客戶端通訊埠. 只有在你的路由器支援 UPnP 且開啟時才有作用.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished">用 &UPnP 設定通訊埠對應</translation>
</message>
<message>
<location line="+23"/>
<source>Connect to the Megacoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished">透過 SOCKS 代理伺服器連線至美卡幣網路 (比如說要透過 Tor 連線).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished">透過 SOCKS 代理伺服器連線:</translation>
</message>
<message>
<location line="+42"/>
<source>Proxy &IP:</source>
<translation type="unfinished">代理伺服器位址:</translation>
</message>
<message>
<location line="+27"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished">代理伺服器的網際網路位址 (比如說 127.0.0.1)</translation>
</message>
<message>
<location line="+30"/>
<source>&Port:</source>
<translation type="unfinished">通訊埠:</translation>
</message>
<message>
<location line="+27"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished">代理伺服器的通訊埠 (比如說 9050)</translation>
</message>
<message>
<location line="+48"/>
<source>SOCKS &Version:</source>
<translation type="unfinished">SOCKS 協定版本:</translation>
</message>
<message>
<location line="+33"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished">代理伺服器的 SOCKS 協定版本 (比如說 5)</translation>
</message>
<message>
<location line="+128"/>
<source>Reset all client options to default.</source>
<translation type="unfinished">回復所有客戶端軟體選項成預設值.</translation>
</message>
<message>
<location line="+22"/>
<source>&Reset Options</source>
<translation type="unfinished">選項回復</translation>
</message>
<message>
<location line="+51"/>
<source>&Apply</source>
<translation type="unfinished">套用</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+159"/>
<source>Form</source>
<translation>表單</translation>
</message>
<message>
<location line="+128"/>
<source>Account status</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+35"/>
<location line="+46"/>
<location line="+46"/>
<source>0 Lrks</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+64"/>
<source>Balance:</source>
<translation>餘額:</translation>
</message>
<message>
<location line="+47"/>
<source>Unconfirmed:</source>
<translation>未確認額:</translation>
</message>
<message>
<location line="+175"/>
<source>Last transactions</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-128"/>
<source>Immature:</source>
<translation>未熟成</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+110"/>
<source>Cannot start megacoin: click-to-pay handler</source>
<translation>無法啟動 megacoin 隨按隨付處理器</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR 條碼對話視窗</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>付款單</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>金額:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>標記:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>訊息:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>儲存為...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+64"/>
<source>Error encoding URI into QR Code.</source>
<translation>將 URI 編碼成 QR 條碼失敗</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>輸入的金額無效, 請檢查看看.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>造出的網址太長了,請把標籤或訊息的文字縮短再試看看.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>儲存 QR 條碼</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG 圖檔 (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>客戶端軟體名稱</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+365"/>
<source>N/A</source>
<translation>無</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>客戶端軟體版本</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>資訊</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>使用 OpenSSL 版本</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>啓動時間</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>網路</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>連線數</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>位於測試網路</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>區塊鎖鏈</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>目前區塊數</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>估計總區塊數</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>最近區塊時間</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>開啓</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>命令列選項</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Megacoin-Qt help message to get a list with possible Megacoin command-line options.</source>
<translation>顯示美卡幣-Qt的求助訊息, 來取得可用的命令列選項列表.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>顯示</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>主控台</translation>
</message>
<message>
<location line="+72"/>
<source>Send network alert</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+5"/>
<source>Send news</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+22"/>
<source>Header</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+33"/>
<source>Tray</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+13"/>
<source>Text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+23"/>
<source>Date</source>
<translation type="unfinished">日期</translation>
</message>
<message>
<location line="+13"/>
<source>Expires On</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+33"/>
<source>ID</source>
<translation type="unfinished">識別碼</translation>
</message>
<message>
<location line="+13"/>
<source>Language</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+26"/>
<source>Signature</source>
<translation type="unfinished">簽章</translation>
</message>
<message>
<location line="+23"/>
<source>Send</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-536"/>
<source>Build date</source>
<translation>建置日期</translation>
</message>
<message>
<location line="-104"/>
<source>Megacoin - Debug window</source>
<translation>美卡幣 - 除錯視窗</translation>
</message>
<message>
<location line="+25"/>
<source>Megacoin Core</source>
<translation>美卡幣核心</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>除錯紀錄檔</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Megacoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>從目前的資料目錄下開啓美卡幣的除錯紀錄檔. 當紀錄檔很大時可能要花好幾秒的時間.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>清主控台</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Megacoin RPC console.</source>
<translation>歡迎使用美卡幣 RPC 主控台.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>請用上下游標鍵來瀏覽歷史指令, 且可用 <b>Ctrl-L</b> 來清理畫面.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>請打 <b>help</b> 來看可用指令的簡介.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+105"/>
<location filename="../sendcoinsdialog.cpp" line="+130"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>付錢</translation>
</message>
<message>
<location line="+278"/>
<source>Remove all transaction fields</source>
<translation>移除所有交易欄位</translation>
</message>
<message>
<location line="+22"/>
<source>Clear &All</source>
<translation>全部清掉</translation>
</message>
<message>
<location line="-75"/>
<source>Balance:</source>
<translation>餘額:</translation>
</message>
<message>
<location line="-115"/>
<source>Send Megacoins</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+137"/>
<source>123.456 MEC</source>
<translation>123.456 MEC</translation>
</message>
<message>
<location line="+75"/>
<source>Confirm the send action</source>
<translation>確認付款動作</translation>
</message>
<message>
<location line="+22"/>
<source>S&end</source>
<translation>付出</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-62"/>
<location line="+2"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> 給 %2 (%3)</translation>
</message>
<message>
<location line="+6"/>
<source>Confirm send coins</source>
<translation>確認要付錢</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>確定要付出 %1 嗎?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>和</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>無效的收款位址, 請再檢查看看.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>付款金額必須大於 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>金額超過餘額了.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>包含 %1 的交易手續費後, 總金額超過你的餘額了.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>發現有重複的位址. 每個付款動作中, 只能付給個別的位址一次.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>錯誤: 交易產生失敗!</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>錯誤: 交易被拒絕. 有時候會發生這種錯誤, 是因為你錢包中的一些錢已經被花掉了. 比如說你複製了錢包檔 wallet.dat, 然後用複製的錢包花掉了錢, 你現在所用的原來的錢包中卻沒有該筆交易紀錄.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+116"/>
<source>A&mount:</source>
<translation>金額:</translation>
</message>
<message>
<location line="-40"/>
<source>Pay &To:</source>
<translation>付給:</translation>
</message>
<message>
<location line="+86"/>
<source>The address to send the payment to (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>付款的目標位址 (比如說 MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="-13"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>輸入一個標記給這個位址, 並加到位址簿中</translation>
</message>
<message>
<location line="-53"/>
<source>&Label:</source>
<translation>標記:</translation>
</message>
<message>
<location line="+94"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished">一次付給多個人</translation>
</message>
<message>
<location line="+92"/>
<source>Choose address from address book</source>
<translation>從位址簿中選一個位址</translation>
</message>
<message>
<location line="-22"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-24"/>
<source>Paste address from clipboard</source>
<translation>從剪貼簿貼上位址</translation>
</message>
<message>
<location line="-22"/>
<location line="+92"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+22"/>
<source>Remove this recipient</source>
<translation>去掉這個收款人</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Megacoin address (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>輸入美卡幣位址 (比如說 MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
</context>
<context>
<name>ServiceMessagesPage</name>
<message>
<location filename="../forms/servicemessagespage.ui" line="+159"/>
<source>Form</source>
<translation type="unfinished">表單</translation>
</message>
<message>
<location line="+107"/>
<source>Messages from Megacoin</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+60"/>
<source>Date</source>
<translation type="unfinished">日期</translation>
</message>
<message>
<location line="+20"/>
<source>Message content</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../servicemessagespage.cpp" line="+33"/>
<source>17:56, 01.03.2012</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>SignMessagePage</name>
<message>
<location filename="../forms/signmessagepage.ui" line="+159"/>
<source>Form</source>
<translation type="unfinished">表單</translation>
</message>
<message>
<location line="+110"/>
<source>Sign Message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+73"/>
<source>Signature</source>
<translation type="unfinished">簽章</translation>
</message>
<message>
<location line="+25"/>
<source>Choose an address from the address book</source>
<translation type="unfinished">從位址簿選一個位址</translation>
</message>
<message>
<location line="+21"/>
<source>Alt+A</source>
<translation type="unfinished">Alt+A</translation>
</message>
<message>
<location line="+22"/>
<source>Paste address from clipboard</source>
<translation type="unfinished">從剪貼簿貼上位址</translation>
</message>
<message>
<location line="+21"/>
<source>Alt+P</source>
<translation type="unfinished">Alt+P</translation>
</message>
<message>
<location line="+22"/>
<source>Address</source>
<translation type="unfinished">位址</translation>
</message>
<message>
<location line="+24"/>
<source>The address to sign the message with (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished">用來簽署訊息的位址 (比如說 MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+22"/>
<source>Text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+18"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished">在這裡輸入你想簽署的訊息</translation>
</message>
<message>
<location line="+30"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished">複製目前的簽章到系統剪貼簿</translation>
</message>
<message>
<location line="+110"/>
<source>Reset all sign message fields</source>
<translation type="unfinished">重置所有訊息簽署欄位</translation>
</message>
<message>
<location line="+22"/>
<source>Clear &All</source>
<translation type="unfinished">全部清掉</translation>
</message>
<message>
<location line="+16"/>
<source>Sign the message to prove you own this Megacoin address</source>
<translation type="unfinished">簽署訊息是用來證明這個美卡幣位址是你的</translation>
</message>
<message>
<location line="+22"/>
<source>Sign &Message</source>
<translation type="unfinished">訊息簽署</translation>
</message>
<message>
<location filename="../signmessagepage.cpp" line="+28"/>
<source>Enter a Megacoin address (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished">輸入美卡幣位址 (比如說 MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+1"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished">按"訊息簽署"來產生簽章</translation>
</message>
<message>
<location line="+12"/>
<location line="+53"/>
<source>The entered address is invalid.</source>
<translation type="unfinished">輸入的位址無效.</translation>
</message>
<message>
<location line="-53"/>
<location line="+53"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished">請檢查位址是否正確後再試一次.</translation>
</message>
<message>
<location line="+0"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished">輸入的位址沒有指到任何密鑰.</translation>
</message>
<message>
<location line="+8"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished">錢包解鎖已取消.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished">沒有所輸入位址的密鑰.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished">訊息簽署失敗.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished">訊息已簽署.</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<location filename="../signverifymessagedialog.cpp" line="+30"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>簽章 - 簽署或驗證訊息</translation>
</message>
<message>
<location line="+105"/>
<source>Edit record</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+49"/>
<source>&Sign Message</source>
<translation>訊息簽署</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>你可以用自己的位址來簽署訊息, 以證明你對它的所有權. 但是請小心, 不要簽署語意含糊不清的內容, 因為釣魚式詐騙可能會用騙你簽署的手法來冒充是你. 只有在語句中的細節你都同意時才簽署.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>用來簽署訊息的位址 (比如說 MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>從位址簿選一個位址</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>從剪貼簿貼上位址</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>在這裡輸入你想簽署的訊息</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>簽章</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>複製目前的簽章到系統剪貼簿</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Megacoin address</source>
<translation>簽署訊息是用來證明這個美卡幣位址是你的</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>訊息簽署</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>重置所有訊息簽署欄位</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>全部清掉</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>訊息驗證</translation>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>請在下面輸入簽署的位址, 訊息(請確認完整複製了所包含的換行, 空格, 跳位符號等等), 與簽章, 以驗證該訊息. 請小心, 除了訊息內容外, 不要對簽章本身過度解讀, 以避免被用"中間人攻擊法"詐騙.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>簽署該訊息的位址 (比如說 MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Megacoin address</source>
<translation>驗證訊息是用來確認訊息是用指定的美卡幣位址簽署的</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>訊息驗證</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>重置所有訊息驗證欄位</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+4"/>
<location line="+3"/>
<source>Enter a Megacoin address (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>輸入美卡幣位址 (比如說 MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>按"訊息簽署"來產生簽章</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Megacoin signature</source>
<translation>輸入美卡幣簽章</translation>
</message>
<message>
<location line="+92"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>輸入的位址無效.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>請檢查位址是否正確後再試一次.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>輸入的位址沒有指到任何密鑰.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>錢包解鎖已取消.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>沒有所輸入位址的密鑰.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>訊息簽署失敗.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>訊息已簽署.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>無法將這個簽章解碼.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>請檢查簽章是否正確後再試一次.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>這個簽章與訊息的數位摘要不符.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>訊息驗證失敗.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>訊息已驗證.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+24"/>
<source>Dr. Kimoto Chan</source>
<translation>美卡幣開發人員</translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>在 %1 前未定</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/離線中</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/未確認</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>經確認 %1 次</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>狀態</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation>
<numerusform>, 已公告至 %n 個節點</numerusform>
</translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>日期</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>來源</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>生產出</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>來處</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>目的</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>自己的位址</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>標籤</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>入帳</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation>
<numerusform>將在 %n 個區塊產出後熟成</numerusform>
</translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>不被接受</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>出帳</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>交易手續費</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>淨額</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>訊息</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>附註</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>交易識別碼</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>生產出來的錢要再等 120 個區塊熟成之後, 才能夠花用. 當你產出區塊時, 它會被公布到網路上, 以被串連至區塊鎖鏈. 如果串連失敗了, 它的狀態就會變成"不被接受", 且不能被花用. 當你產出區塊的幾秒鐘內, 也有其他節點產出區塊的話, 有時候就會發生這種情形.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>除錯資訊</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>交易</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>輸入</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>金額</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>是</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>否</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, 尚未成功公告出去</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation>
<numerusform>在接下來 %n 個區塊產出前未定</numerusform>
</translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>未知</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+105"/>
<source>Transaction details</source>
<translation>交易明細</translation>
</message>
<message>
<location line="+76"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>此版面顯示交易的詳細說明</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+230"/>
<source>Date</source>
<translation>日期</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>種類</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>位址</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>金額</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation>
<numerusform>在接下來 %n 個區塊產出前未定</numerusform>
</translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>在 %1 前未定</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>離線中 (經確認 %1 次)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>未確認 (經確認 %1 次, 應確認 %2 次)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>已確認 (經確認 %1 次)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation>
<numerusform>開採金額將可在 %n 個區塊熟成後可用</numerusform>
</translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>沒有其他節點收到這個區塊, 也許它不被接受!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>生產出但不被接受</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>收受於</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>收受自</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>付出至</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>付給自己</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>開採所得</translation>
</message>
<message>
<location line="+40"/>
<source>(n/a)</source>
<translation>(不適用)</translation>
</message>
<message>
<location line="+201"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>交易狀態. 移動游標至欄位上方來顯示確認次數.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>收到交易的日期與時間.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>交易的種類.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>交易的目標位址.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>減去或加入至餘額的金額</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+62"/>
<location line="+17"/>
<source>All</source>
<translation>全部</translation>
</message>
<message>
<location line="-16"/>
<source>Today</source>
<translation>今天</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>這週</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>這個月</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>上個月</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>今年</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>指定範圍...</translation>
</message>
<message>
<location line="+12"/>
<source>Received with</source>
<translation>收受於</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>付出至</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>給自己</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>開採所得</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>其他</translation>
</message>
<message>
<location line="+9"/>
<source>Enter address or label to search</source>
<translation>輸入位址或標記來搜尋</translation>
</message>
<message>
<location line="+8"/>
<source>Min amount</source>
<translation>最小金額</translation>
</message>
<message>
<location line="+37"/>
<source>Copy address</source>
<translation>複製位址</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>複製標記</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>複製金額</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>複製交易識別碼</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>編輯標記</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>顯示交易明細</translation>
</message>
<message>
<location line="+150"/>
<source>Export Transaction Data</source>
<translation>匯出交易資料</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>逗號分隔資料檔 (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>已確認</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>日期</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>種類</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>標記</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>位址</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>金額</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>識別碼</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>匯出失敗</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>無法寫入至 %1 檔案.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>範圍:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>至</translation>
</message>
</context>
<context>
<name>TransactionsPage</name>
<message>
<location filename="../forms/transactionspage.ui" line="+159"/>
<source>Form</source>
<translation type="unfinished">表單</translation>
</message>
<message>
<location line="+101"/>
<source>Transactions</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>VerifyMessagePage</name>
<message>
<location filename="../forms/verifymessagepage.ui" line="+159"/>
<source>Form</source>
<translation type="unfinished">表單</translation>
</message>
<message>
<location line="+110"/>
<source>Verify Message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+93"/>
<source>Signature</source>
<translation type="unfinished">簽章</translation>
</message>
<message>
<location line="+43"/>
<source>Text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+45"/>
<source>Address</source>
<translation type="unfinished">位址</translation>
</message>
<message>
<location line="+24"/>
<source>The address the message was signed with (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished">簽署該訊息的位址 (比如說 MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+22"/>
<source>Choose an address from the address book</source>
<translation type="unfinished">從位址簿選一個位址</translation>
</message>
<message>
<location line="+21"/>
<source>Alt+A</source>
<translation type="unfinished">Alt+A</translation>
</message>
<message>
<location line="+101"/>
<source>Reset all verify message fields</source>
<translation type="unfinished">重置所有訊息驗證欄位</translation>
</message>
<message>
<location line="+22"/>
<source>Clear &All</source>
<translation type="unfinished">全部清掉</translation>
</message>
<message>
<location line="+16"/>
<source>Verify the message to ensure it was signed with the specified Megacoin address</source>
<translation type="unfinished">驗證訊息是用來確認訊息是用指定的美卡幣位址簽署的</translation>
</message>
<message>
<location line="+22"/>
<source>Verify &Message</source>
<translation type="unfinished">訊息驗證</translation>
</message>
<message>
<location filename="../verifymessagepage.cpp" line="+28"/>
<source>Enter a Megacoin address (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished">輸入美卡幣位址 (比如說 MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+1"/>
<source>Enter Megacoin signature</source>
<translation type="unfinished">輸入美卡幣簽章</translation>
</message>
<message>
<location line="+12"/>
<location line="+45"/>
<source>The entered address is invalid.</source>
<translation type="unfinished">輸入的位址無效.</translation>
</message>
<message>
<location line="-45"/>
<location line="+45"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished">請檢查位址是否正確後再試一次.</translation>
</message>
<message>
<location line="+0"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished">輸入的位址沒有指到任何密鑰.</translation>
</message>
<message>
<location line="+11"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished">無法將這個簽章解碼.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished">請檢查簽章是否正確後再試一次.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished">這個簽章與訊息的數位摘要不符.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished">訊息驗證失敗.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished">訊息已驗證.</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>付錢</translation>
</message>
</context>
<context>
<name>megacoin-core</name>
<message>
<location filename="../megacoinstrings.cpp" line="+94"/>
<source>Megacoin version</source>
<translation>美卡幣版本</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>用法:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or megacoind</source>
<translation>送指令給 -server 或 megacoind
</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>列出指令
</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>取得指令說明
</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>選項:
</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: megacoin.conf)</source>
<translation>指定設定檔 (預設: megacoin.conf)
</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: megacoind.pid)</source>
<translation>指定行程識別碼檔案 (預設: megacoind.pid)
</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>指定資料目錄
</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>設定資料庫快取大小為多少百萬位元組(MB, 預設: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 7951 or testnet: 17951)</source>
<translation>在通訊埠 <port> 聽候連線 (預設: 7951, 或若為測試網路: 17951)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>維持與節點連線數的上限為 <n> 個 (預設: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>連線到某個節點以取得其它節點的位址, 然後斷線</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>指定自己公開的位址</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>與亂搞的節點斷線的臨界值 (預設: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>避免與亂搞的節點連線的秒數 (預設: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>在 IPv4 網路上以通訊埠 %u 聽取 RPC 連線時發生錯誤: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 7950 or testnet: 17950)</source>
<translation>在通訊埠 <port> 聽候 JSON-RPC 連線 (預設: 7950, 或若為測試網路: 17950)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>接受命令列與 JSON-RPC 指令
</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>以背景程式執行並接受指令</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>使用測試網路
</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>是否接受外來連線 (預設: 當沒有 -proxy 或 -connect 時預設為 1)</translation>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=megacoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Megacoin Alert" [email protected]
</source>
<translation>%s, 你必須要在以下設定檔中設定 RPC 密碼(rpcpassword):
%s
建議你使用以下隨機產生的密碼:
rpcuser=megacoinrpc
rpcpassword=%s
(你不用記住這個密碼)
使用者名稱(rpcuser)和密碼(rpcpassword)不可以相同!
如果設定檔還不存在, 請在新增時, 設定檔案權限為"只有主人才能讀取".
也建議你設定警示通知, 發生問題時你才會被通知到;
比如說設定為:
alertnotify=echo %%s | mail -s "Megacoin Alert" [email protected]
</translation>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>設定在 IPv6 網路的通訊埠 %u 上聽候 RPC 連線失敗, 退而改用 IPv4 網路: %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>和指定的位址繫結, 並總是在該位址聽候連線. IPv6 請用 "[主機]:通訊埠" 這種格式</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Megacoin is probably already running.</source>
<translation>無法鎖定資料目錄 %s. 也許美卡幣已經在執行了.</translation>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>錯誤: 交易被拒絕了! 有時候會發生這種錯誤, 是因為你錢包中的一些錢已經被花掉了. 比如說你複製了錢包檔 wallet.dat, 然後用複製的錢包花掉了錢, 你現在所用的原來的錢包中卻沒有該筆交易紀錄.</translation>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation>錯誤: 這筆交易需要至少 %s 的手續費! 因為它的金額太大, 或複雜度太高, 或是使用了最近才剛收到的款項.</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>當收到相關警示時所要執行的指令 (指令中的 %s 會被取代為警示訊息)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>當錢包有交易改變時所要執行的指令 (指令中的 %s 會被取代為交易識別碼)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>設定高優先權或低手續費的交易資料大小上限為多少位元組 (預設: 27000)</translation>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>這是尚未發表的測試版本 - 使用請自負風險 - 請不要用於開採或商業應用</translation>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>警告: -paytxfee 設定了很高的金額! 這可是你交易付款所要付的手續費.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>警告: 顯示的交易可能不正確! 你可能需要升級, 或者需要等其它的節點升級.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Megacoin will not work properly.</source>
<translation>警告: 請檢查電腦時間與日期是否正確! 美卡幣無法在時鐘不準的情況下正常運作.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>警告: 讀取錢包檔 wallet.dat 失敗了! 所有的密鑰都正確讀取了, 但是交易資料或位址簿資料可能會缺少或不正確.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>警告: 錢包檔 wallet.dat 壞掉, 但資料被拯救回來了! 原來的 wallet.dat 會改儲存在 %s, 檔名為 wallet.{timestamp}.bak. 如果餘額或交易資料有誤, 你應該要用備份資料復原回來.</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>嘗試從壞掉的錢包檔 wallet.dat 復原密鑰</translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>區塊產生選項:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>只連線至指定節點(可多個)</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>發現區塊資料庫壞掉了</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>找出自己的網際網路位址 (預設: 當有聽候連線且沒有 -externalip 時為 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>你要現在重建區塊資料庫嗎?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>初始化區塊資料庫失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>錢包資料庫環境 %s 初始化錯誤!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>載入區塊資料庫失敗</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>打開區塊資料庫檔案失敗</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>錯誤: 磁碟空間很少!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>錯誤: 錢包被上鎖了, 無法產生新的交易!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>錯誤: 系統錯誤:</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>在任意的通訊埠聽候失敗. 如果你想的話可以用 -listen=0.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>讀取區塊資訊失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>讀取區塊失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>同步區塊索引失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>寫入區塊索引失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>寫入區塊資訊失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>寫入區塊失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source><|fim▁hole|> </message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>寫入美卡幣資料庫失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>寫入交易索引失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>寫入回復資料失敗</translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>是否允許在找節點時使用域名查詢 (預設: 當沒用 -connect 時為 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>生產美卡幣 (預設值: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>啓動時檢查的區塊數 (預設: 288, 指定 0 表示全部)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>區塊檢查的仔細程度 (0 至 4, 預設: 3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation>檔案描述器不足.</translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>從目前的區塊檔 blk000??.dat 重建鎖鏈索引</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>設定處理 RPC 服務請求的執行緒數目 (預設為 4)</translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>驗證區塊資料中...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>驗證錢包資料中...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>從其它來源的 blk000??.dat 檔匯入區塊</translation>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation>設定指令碼驗證的執行緒數目 (最多為 16, 若為 0 表示程式自動決定, 小於 0 表示保留不用的處理器核心數目, 預設為 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>資訊</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>無效的 -tor 位址: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>設定 -minrelaytxfee=<金額> 的金額無效: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>設定 -mintxfee=<amount> 的金額無效: '%s'</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>維護全部交易的索引 (預設為 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>每個連線的接收緩衝區大小上限為 <n>*1000 個位元組 (預設: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>每個連線的傳送緩衝區大小上限為 <n>*1000 位元組 (預設: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>只接受與內建的檢查段點吻合的區塊鎖鏈 (預設: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>只和 <net> 網路上的節點連線 (IPv4, IPv6, 或 Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>輸出額外的除錯資訊. 包含了其它所有的 -debug* 選項</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>輸出額外的網路除錯資訊</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>在除錯輸出內容前附加時間</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Megacoin Wiki for SSL setup instructions)</source>
<translation>SSL 選項: (SSL 設定程序請見 Megacoin Wiki)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>選擇 SOCKS 代理伺服器的協定版本(4 或 5, 預設: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>在終端機顯示追蹤或除錯資訊, 而非寫到 debug.log 檔</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>輸出追蹤或除錯資訊給除錯器</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>設定區塊大小上限為多少位元組 (預設: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>設定區塊大小下限為多少位元組 (預設: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>客戶端軟體啓動時將 debug.log 檔縮小 (預設: 當沒有 -debug 時為 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>簽署交易失敗</translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>指定連線在幾毫秒後逾時 (預設: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>系統錯誤:</translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>交易金額太小</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>交易金額必須是正的</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>交易位元量太大</translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>是否使用通用即插即用(UPnP)協定來設定聽候連線的通訊埠 (預設: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>是否使用通用即插即用(UPnP)協定來設定聽候連線的通訊埠 (預設: 當有聽候連線為 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>透過代理伺服器來使用 Tor 隱藏服務 (預設: 同 -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>JSON-RPC 連線使用者名稱</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>警告</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>警告: 這個版本已經被淘汰掉了, 必須要升級!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>改變 -txindex 參數後, 必須要用 -reindex 參數來重建資料庫</translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>錢包檔 weallet.dat 壞掉了, 拯救失敗</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>JSON-RPC 連線密碼</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>只允許從指定網路位址來的 JSON-RPC 連線</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>送指令給在 <ip> 的節點 (預設: 127.0.0.1)
</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>當最新區塊改變時所要執行的指令 (指令中的 %s 會被取代為區塊的雜湊值)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>將錢包升級成最新的格式</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>設定密鑰池大小為 <n> (預設: 100)
</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>重新掃描區塊鎖鏈, 以尋找錢包所遺漏的交易.</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>於 JSON-RPC 連線使用 OpenSSL (https)
</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>伺服器憑證檔 (預設: server.cert)
</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>伺服器密鑰檔 (預設: server.pem)
</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>可以接受的加密法 (預設: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)
</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>此協助訊息
</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>無法和這台電腦上的 %s 繫結 (繫結回傳錯誤 %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>透過 SOCKS 代理伺服器連線</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>允許對 -addnode, -seednode, -connect 的參數使用域名查詢 </translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>載入位址中...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>載入檔案 wallet.dat 失敗: 錢包壞掉了</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Megacoin</source>
<translation>載入檔案 wallet.dat 失敗: 此錢包需要新版的 Megacoin</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Megacoin to complete</source>
<translation>錢包需要重寫: 請重啟美卡幣來完成</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>載入檔案 wallet.dat 失敗</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>無效的 -proxy 位址: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>在 -onlynet 指定了不明的網路別: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>在 -socks 指定了不明的代理協定版本: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>無法解析 -bind 位址: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>無法解析 -externalip 位址: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>設定 -paytxfee=<金額> 的金額無效: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>無效的金額</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>累積金額不足</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>載入區塊索引中...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>加入一個要連線的節線, 並試著保持對它的連線暢通</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Megacoin is probably already running.</source>
<translation>無法和這台電腦上的 %s 繫結. 也許美卡幣已經在執行了.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>交易付款時每 KB 的交易手續費</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>載入錢包中...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>無法將錢包格式降級</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>無法寫入預設位址</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>重新掃描中...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>載入完成</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>為了要使用 %s 選項</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>錯誤</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>你必須在下列設定檔中設定 RPC 密碼(rpcpassword=<password>):
%s
如果這個檔案還不存在, 請在新增時, 設定檔案權限為"只有主人才能讀取".</translation>
</message>
</context>
</TS><|fim▁end|>
|
<translation>寫入檔案資訊失敗</translation>
|
<|file_name|>getFile.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from minifi import * # noqa F403
from argparse import ArgumentParser
from ctypes import cdll # noqa F401
import ctypes # noqa F401
import sys
from _cffi_backend import callback # noqa F401<|fim▁hole|>
class GetFilePrinterProcessor(PyProcessor): # noqa F405
def __init__(self, minifi, flow):
PyProcessor.__init__(self, minifi, flow) # noqa F405
self._callback = None
def _onTriggerCallback(self):
def onTrigger(session, context):
flow_file = self.get(session, context)
if flow_file:
if flow_file.add_attribute("python_test", "value"):
print("Add attribute succeeded")
if not flow_file.add_attribute("python_test", "value2"):
print("Cannot add the same attribute twice!")
print("original file name: " + flow_file.get_attribute("filename"))
target_relationship = "success"
if not self.transfer(session, flow_file, target_relationship):
print("transfer to relationship " + target_relationship + " failed")
return CALLBACK(onTrigger) # noqa F405
parser = ArgumentParser()
parser.add_argument("-s", "--dll", dest="dll_file",
help="DLL filename", metavar="FILE")
parser.add_argument("-n", "--nifi", dest="nifi_instance",
help="NiFi Instance")
parser.add_argument("-i", "--input", dest="input_port",
help="NiFi Input Port")
parser.add_argument("-d", "--dir", dest="dir",
help="GetFile Dir to monitor", metavar="FILE")
args = parser.parse_args()
""" dll_file is the path to the shared object """
minifi = MiNiFi(dll_file=args.dll_file, url=args.nifi_instance.encode('utf-8'), port=args.input_port.encode('utf-8')) # noqa F405
minifi.set_property("nifi.remote.input.http.enabled", "true")
processor = minifi.add_processor(GetFile()) # noqa F405
processor.set_property("Input Directory", args.dir)
processor.set_property("Keep Source File", "true")
current_module = sys.modules[__name__]
processor = minifi.create_python_processor(current_module, "GetFilePrinterProcessor")
ff = minifi.get_next_flowfile()
if ff:
minifi.transmit_flowfile(ff)<|fim▁end|>
| |
<|file_name|>package.py<|end_file_name|><|fim▁begin|># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Gengeo(AutotoolsPackage):
"""GenGeo is a library of tools for creating complex particle
geometries for use in ESyS-Particle simulations. GenGeo is a standalone
application with a Python API that creates geometry files suitable for
importing into ESyS-Particle simulations. The functionality of GenGeo far
exceeds the in-simulation geometry creation utilities
provided by ESyS-Particle itself."""
homepage = "https://launchpad.net/esys-particle/gengeo"
url = "https://launchpad.net/esys-particle/trunk/3.0-alpha/+download/gengeo-163.tar.gz"
maintainers = ['dorton21']
version('163', sha256='9c896d430d8f315a45379d2b82e7d374f36259af66a745bfdee4c022a080d34d')
extends('python')
depends_on('autoconf', type='build')
depends_on('automake', type='build')
depends_on('libtool', type='build')
depends_on('m4', type='build')
depends_on('boost+python')
depends_on('openmpi')
def autoreconf(self, spec, prefix):
autogen = Executable('./autogen.sh')
autogen()
def configure_args(self):
args = [<|fim▁hole|> 'CXXFLAGS=-fpermissive',
]
return args<|fim▁end|>
|
'--verbose',
'--with-boost=' + self.spec['boost'].prefix,
'CCFLAGS=-fpermissive',
|
<|file_name|>package-info.java<|end_file_name|><|fim▁begin|>/**
* Contains methods for extracting/selecting final multiword candidates.
* @author Valeria Quochi @author Francesca Frontini @author Francesco Rubino
<|fim▁hole|> */
package multiword;<|fim▁end|>
|
* Istituto di linguistica Computazionale "A. Zampolli" - CNR Pisa - Italy
*
|
<|file_name|>dirac-admin-proxy-upload.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
########################################################################
# File : dirac-admin-proxy-upload.py
# Author : Adrian Casajus
########################################################################
from __future__ import print_function
import sys
from DIRAC.Core.Base import Script
from DIRAC.FrameworkSystem.Client.ProxyUpload import CLIParams, uploadProxy
__RCSID__ = "$Id$"
if __name__ == "__main__":
cliParams = CLIParams()
cliParams.registerCLISwitches()
Script.parseCommandLine()
<|fim▁hole|> if not retVal['OK']:
print(retVal['Message'])
sys.exit(1)
sys.exit(0)<|fim▁end|>
|
retVal = uploadProxy(cliParams)
|
<|file_name|>test_aras.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
import sys
sys.path.append('../fml/')
import os
import numpy as np
import fml
import random
t_width = np.pi / 4.0 # 0.7853981633974483
d_width = 0.2
cut_distance = 6.0
r_width = 1.0
c_width = 0.5
PTP = {\
1 :[1,1] ,2: [1,8]#Row1
,3 :[2,1] ,4: [2,2]#Row2\
,5 :[2,3] ,6: [2,4] ,7 :[2,5] ,8 :[2,6] ,9 :[2,7] ,10 :[2,8]\
,11 :[3,1] ,12: [3,2]#Row3\
,13 :[3,3] ,14: [3,4] ,15 :[3,5] ,16 :[3,6] ,17 :[3,7] ,18 :[3,8]\
,19 :[4,1] ,20: [4,2]#Row4\
,31 :[4,3] ,32: [4,4] ,33 :[4,5] ,34 :[4,6] ,35 :[4,7] ,36 :[4,8]\
,21 :[4,9] ,22: [4,10],23 :[4,11],24 :[4,12],25 :[4,13],26 :[4,14],27 :[4,15],28 :[4,16],29 :[4,17],30 :[4,18]\
,37 :[5,1] ,38: [5,2]#Row5\
,49 :[5,3] ,50: [5,4] ,51 :[5,5] ,52 :[5,6] ,53 :[5,7] ,54 :[5,8]\
,39 :[5,9] ,40: [5,10],41 :[5,11],42 :[5,12],43 :[5,13],44 :[5,14],45 :[5,15],46 :[5,16],47 :[5,17],48 :[5,18]\
,55 :[6,1] ,56: [6,2]#Row6\
,81 :[6,3] ,82: [6,4] ,83 :[6,5] ,84 :[6,6] ,85 :[6,7] ,86 :[6,8]
,72: [6,10],73 :[6,11],74 :[6,12],75 :[6,13],76 :[6,14],77 :[6,15],78 :[6,16],79 :[6,17],80 :[6,18]\
,57 :[6,19],58: [6,20],59 :[6,21],60 :[6,22],61 :[6,23],62 :[6,24],63 :[6,25],64 :[6,26],65 :[6,27],66 :[6,28],67 :[6,29],68 :[6,30],69 :[6,31],70 :[6,32],71 :[6,33]\
,87 :[7,1] ,88: [7,2]#Row7\
,113:[7,3] ,114:[7,4] ,115:[7,5] ,116:[7,6] ,117:[7,7] ,118:[7,8]\
,104:[7,10],105:[7,11],106:[7,12],107:[7,13],108:[7,14],109:[7,15],110:[7,16],111:[7,17],112:[7,18]\
,89 :[7,19],90: [7,20],91 :[7,21],92 :[7,22],93 :[7,23],94 :[7,24],95 :[7,25],96 :[7,26],97 :[7,27],98 :[7,28],99 :[7,29],100:[7,30],101:[7,31],101:[7,32],102:[7,14],103:[7,33]}
def periodic_distance(a, b):
ra = PTP[int(a)][0]
rb = PTP[int(b)][0]
ca = PTP[int(a)][1]
cb = PTP[int(b)][1]
return (r_width**2 + (ra - rb)**2) * (c_width**2 + (ca - cb)**2)
def ksi(x):
return 1.0 - np.sin(np.pi * x/(2.0 * cut_distance))
def aras_scalar(atom1, atom2, q1, q2, n1, n2, qall1, qall2):
ksi1 = ksi(atom1[0,:n1])
ksi2 = ksi(atom2[0,:n2])
a = 1.0 / (np.sum(ksi1) * np.sum(ksi2)) \
* np.sqrt(np.pi) * d_width * r_width**4 * c_width**4 \
/ periodic_distance(q1, q2)
b = 0.0
for i in range(n1):
c = 0.0
for j in range(n2):
d = 0.0
for k in range(n1):
e = 0.0
for l in range(n2):
e += ksi2[l] * np.exp(-(atom1[i+3,k] - atom2[j+3,l])**2 / (4.0 * t_width**2))
d += e * ksi1[k]
c += d * np.exp(-(atom1[0,i] - atom2[0,j])**2 / (4.0 * d_width**2)) * ksi2[j] \
/ periodic_distance(qall1[i], qall2[j])
b += c * ksi1[i]
dist = a * b<|fim▁hole|>
d = np.zeros((mol1.natoms, mol2.natoms))
aa = np.zeros((mol1.natoms))
bb = np.zeros((mol2.natoms))
for i in range(mol1.natoms):
atom1 = mol1.aras_descriptor[i]
aa[i] = aras_scalar(atom1, atom1,
mol1.nuclear_charges[i],
mol1.nuclear_charges[i],
mol1.natoms, mol1.natoms,
mol1.nuclear_charges, mol1.nuclear_charges)
for i in range(mol2.natoms):
atom2 = mol2.aras_descriptor[i]
bb[i] = aras_scalar(atom2, atom2,
mol2.nuclear_charges[i],
mol2.nuclear_charges[i],
mol2.natoms, mol2.natoms,
mol2.nuclear_charges, mol2.nuclear_charges)
for i in range(mol1.natoms):
atom1 = mol1.aras_descriptor[i]
for j in range(mol2.natoms):
atom2 = mol2.aras_descriptor[j]
ab = aras_scalar(atom1, atom2,
mol1.nuclear_charges[i],
mol2.nuclear_charges[j],
mol1.natoms, mol2.natoms,
mol1.nuclear_charges, mol2.nuclear_charges)
d[i,j] = aa[i] + bb[j] - 2.0 * ab
return d
def get_kernel(mols1, mols2, sigma, max_size=30):
K = np.zeros((len(mols1), len(mols2)))
for i, mol1 in enumerate(mols1):
for j, mol2 in enumerate(mols2):
print i, j
d = aras_distance(mol1, mol2)
d *= -0.5 / (sigma**2)
np.exp(d, d)
K[i,j] = np.sum(d)
return K
def gen_pd(emax=20):
pd = np.zeros((emax,emax))
for i in range(emax):
for j in range(emax):
pd[i,j] = 1.0 / periodic_distance(i+1, j+1)
return pd
def fdist(mol1, mol2):
from faras import faras_molecular_distance as fd
pd = gen_pd()
amax = 11
x1 = np.array(mol1.aras_descriptor).reshape((1,amax,3+amax,amax))
x2 = np.array(mol2.aras_descriptor).reshape((1,amax,3+amax,amax))
q1 = np.array(mol1.nuclear_charges, \
dtype = np.int32).reshape(1,mol1.natoms)
q2 = np.array(mol2.nuclear_charges, \
dtype = np.int32).reshape(1,mol2.natoms)
n1 = np.array([mol1.natoms], dtype=np.int32)
n2 = np.array([mol2.natoms], dtype=np.int32)
nm1 = 1
nm2 = 1
d = fd(x1, x2, q1, q2, n1, n2, nm1, nm2, amax, pd)
return d
def fdists(mols1, mols2):
from faras import faras_molecular_distance as fd
pd = gen_pd()
amax = mols1[0].aras_descriptor.shape[0]
nm1 = len(mols1)
nm2 = len(mols2)
x1 = np.array([mol.aras_descriptor for mol in mols1]).reshape((nm1,amax,3+amax,amax))
x2 = np.array([mol.aras_descriptor for mol in mols2]).reshape((nm2,amax,3+amax,amax))
q1 = np.zeros((nm1,amax), dtype=np.int32)
q2 = np.zeros((nm1,amax), dtype=np.int32)
for a in range(nm1):
for i, charge in enumerate(mols[a].nuclear_charges):
q1[a,i] = int(charge)
for b in range(nm2):
for j, charge in enumerate(mols[b].nuclear_charges):
q2[b,j] = int(charge)
n1 = np.array([mol.natoms for mol in mols1], dtype=np.int32)
n2 = np.array([mol.natoms for mol in mols2], dtype=np.int32)
d = fd(x1, x2, q1, q2, n1, n2, nm1, nm2, amax, pd)
return d
if __name__ == "__main__":
mols = []
path = "xyz/"
filenames = os.listdir(path)
np.set_printoptions(linewidth=99999999999999999)
print "Generating ARAS descriptors from FML interface ..."
for filename in sorted(filenames):
mol = fml.Molecule()
mol.read_xyz(path + filename)
mol.generate_aras_descriptor(size=11)
mols.append(mol)
train = mols[:10]
test = mols[-10:]
a = 1
b = 1
d = aras_distance(mols[a], mols[b])
print d
d2 = fdist(mols[a], mols[b])
print d2[0,0,:mols[a].natoms,:mols[b].natoms]<|fim▁end|>
|
return dist
def aras_distance(mol1, mol2, max_size=30):
|
<|file_name|>preset.js<|end_file_name|><|fim▁begin|>var winston = require('winston');
var fs = require('fs');
var presets = {};
function presetsAction(player, values, callback) {
var value = decodeURIComponent(values[0]);
if (value.startsWith('{'))
var preset = JSON.parse(value);
else
var preset = presets[value];
if (preset) {
winston.info("Preset found: ", preset);
player.discovery.applyPreset(preset, function (err, result) {
if (err) {
winston.error("Error loading preset: ", err);
} else {
winston.info("Playing ", preset);
}
});
} else {
winston.error("No preset found...");
var simplePresets = [];
for (var key in presets) {
if (presets.hasOwnProperty(key)) {
simplePresets.push(key);
}
}
callback(simplePresets);
}
}
function initPresets(api) {
var presetsFilename = __dirname + '/../../presets.json';
fs.exists(presetsFilename, function (exists) {
if (exists) {
presets = require(presetsFilename);
winston.info('loaded presets', presets);
} else {
winston.info('no preset file, ignoring...');
}
api.registerAction('preset', presetsAction);
});
}<|fim▁hole|>module.exports = function (api) {
initPresets(api);
}<|fim▁end|>
| |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>let fs = require('fs');
const {dialog} = require('electron').remote;
let drivelist = require('drivelist');
let distrosList = require('./js/distros.json');
let numeral = require('numeral');
let fileNameRoute;
let fileName;
let fileChoosed = false;
let downloadFile = false;
let checksumFileDownloaded;
let distroToDownload;
let devs = [];
let devRoute;
let devSelectedName;
let devSelected = false;
let listDistros = (distrosList) => {
let enumDistros = document.getElementById('enum-distros');
let distrosListLength = distrosList.length;
for (let i = 0; i < distrosListLength; i++) {
let optionDistro = document.createElement('option');
optionDistro.text = distrosList[i].name;
enumDistros.add(optionDistro, enumDistros[i]);
}
};
let selectDistro = () => {
let distros = document.getElementById('enum-distros');
distroToDownload = distros.options[distros.selectedIndex].index;
console.log(distroToDownload);
if (distroToDownload !== distrosList.length) {
document.getElementById('btn-download').innerHTML = 'Download & Create';
document.getElementById('iso-table').style.display = 'none';
let distroDetailsKeys = Object.keys(distrosList[distroToDownload]);
let distroDetailsValues = Object.keys(distrosList[distroToDownload]).map((value) => {
return distrosList[distroToDownload][value];
});
console.log(distroDetailsKeys);
let distroDetailsKeysLength = distroDetailsKeys.length;
for (let i = 0; i < distroDetailsKeysLength; i++) {
document.getElementById('distro-' + distroDetailsKeys[i]).innerHTML = distroDetailsValues[i];
}
document.getElementById('distro-details').style.display = 'block';
document.getElementById('distro-table').style.display = 'block';
downloadFile = true;
}
};
let listDevs = () => {
drivelist.list((error, disks) => {
console.log(disks);
if (error) {
console.log('Error getting drives: ' + error);
} else {
devs = disks;
let devAvailable = false;
let disksLength = disks.length;
for (let i = 0; i < disksLength; i++) {
if (disks[i].system === false) {
let addDevHtml = `<div id="dev-${i}" onclick="devDetails(this.id)"><span class="icon icon icon-drive"></span> ${disks[i].name} </div><br>`;
document.getElementById('dev-status').innerHTML = 'Devices';
document.getElementById('dev-list').insertAdjacentHTML('beforeend', addDevHtml);
devAvailable = true;
}
}
if (!devAvailable) {
document.getElementById('dev-status').innerHTML = '<center>No devices found please connect one</center>';
}
}
});
};
let devDetails = (devId) => {
let devIndexSplited = devId.split('-');
let devIndex = devIndexSplited[1];
delete devs[devIndex].raw;
devs[devIndex].size = typeof devs[devIndex].size === 'number' ? numeral(devs[devIndex].size).format('0.00 b') : devs[devIndex].size;
console.log(devs[devIndex]);
devRoute = devs[devIndex].device;
devSelectedName = devs[devIndex].name;
devSelected = true;
let devDetailsKeys = Object.keys(devs[devIndex]);
let devDetailsValues = Object.keys(devs[devIndex]).map((value) => {
return devs[devIndex][value];
});
for (let key in devDetailsKeys) {
if (devDetailsValues[key]) {
document.getElementById('detail-' + devDetailsKeys[key]).innerHTML = devDetailsValues[key].toString();
} else {
document.getElementById('detail-' + devDetailsKeys[key]).innerHTML = 'none';
}
}
document.getElementById('dev-details').style.display = 'block';
};
let openIso = () => {
dialog.showOpenDialog({ filters: [
{ name: 'iso', extensions: ['iso'] }
]}, function (fileDeails) {
if (fileDeails === undefined) {
return;
} else {
fileNameRoute = fileDeails[0];
let fileNameSplited = fileNameRoute.split('/');
fileName = fileNameSplited[fileNameSplited.length - 1];
console.log(fileName);
fileChoosed = true;
let resetDevList = '<option selected="true" style="display:none;">Distro</option>';
document.getElementById('enum-distros').innerHTML = resetDevList;
listDistros(distrosList);
document.getElementById('btn-download').innerHTML = 'Create';
document.getElementById('distro-table').style.display = 'none';
document.getElementById('distro-details').style.display = 'block';
document.getElementById('iso-table').style.display = 'block';
// Update values with iso info
document.getElementById('iso-file').innerHTML = fileName;
document.getElementById('iso-location').innerHTML = fileNameRoute;
document.getElementById('iso-checksum').innerHTML = 'None'; // Set checksume
let fileNameRouteStat = fs.statSync(fileNameRoute);
document.getElementById('iso-size').innerHTML = numeral(fileNameRouteStat.size).format('0.00 b');
downloadFile = false;
}
});
};
let downloadDistro = () => {
if (devSelected) {
basicModal.show({
body: '<center id="alert-center"><img id="alert-loader" src="../img/ajax_loader_rocket_48.gif"><p id="alert-msg"></p></center>',
closable: true,
buttons: {
action: {
title: 'Cancel',
fn: basicModal.close
}
}
});
let request = require('request');
let filed = require('filed');
fileName = distrosList[distroToDownload].name.replace(/\s+/g, '_') + '.iso';
fileNameRoute = 'downloads/' + fileName;
let stream = filed(fileNameRoute);
let req = request(distrosList[distroToDownload].link).pipe(stream);
let dataLength = null;
req.on('data', (data) => {
dataLength += data.length;
document.getElementById('alert-msg').innerHTML = `Downloading: ${numeral(dataLength).format('0.00 b')} of ${distrosList[distroToDownload].size} MB`;
});
stream.on('end', () => {
basicModal.show({
body: `<center id="alert-center"><p id="alert-msg">Download successful!<br>File: ${fileNameRoute} (${numeral(dataLength).format('0.00 b')}) <br>Do you wanto to checksum the file?</p></center>`,
closable: true,
buttons: {
cancel: {
title: 'CheckSum',
fn: checkSumFile
},
action: {
title: 'Just write it!',
fn: confirmWrite
}
}
});
downloadFile = false;
fileChoosed = true;
});
stream.on('error', (err) => {
document.getElementById('alert-msg').innerHTML = 'Error downloading the file<br>Please try again';
document.getElementsByClassName('basicModal__buttons')[0].innerHTML = '<a id="basicModal__action" class="basicModal__button" onclick="basicModal.close();">Close</a>';
console.log(err);
fileChoosed = false;
});
} else {
infoSelectDev();
}
};
// Modify this to ask the user if he/she wants to checksuming the file
let checkSumFile = () => {
basicModal.show({
body: '<center id="alert-center"><img id="alert-loader" src="../img/ajax_loader_rocket_48.gif"><p id="alert-msg">Checksuming... This could take awhile.</p></center>',
closable: true,
buttons: {
action: {
title: 'Please wait',
fn: basicModal.visible
}
}
});
// Check documentation how to pass the kind of checksum: md5 or sha1
let checksum = require('checksum');
checksum.file(fileNameRoute, (err, sum) => {
console.log('Checksuming...');
if (err === null && distrosList[distroToDownload].checkSum === sum) {
document.getElementById('alert-center').removeChild(document.getElementById('alert-loader'));
document.getElementById('alert-msg').innerHTML = 'Awesome... Checksums match!<br>' + sum;
document.getElementsByClassName('basicModal__buttons')[0].innerHTML = '<a id="basicModal__action" class="basicModal__button" onclick="ddWrites(); basicModal.close();">Continue</a>';
console.log(sum + ' null && sum');
fileChoosed = true;
} else {
document.getElementById('alert-center').removeChild(document.getElementById('alert-loader'));
document.getElementById('alert-msg').innerHTML = 'Sorry<br>Checksums do not match<br>Try to download it again.<br>' + sum;
document.getElementsByClassName('basicModal__buttons')[0].innerHTML = '<a id="basicModal__action" class="basicModal__button" onclick="basicModal.close();">Close</a>';
console.log(err);
fileChoosed = false;
}
});
};
<|fim▁hole|> try {
downloadDistro();
} catch (err) {
infoDownloadFail();
/*
Set diferent dialog for erros:
No enough space on hdd
No Internet conection
...
*/
fileChoosed = false;
infoCheckSumFail();
console.log(err);
}
} else if (fileChoosed) {
ddWrites();
} else {
infoSelectSourceFile();
}
};
let ddWrites = () => {
if (devSelected) {
if (fileChoosed) {
let confirmWriteResponse = dialog.showMessageBox({
type: 'question',
buttons: ['Cancel', 'Yes' ],
title : 'Write ISO file',
message: 'Please confirm',
detail: `All data on ${devSelectedName} will be overwriten with ${fileName} data.\nWould you like to proceed?`
});
if (confirmWriteResponse === 1) {
basicModal.show({
body: '<center id="alert-center"><img id="alert-loader" src="../img/ajax_loader_rocket_48.gif"><p id="alert-msg"></p></center>',
closable: true,
buttons: {
action: {
title: 'Please wait',
fn: basicModal.visible
}
}
});
let imageWrite = require('etcher-image-write');
let myStream = fs.createReadStream(fileNameRoute);
let emitter = imageWrite.write(devRoute, myStream, {
check: false,
size: fs.statSync(fileNameRoute).size
});
emitter.on('progress', (state) => {
document.getElementById('alert-msg').innerHTML = `Writing: ${Math.round(state.percentage)} % (${numeral(state.transferred).format('0.00 b')})<br>Speed: ${numeral(state.speed).format('0.00 b')}/s ETA: ${numeral(state.eta).format('00:00:00')}`;
console.log(state);
});
emitter.on('error', (error) => {
document.getElementById('alert-center').removeChild(document.getElementById('alert-loader'));
document.getElementById('alert-msg').innerHTML = `heads-up!<br>${error}<br>Please try again`;
document.getElementsByClassName('basicModal__buttons')[0].innerHTML = '<a id="basicModal__action" class="basicModal__button" onclick="basicModal.close();">Close</a>';
console.error(error);
});
emitter.on('done', (success) => {
if (success) {
document.getElementById('alert-center').removeChild(document.getElementById('alert-loader'));
document.getElementById('alert-msg').innerHTML = `VirtyDrive succesfully created!<br> ${fileName} on: ${devRoute} <br>Now you can boot in your new GNU/Linux have fun!`;
document.getElementsByClassName('basicModal__buttons')[0].innerHTML = '<a id="basicModal__action" class="basicModal__button" onclick="basicModal.close();">Finish</a>';
console.log('Success!');
} else {
document.getElementById('alert-center').removeChild(document.getElementById('alert-loader'));
document.getElementById('alert-msg').innerHTML = 'heads-up! something went wrong,<br>Please try again';
document.getElementsByClassName('basicModal__buttons')[0].innerHTML = '<a id="basicModal__action" class="basicModal__button" onclick="basicModal.close();">Close</a>';
console.log('Failed!');
}
});
}
} else {
infoSelectSourceFile();
}
} else {
infoSelectDev();
}
};
let infoSelectSourceFile = () => {
dialog.showMessageBox({
type: 'info',
buttons: ['OK'],
title : 'Select a source',
message: '',
detail: 'Please select an .iso file or a distribution to download'
});
};
let infoSelectDev = () => {
dialog.showMessageBox({
type: 'info',
buttons: ['OK'],
title : 'Select a Device',
message: '',
detail: 'Please select a divice to setup a distro'
});
};
let infoDownloadFail = () => {
dialog.showMessageBox({
type: 'info',
buttons: ['OK'],
title : 'Fail',
message: '',
detail: 'Download fail! Please, check your Internet connection and try again'
});
};
let infoCheckSumFail = () => {
dialog.showMessageBox({
type: 'info',
buttons: ['OK'],
title : 'Fail',
message: '',
detail: 'Download/Checksum fail! Please, check that you have enough space and writing permissions avalable on disk'
});
};
let infoCheckDevs = () => {
document.getElementById('dev-details').style.display = 'none';
let allDevsListed = document.getElementById('dev-list');
while (allDevsListed.hasChildNodes()) {
allDevsListed.removeChild(allDevsListed.lastChild);
}
devSelected = false;
basicModal.show({
body: '<center id="alert-center"><img id="alert-loader" src="../img/ajax_loader_rocket_48.gif"><p id="alert-msg">Checking for Drives</p></center>',
closable: true,
callback: () => {
setTimeout(basicModal.close, 3000);
setTimeout(listDevs, 3000); },
buttons: {
action: {
title: 'Please wait',
fn: basicModal.visible
}
}
});
};<|fim▁end|>
|
let confirmWrite = () => {
if (downloadFile) {
|
<|file_name|>test_suite_test.go<|end_file_name|><|fim▁begin|>// Copyright 2015 The Drydock 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 test
import (
"strings"
"testing"
)
// SuiteSuite is the test suite for test.Suite.
type SuiteSuite struct {
Suite
}
// TestTestSuite runs the test.Suite test suite.
func TestTestSuite(t *testing.T) {
RunSuite(t, new(SuiteSuite))
}
// GetFileLine verify returns the correct file and line number information.
func (t *SuiteSuite) GetFileLine() {
expected := "drydock/runtime/base/test/test_suite_test.go:39"
wrapper := func() string {
return t.getFileLine()
}
if s := wrapper(); !strings.HasSuffix(s, expected) {
t.Errorf("Invalid file and line: Got: %s, Want: %s", s, expected)
}
}
// TestInfof ensures that Infof has code coverage.
func (t *SuiteSuite) TestInfof() {
t.Infof("This is a log statement produced by t.Infof")
}
// VerifyMethodsWrongSignatureSkipped1 ensures that public methods with the wrong signature
// (e.g. take arguments) are not executed as test methods.
func (t *SuiteSuite) VerifyMethodsWrongSignatureSkipped1(x int) {
t.Fatalf("This should never run.")
}
// VerifyMethodsWrongSignatureSkipped2 ensures that public methods with the wrong signature
// (e.g. have return values) are not executed as test methods.
func (t *SuiteSuite) VerifyMethodsWrongSignatureSkipped2() int {<|fim▁hole|>}<|fim▁end|>
|
t.Fatalf("This should never run.")
return 0
|
<|file_name|>call_record.py<|end_file_name|><|fim▁begin|>from office365.directory.identities.identity_set import IdentitySet
from office365.entity import Entity
class CallRecord(Entity):
"""Represents a single peer-to-peer call or a group call between multiple participants,
sometimes referred to as an online meeting."""
@property<|fim▁hole|> def join_web_url(self):
"""Meeting URL associated to the call. May not be available for a peerToPeer call record type."""
return self.properties.get("joinWebUrl", None)
@property
def organizer(self):
"""The organizing party's identity.."""
return self.properties.get("organizer", IdentitySet())<|fim▁end|>
| |
<|file_name|>daypicker.ts<|end_file_name|><|fim▁begin|>import {Component, OnInit} from 'angular2/core';
import {CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass} from 'angular2/common';
import {Ng2BootstrapConfig, Ng2BootstrapTheme} from '../ng2-bootstrap-config';
import {DatePickerInner} from './datepicker-inner';
// write an interface for template options
const TEMPLATE_OPTIONS:any = {
[Ng2BootstrapTheme.BS4]: {
DAY_TITLE: `<|fim▁hole|> WEEK_ROW: `
<td *ngIf="datePicker.showWeeks" class="text-xs-center h6"><em>{{ weekNumbers[index] }}</em></td>
<td *ngFor="#dtz of rowz" class="text-xs-center" role="gridcell" [id]="dtz.uid">
<button type="button" style="min-width:100%;" class="btn btn-sm {{dtz.customClass}}"
*ngIf="!(datePicker.onlyCurrentMonth && dtz.secondary)"
[ngClass]="{'btn-secondary': !dtz.selected && !datePicker.isActive(dtz), 'btn-info': dtz.selected, disabled: dtz.disabled}"
[disabled]="dtz.disabled"
(click)="datePicker.select(dtz.date)" tabindex="-1">
<span [ngClass]="{'text-muted': dtz.secondary || dtz.current}">{{dtz.label}}</span>
</button>
</td>
`,
ARROW_LEFT: '<',
ARROW_RIGHT: '>'
},
[Ng2BootstrapTheme.BS3]: {
DAY_TITLE: `
<th *ngFor="#labelz of labels" class="text-center"><small aria-label="labelz.full"><b>{{labelz.abbr}}</b></small></th>
`,
WEEK_ROW: `
<td *ngIf="datePicker.showWeeks" class="text-center h6"><em>{{ weekNumbers[index] }}</em></td>
<td *ngFor="#dtz of rowz" class="text-center" role="gridcell" [id]="dtz.uid">
<button type="button" style="min-width:100%;" class="btn btn-default btn-sm {{dtz.customClass}}"
*ngIf="!(datePicker.onlyCurrentMonth && dtz.secondary)"
[ngClass]="{'btn-info': dtz.selected, active: datePicker.isActive(dtz), disabled: dtz.disabled}"
[disabled]="dtz.disabled"
(click)="datePicker.select(dtz.date)" tabindex="-1">
<span [ngClass]="{'text-muted': dtz.secondary, 'text-info': dtz.current}">{{dtz.label}}</span>
</button>
</td>
`,
ARROW_LEFT: `
<i class="glyphicon glyphicon-chevron-left"></i>
`,
ARROW_RIGHT: `
<i class="glyphicon glyphicon-chevron-right"></i>
`
}
};
const CURRENT_THEME_TEMPLATE:any = TEMPLATE_OPTIONS[Ng2BootstrapConfig.theme || Ng2BootstrapTheme.BS3];
@Component({
selector: 'daypicker',
template: `
<table *ngIf="datePicker.datepickerMode==='day'" role="grid" aria-labelledby="uniqueId+'-title'" aria-activedescendant="activeDateId">
<thead>
<tr>
<th>
<button type="button" class="btn btn-default btn-secondary btn-sm pull-left" (click)="datePicker.move(-1)" tabindex="-1">
${CURRENT_THEME_TEMPLATE.ARROW_LEFT}
</button>
</th>
<th [attr.colspan]="5 + datePicker.showWeeks">
<button [id]="datePicker.uniqueId + '-title'"
type="button" class="btn btn-default btn-secondary btn-sm"
(click)="datePicker.toggleMode()"
[disabled]="datePicker.datepickerMode === datePicker.maxMode"
[ngClass]="{disabled: datePicker.datepickerMode === datePicker.maxMode}" tabindex="-1" style="width:100%;">
<strong>{{title}}</strong>
</button>
</th>
<th>
<button type="button" class="btn btn-default btn-secondary btn-sm pull-right" (click)="datePicker.move(1)" tabindex="-1">
${CURRENT_THEME_TEMPLATE.ARROW_RIGHT}
</button>
</th>
</tr>
<tr>
<th *ngIf="datePicker.showWeeks"></th>
${CURRENT_THEME_TEMPLATE.DAY_TITLE}
</tr>
</thead>
<tbody>
<template ngFor [ngForOf]="rows" #rowz="$implicit" #index="index">
<tr *ngIf="!(datePicker.onlyCurrentMonth && rowz[0].secondary && rowz[6].secondary)">
${CURRENT_THEME_TEMPLATE.WEEK_ROW}
</tr>
</template>
</tbody>
</table>
`,
directives: [FORM_DIRECTIVES, CORE_DIRECTIVES, NgClass]
})
export class DayPicker implements OnInit {
public labels:Array<any> = [];
public title:string;
public rows:Array<any> = [];
public weekNumbers:Array<number> = [];
public datePicker:DatePickerInner;
public constructor(datePicker:DatePickerInner) {
this.datePicker = datePicker;
}
/*private getDaysInMonth(year:number, month:number) {
return ((month === 1) && (year % 4 === 0) &&
((year % 100 !== 0) || (year % 400 === 0))) ? 29 : DAYS_IN_MONTH[month];
}*/
public ngOnInit():void {
let self = this;
this.datePicker.stepDay = {months: 1};
this.datePicker.setRefreshViewHandler(function ():void {
let year = this.activeDate.getFullYear();
let month = this.activeDate.getMonth();
let firstDayOfMonth = new Date(year, month, 1);
let difference = this.startingDay - firstDayOfMonth.getDay();
let numDisplayedFromPreviousMonth = (difference > 0)
? 7 - difference
: -difference;
let firstDate = new Date(firstDayOfMonth.getTime());
if (numDisplayedFromPreviousMonth > 0) {
firstDate.setDate(-numDisplayedFromPreviousMonth + 1);
}
// 42 is the number of days on a six-week calendar
let _days:Array<Date> = self.getDates(firstDate, 42);
let days:Array<any> = [];
for (let i = 0; i < 42; i++) {
let _dateObject = this.createDateObject(_days[i], this.formatDay);
_dateObject.secondary = _days[i].getMonth() !== month;
_dateObject.uid = this.uniqueId + '-' + i;
days[i] = _dateObject;
}
self.labels = [];
for (let j = 0; j < 7; j++) {
self.labels[j] = {};
self.labels[j].abbr = this.dateFilter(days[j].date, this.formatDayHeader);
self.labels[j].full = this.dateFilter(days[j].date, 'EEEE');
}
self.title = this.dateFilter(this.activeDate, this.formatDayTitle);
self.rows = this.split(days, 7);
if (this.showWeeks) {
self.weekNumbers = [];
let thursdayIndex = (4 + 7 - this.startingDay) % 7,
numWeeks = self.rows.length;
for (let curWeek = 0; curWeek < numWeeks; curWeek++) {
self.weekNumbers.push(self.getISO8601WeekNumber(self.rows[curWeek][thursdayIndex].date));
}
}
}, 'day');
this.datePicker.setCompareHandler(function (date1:Date, date2:Date):number {
let d1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
let d2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
return d1.getTime() - d2.getTime();
}, 'day');
this.datePicker.refreshView();
}
private getDates(startDate:Date, n:number):Array<Date> {
let dates:Array<Date> = new Array(n);
let current = new Date(startDate.getTime());
let i = 0;
let date:Date;
while (i < n) {
date = new Date(current.getTime());
date = this.datePicker.fixTimeZone(date);
dates[i++] = date;
current = new Date(current.getFullYear(), current.getMonth(), current.getDate() + 1);
}
return dates;
}
private getISO8601WeekNumber(date:Date):number {
let checkDate = new Date(date.getTime());
// Thursday
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
let time = checkDate.getTime();
// Compare with Jan 1
checkDate.setMonth(0);
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate.getTime()) / 86400000) / 7) + 1;
}
// todo: key events implementation
}<|fim▁end|>
|
<th *ngFor="#labelz of labels" class="text-xs-center"><small aria-label="labelz.full"><b>{{labelz.abbr}}</b></small></th>
`,
|
<|file_name|>Methuselah.py<|end_file_name|><|fim▁begin|>from .View import View
class MethuselahView(View):<|fim▁hole|> "stableAfter": {"pick": "l"}
}<|fim▁end|>
|
type = "Methuselah"
trans = {
|
<|file_name|>set-user.go<|end_file_name|><|fim▁begin|>// Copyright 2016 The acbuild 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 oci
import (
"fmt"
"strings"
)
// SetUser will set the user (username or UID) the app in this container will
// run as<|fim▁hole|> }
if strings.Contains(user, ":") {
return fmt.Errorf("user cannot contain a ':' character")
}
if !strings.Contains(i.config.Config.User, ":") {
i.config.Config.User = user
} else {
tokens := strings.Split(i.config.Config.User, ":")
if len(tokens) != 2 {
return fmt.Errorf("something has gone horribly wrong setting the user")
}
i.config.Config.User = user + ":" + tokens[1]
}
return i.save()
}<|fim▁end|>
|
func (i *Image) SetUser(user string) error {
if user == "" {
return fmt.Errorf("user cannot be empty")
|
<|file_name|>user.js<|end_file_name|><|fim▁begin|>import modelExtend from 'dva-model-extend'
import { create, remove, update } from '../services/user'
import * as usersService from '../services/users'
import { pageModel } from './common'
import { config } from 'utils'
const { query } = usersService
const { prefix } = config
export default modelExtend(pageModel, {
namespace: 'user',
state: {
currentItem: {},
modalVisible: false,
modalType: 'create',
selectedRowKeys: [],
isMotion: localStorage.getItem(`${prefix}userIsMotion`) === 'true',
},
subscriptions: {
setup ({ dispatch, history }) {
history.listen(location => {
if (location.pathname === '/user') {
dispatch({
type: 'query',
payload: location.query,
})
}
})
},
},
effects: {
*query ({ payload = {} }, { call, put }) {
const data = yield call(query, payload)
if (data) {
yield put({
type: 'querySuccess',
payload: {
list: data.data,
pagination: {
current: Number(payload.page) || 1,
pageSize: Number(payload.pageSize) || 10,
total: data.total,
},
},
})
}
},
*'delete' ({ payload }, { call, put, select }) {
const data = yield call(remove, { id: payload })
const { selectedRowKeys } = yield select(_ => _.user)
if (data.success) {
yield put({ type: 'updateState', payload: { selectedRowKeys: selectedRowKeys.filter(_ => _ !== payload) } })
yield put({ type: 'query' })
} else {
throw data
}
},
*'multiDelete' ({ payload }, { call, put }) {
const data = yield call(usersService.remove, payload)
if (data.success) {
yield put({ type: 'updateState', payload: { selectedRowKeys: [] } })
yield put({ type: 'query' })
} else {
throw data
}
},
*create ({ payload }, { call, put }) {
const data = yield call(create, payload)<|fim▁hole|> throw data
}
},
*update ({ payload }, { select, call, put }) {
const id = yield select(({ user }) => user.currentItem.id)
const newUser = { ...payload, id }
const data = yield call(update, newUser)
if (data.success) {
yield put({ type: 'hideModal' })
yield put({ type: 'query' })
} else {
throw data
}
},
},
reducers: {
showModal (state, { payload }) {
return { ...state, ...payload, modalVisible: true }
},
hideModal (state) {
return { ...state, modalVisible: false }
},
switchIsMotion (state) {
localStorage.setItem(`${prefix}userIsMotion`, !state.isMotion)
return { ...state, isMotion: !state.isMotion }
},
},
})<|fim▁end|>
|
if (data.success) {
yield put({ type: 'hideModal' })
yield put({ type: 'query' })
} else {
|
<|file_name|>ChartRendererTest.java<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2013-2016 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public License
* version 2 and the aforementioned licenses.
*
* 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.
*/
package org.n52.io.measurement.img;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Before;
import org.junit.Test;
import org.n52.io.IoStyleContext;
import org.n52.io.MimeType;
import org.n52.io.request.RequestSimpleParameterSet;
import org.n52.io.response.dataset.DataCollection;
import org.n52.io.response.dataset.measurement.MeasurementData;
public class ChartRendererTest {
private static final String VALID_ISO8601_RELATIVE_START = "PT6H/2013-08-13TZ";
private static final String VALID_ISO8601_ABSOLUTE_START = "2013-07-13TZ/2013-08-13TZ";
private static final String VALID_ISO8601_DAYLIGHT_SAVING_SWITCH = "2013-10-28T02:00:00+02:00/2013-10-28T02:00:00+01:00";
private MyChartRenderer chartRenderer;
@Before
public void
setUp() {
this.chartRenderer = new MyChartRenderer(IoStyleContext.createEmpty());
}
@Test
public void
shouldParseBeginFromIso8601PeriodWithRelativeStart() {
Date start = chartRenderer.getStartTime(VALID_ISO8601_RELATIVE_START);
assertThat(start, is(DateTime.parse("2013-08-13TZ").minusHours(6).toDate()));
}
@Test
public void
shouldParseBeginFromIso8601PeriodWithAbsoluteStart() {
Date start = chartRenderer.getStartTime(VALID_ISO8601_ABSOLUTE_START);
assertThat(start, is(DateTime.parse("2013-08-13TZ").minusMonths(1).toDate()));
}
@Test
public void
shouldParseBeginAndEndFromIso8601PeriodContainingDaylightSavingTimezoneSwith() {
Date start = chartRenderer.getStartTime(VALID_ISO8601_DAYLIGHT_SAVING_SWITCH);
Date end = chartRenderer.getEndTime(VALID_ISO8601_DAYLIGHT_SAVING_SWITCH);
assertThat(start, is(DateTime.parse("2013-10-28T00:00:00Z").toDate()));
assertThat(end, is(DateTime.parse("2013-10-28T01:00:00Z").toDate()));<|fim▁hole|> public void
shouldHaveCETTimezoneIncludedInDomainAxisLabel() {
IoStyleContext context = IoStyleContext.createEmpty();
context.getChartStyleDefinitions().setTimespan(VALID_ISO8601_DAYLIGHT_SAVING_SWITCH);
this.chartRenderer = new MyChartRenderer(context);
String label = chartRenderer.getXYPlot().getDomainAxis().getLabel();
assertThat(label, is("Time (+01:00)"));
}
@Test
public void
shouldHandleEmptyTimespanWhenIncludingTimezoneInDomainAxisLabel() {
IoStyleContext context = IoStyleContext.createEmpty();
context.getChartStyleDefinitions().setTimespan(null);
this.chartRenderer = new MyChartRenderer(context);
String label = chartRenderer.getXYPlot().getDomainAxis().getLabel();
//assertThat(label, is("Time (+01:00)"));
}
@Test
public void
shouldHaveUTCTimezoneIncludedInDomainAxisLabel() {
IoStyleContext context = IoStyleContext.createEmpty();
context.getChartStyleDefinitions().setTimespan(VALID_ISO8601_ABSOLUTE_START);
this.chartRenderer = new MyChartRenderer(context);
String label = chartRenderer.getXYPlot().getDomainAxis().getLabel();
ISODateTimeFormat.dateTimeParser().withOffsetParsed().parseDateTime(VALID_ISO8601_ABSOLUTE_START.split("/")[1]);
assertThat(label, is("Time (UTC)"));
}
static class MyChartRenderer extends ChartIoHandler {
public MyChartRenderer(IoStyleContext context) {
super(new RequestSimpleParameterSet(), null, context);
}
public MyChartRenderer() {
super(new RequestSimpleParameterSet(), null, null);
}
@Override
public void setMimeType(MimeType mimetype) {
throw new UnsupportedOperationException();
}
@Override
public void writeDataToChart(DataCollection<MeasurementData> data) {
throw new UnsupportedOperationException();
}
}
}<|fim▁end|>
|
}
@Test
|
<|file_name|>panic-task-name-owned.rs<|end_file_name|><|fim▁begin|>// run-fail
// error-pattern:thread 'owned name' panicked at 'test'
// ignore-emscripten Needs threads.
use std::thread::Builder;
<|fim▁hole|> let r: () = Builder::new()
.name("owned name".to_string())
.spawn(move || {
panic!("test");
()
})
.unwrap()
.join()
.unwrap();
panic!();
}<|fim▁end|>
|
fn main() {
|
<|file_name|>gce_loadbalancer_external_test.go<|end_file_name|><|fim▁begin|>/*
Copyright 2017 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 gce
import (
"context"
"fmt"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
computealpha "google.golang.org/api/compute/v0.alpha"
compute "google.golang.org/api/compute/v1"
ga "google.golang.org/api/compute/v1"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
"k8s.io/kubernetes/pkg/cloudprovider/providers/gce/cloud"
"k8s.io/kubernetes/pkg/cloudprovider/providers/gce/cloud/meta"
"k8s.io/kubernetes/pkg/cloudprovider/providers/gce/cloud/mock"
netsets "k8s.io/kubernetes/pkg/util/net/sets"
)
func TestEnsureStaticIP(t *testing.T) {
t.Parallel()
gce, err := fakeGCECloud(DefaultTestClusterValues())
require.NoError(t, err)
ipName := "some-static-ip"
serviceName := "some-service"
// First ensure call
ip, existed, err := ensureStaticIP(gce, ipName, serviceName, gce.region, "", cloud.NetworkTierDefault)
if err != nil || existed {
t.Fatalf(`ensureStaticIP(%v, %v, %v, %v, "") = %v, %v, %v; want valid ip, false, nil`, gce, ipName, serviceName, gce.region, ip, existed, err)
}
// Second ensure call
var ipPrime string
ipPrime, existed, err = ensureStaticIP(gce, ipName, serviceName, gce.region, ip, cloud.NetworkTierDefault)
if err != nil || !existed || ip != ipPrime {
t.Fatalf(`ensureStaticIP(%v, %v, %v, %v, %v) = %v, %v, %v; want %v, true, nil`, gce, ipName, serviceName, gce.region, ip, ipPrime, existed, err, ip)
}
}
func TestEnsureStaticIPWithTier(t *testing.T) {
t.Parallel()
s, err := fakeGCECloud(DefaultTestClusterValues())
require.NoError(t, err)
serviceName := "some-service"
for desc, tc := range map[string]struct {
name string
netTier cloud.NetworkTier
expected string
}{
"Premium (default)": {
name: "foo-1",
netTier: cloud.NetworkTierPremium,
expected: "PREMIUM",
},
"Standard": {
name: "foo-2",
netTier: cloud.NetworkTierStandard,
expected: "STANDARD",
},
} {
t.Run(desc, func(t *testing.T) {
ip, existed, err := ensureStaticIP(s, tc.name, serviceName, s.region, "", tc.netTier)
assert.NoError(t, err)
assert.False(t, existed)
assert.NotEqual(t, ip, "")
// Get the Address from the fake address service and verify that the tier
// is set correctly.
alphaAddr, err := s.GetAlphaRegionAddress(tc.name, s.region)
require.NoError(t, err)
assert.Equal(t, tc.expected, alphaAddr.NetworkTier)
})
}
}
func TestVerifyRequestedIP(t *testing.T) {
t.Parallel()
lbRef := "test-lb"
for desc, tc := range map[string]struct {
requestedIP string
fwdRuleIP string
netTier cloud.NetworkTier
addrList []*computealpha.Address
expectErr bool
expectUserOwned bool
}{
"requested IP exists": {
requestedIP: "1.1.1.1",
netTier: cloud.NetworkTierPremium,
addrList: []*computealpha.Address{{Name: "foo", Address: "1.1.1.1", NetworkTier: "PREMIUM"}},
expectErr: false,
expectUserOwned: true,
},
"requested IP is not static, but is in use by the fwd rule": {
requestedIP: "1.1.1.1",
fwdRuleIP: "1.1.1.1",
netTier: cloud.NetworkTierPremium,
expectErr: false,
},
"requested IP is not static and is not used by the fwd rule": {
requestedIP: "1.1.1.1",
fwdRuleIP: "2.2.2.2",
netTier: cloud.NetworkTierPremium,
expectErr: true,
},
"no requested IP": {
netTier: cloud.NetworkTierPremium,
expectErr: false,
},
"requested IP exists, but network tier does not match": {
requestedIP: "1.1.1.1",
netTier: cloud.NetworkTierStandard,<|fim▁hole|> addrList: []*computealpha.Address{{Name: "foo", Address: "1.1.1.1", NetworkTier: "PREMIUM"}},
expectErr: true,
},
} {
t.Run(desc, func(t *testing.T) {
s, err := fakeGCECloud(DefaultTestClusterValues())
require.NoError(t, err)
for _, addr := range tc.addrList {
s.ReserveAlphaRegionAddress(addr, s.region)
}
isUserOwnedIP, err := verifyUserRequestedIP(s, s.region, tc.requestedIP, tc.fwdRuleIP, lbRef, tc.netTier)
assert.Equal(t, tc.expectErr, err != nil, fmt.Sprintf("err: %v", err))
assert.Equal(t, tc.expectUserOwned, isUserOwnedIP)
})
}
}
func TestCreateForwardingRuleWithTier(t *testing.T) {
t.Parallel()
// Common variables among the tests.
ports := []v1.ServicePort{{Name: "foo", Protocol: v1.ProtocolTCP, Port: int32(123)}}
target := "test-target-pool"
vals := DefaultTestClusterValues()
serviceName := "foo-svc"
baseLinkURL := "https://www.googleapis.com/compute/%v/projects/%v/regions/%v/forwardingRules/%v"
for desc, tc := range map[string]struct {
netTier cloud.NetworkTier
expectedRule *computealpha.ForwardingRule
}{
"Premium tier": {
netTier: cloud.NetworkTierPremium,
expectedRule: &computealpha.ForwardingRule{
Name: "lb-1",
Description: `{"kubernetes.io/service-name":"foo-svc"}`,
IPAddress: "1.1.1.1",
IPProtocol: "TCP",
PortRange: "123-123",
Target: target,
NetworkTier: "PREMIUM",
SelfLink: fmt.Sprintf(baseLinkURL, "v1", vals.ProjectID, vals.Region, "lb-1"),
},
},
"Standard tier": {
netTier: cloud.NetworkTierStandard,
expectedRule: &computealpha.ForwardingRule{
Name: "lb-2",
Description: `{"kubernetes.io/service-name":"foo-svc"}`,
IPAddress: "2.2.2.2",
IPProtocol: "TCP",
PortRange: "123-123",
Target: target,
NetworkTier: "STANDARD",
SelfLink: fmt.Sprintf(baseLinkURL, "alpha", vals.ProjectID, vals.Region, "lb-2"),
},
},
} {
t.Run(desc, func(t *testing.T) {
s, err := fakeGCECloud(vals)
require.NoError(t, err)
lbName := tc.expectedRule.Name
ipAddr := tc.expectedRule.IPAddress
err = createForwardingRule(s, lbName, serviceName, s.region, ipAddr, target, ports, tc.netTier)
assert.NoError(t, err)
alphaRule, err := s.GetAlphaRegionForwardingRule(lbName, s.region)
assert.NoError(t, err)
assert.Equal(t, tc.expectedRule, alphaRule)
})
}
}
func TestDeleteAddressWithWrongTier(t *testing.T) {
t.Parallel()
lbRef := "test-lb"
s, err := fakeGCECloud(DefaultTestClusterValues())
require.NoError(t, err)
// Enable the cloud.NetworkTiers feature
s.AlphaFeatureGate.features[AlphaFeatureNetworkTiers] = true
for desc, tc := range map[string]struct {
addrName string
netTier cloud.NetworkTier
addrList []*computealpha.Address
expectDelete bool
}{
"Network tiers (premium) match; do nothing": {
addrName: "foo1",
netTier: cloud.NetworkTierPremium,
addrList: []*computealpha.Address{{Name: "foo1", Address: "1.1.1.1", NetworkTier: "PREMIUM"}},
},
"Network tiers (standard) match; do nothing": {
addrName: "foo2",
netTier: cloud.NetworkTierStandard,
addrList: []*computealpha.Address{{Name: "foo2", Address: "1.1.1.2", NetworkTier: "STANDARD"}},
},
"Wrong network tier (standard); delete address": {
addrName: "foo3",
netTier: cloud.NetworkTierPremium,
addrList: []*computealpha.Address{{Name: "foo3", Address: "1.1.1.3", NetworkTier: "STANDARD"}},
expectDelete: true,
},
"Wrong network tier (premium); delete address": {
addrName: "foo4",
netTier: cloud.NetworkTierStandard,
addrList: []*computealpha.Address{{Name: "foo4", Address: "1.1.1.4", NetworkTier: "PREMIUM"}},
expectDelete: true,
},
} {
t.Run(desc, func(t *testing.T) {
for _, addr := range tc.addrList {
s.ReserveAlphaRegionAddress(addr, s.region)
}
// Sanity check to ensure we inject the right address.
_, err = s.GetRegionAddress(tc.addrName, s.region)
require.NoError(t, err)
err = deleteAddressWithWrongTier(s, s.region, tc.addrName, lbRef, tc.netTier)
assert.NoError(t, err)
// Check whether the address still exists.
_, err = s.GetRegionAddress(tc.addrName, s.region)
if tc.expectDelete {
assert.True(t, isNotFound(err))
} else {
assert.NoError(t, err)
}
})
}
}
func createExternalLoadBalancer(gce *Cloud, svc *v1.Service, nodeNames []string, clusterName, clusterID, zoneName string) (*v1.LoadBalancerStatus, error) {
nodes, err := createAndInsertNodes(gce, nodeNames, zoneName)
if err != nil {
return nil, err
}
return gce.ensureExternalLoadBalancer(
clusterName,
clusterID,
svc,
nil,
nodes,
)
}
func TestEnsureExternalLoadBalancer(t *testing.T) {
t.Parallel()
vals := DefaultTestClusterValues()
nodeNames := []string{"test-node-1"}
gce, err := fakeGCECloud(vals)
require.NoError(t, err)
svc := fakeLoadbalancerService("")
status, err := createExternalLoadBalancer(gce, svc, nodeNames, vals.ClusterName, vals.ClusterID, vals.ZoneName)
assert.NoError(t, err)
assert.NotEmpty(t, status.Ingress)
assertExternalLbResources(t, gce, svc, vals, nodeNames)
}
func TestUpdateExternalLoadBalancer(t *testing.T) {
t.Parallel()
vals := DefaultTestClusterValues()
nodeName := "test-node-1"
gce, err := fakeGCECloud((DefaultTestClusterValues()))
require.NoError(t, err)
svc := fakeLoadbalancerService("")
_, err = createExternalLoadBalancer(gce, svc, []string{nodeName}, vals.ClusterName, vals.ClusterID, vals.ZoneName)
assert.NoError(t, err)
newNodeName := "test-node-2"
newNodes, err := createAndInsertNodes(gce, []string{nodeName, newNodeName}, vals.ZoneName)
assert.NoError(t, err)
// Add the new node, then check that it is properly added to the TargetPool
err = gce.updateExternalLoadBalancer("", svc, newNodes)
assert.NoError(t, err)
lbName := gce.GetLoadBalancerName(context.TODO(), "", svc)
pool, err := gce.GetTargetPool(lbName, gce.region)
require.NoError(t, err)
// TODO: when testify is updated to v1.2.0+, use ElementsMatch instead
assert.Contains(
t,
pool.Instances,
fmt.Sprintf("/zones/%s/instances/%s", vals.ZoneName, nodeName),
)
assert.Contains(
t,
pool.Instances,
fmt.Sprintf("/zones/%s/instances/%s", vals.ZoneName, newNodeName),
)
newNodes, err = createAndInsertNodes(gce, []string{nodeName}, vals.ZoneName)
assert.NoError(t, err)
// Remove the new node by calling updateExternalLoadBalancer with a list
// only containing the old node, and test that the TargetPool no longer
// contains the new node.
err = gce.updateExternalLoadBalancer(vals.ClusterName, svc, newNodes)
assert.NoError(t, err)
pool, err = gce.GetTargetPool(lbName, gce.region)
require.NoError(t, err)
assert.Equal(
t,
[]string{fmt.Sprintf("/zones/%s/instances/%s", vals.ZoneName, nodeName)},
pool.Instances,
)
}
func TestEnsureExternalLoadBalancerDeleted(t *testing.T) {
t.Parallel()
vals := DefaultTestClusterValues()
gce, err := fakeGCECloud(vals)
require.NoError(t, err)
svc := fakeLoadbalancerService("")
_, err = createExternalLoadBalancer(gce, svc, []string{"test-node-1"}, vals.ClusterName, vals.ClusterID, vals.ZoneName)
assert.NoError(t, err)
err = gce.ensureExternalLoadBalancerDeleted(vals.ClusterName, vals.ClusterID, svc)
assert.NoError(t, err)
assertExternalLbResourcesDeleted(t, gce, svc, vals, true)
}
func TestLoadBalancerWrongTierResourceDeletion(t *testing.T) {
t.Parallel()
vals := DefaultTestClusterValues()
gce, err := fakeGCECloud(vals)
require.NoError(t, err)
// Enable the cloud.NetworkTiers feature
gce.AlphaFeatureGate.features[AlphaFeatureNetworkTiers] = true
svc := fakeLoadbalancerService("")
svc.Annotations = map[string]string{NetworkTierAnnotationKey: "Premium"}
// cloud.NetworkTier defaults to Premium
desiredTier, err := gce.getServiceNetworkTier(svc)
require.NoError(t, err)
assert.Equal(t, cloud.NetworkTierPremium, desiredTier)
lbName := gce.GetLoadBalancerName(context.TODO(), "", svc)
serviceName := types.NamespacedName{Namespace: svc.Namespace, Name: svc.Name}
// create ForwardingRule and Address with the wrong tier
err = createForwardingRule(
gce,
lbName,
serviceName.String(),
gce.region,
"",
gce.targetPoolURL(lbName),
svc.Spec.Ports,
cloud.NetworkTierStandard,
)
require.NoError(t, err)
addressObj := &computealpha.Address{
Name: lbName,
Description: serviceName.String(),
NetworkTier: cloud.NetworkTierStandard.ToGCEValue(),
}
err = gce.ReserveAlphaRegionAddress(addressObj, gce.region)
require.NoError(t, err)
_, err = createExternalLoadBalancer(gce, svc, []string{"test-node-1"}, vals.ClusterName, vals.ClusterID, vals.ZoneName)
require.NoError(t, err)
// Expect forwarding rule tier to not be Standard
tier, err := gce.getNetworkTierFromForwardingRule(lbName, gce.region)
assert.NoError(t, err)
assert.Equal(t, cloud.NetworkTierDefault.ToGCEValue(), tier)
// Expect address to be deleted
_, err = gce.GetRegionAddress(lbName, gce.region)
assert.True(t, isNotFound(err))
}
func TestEnsureExternalLoadBalancerFailsIfInvalidNetworkTier(t *testing.T) {
t.Parallel()
vals := DefaultTestClusterValues()
gce, err := fakeGCECloud(DefaultTestClusterValues())
require.NoError(t, err)
nodeNames := []string{"test-node-1"}
nodes, err := createAndInsertNodes(gce, nodeNames, vals.ZoneName)
require.NoError(t, err)
// Enable the cloud.NetworkTiers feature
gce.AlphaFeatureGate.features[AlphaFeatureNetworkTiers] = true
svc := fakeLoadbalancerService("")
svc.Annotations = map[string]string{NetworkTierAnnotationKey: wrongTier}
_, err = gce.ensureExternalLoadBalancer(vals.ClusterName, vals.ClusterID, svc, nil, nodes)
require.Error(t, err)
assert.EqualError(t, err, errStrUnsupportedTier)
}
func TestEnsureExternalLoadBalancerFailsWithNoNodes(t *testing.T) {
t.Parallel()
vals := DefaultTestClusterValues()
gce, err := fakeGCECloud(DefaultTestClusterValues())
require.NoError(t, err)
svc := fakeLoadbalancerService("")
_, err = gce.ensureExternalLoadBalancer(vals.ClusterName, vals.ClusterID, svc, nil, []*v1.Node{})
require.Error(t, err)
assert.EqualError(t, err, errStrLbNoHosts)
}
func TestForwardingRuleNeedsUpdate(t *testing.T) {
t.Parallel()
vals := DefaultTestClusterValues()
gce, err := fakeGCECloud(DefaultTestClusterValues())
require.NoError(t, err)
status, err := createExternalLoadBalancer(gce, fakeLoadbalancerService(""), []string{"test-node-1"}, vals.ClusterName, vals.ClusterID, vals.ZoneName)
require.NotNil(t, status)
require.NoError(t, err)
svc := fakeLoadbalancerService("")
lbName := gce.GetLoadBalancerName(context.TODO(), "", svc)
ipAddr := status.Ingress[0].IP
lbIP := svc.Spec.LoadBalancerIP
wrongPorts := []v1.ServicePort{svc.Spec.Ports[0]}
wrongPorts[0].Port = wrongPorts[0].Port + 1
wrongProtocolPorts := []v1.ServicePort{svc.Spec.Ports[0]}
wrongProtocolPorts[0].Protocol = v1.ProtocolUDP
for desc, tc := range map[string]struct {
lbIP string
ports []v1.ServicePort
exists bool
needsUpdate bool
expectIPAddr string
expectError bool
}{
"When the loadBalancerIP does not equal the FwdRule IP address.": {
lbIP: "1.2.3.4",
ports: svc.Spec.Ports,
exists: true,
needsUpdate: true,
expectIPAddr: ipAddr,
expectError: false,
},
"When loadBalancerPortRange returns an error.": {
lbIP: lbIP,
ports: []v1.ServicePort{},
exists: true,
needsUpdate: false,
expectIPAddr: "",
expectError: true,
},
"When portRange not equals to the forwardingRule port range.": {
lbIP: lbIP,
ports: wrongPorts,
exists: true,
needsUpdate: true,
expectIPAddr: ipAddr,
expectError: false,
},
"When the ports protocol does not equal the ForwardingRuel IP Protocol.": {
lbIP: lbIP,
ports: wrongProtocolPorts,
exists: true,
needsUpdate: true,
expectIPAddr: ipAddr,
expectError: false,
},
"When basic workflow.": {
lbIP: lbIP,
ports: svc.Spec.Ports,
exists: true,
needsUpdate: false,
expectIPAddr: ipAddr,
expectError: false,
},
} {
t.Run(desc, func(t *testing.T) {
exists, needsUpdate, ipAddress, err := gce.forwardingRuleNeedsUpdate(lbName, vals.Region, tc.lbIP, tc.ports)
assert.Equal(t, tc.exists, exists, "'exists' didn't return as expected "+desc)
assert.Equal(t, tc.needsUpdate, needsUpdate, "'needsUpdate' didn't return as expected "+desc)
assert.Equal(t, tc.expectIPAddr, ipAddress, "'ipAddress' didn't return as expected "+desc)
if tc.expectError {
assert.Error(t, err, "Should returns an error "+desc)
} else {
assert.NoError(t, err, "Should not returns an error "+desc)
}
})
}
}
func TestTargetPoolNeedsRecreation(t *testing.T) {
t.Parallel()
vals := DefaultTestClusterValues()
gce, err := fakeGCECloud(DefaultTestClusterValues())
require.NoError(t, err)
svc := fakeLoadbalancerService("")
serviceName := svc.ObjectMeta.Name
lbName := gce.GetLoadBalancerName(context.TODO(), "", svc)
nodes, err := createAndInsertNodes(gce, []string{"test-node-1"}, vals.ZoneName)
require.NoError(t, err)
hostNames := nodeNames(nodes)
hosts, err := gce.getInstancesByNames(hostNames)
var instances []string
for _, host := range hosts {
instances = append(instances, host.makeComparableHostPath())
}
pool := &compute.TargetPool{
Name: lbName,
Description: fmt.Sprintf(`{"kubernetes.io/service-name":"%s"}`, serviceName),
Instances: instances,
SessionAffinity: translateAffinityType(v1.ServiceAffinityNone),
}
err = gce.CreateTargetPool(pool, vals.Region)
require.NoError(t, err)
c := gce.c.(*cloud.MockGCE)
c.MockTargetPools.GetHook = mock.GetTargetPoolInternalErrHook
exists, needsRecreation, err := gce.targetPoolNeedsRecreation(lbName, vals.Region, v1.ServiceAffinityNone)
assert.True(t, exists)
assert.False(t, needsRecreation)
require.NotNil(t, err)
assert.True(t, strings.HasPrefix(err.Error(), errPrefixGetTargetPool))
c.MockTargetPools.GetHook = nil
exists, needsRecreation, err = gce.targetPoolNeedsRecreation(lbName, vals.Region, v1.ServiceAffinityClientIP)
assert.True(t, exists)
assert.True(t, needsRecreation)
assert.NoError(t, err)
exists, needsRecreation, err = gce.targetPoolNeedsRecreation(lbName, vals.Region, v1.ServiceAffinityNone)
assert.True(t, exists)
assert.False(t, needsRecreation)
assert.NoError(t, err)
}
func TestFirewallNeedsUpdate(t *testing.T) {
t.Parallel()
vals := DefaultTestClusterValues()
gce, err := fakeGCECloud(DefaultTestClusterValues())
require.NoError(t, err)
svc := fakeLoadbalancerService("")
status, err := createExternalLoadBalancer(gce, svc, []string{"test-node-1"}, vals.ClusterName, vals.ClusterID, vals.ZoneName)
require.NotNil(t, status)
require.NoError(t, err)
svcName := "/" + svc.ObjectMeta.Name
region := vals.Region
ipAddr := status.Ingress[0].IP
lbName := gce.GetLoadBalancerName(context.TODO(), "", svc)
ipnet, err := netsets.ParseIPNets("0.0.0.0/0")
require.NoError(t, err)
wrongIpnet, err := netsets.ParseIPNets("1.0.0.0/10")
require.NoError(t, err)
fw, err := gce.GetFirewall(MakeFirewallName(lbName))
require.NoError(t, err)
for desc, tc := range map[string]struct {
lbName string
ipAddr string
ports []v1.ServicePort
ipnet netsets.IPNet
fwIPProtocol string
getHook func(context.Context, *meta.Key, *cloud.MockFirewalls) (bool, *ga.Firewall, error)
sourceRange string
exists bool
needsUpdate bool
hasErr bool
}{
"When response is a Non-400 HTTP error.": {
lbName: lbName,
ipAddr: ipAddr,
ports: svc.Spec.Ports,
ipnet: ipnet,
fwIPProtocol: "tcp",
getHook: mock.GetFirewallsUnauthorizedErrHook,
sourceRange: fw.SourceRanges[0],
exists: false,
needsUpdate: false,
hasErr: true,
},
"When given a wrong description.": {
lbName: lbName,
ipAddr: "",
ports: svc.Spec.Ports,
ipnet: ipnet,
fwIPProtocol: "tcp",
getHook: nil,
sourceRange: fw.SourceRanges[0],
exists: true,
needsUpdate: true,
hasErr: false,
},
"When IPProtocol doesn't match.": {
lbName: lbName,
ipAddr: ipAddr,
ports: svc.Spec.Ports,
ipnet: ipnet,
fwIPProtocol: "usps",
getHook: nil,
sourceRange: fw.SourceRanges[0],
exists: true,
needsUpdate: true,
hasErr: false,
},
"When the ports don't match.": {
lbName: lbName,
ipAddr: ipAddr,
ports: []v1.ServicePort{{Protocol: v1.ProtocolTCP, Port: int32(666)}},
ipnet: ipnet,
fwIPProtocol: "tcp",
getHook: nil,
sourceRange: fw.SourceRanges[0],
exists: true,
needsUpdate: true,
hasErr: false,
},
"When parseIPNets returns an error.": {
lbName: lbName,
ipAddr: ipAddr,
ports: svc.Spec.Ports,
ipnet: ipnet,
fwIPProtocol: "tcp",
getHook: nil,
sourceRange: "badSourceRange",
exists: true,
needsUpdate: true,
hasErr: false,
},
"When the source ranges are not equal.": {
lbName: lbName,
ipAddr: ipAddr,
ports: svc.Spec.Ports,
ipnet: wrongIpnet,
fwIPProtocol: "tcp",
getHook: nil,
sourceRange: fw.SourceRanges[0],
exists: true,
needsUpdate: true,
hasErr: false,
},
"When basic flow without exceptions.": {
lbName: lbName,
ipAddr: ipAddr,
ports: svc.Spec.Ports,
ipnet: ipnet,
fwIPProtocol: "tcp",
getHook: nil,
sourceRange: fw.SourceRanges[0],
exists: true,
needsUpdate: false,
hasErr: false,
},
} {
t.Run(desc, func(t *testing.T) {
fw, err = gce.GetFirewall(MakeFirewallName(tc.lbName))
fw.Allowed[0].IPProtocol = tc.fwIPProtocol
fw, err = gce.GetFirewall(MakeFirewallName(tc.lbName))
require.Equal(t, fw.Allowed[0].IPProtocol, tc.fwIPProtocol)
trueSourceRange := fw.SourceRanges[0]
fw.SourceRanges[0] = tc.sourceRange
fw, err = gce.GetFirewall(MakeFirewallName(lbName))
require.Equal(t, fw.SourceRanges[0], tc.sourceRange)
c := gce.c.(*cloud.MockGCE)
c.MockFirewalls.GetHook = tc.getHook
exists, needsUpdate, err := gce.firewallNeedsUpdate(
tc.lbName,
svcName,
region,
tc.ipAddr,
tc.ports,
tc.ipnet)
assert.Equal(t, tc.exists, exists, "'exists' didn't return as expected "+desc)
assert.Equal(t, tc.needsUpdate, needsUpdate, "'needsUpdate' didn't return as expected "+desc)
if tc.hasErr {
assert.Error(t, err, "Should returns an error "+desc)
} else {
assert.NoError(t, err, "Should not returns an error "+desc)
}
c.MockFirewalls.GetHook = nil
fw.Allowed[0].IPProtocol = "tcp"
fw.SourceRanges[0] = trueSourceRange
fw, err = gce.GetFirewall(MakeFirewallName(tc.lbName))
require.Equal(t, fw.Allowed[0].IPProtocol, "tcp")
require.Equal(t, fw.SourceRanges[0], trueSourceRange)
})
}
}
func TestDeleteWrongNetworkTieredResourcesSucceedsWhenNotFound(t *testing.T) {
t.Parallel()
gce, err := fakeGCECloud(DefaultTestClusterValues())
require.NoError(t, err)
gce.AlphaFeatureGate.features[AlphaFeatureNetworkTiers] = true
assert.Nil(t, gce.deleteWrongNetworkTieredResources("Wrong_LB_Name", "", cloud.NetworkTier("")))
}
func TestEnsureTargetPoolAndHealthCheck(t *testing.T) {
t.Parallel()
vals := DefaultTestClusterValues()
gce, err := fakeGCECloud(DefaultTestClusterValues())
require.NoError(t, err)
nodes, err := createAndInsertNodes(gce, []string{"test-node-1"}, vals.ZoneName)
require.NoError(t, err)
svc := fakeLoadbalancerService("")
status, err := gce.ensureExternalLoadBalancer(
vals.ClusterName,
vals.ClusterID,
svc,
nil,
nodes,
)
require.NotNil(t, status)
require.NoError(t, err)
hostNames := nodeNames(nodes)
hosts, err := gce.getInstancesByNames(hostNames)
clusterID := vals.ClusterID
ipAddr := status.Ingress[0].IP
lbName := gce.GetLoadBalancerName(context.TODO(), "", svc)
region := vals.Region
hcToCreate := makeHTTPHealthCheck(MakeNodesHealthCheckName(clusterID), GetNodesHealthCheckPath(), GetNodesHealthCheckPort())
hcToDelete := makeHTTPHealthCheck(MakeNodesHealthCheckName(clusterID), GetNodesHealthCheckPath(), GetNodesHealthCheckPort())
// Apply a tag on the target pool. By verifying the change of the tag, target pool update can be ensured.
tag := "A Tag"
pool, err := gce.GetTargetPool(lbName, region)
pool.CreationTimestamp = tag
pool, err = gce.GetTargetPool(lbName, region)
require.Equal(t, tag, pool.CreationTimestamp)
err = gce.ensureTargetPoolAndHealthCheck(true, true, svc, lbName, clusterID, ipAddr, hosts, hcToCreate, hcToDelete)
assert.NoError(t, err)
pool, err = gce.GetTargetPool(lbName, region)
assert.NotEqual(t, pool.CreationTimestamp, tag)
pool, err = gce.GetTargetPool(lbName, region)
assert.Equal(t, 1, len(pool.Instances))
var manyNodeName [maxTargetPoolCreateInstances + 1]string
for i := 0; i < maxTargetPoolCreateInstances+1; i++ {
manyNodeName[i] = fmt.Sprintf("testnode_%d", i)
}
manyNodes, err := createAndInsertNodes(gce, manyNodeName[:], vals.ZoneName)
require.NoError(t, err)
manyHostNames := nodeNames(manyNodes)
manyHosts, err := gce.getInstancesByNames(manyHostNames)
err = gce.ensureTargetPoolAndHealthCheck(true, true, svc, lbName, clusterID, ipAddr, manyHosts, hcToCreate, hcToDelete)
assert.NoError(t, err)
pool, err = gce.GetTargetPool(lbName, region)
assert.Equal(t, maxTargetPoolCreateInstances+1, len(pool.Instances))
err = gce.ensureTargetPoolAndHealthCheck(true, false, svc, lbName, clusterID, ipAddr, hosts, hcToCreate, hcToDelete)
assert.NoError(t, err)
pool, err = gce.GetTargetPool(lbName, region)
assert.Equal(t, 1, len(pool.Instances))
}
func TestCreateAndUpdateFirewallSucceedsOnXPN(t *testing.T) {
t.Parallel()
gce, err := fakeGCECloud(DefaultTestClusterValues())
require.NoError(t, err)
vals := DefaultTestClusterValues()
c := gce.c.(*cloud.MockGCE)
c.MockFirewalls.InsertHook = mock.InsertFirewallsUnauthorizedErrHook
c.MockFirewalls.UpdateHook = mock.UpdateFirewallsUnauthorizedErrHook
gce.onXPN = true
require.True(t, gce.OnXPN())
recorder := record.NewFakeRecorder(1024)
gce.eventRecorder = recorder
svc := fakeLoadbalancerService("")
nodes, err := createAndInsertNodes(gce, []string{"test-node-1"}, vals.ZoneName)
require.NoError(t, err)
hostNames := nodeNames(nodes)
hosts, err := gce.getInstancesByNames(hostNames)
require.NoError(t, err)
ipnet, err := netsets.ParseIPNets("10.0.0.0/20")
require.NoError(t, err)
gce.createFirewall(
svc,
gce.GetLoadBalancerName(context.TODO(), "", svc),
gce.region,
"A sad little firewall",
ipnet,
svc.Spec.Ports,
hosts)
require.Nil(t, err)
msg := fmt.Sprintf("%s %s %s", v1.EventTypeNormal, eventReasonManualChange, eventMsgFirewallChange)
checkEvent(t, recorder, msg, true)
gce.updateFirewall(
svc,
gce.GetLoadBalancerName(context.TODO(), "", svc),
gce.region,
"A sad little firewall",
ipnet,
svc.Spec.Ports,
hosts)
require.Nil(t, err)
msg = fmt.Sprintf("%s %s %s", v1.EventTypeNormal, eventReasonManualChange, eventMsgFirewallChange)
checkEvent(t, recorder, msg, true)
}
func TestEnsureExternalLoadBalancerDeletedSucceedsOnXPN(t *testing.T) {
t.Parallel()
vals := DefaultTestClusterValues()
gce, err := fakeGCECloud(DefaultTestClusterValues())
require.NoError(t, err)
_, err = createExternalLoadBalancer(gce, fakeLoadbalancerService(""), []string{"test-node-1"}, vals.ClusterName, vals.ClusterID, vals.ZoneName)
require.NoError(t, err)
c := gce.c.(*cloud.MockGCE)
c.MockFirewalls.DeleteHook = mock.DeleteFirewallsUnauthorizedErrHook
gce.onXPN = true
require.True(t, gce.OnXPN())
recorder := record.NewFakeRecorder(1024)
gce.eventRecorder = recorder
svc := fakeLoadbalancerService("")
err = gce.ensureExternalLoadBalancerDeleted(vals.ClusterName, vals.ClusterID, svc)
require.NoError(t, err)
msg := fmt.Sprintf("%s %s %s", v1.EventTypeNormal, eventReasonManualChange, eventMsgFirewallChange)
checkEvent(t, recorder, msg, true)
}
type EnsureELBParams struct {
clusterName string
clusterID string
service *v1.Service
existingFwdRule *compute.ForwardingRule
nodes []*v1.Node
}
// newEnsureELBParams is the constructor of EnsureELBParams.
func newEnsureELBParams(nodes []*v1.Node, svc *v1.Service) *EnsureELBParams {
vals := DefaultTestClusterValues()
return &EnsureELBParams{
vals.ClusterName,
vals.ClusterID,
svc,
nil,
nodes,
}
}
// TestEnsureExternalLoadBalancerErrors tests the function
// ensureExternalLoadBalancer, making sure the system won't panic when
// exceptions raised by gce.
func TestEnsureExternalLoadBalancerErrors(t *testing.T) {
t.Parallel()
vals := DefaultTestClusterValues()
var params *EnsureELBParams
for desc, tc := range map[string]struct {
adjustParams func(*EnsureELBParams)
injectMock func(*cloud.MockGCE)
}{
"No hosts provided": {
adjustParams: func(params *EnsureELBParams) {
params.nodes = []*v1.Node{}
},
},
"Invalid node provided": {
adjustParams: func(params *EnsureELBParams) {
params.nodes = []*v1.Node{{}}
},
},
"Get forwarding rules failed": {
injectMock: func(c *cloud.MockGCE) {
c.MockForwardingRules.GetHook = mock.GetForwardingRulesInternalErrHook
},
},
"Get addresses failed": {
injectMock: func(c *cloud.MockGCE) {
c.MockAddresses.GetHook = mock.GetAddressesInternalErrHook
},
},
"Bad load balancer source range provided": {
adjustParams: func(params *EnsureELBParams) {
params.service.Spec.LoadBalancerSourceRanges = []string{"BadSourceRange"}
},
},
"Get firewall failed": {
injectMock: func(c *cloud.MockGCE) {
c.MockFirewalls.GetHook = mock.GetFirewallsUnauthorizedErrHook
},
},
"Create firewall failed": {
injectMock: func(c *cloud.MockGCE) {
c.MockFirewalls.InsertHook = mock.InsertFirewallsUnauthorizedErrHook
},
},
"Get target pool failed": {
injectMock: func(c *cloud.MockGCE) {
c.MockTargetPools.GetHook = mock.GetTargetPoolInternalErrHook
},
},
"Get HTTP health checks failed": {
injectMock: func(c *cloud.MockGCE) {
c.MockHttpHealthChecks.GetHook = mock.GetHTTPHealthChecksInternalErrHook
},
},
"Create target pools failed": {
injectMock: func(c *cloud.MockGCE) {
c.MockTargetPools.InsertHook = mock.InsertTargetPoolsInternalErrHook
},
},
"Create forwarding rules failed": {
injectMock: func(c *cloud.MockGCE) {
c.MockForwardingRules.InsertHook = mock.InsertForwardingRulesInternalErrHook
},
},
} {
t.Run(desc, func(t *testing.T) {
gce, err := fakeGCECloud(DefaultTestClusterValues())
nodes, err := createAndInsertNodes(gce, []string{"test-node-1"}, vals.ZoneName)
require.NoError(t, err)
svc := fakeLoadbalancerService("")
params = newEnsureELBParams(nodes, svc)
if tc.adjustParams != nil {
tc.adjustParams(params)
}
if tc.injectMock != nil {
tc.injectMock(gce.c.(*cloud.MockGCE))
}
status, err := gce.ensureExternalLoadBalancer(
params.clusterName,
params.clusterID,
params.service,
params.existingFwdRule,
params.nodes,
)
assert.Error(t, err, "Should return an error when "+desc)
assert.Nil(t, status, "Should not return a status when "+desc)
})
}
}
func TestExternalLoadBalancerEnsureHttpHealthCheck(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
desc string
modifier func(*compute.HttpHealthCheck) *compute.HttpHealthCheck
wantEqual bool
}{
{"should ensure HC", func(_ *compute.HttpHealthCheck) *compute.HttpHealthCheck { return nil }, false},
{
"should reconcile HC interval",
func(hc *compute.HttpHealthCheck) *compute.HttpHealthCheck {
hc.CheckIntervalSec = gceHcCheckIntervalSeconds - 1
return hc
},
false,
},
{
"should allow HC to be configurable to bigger intervals",
func(hc *compute.HttpHealthCheck) *compute.HttpHealthCheck {
hc.CheckIntervalSec = gceHcCheckIntervalSeconds * 10
return hc
},
true,
},
{
"should allow HC to accept bigger intervals while applying default value to small thresholds",
func(hc *compute.HttpHealthCheck) *compute.HttpHealthCheck {
hc.CheckIntervalSec = gceHcCheckIntervalSeconds * 10
hc.UnhealthyThreshold = gceHcUnhealthyThreshold - 1
return hc
},
false,
},
} {
t.Run(tc.desc, func(t *testing.T) {
gce, err := fakeGCECloud(DefaultTestClusterValues())
require.NoError(t, err)
c := gce.c.(*cloud.MockGCE)
c.MockHttpHealthChecks.UpdateHook = func(ctx context.Context, key *meta.Key, obj *ga.HttpHealthCheck, m *cloud.MockHttpHealthChecks) error {
m.Objects[*key] = &cloud.MockHttpHealthChecksObj{Obj: obj}
return nil
}
hcName, hcPath, hcPort := "test-hc", "/healthz", int32(12345)
existingHC := makeHTTPHealthCheck(hcName, hcPath, hcPort)
existingHC = tc.modifier(existingHC)
if existingHC != nil {
if err := gce.CreateHTTPHealthCheck(existingHC); err != nil {
t.Fatalf("gce.CreateHttpHealthCheck(%#v) = %v; want err = nil", existingHC, err)
}
}
if _, err := gce.ensureHTTPHealthCheck(hcName, hcPath, hcPort); err != nil {
t.Fatalf("gce.ensureHttpHealthCheck(%q, %q, %v) = _, %d; want err = nil", hcName, hcPath, hcPort, err)
}
if hc, err := gce.GetHTTPHealthCheck(hcName); err != nil {
t.Fatalf("gce.GetHttpHealthCheck(%q) = _, %d; want err = nil", hcName, err)
} else {
if tc.wantEqual {
assert.Equal(t, hc, existingHC)
} else {
assert.NotEqual(t, hc, existingHC)
}
}
})
}
}
func TestMergeHttpHealthChecks(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
desc string
checkIntervalSec int64
timeoutSec int64
healthyThreshold int64
unhealthyThreshold int64
wantCheckIntervalSec int64
wantTimeoutSec int64
wantHealthyThreshold int64
wantUnhealthyThreshold int64
}{
{"unchanged", gceHcCheckIntervalSeconds, gceHcTimeoutSeconds, gceHcHealthyThreshold, gceHcUnhealthyThreshold, gceHcCheckIntervalSeconds, gceHcTimeoutSeconds, gceHcHealthyThreshold, gceHcUnhealthyThreshold},
{"interval - too small - should reconcile", gceHcCheckIntervalSeconds - 1, gceHcTimeoutSeconds, gceHcHealthyThreshold, gceHcUnhealthyThreshold, gceHcCheckIntervalSeconds, gceHcTimeoutSeconds, gceHcHealthyThreshold, gceHcUnhealthyThreshold},
{"timeout - too small - should reconcile", gceHcCheckIntervalSeconds, gceHcTimeoutSeconds - 1, gceHcHealthyThreshold, gceHcUnhealthyThreshold, gceHcCheckIntervalSeconds, gceHcTimeoutSeconds, gceHcHealthyThreshold, gceHcUnhealthyThreshold},
{"healthy threshold - too small - should reconcile", gceHcCheckIntervalSeconds, gceHcTimeoutSeconds, gceHcHealthyThreshold - 1, gceHcUnhealthyThreshold, gceHcCheckIntervalSeconds, gceHcTimeoutSeconds, gceHcHealthyThreshold, gceHcUnhealthyThreshold},
{"unhealthy threshold - too small - should reconcile", gceHcCheckIntervalSeconds, gceHcTimeoutSeconds, gceHcHealthyThreshold, gceHcUnhealthyThreshold - 1, gceHcCheckIntervalSeconds, gceHcTimeoutSeconds, gceHcHealthyThreshold, gceHcUnhealthyThreshold},
{"interval - user configured - should keep", gceHcCheckIntervalSeconds + 1, gceHcTimeoutSeconds, gceHcHealthyThreshold, gceHcUnhealthyThreshold, gceHcCheckIntervalSeconds + 1, gceHcTimeoutSeconds, gceHcHealthyThreshold, gceHcUnhealthyThreshold},
{"timeout - user configured - should keep", gceHcCheckIntervalSeconds, gceHcTimeoutSeconds + 1, gceHcHealthyThreshold, gceHcUnhealthyThreshold, gceHcCheckIntervalSeconds, gceHcTimeoutSeconds + 1, gceHcHealthyThreshold, gceHcUnhealthyThreshold},
{"healthy threshold - user configured - should keep", gceHcCheckIntervalSeconds, gceHcTimeoutSeconds, gceHcHealthyThreshold + 1, gceHcUnhealthyThreshold, gceHcCheckIntervalSeconds, gceHcTimeoutSeconds, gceHcHealthyThreshold + 1, gceHcUnhealthyThreshold},
{"unhealthy threshold - user configured - should keep", gceHcCheckIntervalSeconds, gceHcTimeoutSeconds, gceHcHealthyThreshold, gceHcUnhealthyThreshold + 1, gceHcCheckIntervalSeconds, gceHcTimeoutSeconds, gceHcHealthyThreshold, gceHcUnhealthyThreshold + 1},
} {
t.Run(tc.desc, func(t *testing.T) {
wantHC := makeHTTPHealthCheck("hc", "/", 12345)
hc := &compute.HttpHealthCheck{
CheckIntervalSec: tc.checkIntervalSec,
TimeoutSec: tc.timeoutSec,
HealthyThreshold: tc.healthyThreshold,
UnhealthyThreshold: tc.unhealthyThreshold,
}
mergeHTTPHealthChecks(hc, wantHC)
if wantHC.CheckIntervalSec != tc.wantCheckIntervalSec {
t.Errorf("wantHC.CheckIntervalSec = %d; want %d", wantHC.CheckIntervalSec, tc.checkIntervalSec)
}
if wantHC.TimeoutSec != tc.wantTimeoutSec {
t.Errorf("wantHC.TimeoutSec = %d; want %d", wantHC.TimeoutSec, tc.timeoutSec)
}
if wantHC.HealthyThreshold != tc.wantHealthyThreshold {
t.Errorf("wantHC.HealthyThreshold = %d; want %d", wantHC.HealthyThreshold, tc.healthyThreshold)
}
if wantHC.UnhealthyThreshold != tc.wantUnhealthyThreshold {
t.Errorf("wantHC.UnhealthyThreshold = %d; want %d", wantHC.UnhealthyThreshold, tc.unhealthyThreshold)
}
})
}
}
func TestNeedToUpdateHttpHealthChecks(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
desc string
modifier func(*compute.HttpHealthCheck)
wantChanged bool
}{
{"unchanged", nil, false},
{"desc does not match", func(hc *compute.HttpHealthCheck) { hc.Description = "bad-desc" }, true},
{"port does not match", func(hc *compute.HttpHealthCheck) { hc.Port = 54321 }, true},
{"requestPath does not match", func(hc *compute.HttpHealthCheck) { hc.RequestPath = "/anotherone" }, true},
{"interval needs update", func(hc *compute.HttpHealthCheck) { hc.CheckIntervalSec = gceHcCheckIntervalSeconds - 1 }, true},
{"timeout needs update", func(hc *compute.HttpHealthCheck) { hc.TimeoutSec = gceHcTimeoutSeconds - 1 }, true},
{"healthy threshold needs update", func(hc *compute.HttpHealthCheck) { hc.HealthyThreshold = gceHcHealthyThreshold - 1 }, true},
{"unhealthy threshold needs update", func(hc *compute.HttpHealthCheck) { hc.UnhealthyThreshold = gceHcUnhealthyThreshold - 1 }, true},
{"interval does not need update", func(hc *compute.HttpHealthCheck) { hc.CheckIntervalSec = gceHcCheckIntervalSeconds + 1 }, false},
{"timeout does not need update", func(hc *compute.HttpHealthCheck) { hc.TimeoutSec = gceHcTimeoutSeconds + 1 }, false},
{"healthy threshold does not need update", func(hc *compute.HttpHealthCheck) { hc.HealthyThreshold = gceHcHealthyThreshold + 1 }, false},
{"unhealthy threshold does not need update", func(hc *compute.HttpHealthCheck) { hc.UnhealthyThreshold = gceHcUnhealthyThreshold + 1 }, false},
} {
t.Run(tc.desc, func(t *testing.T) {
hc := makeHTTPHealthCheck("hc", "/", 12345)
wantHC := makeHTTPHealthCheck("hc", "/", 12345)
if tc.modifier != nil {
tc.modifier(hc)
}
if gotChanged := needToUpdateHTTPHealthChecks(hc, wantHC); gotChanged != tc.wantChanged {
t.Errorf("needToUpdateHTTPHealthChecks(%#v, %#v) = %t; want changed = %t", hc, wantHC, gotChanged, tc.wantChanged)
}
})
}
}<|fim▁end|>
| |
<|file_name|>attachment.rs<|end_file_name|><|fim▁begin|>// notty is a new kind of terminal emulator.
// Copyright (C) 2015 without boats
//
// 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/>.
use base64;
pub struct Attachments {
data: Vec<String>,
}
impl Default for Attachments {
fn default() -> Attachments {
Attachments { data: vec![String::new()] }
}
}
impl Attachments {
pub fn clear(&mut self) {
self.data.truncate(1);
self.data.last_mut().unwrap().clear();
}
pub fn iter(&self) -> AttachmentIter {
self.into_iter()
}
pub fn append(&mut self, ch: char) -> Option<bool> {
match ch {
'0'...'9' | 'A'...'Z' | 'a'...'z' | '+' | '/' | '=' => {
self.data.last_mut().unwrap().push(ch);
None
}
'#' => {
self.data.push(String::new());
None
}
'\u{9c}' => Some(true),
_ => Some(false),
}
}
}
impl<'a> IntoIterator for &'a Attachments {
type Item = Vec<u8>;
type IntoIter = AttachmentIter<'a>;
fn into_iter(self) -> AttachmentIter<'a> {
AttachmentIter {
attachments: self.data.iter(),
}
}
}
pub struct AttachmentIter<'a>{
attachments: <&'a Vec<String> as IntoIterator>::IntoIter,
}
impl<'a> Iterator for AttachmentIter<'a> {
type Item = Vec<u8>;
fn next(&mut self) -> Option<Vec<u8>> {
self.attachments.next().and_then(|data| base64::u8de(data.as_bytes()).ok())
}
}
#[cfg(test)]
mod tests {
use base64;
use super::*;
static BLOCKS: &'static [&'static str] = &[
"YELLOW SUBMARINE",
"Hello, world!",
"History is a nightmare from which I am trying to awaken.",
"#",
"Happy familie are all alike; every unhappy family is unhappy in its own way.",
"--A little more test data.--"
];
#[test]
fn iterates() {
let attachments = Attachments {
data: BLOCKS.iter().map(|s| base64::encode(s).unwrap()).collect()
};
for (attachment, block) in (&attachments).into_iter().zip(BLOCKS) {
assert_eq!(attachment, block.as_bytes());
}
}
#[test]
fn appends() {
let mut attachments = Attachments::default();
for data in BLOCKS.iter().map(|s| base64::encode(s).unwrap()) {
for ch in data.chars() {
assert_eq!(attachments.append(ch), None);
}
assert_eq!(attachments.append('#'), None);
}
assert_eq!(attachments.append('\u{9c}'), Some(true));
for (attachment, block) in (&attachments).into_iter().zip(BLOCKS) {
assert_eq!(attachment, block.as_bytes());
}
}
#[test]
fn wont_append_invalid_chars() {
let mut attachments = Attachments::default();
assert_eq!(attachments.append('~'), Some(false));
assert_eq!(attachments.data.last().unwrap().len(), 0);
}
}<|fim▁end|>
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
|
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>struct Lexer<'a> {
src: &'a [u8],
pos: usize
}
impl<'a> Lexer<'a> {
fn new(src: &'a [u8]) -> Lexer {
Lexer { src: src, pos: 0 }
}
}
impl<'a> Lexer<'a> {
fn ch(&self) -> u8 {
self.src[self.pos]
}
fn eof(&self) -> bool {
self.pos >= self.src.len()
}
fn skip_ws(&mut self) -> usize {
let prev_pos = self.pos;
while self.valid_ws() {
self.pos += 1;
}
self.pos - prev_pos
}
fn string(&mut self) -> Option<String> {
let mut tok = Vec::<u8>::new();
loop {
if self.eof() {
break
}
match self.ch() {
b' ' => break,
b'\t' => break,
b'\r' => break,
b'\n' => break,
b'"' => break,
_ => ()
}
tok.push(self.ch());
self.pos += 1;
}
match tok.len() {
0 => None,
_ => Some(String::from_utf8(tok).unwrap())
}
}
fn quoted_string(&mut self) -> Option<String> {
let mut tok = Vec::<u8>::new();
self.pos += 1;
loop {
if self.eof() {
break;
}
match self.ch() {
b'"' => { self.pos += 1; break; },
_ => ()
}
tok.push(self.ch());
self.pos += 1;
}
match tok.len() {
0 => None,
_ => Some(String::from_utf8(tok).unwrap())
}
}
fn valid_ws(&self) -> bool {
if self.eof() {
return false;
}
match self.ch() {
b' ' => true,
b'\t' => true,
b'\r' => true,
b'\n' => true,
_ => false
}
}
}
impl<'a> Iterator for Lexer<'a> {
type Item = String;
fn next(&mut self) -> Option<String> {<|fim▁hole|> if self.eof() {
return None;
}
match self.ch() {
b'"' => self.quoted_string(),
_ => self.string()
}
}
}
#[test]
fn tokenize() {
let src = b" foo bar \"a b\" baz ";
let lexer = Lexer::new(src);
let tokens: Vec<_> = lexer.collect();
assert_eq!(4, tokens.len());
assert_eq!("foo".to_string(), tokens[0]);
assert_eq!("bar".to_string(), tokens[1]);
assert_eq!("a b".to_string(), tokens[2]);
assert_eq!("baz".to_string(), tokens[3]);
}<|fim▁end|>
|
self.skip_ws();
|
<|file_name|>__openerp__.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
##############################################################################
#
# Account Journal Always Check Date module for OpenERP
# Copyright (C) 2013-2014 Akretion (http://www.akretion.com)
# @author Alexis de Lattre <[email protected]>
#
# 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
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# 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/>.
#
##############################################################################<|fim▁hole|>{
'name': 'Account Journal Always Check Date',
'version': '0.1',
'category': 'Accounting & Finance',
'license': 'AGPL-3',
'summary': 'Option Check Date in Period always active on journals',
'description': """
Check Date in Period always active on Account Journals
======================================================
This module:
* activates the 'Check Date in Period' option on all existing account journals,
* enable the 'Check Date in Period' option on new account journals,
* prevent users from deactivating the 'Check Date in Period' option.
So this module is an additionnal security for countries where, on an account
move, the date must be inside the period.
Please contact Alexis de Lattre from Akretion <[email protected]>
for any help or question about this module.
""",
'author': "Akretion,Odoo Community Association (OCA)",
'website': 'http://www.akretion.com',
'depends': ['account'],
'data': [],
'installable': True,
'active': False,
}<|fim▁end|>
| |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 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.
/*!
Syntax extension to generate FourCCs.
Once loaded, fourcc!() is called with a single 4-character string,
and an optional ident that is either `big`, `little`, or `target`.
The ident represents endianness, and specifies in which direction
the characters should be read. If the ident is omitted, it is assumed
to be `big`, i.e. left-to-right order. It returns a u32.
# Examples
To load the extension and use it:
```rust,ignore
#[phase(plugin)]
extern crate fourcc;
fn main() {
let val = fourcc!("\xC0\xFF\xEE!");
assert_eq!(val, 0xC0FFEE21u32);
let little_val = fourcc!("foo ", little);
assert_eq!(little_val, 0x21EEFFC0u32);
}
```
# References
* [Wikipedia: FourCC](http://en.wikipedia.org/wiki/FourCC)
*/
#![crate_name = "fourcc"]
#![experimental]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/master/")]
#![feature(plugin_registrar, managed_boxes)]
extern crate syntax;
extern crate rustc;
use syntax::ast;
use syntax::attr::contains;
use syntax::codemap::{Span, mk_sp};
use syntax::ext::base;
use syntax::ext::base::{ExtCtxt, MacExpr};
use syntax::ext::build::AstBuilder;
use syntax::parse::token;
use syntax::parse::token::InternedString;
use rustc::plugin::Registry;
use std::gc::Gc;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_macro("fourcc", expand_syntax_ext);
}
pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult> {
let (expr, endian) = parse_tts(cx, tts);
let little = match endian {
None => false,
Some(Ident{ident, span}) => match token::get_ident(ident).get() {
"little" => true,
"big" => false,
"target" => target_endian_little(cx, sp),
_ => {
cx.span_err(span, "invalid endian directive in fourcc!");
target_endian_little(cx, sp)
}
}
};
let s = match expr.node {
// expression is a literal
ast::ExprLit(ref lit) => match lit.node {
// string literal
ast::LitStr(ref s, _) => {<|fim▁hole|> cx.span_err(expr.span, "string literal with len != 4 in fourcc!");
}
s
}
_ => {
cx.span_err(expr.span, "unsupported literal in fourcc!");
return base::DummyResult::expr(sp)
}
},
_ => {
cx.span_err(expr.span, "non-literal in fourcc!");
return base::DummyResult::expr(sp)
}
};
let mut val = 0u32;
for codepoint in s.get().chars().take(4) {
let byte = if codepoint as u32 > 0xFF {
cx.span_err(expr.span, "fourcc! literal character out of range 0-255");
0u8
} else {
codepoint as u8
};
val = if little {
(val >> 8) | ((byte as u32) << 24)
} else {
(val << 8) | (byte as u32)
};
}
let e = cx.expr_lit(sp, ast::LitUint(val as u64, ast::TyU32));
MacExpr::new(e)
}
struct Ident {
ident: ast::Ident,
span: Span
}
fn parse_tts(cx: &ExtCtxt,
tts: &[ast::TokenTree]) -> (Gc<ast::Expr>, Option<Ident>) {
let p = &mut cx.new_parser_from_tts(tts);
let ex = p.parse_expr();
let id = if p.token == token::EOF {
None
} else {
p.expect(&token::COMMA);
let lo = p.span.lo;
let ident = p.parse_ident();
let hi = p.last_span.hi;
Some(Ident{ident: ident, span: mk_sp(lo, hi)})
};
if p.token != token::EOF {
p.unexpected();
}
(ex, id)
}
fn target_endian_little(cx: &ExtCtxt, sp: Span) -> bool {
let meta = cx.meta_name_value(sp, InternedString::new("target_endian"),
ast::LitStr(InternedString::new("little"), ast::CookedStr));
contains(cx.cfg().as_slice(), meta)
}
// FIXME (10872): This is required to prevent an LLVM assert on Windows
#[test]
fn dummy_test() { }<|fim▁end|>
|
if s.get().char_len() != 4 {
|
<|file_name|>helper.py<|end_file_name|><|fim▁begin|>from plenum.test.spy_helpers import get_count
def sum_of_request_propagates(node):
return get_count(node.replicas[0]._ordering_service,
node.replicas[0]._ordering_service._request_propagates_if_needed) + \
get_count(node.replicas[1]._ordering_service,<|fim▁hole|><|fim▁end|>
|
node.replicas[1]._ordering_service._request_propagates_if_needed)
|
<|file_name|>app.test.js<|end_file_name|><|fim▁begin|>import { expect } from 'chai';
import * as types from '../../app/js/utils/actionTypes';
import { changeLanguage } from '../../app/js/actions/app';<|fim▁hole|>
describe('App action', () => {
it('changes language on the parameter passed', () => {
const lang = 'en';
const expectedAction = {
type: types.LANGUAGE,
payload: lang,
};
expect(changeLanguage(lang)).to.deep.equal(expectedAction);
})
});<|fim▁end|>
| |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># See e.g. http://stackoverflow.com/a/14076841/931303
try:
import pymysql
pymysql.install_as_MySQLdb()<|fim▁hole|><|fim▁end|>
|
except ImportError:
pass
|
<|file_name|>user.client.controller.js<|end_file_name|><|fim▁begin|>(function () {
'use strict';
angular
.module('users.admin')
.controller('UserController', UserController);
UserController.$inject = ['$scope', '$state', '$window', 'Authentication', 'userResolve', '$mdToast'];
function UserController($scope, $state, $window, Authentication, user, $mdToast) {
var vm = this;
vm.authentication = Authentication;
vm.user = user;
vm.remove = remove;
vm.update = update;
function remove(user) {
if ($window.confirm('Are you sure you want to delete this user?')) {
if (user) {
user.$remove();
vm.users.splice(vm.users.indexOf(user), 1);
} else {
vm.user.$remove(function () {
$state.go('admin.users');<|fim▁hole|> });
}
}
}
function update(isValid) {
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.userForm');
return false;
}
var user = vm.user;
user.$update(function () {
$state.go('admin.user', {
userId: user._id
});
}, function (errorResponse) {
vm.error = errorResponse.data.message;
$mdToast.show(
$mdToast.simple()
.textContent(vm.error)
.hideDelay(3000)
);
});
}
}
}());<|fim▁end|>
| |
<|file_name|>about.client.controller.js<|end_file_name|><|fim▁begin|>'use strict';
// Projects controller
angular.module('about').controller('AboutUsController', ['$scope', '$stateParams', '$state', '$location', 'Authentication',
function($scope, $stateParams, $state, $location, Authentication) {
$scope.authentication = Authentication;
<|fim▁hole|>]);<|fim▁end|>
|
}
|
<|file_name|>index.js<|end_file_name|><|fim▁begin|>module.exports = {<|fim▁hole|> name: 1,
status: {
child: 0,
attribute: 'class',
regex: / ([a-z]+)$/
}
}
};<|fim▁end|>
|
selector: '.skilifts .skilift',
parse: {
|
<|file_name|>gm_json.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Schema of the JSON summary file written out by the GM tool.
This must be kept in sync with the kJsonKey_ constants in gm_expectations.cpp !
"""
__author__ = 'Elliot Poger'
# system-level imports<|fim▁hole|>
# Key strings used in GM results JSON files (both expected-results.json and
# actual-results.json).
#
# These constants must be kept in sync with the kJsonKey_ constants in
# gm_expectations.cpp !
JSONKEY_ACTUALRESULTS = 'actual-results'
# Tests whose results failed to match expectations.
JSONKEY_ACTUALRESULTS_FAILED = 'failed'
# Tests whose results failed to match expectations, but IGNOREFAILURE causes
# us to take them less seriously.
JSONKEY_ACTUALRESULTS_FAILUREIGNORED = 'failure-ignored'
# Tests for which we do not have any expectations. They may be new tests that
# we haven't had a chance to check in expectations for yet, or we may have
# consciously decided to leave them without expectations because we are unhappy
# with the results (although we should try to move away from that, and instead
# check in expectations with the IGNOREFAILURE flag set).
JSONKEY_ACTUALRESULTS_NOCOMPARISON = 'no-comparison'
# Tests whose results matched their expectations.
JSONKEY_ACTUALRESULTS_SUCCEEDED = 'succeeded'
JSONKEY_EXPECTEDRESULTS = 'expected-results'
# One or more [HashType/DigestValue] pairs representing valid results for this
# test. Typically, there will just be one pair, but we allow for multiple
# expectations, and the test will pass if any one of them is matched.
JSONKEY_EXPECTEDRESULTS_ALLOWEDDIGESTS = 'allowed-digests'
# Optional: one or more integers listing Skia bugs (under
# https://code.google.com/p/skia/issues/list ) that pertain to this expectation.
JSONKEY_EXPECTEDRESULTS_BUGS = 'bugs'
# If IGNOREFAILURE is set to True, a failure of this test will be reported
# within the FAILUREIGNORED section (thus NOT causing the buildbots to go red)
# rather than the FAILED section (which WOULD cause the buildbots to go red).
JSONKEY_EXPECTEDRESULTS_IGNOREFAILURE = 'ignore-failure'
# Optional: a free-form text string with human-readable information about
# this expectation.
JSONKEY_EXPECTEDRESULTS_NOTES = 'notes'
# Optional: boolean indicating whether this expectation was reviewed/approved
# by a human being.
# If True: a human looked at this image and approved it.
# If False: this expectation was committed blind. (In such a case, please
# add notes indicating why!)
# If absent: this expectation was committed by a tool that didn't enforce human
# review of expectations.
JSONKEY_EXPECTEDRESULTS_REVIEWED = 'reviewed-by-human'
# Allowed hash types for test expectations.
JSONKEY_HASHTYPE_BITMAP_64BITMD5 = 'bitmap-64bitMD5'
# Root directory where the buildbots store their actually-generated images...
# as a publicly readable HTTP URL:
GM_ACTUALS_ROOT_HTTP_URL = (
'http://chromium-skia-gm.commondatastorage.googleapis.com/gm')
# as a GS URL that allows credential-protected write access:
GM_ACTUALS_ROOT_GS_URL = 'gs://chromium-skia-gm/gm'
# Root directory where buildbots store skimage actual results json files.
SKIMAGE_ACTUALS_BASE_URL = (
'http://chromium-skia-gm.commondatastorage.googleapis.com/skimage/actuals')
# Root directory inside trunk where skimage expectations are stored.
SKIMAGE_EXPECTATIONS_ROOT = os.path.join('expectations', 'skimage')
# Pattern used to assemble each image's filename
IMAGE_FILENAME_PATTERN = '(.+)_(.+)\.png' # matches (testname, config)
def CreateGmActualUrl(test_name, hash_type, hash_digest,
gm_actuals_root_url=GM_ACTUALS_ROOT_HTTP_URL):
"""Return the URL we can use to download a particular version of
the actually-generated image for this particular GM test.
test_name: name of the test, e.g. 'perlinnoise'
hash_type: string indicating the hash type used to generate hash_digest,
e.g. JSONKEY_HASHTYPE_BITMAP_64BITMD5
hash_digest: the hash digest of the image to retrieve
gm_actuals_root_url: root url where actual images are stored
"""
return '%s/%s/%s/%s.png' % (gm_actuals_root_url, hash_type, test_name,
hash_digest)
def LoadFromString(file_contents):
"""Loads the JSON summary written out by the GM tool.
Returns a dictionary keyed by the values listed as JSONKEY_ constants
above."""
# TODO(epoger): we should add a version number to the JSON file to ensure
# that the writer and reader agree on the schema (raising an exception
# otherwise).
json_dict = json.loads(file_contents)
return json_dict
def LoadFromFile(file_path):
"""Loads the JSON summary written out by the GM tool.
Returns a dictionary keyed by the values listed as JSONKEY_ constants
above."""
file_contents = open(file_path, 'r').read()
return LoadFromString(file_contents)
def WriteToFile(json_dict, file_path):
"""Writes the JSON summary in json_dict out to file_path.
The file is written Unix-style (each line ends with just LF, not CRLF);
see https://code.google.com/p/skia/issues/detail?id=1815 for reasons."""
with io.open(file_path, mode='w', newline='', encoding='utf-8') as outfile:
outfile.write(unicode(json.dumps(json_dict, outfile, sort_keys=True,
indent=2)))<|fim▁end|>
|
import io
import json
import os
|
<|file_name|>test.py<|end_file_name|><|fim▁begin|>import mms
import unittest
from mooseutils import fuzzyAbsoluteEqual
class TestOutflow(unittest.TestCase):
def test(self):
df1 = mms.run_spatial('advection-outflow.i', 7, y_pp=['L2u', 'L2v'])
fig = mms.ConvergencePlot(xlabel='Element Size ($h$)', ylabel='$L_2$ Error')
fig.plot(df1,
label=['L2u', 'L2v'],
marker='o',
markersize=8,
num_fitted_points=3,
slope_precision=1)
fig.save('outflow.png')
for label,value in fig.label_to_slope.items():
if label == 'L2u':
self.assertTrue(fuzzyAbsoluteEqual(value, 1., .05))
else:
self.assertTrue(fuzzyAbsoluteEqual(value, 2., .05))
class TestExtrapolation(unittest.TestCase):
def test(self):
df1 = mms.run_spatial('advection.i', 7, y_pp=['L2u', 'L2v'])
fig = mms.ConvergencePlot(xlabel='Element Size ($h$)', ylabel='$L_2$ Error')
fig.plot(df1,
label=['L2u', 'L2v'],
marker='o',
markersize=8,
num_fitted_points=3,
slope_precision=1)
fig.save('extrapolation.png')
for label,value in fig.label_to_slope.items():
if label == 'L2u':
self.assertTrue(fuzzyAbsoluteEqual(value, 1., .05))
else:
self.assertTrue(fuzzyAbsoluteEqual(value, 2., .05))
class UpwindLimiter(unittest.TestCase):
def test(self):
df1 = mms.run_spatial('limited-advection.i', 7, "FVKernels/advection_u/limiter='upwind'", y_pp=['L2u'])
fig = mms.ConvergencePlot(xlabel='Element Size ($h$)', ylabel='$L_2$ Error')<|fim▁hole|> marker='o',
markersize=8,
num_fitted_points=3,
slope_precision=1)
fig.save('upwind-limiter.png')
for label,value in fig.label_to_slope.items():
self.assertTrue(fuzzyAbsoluteEqual(value, 1., .05))
class CentralDifferenceLimiter(unittest.TestCase):
def test(self):
df1 = mms.run_spatial('limited-advection.i', 7, "FVKernels/advection_u/limiter='central_difference'", y_pp=['L2u'])
fig = mms.ConvergencePlot(xlabel='Element Size ($h$)', ylabel='$L_2$ Error')
fig.plot(df1,
label=['L2u'],
marker='o',
markersize=8,
num_fitted_points=3,
slope_precision=1)
fig.save('cd-limiter.png')
for label,value in fig.label_to_slope.items():
self.assertTrue(fuzzyAbsoluteEqual(value, 2., .05))
class VanLeerLimiter(unittest.TestCase):
def test(self):
df1 = mms.run_spatial('limited-advection.i', 9, "FVKernels/advection_u/limiter='vanLeer'", y_pp=['L2u'])
fig = mms.ConvergencePlot(xlabel='Element Size ($h$)', ylabel='$L_2$ Error')
fig.plot(df1,
label=['L2u'],
marker='o',
markersize=8,
num_fitted_points=3,
slope_precision=1)
fig.save('vanLeer-limiter.png')
for label,value in fig.label_to_slope.items():
self.assertTrue(fuzzyAbsoluteEqual(value, 2., .05))
class MinModLimiter(unittest.TestCase):
def test(self):
df1 = mms.run_spatial('limited-advection.i', 9, "FVKernels/advection_u/limiter='min_mod'", y_pp=['L2u'])
fig = mms.ConvergencePlot(xlabel='Element Size ($h$)', ylabel='$L_2$ Error')
fig.plot(df1,
label=['L2u'],
marker='o',
markersize=8,
num_fitted_points=3,
slope_precision=1)
fig.save('min-mod-limiter.png')
for label,value in fig.label_to_slope.items():
self.assertTrue(fuzzyAbsoluteEqual(value, 2., .05))
class SOULimiter(unittest.TestCase):
def test(self):
df1 = mms.run_spatial('limited-advection.i', 9, "FVKernels/advection_u/limiter='sou'", y_pp=['L2u'])
fig = mms.ConvergencePlot(xlabel='Element Size ($h$)', ylabel='$L_2$ Error')
fig.plot(df1,
label=['L2u'],
marker='o',
markersize=8,
num_fitted_points=3,
slope_precision=1)
fig.save('sou-limiter.png')
for label,value in fig.label_to_slope.items():
self.assertTrue(fuzzyAbsoluteEqual(value, 2., .05))
class QUICKLimiter(unittest.TestCase):
def test(self):
df1 = mms.run_spatial('limited-advection.i', 15, "FVKernels/advection_u/limiter='quick'", y_pp=['L2u'])
fig = mms.ConvergencePlot(xlabel='Element Size ($h$)', ylabel='$L_2$ Error')
fig.plot(df1,
label=['L2u'],
marker='o',
markersize=8,
num_fitted_points=3,
slope_precision=1)
fig.save('quick-limiter.png')
for label,value in fig.label_to_slope.items():
self.assertTrue(fuzzyAbsoluteEqual(value, 2., .05))
class KTLimitedCD(unittest.TestCase):
def test(self):
df1 = mms.run_spatial('kt-limited-advection.i', 11, "FVKernels/advection_u/limiter='central_difference'", y_pp=['L2u'])
fig = mms.ConvergencePlot(xlabel='Element Size ($h$)', ylabel='$L_2$ Error')
fig.plot(df1,
label=['L2u'],
marker='o',
markersize=8,
num_fitted_points=3,
slope_precision=1)
fig.save('kt-cd-limiter.png')
for key,value in fig.label_to_slope.items():
self.assertTrue(fuzzyAbsoluteEqual(value, 2., .05))
print("%s slope, %f" % (key, value))
class KTLimitedUpwind(unittest.TestCase):
def test(self):
df1 = mms.run_spatial('kt-limited-advection.i', 13, "FVKernels/advection_u/limiter='upwind'", y_pp=['L2u'])
fig = mms.ConvergencePlot(xlabel='Element Size ($h$)', ylabel='$L_2$ Error')
fig.plot(df1,
label=['L2u'],
marker='o',
markersize=8,
num_fitted_points=3,
slope_precision=1)
fig.save('kt-upwind-limiter.png')
for key,value in fig.label_to_slope.items():
self.assertTrue(fuzzyAbsoluteEqual(value, 1., .05))
print("%s slope, %f" % (key, value))
class KTLimitedVanLeer(unittest.TestCase):
def test(self):
df1 = mms.run_spatial('kt-limited-advection.i', 11, "FVKernels/advection_u/limiter='vanLeer'", y_pp=['L2u'])
fig = mms.ConvergencePlot(xlabel='Element Size ($h$)', ylabel='$L_2$ Error')
fig.plot(df1,
label=['L2u'],
marker='o',
markersize=8,
num_fitted_points=3,
slope_precision=1)
fig.save('kt-van-leer-limiter.png')
for key,value in fig.label_to_slope.items():
self.assertTrue(fuzzyAbsoluteEqual(value, 2.5, .05))
print("%s slope, %f" % (key, value))<|fim▁end|>
|
fig.plot(df1,
label=['L2u'],
|
<|file_name|>dashboard.component.ts<|end_file_name|><|fim▁begin|>import {Component, OnInit} from 'angular2/core';
import {Router} from 'angular2/router';
import {Hero} from './hero';
import {HeroService} from './hero.service';
@Component({
selector: 'my-dashboard',
templateUrl: 'app/dashboard.component.html',
styleUrls: ['app/dashboard.component.css']
})
export class DashboardComponent implements OnInit {
public heroes: Hero[] = [];
constructor(private _heroService: HeroService, private _router: Router) { }
ngOnInit() {
this._heroService.getHeroes().then(heroes => this.heroes = heroes.slice(1,5));
}<|fim▁hole|> gotoDetail(hero: Hero) {
this._router.navigate(['HeroDetail', { id: hero.id }]);
}
}<|fim▁end|>
| |
<|file_name|>expressions.py<|end_file_name|><|fim▁begin|>__all__ = ['E']
import operator
import sys
import threading
import numpy
# Declare a double type that does not exist in Python space
double = numpy.double
# The default kind for undeclared variables
default_kind = 'double'
type_to_kind = {bool: 'bool', int: 'int', long: 'long', float: 'float',
double: 'double', complex: 'complex', str: 'str'}
kind_to_type = {'bool': bool, 'int': int, 'long': long, 'float': float,
'double': double, 'complex': complex, 'str': str}
kind_rank = ['bool', 'int', 'long', 'float', 'double', 'complex', 'none']
from numexpr import interpreter
class Expression(object):
def __init__(self):
object.__init__(self)
def __getattr__(self, name):
if name.startswith('_'):
return self.__dict__[name]
else:
return VariableNode(name, default_kind)
E = Expression()
class Context(threading.local):
initialized = False
def __init__(self, dict_):
if self.initialized:
raise SystemError('__init__ called too many times')
self.initialized = True
self.__dict__.update(dict_)
def get(self, value, default):
return self.__dict__.get(value, default)
def get_current_context(self):
return self.__dict__
def set_new_context(self, dict_):
self.__dict__.update(dict_)
# This will be called each time the local object is used in a separate thread
_context = Context({})
def get_optimization():
return _context.get('optimization', 'none')
# helper functions for creating __magic__ methods
def ophelper(f):
def func(*args):
args = list(args)
for i, x in enumerate(args):
if isConstant(x):
args[i] = x = ConstantNode(x)
if not isinstance(x, ExpressionNode):
raise TypeError("unsupported object type: %s" % (type(x),))
return f(*args)
func.__name__ = f.__name__
func.__doc__ = f.__doc__
func.__dict__.update(f.__dict__)
return func
def allConstantNodes(args):
"returns True if args are all ConstantNodes."
for x in args:
if not isinstance(x, ConstantNode):
return False
return True
def isConstant(ex):
"Returns True if ex is a constant scalar of an allowed type."
return isinstance(ex, (bool, int, long, float, double, complex, str))
def commonKind(nodes):
node_kinds = [node.astKind for node in nodes]
str_count = node_kinds.count('str')
if 0 < str_count < len(node_kinds): # some args are strings, but not all
raise TypeError("strings can only be operated with strings")
if str_count > 0: # if there are some, all of them must be
return 'str'
n = -1
for x in nodes:
n = max(n, kind_rank.index(x.astKind))
return kind_rank[n]
max_int32 = 2147483647
min_int32 = -max_int32 - 1
def bestConstantType(x):
if isinstance(x, str): # ``numpy.string_`` is a subclass of ``str``
return str
# ``long`` objects are kept as is to allow the user to force
# promotion of results by using long constants, e.g. by operating
# a 32-bit array with a long (64-bit) constant.
if isinstance(x, (long, numpy.int64)):
return long
# ``double`` objects are kept as is to allow the user to force
# promotion of results by using double constants, e.g. by operating
# a float (32-bit) array with a double (64-bit) constant.
if isinstance(x, (double)):
return double
# Numeric conversion to boolean values is not tried because
# ``bool(1) == True`` (same for 0 and False), so 0 and 1 would be
# interpreted as booleans when ``False`` and ``True`` are already
# supported.
if isinstance(x, (bool, numpy.bool_)):
return bool
# ``long`` is not explicitly needed since ``int`` automatically
# returns longs when needed (since Python 2.3).
# The duality of float and double in Python avoids that we have to list
# ``double`` too.
for converter in int, float, complex:
try:
y = converter(x)
except StandardError, err:
continue
if x == y:
# Constants needing more than 32 bits are always
# considered ``long``, *regardless of the platform*, so we
# can clearly tell 32- and 64-bit constants apart.
if converter is int and not (min_int32 <= x <= max_int32):
return long
return converter
def getKind(x):
converter = bestConstantType(x)
return type_to_kind[converter]
def binop(opname, reversed=False, kind=None):
# Getting the named method from self (after reversal) does not
# always work (e.g. int constants do not have a __lt__ method).
opfunc = getattr(operator, "__%s__" % opname)
@ophelper
def operation(self, other):
if reversed:
self, other = other, self
if allConstantNodes([self, other]):
return ConstantNode(opfunc(self.value, other.value))
else:
return OpNode(opname, (self, other), kind=kind)
return operation
def func(func, minkind=None, maxkind=None):
@ophelper
def function(*args):
if allConstantNodes(args):
return ConstantNode(func(*[x.value for x in args]))
kind = commonKind(args)
if kind in ('int', 'long'):
# Exception for following NumPy casting rules
kind = 'double'
else:
# Apply regular casting rules
if minkind and kind_rank.index(minkind) > kind_rank.index(kind):
kind = minkind
if maxkind and kind_rank.index(maxkind) < kind_rank.index(kind):
kind = maxkind
return FuncNode(func.__name__, args, kind)
return function
@ophelper
def where_func(a, b, c):
if isinstance(a, ConstantNode):
raise ValueError("too many dimensions")
if allConstantNodes([a,b,c]):
return ConstantNode(numpy.where(a, b, c))
return FuncNode('where', [a,b,c])
def encode_axis(axis):
if isinstance(axis, ConstantNode):
axis = axis.value
if axis is None:
axis = interpreter.allaxes
else:
if axis < 0:
axis = interpreter.maxdims - axis
if axis > 254:
raise ValueError("cannot encode axis")
return RawNode(axis)
def sum_func(a, axis=-1):
axis = encode_axis(axis)
if isinstance(a, ConstantNode):
return a
if isinstance(a, (bool, int, long, float, double, complex)):
a = ConstantNode(a)
return FuncNode('sum', [a, axis], kind=a.astKind)
def prod_func(a, axis=-1):
axis = encode_axis(axis)
if isinstance(a, (bool, int, long, float, double, complex)):
a = ConstantNode(a)
if isinstance(a, ConstantNode):
return a
return FuncNode('prod', [a, axis], kind=a.astKind)
@ophelper
def div_op(a, b):
if get_optimization() in ('moderate', 'aggressive'):
if (isinstance(b, ConstantNode) and
(a.astKind == b.astKind) and
a.astKind in ('float', 'double', 'complex')):
return OpNode('mul', [a, ConstantNode(1./b.value)])
return OpNode('div', [a,b])
@ophelper
def pow_op(a, b):
if allConstantNodes([a,b]):
return ConstantNode(a**b)
if isinstance(b, ConstantNode):
x = b.value
if get_optimization() == 'aggressive':
RANGE = 50 # Approximate break even point with pow(x,y)
# Optimize all integral and half integral powers in [-RANGE, RANGE]
# Note: for complex numbers RANGE could be larger.
if (int(2*x) == 2*x) and (-RANGE <= abs(x) <= RANGE):
n = int(abs(x))
ishalfpower = int(abs(2*x)) % 2
def multiply(x, y):
if x is None: return y
return OpNode('mul', [x, y])
r = None
p = a
mask = 1
while True:
if (n & mask):
r = multiply(r, p)
mask <<= 1
if mask > n:
break
p = OpNode('mul', [p,p])
if ishalfpower:
kind = commonKind([a])
if kind in ('int', 'long'): kind = 'double'
r = multiply(r, OpNode('sqrt', [a], kind))
if r is None:
r = OpNode('ones_like', [a])
if x < 0:
r = OpNode('div', [ConstantNode(1), r])
return r
if get_optimization() in ('moderate', 'aggressive'):
if x == -1:
return OpNode('div', [ConstantNode(1),a])
if x == 0:
return FuncNode('ones_like', [a])
if x == 0.5:
kind = a.astKind
if kind in ('int', 'long'): kind = 'double'
return FuncNode('sqrt', [a], kind=kind)
if x == 1:
return a
if x == 2:
return OpNode('mul', [a,a])
return OpNode('pow', [a,b])
# The functions and the minimum and maximum types accepted
functions = {<|fim▁hole|> 'ones_like' : func(numpy.ones_like),
'sqrt' : func(numpy.sqrt, 'float'),
'sin' : func(numpy.sin, 'float'),
'cos' : func(numpy.cos, 'float'),
'tan' : func(numpy.tan, 'float'),
'arcsin' : func(numpy.arcsin, 'float'),
'arccos' : func(numpy.arccos, 'float'),
'arctan' : func(numpy.arctan, 'float'),
'sinh' : func(numpy.sinh, 'float'),
'cosh' : func(numpy.cosh, 'float'),
'tanh' : func(numpy.tanh, 'float'),
'arcsinh' : func(numpy.arcsinh, 'float'),
'arccosh' : func(numpy.arccosh, 'float'),
'arctanh' : func(numpy.arctanh, 'float'),
'fmod' : func(numpy.fmod, 'float'),
'arctan2' : func(numpy.arctan2, 'float'),
'log' : func(numpy.log, 'float'),
'log1p' : func(numpy.log1p, 'float'),
'log10' : func(numpy.log10, 'float'),
'exp' : func(numpy.exp, 'float'),
'expm1' : func(numpy.expm1, 'float'),
'abs': func(numpy.absolute, 'float'),
'where' : where_func,
'real' : func(numpy.real, 'double', 'double'),
'imag' : func(numpy.imag, 'double', 'double'),
'complex' : func(complex, 'complex'),
'sum' : sum_func,
'prod' : prod_func,
}
class ExpressionNode(object):
"""An object that represents a generic number object.
This implements the number special methods so that we can keep
track of how this object has been used.
"""
astType = 'generic'
def __init__(self, value=None, kind=None, children=None):
object.__init__(self)
self.value = value
if kind is None:
kind = 'none'
self.astKind = kind
if children is None:
self.children = ()
else:
self.children = tuple(children)
def get_real(self):
if self.astType == 'constant':
return ConstantNode(complex(self.value).real)
return OpNode('real', (self,), 'double')
real = property(get_real)
def get_imag(self):
if self.astType == 'constant':
return ConstantNode(complex(self.value).imag)
return OpNode('imag', (self,), 'double')
imag = property(get_imag)
def __str__(self):
return '%s(%s, %s, %s)' % (self.__class__.__name__, self.value,
self.astKind, self.children)
def __repr__(self):
return self.__str__()
def __neg__(self):
return OpNode('neg', (self,))
def __invert__(self):
return OpNode('invert', (self,))
def __pos__(self):
return self
__add__ = __radd__ = binop('add')
__sub__ = binop('sub')
__rsub__ = binop('sub', reversed=True)
__mul__ = __rmul__ = binop('mul')
__div__ = div_op
__rdiv__ = binop('div', reversed=True)
__pow__ = pow_op
__rpow__ = binop('pow', reversed=True)
__mod__ = binop('mod')
__rmod__ = binop('mod', reversed=True)
# boolean operations
__and__ = binop('and', kind='bool')
__or__ = binop('or', kind='bool')
__gt__ = binop('gt', kind='bool')
__ge__ = binop('ge', kind='bool')
__eq__ = binop('eq', kind='bool')
__ne__ = binop('ne', kind='bool')
__lt__ = binop('gt', reversed=True, kind='bool')
__le__ = binop('ge', reversed=True, kind='bool')
class LeafNode(ExpressionNode):
leafNode = True
class VariableNode(LeafNode):
astType = 'variable'
def __init__(self, value=None, kind=None, children=None):
LeafNode.__init__(self, value=value, kind=kind)
class RawNode(object):
"""Used to pass raw integers to interpreter.
For instance, for selecting what function to use in func1.
Purposely don't inherit from ExpressionNode, since we don't wan't
this to be used for anything but being walked.
"""
astType = 'raw'
astKind = 'none'
def __init__(self, value):
self.value = value
self.children = ()
def __str__(self):
return 'RawNode(%s)' % (self.value,)
__repr__ = __str__
class ConstantNode(LeafNode):
astType = 'constant'
def __init__(self, value=None, children=None):
kind = getKind(value)
# Python float constants are double precision by default
if kind == 'float':
kind = 'double'
LeafNode.__init__(self, value=value, kind=kind)
def __neg__(self):
return ConstantNode(-self.value)
def __invert__(self):
return ConstantNode(~self.value)
class OpNode(ExpressionNode):
astType = 'op'
def __init__(self, opcode=None, args=None, kind=None):
if (kind is None) and (args is not None):
kind = commonKind(args)
ExpressionNode.__init__(self, value=opcode, kind=kind, children=args)
class FuncNode(OpNode):
def __init__(self, opcode=None, args=None, kind=None):
if (kind is None) and (args is not None):
kind = commonKind(args)
OpNode.__init__(self, opcode, args, kind)<|fim▁end|>
|
'copy' : func(numpy.copy),
|
<|file_name|>network.rs<|end_file_name|><|fim▁begin|>// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// 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.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::io;
use std::io::Write;
use std::net::SocketAddr;
use std::ops::Deref;
use std::thread;
use std::time;
use std::time::{SystemTime, UNIX_EPOCH};
use rand::{thread_rng, Rng};
use deps::bitcoin::network::address as btc_network_address;
use deps::bitcoin::network::constants as btc_constants;
use deps::bitcoin::network::encodable::{ConsensusDecodable, ConsensusEncodable};
use deps::bitcoin::network::message as btc_message;
use deps::bitcoin::network::message_blockdata as btc_message_blockdata;
use deps::bitcoin::network::message_network as btc_message_network;
use deps::bitcoin::network::serialize as btc_serialize;
use deps::bitcoin::network::serialize::{RawDecoder, RawEncoder};
use deps::bitcoin::util::hash::Sha256dHash;
use burnchains::bitcoin::indexer::{network_id_to_bytes, BitcoinIndexer};
use burnchains::bitcoin::messages::BitcoinMessageHandler;
use burnchains::bitcoin::Error as btc_error;
use burnchains::bitcoin::PeerMessage;
use burnchains::indexer::BurnchainIndexer;
use util::get_epoch_time_secs;
use util::log;
// Based on Andrew Poelstra's rust-bitcoin library.
impl BitcoinIndexer {
/// Send a Bitcoin protocol message on the wire
pub fn send_message(&mut self, payload: btc_message::NetworkMessage) -> Result<(), btc_error> {
let message = btc_message::RawNetworkMessage {
magic: network_id_to_bytes(self.runtime.network_id),
payload: payload,
};
self.with_socket(|ref mut sock| {
message
.consensus_encode(&mut RawEncoder::new(&mut *sock))
.map_err(btc_error::SerializationError)?;
sock.flush().map_err(btc_error::Io)
})
}
/// Receive a Bitcoin protocol message on the wire
/// If this method returns Err(ConnectionBroken), then the caller should attempt to re-connect.
pub fn recv_message(&mut self) -> Result<PeerMessage, btc_error> {
let magic = network_id_to_bytes(self.runtime.network_id);
self.with_socket(|ref mut sock| {
// read the message off the wire
let mut decoder = RawDecoder::new(sock);
let decoded: btc_message::RawNetworkMessage =
ConsensusDecodable::consensus_decode(&mut decoder).map_err(|e| {
// if we can't finish a recv(), then report that the connection is broken
match e {
btc_serialize::Error::Io(ref io_error) => {
if io_error.kind() == io::ErrorKind::UnexpectedEof {
btc_error::ConnectionBroken
} else {
btc_error::Io(io::Error::new(
io_error.kind(),
"I/O error when processing message",
))
}
}
_ => btc_error::SerializationError(e),
}
})?;
// sanity check -- must match our network
if decoded.magic != magic {
return Err(btc_error::InvalidMagic);
}
Ok(decoded.payload)
})
}
/// Get sender address from our socket
pub fn get_local_sockaddr(&mut self) -> Result<SocketAddr, btc_error> {
self.with_socket(|ref mut sock| sock.local_addr().map_err(btc_error::Io))
}
/// Get receiver address from our socket
pub fn get_remote_sockaddr(&mut self) -> Result<SocketAddr, btc_error> {
self.with_socket(|ref mut sock| sock.peer_addr().map_err(btc_error::Io))
}
/// Handle and consume message we received, if we can.
/// Returns UnhandledMessage if we can't handle the given message.
pub fn handle_message<T: BitcoinMessageHandler>(
&mut self,
message: PeerMessage,
handler: Option<&mut T>,
) -> Result<bool, btc_error> {
if self.runtime.last_getdata_send_time > 0
&& self.runtime.last_getdata_send_time + self.runtime.timeout < get_epoch_time_secs()
{
warn!("Timed out waiting for block data. Killing connection.");
return Err(btc_error::TimedOut);
}
if self.runtime.last_getheaders_send_time > 0
&& self.runtime.last_getheaders_send_time + self.runtime.timeout < get_epoch_time_secs()
{
warn!("Timed out waiting for headers data. Killing connection.");
return Err(btc_error::TimedOut);
}
// classify the message here, so we can pass it along to the handler explicitly
match message {
btc_message::NetworkMessage::Version(..) => {
return self.handle_version(message).and_then(|_r| Ok(true));
}
btc_message::NetworkMessage::Verack => {
return self.handle_verack(message).and_then(|_r| Ok(true));
}
btc_message::NetworkMessage::Ping(..) => {
return self.handle_ping(message).and_then(|_r| Ok(true));
}
btc_message::NetworkMessage::Pong(..) => {
return self.handle_pong(message).and_then(|_r| Ok(true));
}
_ => match handler {
Some(custom_handler) => custom_handler.handle_message(self, message.clone()),
None => Err(btc_error::UnhandledMessage(message.clone())),
},
}
}
/// Do the initial handshake to the remote peer.
/// Returns the remote peer's block height
pub fn peer_handshake(&mut self) -> Result<u64, btc_error> {
debug!(
"Begin peer handshake to {}:{}",
self.config.peer_host, self.config.peer_port
);
self.send_version()?;
let version_reply = self.recv_message()?;
self.handle_version(version_reply)?;
let verack_reply = self.recv_message()?;
self.handle_verack(verack_reply)?;
debug!(
"Established connection to {}:{}, who has {} blocks",
self.config.peer_host, self.config.peer_port, self.runtime.block_height
);
Ok(self.runtime.block_height)
}
/// Connect to a remote peer, do a handshake with the remote peer, and use exponential backoff until we
/// succeed in establishing a connection.
/// This method masks ConnectionBroken errors, but does not mask other network errors.
/// Returns the remote peer's block height on success
pub fn connect_handshake_backoff(&mut self) -> Result<u64, btc_error> {
let mut backoff: f64 = 1.0;
let mut rng = thread_rng();
loop {
let connection_result = self.connect();
match connection_result {
Ok(()) => {
// connected! now do the handshake
let handshake_result = self.peer_handshake();
match handshake_result {
Ok(block_height) => {
// connected!
return Ok(block_height);
}
Err(btc_error::ConnectionBroken) => {
// need to try again
backoff = 2.0 * backoff + (backoff * rng.gen_range(0.0, 1.0));
}
Err(e) => {
// propagate other network error
warn!(
"Failed to handshake with {}:{}: {:?}",
&self.config.peer_host, self.config.peer_port, &e
);
return Err(e);
}
}
}
Err(err_msg) => {
error!(
"Failed to connect to peer {}:{}: {}",
&self.config.peer_host, self.config.peer_port, err_msg
);
backoff = 2.0 * backoff + (backoff * rng.gen_range(0.0, 1.0));
}
}
// don't sleep more than 60 seconds
if backoff > 60.0 {
backoff = 60.0;
}
if backoff > 10.0 {
warn!("Connection broken; retrying in {} sec...", backoff);
}
let duration = time::Duration::from_millis((backoff * 1_000.0) as u64);
thread::sleep(duration);
}
}
/// Send a Version message
pub fn send_version(&mut self) -> Result<(), btc_error> {
let timestamp = match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(dur) => dur,
Err(err) => err.duration(),
}
.as_secs() as i64;<|fim▁hole|> let local_addr = self.get_local_sockaddr()?;
let remote_addr = self.get_remote_sockaddr()?;
let sender_address = btc_network_address::Address::new(&local_addr, 0);
let remote_address = btc_network_address::Address::new(&remote_addr, 0);
let payload = btc_message_network::VersionMessage {
version: btc_constants::PROTOCOL_VERSION,
services: 0,
timestamp: timestamp,
receiver: remote_address,
sender: sender_address,
nonce: self.runtime.version_nonce,
user_agent: self.runtime.user_agent.to_owned(),
start_height: 0,
relay: false,
};
debug!(
"Send version (nonce={}) to {}:{}",
self.runtime.version_nonce, self.config.peer_host, self.config.peer_port
);
self.send_message(btc_message::NetworkMessage::Version(payload))
}
/// Receive a Version message and reply with a Verack
pub fn handle_version(&mut self, version_message: PeerMessage) -> Result<(), btc_error> {
match version_message {
btc_message::NetworkMessage::Version(msg_body) => {
debug!(
"Handle version -- remote peer blockchain height is {}",
msg_body.start_height
);
self.runtime.block_height = msg_body.start_height as u64;
return self.send_verack();
}
_ => {
error!("Did not receive version, but got {:?}", version_message);
}
};
return Err(btc_error::InvalidMessage(version_message));
}
/// Send a verack
pub fn send_verack(&mut self) -> Result<(), btc_error> {
let payload = btc_message::NetworkMessage::Verack;
debug!("Send verack");
self.send_message(payload)
}
/// Handle a verack we received.
/// Does nothing.
pub fn handle_verack(&mut self, verack_message: PeerMessage) -> Result<(), btc_error> {
match verack_message {
btc_message::NetworkMessage::Verack => {
debug!("Handle verack");
return Ok(());
}
_ => {
error!("Did not receive verack, but got {:?}", verack_message);
}
};
Err(btc_error::InvalidMessage(verack_message))
}
/// Respond to a Ping message by sending a Pong message
pub fn handle_ping(&mut self, ping_message: PeerMessage) -> Result<(), btc_error> {
match ping_message {
btc_message::NetworkMessage::Ping(ref n) => {
debug!("Handle ping {}", n);
let payload = btc_message::NetworkMessage::Pong(*n);
debug!("Send pong {}", n);
return self.send_message(payload);
}
_ => {
error!("Did not receive ping, but got {:?}", ping_message);
}
};
Err(btc_error::InvalidMessage(ping_message))
}
/// Respond to a Pong message.
/// Does nothing.
pub fn handle_pong(&mut self, pong_message: PeerMessage) -> Result<(), btc_error> {
match pong_message {
btc_message::NetworkMessage::Pong(n) => {
debug!("Handle pong {}", n);
return Ok(());
}
_ => {
error!("Did not receive pong, but got {:?}", pong_message);
}
};
Err(btc_error::InvalidReply)
}
/// Send a GetHeaders message
/// Note that this isn't a generic GetHeaders message -- you should use this only to ask
/// for a batch of 2,000 block hashes after this given hash.
pub fn send_getheaders(&mut self, prev_block_hash: Sha256dHash) -> Result<(), btc_error> {
let getheaders =
btc_message_blockdata::GetHeadersMessage::new(vec![prev_block_hash], prev_block_hash);
let payload = btc_message::NetworkMessage::GetHeaders(getheaders);
debug!(
"Send GetHeaders {} for 2000 headers to {}:{}",
prev_block_hash.be_hex_string(),
self.config.peer_host,
self.config.peer_port
);
self.runtime.last_getheaders_send_time = get_epoch_time_secs();
self.send_message(payload)
}
/// Send a GetData message
pub fn send_getdata(&mut self, block_hashes: &Vec<Sha256dHash>) -> Result<(), btc_error> {
assert!(block_hashes.len() > 0);
let getdata_invs = block_hashes
.iter()
.map(|h| btc_message_blockdata::Inventory {
inv_type: btc_message_blockdata::InvType::Block,
hash: h.clone(),
})
.collect();
let getdata = btc_message::NetworkMessage::GetData(getdata_invs);
self.runtime.last_getdata_send_time = get_epoch_time_secs();
debug!(
"Send GetData {}-{} to {}:{}",
block_hashes[0].be_hex_string(),
block_hashes[block_hashes.len() - 1].be_hex_string(),
self.config.peer_host,
self.config.peer_port
);
self.send_message(getdata)
}
}<|fim▁end|>
| |
<|file_name|>descriptionreponamelstm.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Models.FeatureProcessing import *
from keras.models import Sequential
from keras.layers import Activation, Dense, LSTM
from keras.optimizers import Adam, SGD
import numpy as np
import abc
from ClassificationModule import ClassificationModule
class descriptionreponamelstm(ClassificationModule):
"""A basic lstm neural network"""
def __init__(self, num_hidden_layers=3):
ClassificationModule.__init__(self, "Description and reponame LSTM", "A LSTM reading the description and reponame character by character")
hidden_size = 300
self.maxlen = 300
# Set output_size
self.output_size = 7 # Hardcoded for 7 classes
model = Sequential()
# Maximum of self.maxlen charcters allowed, each in one-hot-encoded array
model.add(LSTM(hidden_size, input_shape=(self.maxlen, getLstmCharLength())))
for _ in range(num_hidden_layers):
model.add(Dense(hidden_size))
model.add(Dense(self.output_size))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',
optimizer=SGD(),
metrics=['accuracy'])
self.model = model
print "\t-", self.name
def resetAllTraining(self):
"""Reset classification module to status before training"""
resetWeights(self.model)
def trainOnSample(self, sample, nb_epoch=1, shuffle=True, verbose=True):
"""Trainiere (inkrementell) mit Sample. Evtl zusätzlich mit best. Menge alter Daten, damit overfitten auf neue Daten verhindert wird."""
readme_vec = self.formatInputData(sample)
label_index = getLabelIndex(sample)
label_one_hot = np.expand_dims(oneHot(label_index), axis=0) # [1, 0, 0, ..] -> [[1, 0, 0, ..]] Necessary for keras
self.model.fit(readme_vec, label_one_hot, nb_epoch=nb_epoch, shuffle=shuffle, verbose=verbose)
def train(self, samples, nb_epoch=200, shuffle=True, verbose=True):
"""Trainiere mit Liste von Daten. Evtl weitere Paramter nötig (nb_epoch, learning_rate, ...)"""
train_samples = []
train_lables = []
for sample in samples:
formatted_sample = self.formatInputData(sample)[0].tolist()
train_samples.append(formatted_sample)
train_lables.append(oneHot(getLabelIndex(sample)))
train_lables = np.asarray(train_lables)
train_result = self.model.fit(train_samples, train_lables, nb_epoch=nb_epoch, shuffle=shuffle, verbose=verbose, class_weight=getClassWeights())
self.isTrained = True
return train_result
def predictLabel(self, sample):
"""Gibt zurück, wie der Klassifikator ein gegebenes Sample klassifizieren würde"""
if not self.isTrained:
return 0<|fim▁hole|> def predictLabelAndProbability(self, sample):
"""Return the probability the module assignes each label"""
if not self.isTrained:
return [0, 0, 0, 0, 0, 0, 0, 0]
sample = self.formatInputData(sample)
prediction = self.model.predict(sample)[0]
return [np.argmax(prediction)] + list(prediction) # [0] So 1-D array is returned
def formatInputData(self, sample):
"""Extract description and transform to vector"""
sd = getDescription(sample)
sd += getName(sample)
# Returns numpy array which contains 1 array with features
return np.expand_dims(lstmEncode(sd, maxlen=self.maxlen), axis=0)<|fim▁end|>
|
sample = self.formatInputData(sample)
return np.argmax(self.model.predict(sample))
|
<|file_name|>_shared_galleries_operations.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_request(
subscription_id: str,
location: str,
*,
shared_to: Optional[Union[str, "_models.SharedToValues"]] = None,
**kwargs: Any
) -> HttpRequest:
api_version = "2020-09-30"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/sharedGalleries')
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
"location": _SERIALIZER.url("location", location, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
if shared_to is not None:
query_parameters['sharedTo'] = _SERIALIZER.query("shared_to", shared_to, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_get_request(
subscription_id: str,
location: str,
gallery_unique_name: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2020-09-30"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/sharedGalleries/{galleryUniqueName}')
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
"location": _SERIALIZER.url("location", location, 'str'),
"galleryUniqueName": _SERIALIZER.url("gallery_unique_name", gallery_unique_name, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]<|fim▁hole|> header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class SharedGalleriesOperations(object):
"""SharedGalleriesOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.compute.v2020_09_30.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def list(
self,
location: str,
shared_to: Optional[Union[str, "_models.SharedToValues"]] = None,
**kwargs: Any
) -> Iterable["_models.SharedGalleryList"]:
"""List shared galleries by subscription id or tenant id.
:param location: Resource location.
:type location: str
:param shared_to: The query parameter to decide what shared galleries to fetch when doing
listing operations.
:type shared_to: str or ~azure.mgmt.compute.v2020_09_30.models.SharedToValues
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SharedGalleryList or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.compute.v2020_09_30.models.SharedGalleryList]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.SharedGalleryList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
location=location,
shared_to=shared_to,
template_url=self.list.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_request(
subscription_id=self._config.subscription_id,
location=location,
shared_to=shared_to,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("SharedGalleryList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/sharedGalleries'} # type: ignore
@distributed_trace
def get(
self,
location: str,
gallery_unique_name: str,
**kwargs: Any
) -> "_models.SharedGallery":
"""Get a shared gallery by subscription id or tenant id.
:param location: Resource location.
:type location: str
:param gallery_unique_name: The unique name of the Shared Gallery.
:type gallery_unique_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SharedGallery, or the result of cls(response)
:rtype: ~azure.mgmt.compute.v2020_09_30.models.SharedGallery
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.SharedGallery"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
subscription_id=self._config.subscription_id,
location=location,
gallery_unique_name=gallery_unique_name,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('SharedGallery', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/sharedGalleries/{galleryUniqueName}'} # type: ignore<|fim▁end|>
| |
<|file_name|>console_tests.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2016, Germán Fuentes Capella <[email protected]>
# BSD 3-Clause License
#
# Copyright (c) 2017, Germán Fuentes Capella
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest
from vps.console import get_headers, column_size
class TestDisplay(unittest.TestCase):
def test_headers(self):
h = [
{'h0': 0,
'h1': 1,
},
{'h0': 0,
'h1': 1,
},
]
self.assertEqual(get_headers(h), ['h0', 'h1'])
def test_different_headers(self):
h = [
{'h0': 0,
'h1': 1,
},
{'h0': 0,
'h1': 1,
'h2': 2,
},
]
self.assertEqual(get_headers(h), ['h0', 'h1', 'h2'])
def test_column_size(self):
matrix = [
{'k0': 'text0',
'k1': '1',
},
{'k0': 'txt',
'k1': '',
},
]
csize = column_size(matrix[0].keys(), matrix)<|fim▁hole|> self.assertEqual(csize['k0'], 5)
self.assertEqual(csize['k1'], 2)
def test_column_size_with_boolean(self):
matrix = [{'k0': False}]
csize = column_size(matrix[0].keys(), matrix)
self.assertEqual(csize['k0'], 5)<|fim▁end|>
| |
<|file_name|>ReporterColumnNameForm.java<|end_file_name|><|fim▁begin|>/*L
* Copyright RTI International
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/webgenome/LICENSE.txt for details.
*/
/*
$Revision: 1.1 $
$Date: 2007-08-22 20:03:57 $
*/
package org.rti.webgenome.webui.struts.upload;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.rti.webgenome.util.SystemUtils;
import org.rti.webgenome.webui.struts.BaseForm;
/**
* Form for inputting the name of a rectangular file
* column that contains reporter names.
* @author dhall
*
*/
public class ReporterColumnNameForm extends BaseForm {
/** Serialized version ID. */
private static final long serialVersionUID =
SystemUtils.getLongApplicationProperty("serial.version.uid");
/** Name of column containing reporter names. */
private String reporterColumnName = null;
/**
* Get name of column containing reporter names.
* @return Column heading.
*/
public String getReporterColumnName() {
return reporterColumnName;
}
<|fim▁hole|> * @param reporterColumnName Column heading.
*/
public void setReporterColumnName(final String reporterColumnName) {
this.reporterColumnName = reporterColumnName;
}
/**
* {@inheritDoc}
*/
@Override
public ActionErrors validate(final ActionMapping mapping,
final HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (this.reporterColumnName == null
|| this.reporterColumnName.length() < 1) {
errors.add("reporterColumnName", new ActionError("invalid.field"));
}
if (errors.size() > 0) {
errors.add("global", new ActionError("invalid.fields"));
}
return errors;
}
}<|fim▁end|>
|
/**
* Set name of column containing reporter names.
|
<|file_name|>acscsv.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: UTF-8 -*-
__author__="Scott Hendrickson"
__license__="Simplified BSD"
import sys
import datetime
import fileinput
from io import StringIO
# Experimental: Use numba to speed up some fo the basic function
# that are run many times per record
# from numba import jit
# use fastest option available
try:
import ujson as json
except ImportError:
try:
import json
except ImportError:
import simplejson as json<|fim▁hole|>gnipError = "GNIPERROR"
gnipRemove = "GNIPREMOVE"
gnipDateTime = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.000Z")
INTERNAL_EMPTY_FIELD = "GNIPEMPTYFIELD"
class _Field(object):
"""
Base class for extracting the desired value at the end of a series of keys in a JSON Activity
Streams payload. Set the application-wide default value (for e.g. missing values) here,
but also use child classes to override when necessary. Subclasses also need to define the
key-path (path) to the desired location by overwriting the path attr.
"""
# set some default values; these can be overwritten in custom classes
# twitter format
default_t_fmt = "%Y-%m-%dT%H:%M:%S.000Z"
default_value = INTERNAL_EMPTY_FIELD
path = [] # dict key-path to follow for desired value
label = 'DummyKeyPathLabel' # this must match if-statement in constructor
def __init__(self, json_record):
if self.label == 'DummyKeyPathLabel':
self.label = ':'.join(self.path)
self.value = None # str representation of the field, often = str( self.value_list )
if json_record is not None:
self.value = self.walk_path(json_record)
else:
self.value = self.default_value
def __repr__(self):
return unicode(self.value)
def walk_path(self, json_record, path=None):
res = json_record
if path is None:
path = self.path
for k in path:
if res is None:
break
if k not in res or ( type(res[k]) is list and len(res[k]) == 0 ):
# parenthetical clause for values with empty lists e.g. twitter_entities
return self.default_value
res = res[k]
# handle the special case where the walk_path found null (JSON) which converts to
# a Python None. Only use "None" (str version) if it's assigned to self.default_value
res = res if res is not None else self.default_value
return res
def walk_path_slower(self, json_record, path=None):
"""Slower version fo walk path. Depricated."""
if path is None:
path = self.path
try:
execstr = "res=json_record" + '["{}"]'*len(path)
exec(execstr.format(*path))
except (KeyError, TypeError):
res = None
if res is None:
res = self.default_value
return res
def fix_length(self, iterable, limit=None):
"""
Take an iterable (typically a list) and an optional maximum length (limit).
If limit is not given, and the input iterable is not equal to self.default_value
(typically "None"), the input iterable is returned. If limit is given, the return
value is a list that is either truncated to the first limit items, or padded
with self.default_value until it is of size limit. Note: strings are iterables,
so if you pass this function a string, it will (optionally) truncate the
number of characters in the string according to limit.
"""
res = []
if limit is None:
# no limits on the length of the result, so just return the original iterable
res = iterable
else:
#if len(iterable) == 0:
if iterable == self.default_value or len(iterable) == 0:
# if walk_path() finds the final key, but the value is an empty list
# (common for e.g. the contents of twitter_entities)
# overwrite self.value with a list of self.default_value and of length limit
res = [ self.default_value ]*limit
else:
# found something useful in the iterable, either pad the list or truncate
# to end up with something of the proper length
current_length = len( iterable )
if current_length < limit:
res = iterable + [ self.default_value
for _ in range(limit - current_length) ]
else:
res = iterable[:limit]
return res
class _LimitedField(_Field):
"""
Takes JSON record (in python dict form) and optionally a maximum length (limit,
with default length=5). Uses parent class _Field() to assign the appropriate value
to self.value. When self.value is a list of dictionaries,
inheriting from _LimitedField() class allows for the extraction and combination of
an arbitrary number of fields within self.value into self.value_list.
Ex: if your class would lead to having
self.value = [ {'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6} ], and what you'd like
is a list that looks like [ 1, 2, 4, 5 ], inheriting from _LimitedField() allows you
to overwrite the fields list ( fields=["a", "b"] ) to obtain this result.
Finally, self.value is set to a string representation of the final self.value_list.
"""
#TODO: is there a better way that this class and the fix_length() method in _Field class
# could be combined?
#TODO: set limit=None by default and just return as many as there are, otherwise (by specifying
# limit), return a maximum of limit.
# TODO:
# - consolidate _LimitedField() & fix_length() if possible
def __init__(self, json_record, limit=1):
self.fields = None
super(
_LimitedField
, self).__init__(json_record)
# self.value is possibly a list of dicts for each activity media object
if self.fields:
# start with default list full of the default_values
self.value_list = [ self.default_value ]*( len(self.fields)*limit )
if self.value != self.default_value:
for i,x in enumerate(self.value): # iterate over the dicts in the list
if i < limit: # ... up until you reach limit
for j,y in enumerate(self.fields): # iterate over the dict keys
self.value_list[ len( self.fields )*i + j ] = x[ self.fields[j] ]
# finally, str-ify the list
self.value = str( self.value_list )
class AcsCSV(object):
"""Base class for all delimited list objects. Basic delimited list utility functions"""
def __init__(self, delim, options_keypath):
self.delim = delim
if delim == "":
print >>sys.stderr, "Warning - Output has Null delimiter"
self.rmchars = "\n\r {}".format(self.delim)
self.options_keypath = options_keypath
def string_hook(self, record_string, mode_dummy):
"""
Returns a file-like StringIO object built from the activity record in record_string.
This is ultimately passed down to the FileInput.readline() method. The mode_dummy
parameter is only included so the signature matches other hooks.
"""
return StringIO( record_string )
def file_reader(self, options_filename=None, json_string=None):
"""
Read arbitrary input file(s) or standard Python str. When passing file_reader() a
JSON string, assign it to the json_string arg. Yields a tuple of (line number, record).
"""
line_number = 0
if json_string is not None:
hook = self.string_hook
options_filename = json_string
else:
hook = fileinput.hook_compressed
for r in fileinput.FileInput(options_filename, openhook=hook):
line_number += 1
try:
recs = [json.loads(r.strip())]
except ValueError:
try:
# maybe a missing line feed?
recs = [json.loads(x) for x in r.strip().replace("}{", "}GNIP_SPLIT{")
.split("GNIP_SPLIT")]
except ValueError:
sys.stderr.write("Invalid JSON record (%d) %s, skipping\n"
%(line_number, r.strip()))
continue
for record in recs:
if len(record) == 0:
continue
# hack: let the old source modules still have a self.cnt for error msgs
self.cnt = line_number
yield line_number, record
def cleanField(self,f):
"""Clean fields of new lines and delmiter."""
res = INTERNAL_EMPTY_FIELD
try:
res = f.strip(
).replace("\n"," "
).replace("\r"," "
).replace(self.delim, " "
)
except AttributeError:
try:
# odd edge case that f is a number
# then can't call string functions
float(f)
res = str(f)
except TypeError:
pass
return res
def buildListString(self,l):
"""Generic list builder returns a string representation of list"""
# unicode output of list (without u's)
res = '['
for r in l:
# handle the various types of lists we might see
try:
if isinstance(r, list):
res += "'" + self.buildListString(r) + "',"
elif isinstance(r, str) or isinstance(r, unicode):
res += "'" + r + "',"
else:
res += "'" + str(r) + "',"
except NameError:
if isinstance(r, list):
res += "'" + self.buildListString(r) + "',"
elif isinstance(r, str):
res += "'" + r + "',"
else:
res += "'" + str(r) + "',"
if res.endswith(','):
res = res[:-1]
res += ']'
return res
def splitId(self, x, index=1):
"""Generic functions for splitting id parts"""
tmp = x.split("/")
if len(tmp) > index:
return tmp[index]
else:
return x
def asString(self, l, emptyField):
"""Returns a delimited list object as a properly delimited string."""
if l is None:
return None
for i, x in enumerate(l):
if x == INTERNAL_EMPTY_FIELD:
l[i] = emptyField
return self.delim.join(l)
def get_source_list(self, x):
"""Wrapper for the core activity parsing function."""
source_list = self.procRecordToList(x)
if self.options_keypath:
source_list.append(self.keyPath(x))
# ensure no pipes, newlines, etc
return [ self.cleanField(x) for x in source_list ]
def procRecord(self, x, emptyField="None"):
return self.asString(self.get_source_list(x), emptyField)
def asGeoJSON(self, x):
"""Get results as GeoJSON representation."""
record_list = self.procRecordToList(x)
if self.__class__.__name__ == "TwacsCSV" and self.options_geo:
if self.geoCoordsList is None:
return
lon_lat = self.geoCoordsList[::-1]
elif self.__class__.__name__ == "FsqacsCSV" and self.options_geo:
lon_lat = self.geo_coords_list
else:
return {"Error":"This publisher doesn't have geo"}
return {
"type": "Feature"
, "geometry": { "type": "Point", "coordinates": lon_lat }
, "properties": { "id": record_list[0] }
}
def keyPath(self,d):
"""Get a generic key path specified at run time. Consider using jq instead?"""
#key_list = self.options_keypath.split(":")
delim = ":"
#print >> sys.stderr, "self.__class__ " + str(self.__class__)
if self.__class__.__name__ == "NGacsCSV":
delim = ","
key_stack = self.options_keypath.split(delim)
#print >> sys.stderr, "key_stack " + str(key_stack)
x = d
while len(key_stack) > 0:
try:
k = key_stack.pop(0)
try:
idx = int(k)
except ValueError:
# keys are ascii strings
idx = str(k)
x = x[idx]
except (IndexError, TypeError, KeyError) as e:
#sys.stderr.write("Keypath error at %s\n"%k)
return "PATH_EMPTY"
return unicode(x)<|fim▁end|>
| |
<|file_name|>test_crashstorage_base.py<|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/.
from unittest import mock
from configman import Namespace, ConfigurationManager
from configman.dotdict import DotDict
import pytest
from socorro.external.crashstorage_base import (
CrashStorageBase,
PolyStorageError,
PolyCrashStorage,
Redactor,
BenchmarkingCrashStorage,
MemoryDumpsMapping,
MetricsCounter,
MetricsBenchmarkingWrapper,
)
class A(CrashStorageBase):
foo = "a"
required_config = Namespace()
required_config.add_option("x", default=1)
required_config.add_option("y", default=2)
def __init__(self, config, namespace=""):
super().__init__(config, namespace)
self.raw_crash_count = 0
def save_raw_crash(self, raw_crash, dump):
pass
def save_processed_crash(self, processed_crash):
pass
class B(A):
foo = "b"
required_config = Namespace()
required_config.add_option("z", default=2)
class TestCrashStorageBase:
def test_basic_crashstorage(self):
required_config = Namespace()
mock_logging = mock.Mock()
required_config.add_option("logger", default=mock_logging)
required_config.update(CrashStorageBase.required_config)
config_manager = ConfigurationManager(
[required_config],
app_name="testapp",
app_version="1.0",
app_description="app description",
values_source_list=[{"logger": mock_logging}],
argv_source=[],
)
with config_manager.context() as config:
crashstorage = CrashStorageBase(config)
crashstorage.save_raw_crash({}, "payload", "ooid")
with pytest.raises(NotImplementedError):
crashstorage.get_raw_crash("ooid")
with pytest.raises(NotImplementedError):
crashstorage.get_raw_dump("ooid")
with pytest.raises(NotImplementedError):
crashstorage.get_unredacted_processed("ooid")
with pytest.raises(NotImplementedError):
crashstorage.remove("ooid")
crashstorage.close()
def test_polyerror(self):
p = PolyStorageError("hell")
try:
try:
raise NameError("dwight")
except NameError:
p.gather_current_exception()
try:
raise KeyError("wilma")
except KeyError:
p.gather_current_exception()
try:
raise AttributeError("sarita")
except AttributeError:
p.gather_current_exception()
raise p
except PolyStorageError as x:
assert len(x) == 3
assert x.has_exceptions()
expected = [NameError, KeyError, AttributeError]
assert [exc[0] for exc in x] == expected
assert 1 not in x
assert str(x[0][1]) == "dwight"
assert all(
sample in str(x)
for sample in ["hell", "NameError", "KeyError", "AttributeError"]
)
assert (
str(x)
== "hell,NameError('dwight'),KeyError('wilma'),AttributeError('sarita')"
)
x[0] = x[1]
assert x[0] == x[1]
def test_polyerror_str_missing_args(self):
p = PolyStorageError()
try:
try:
raise NameError("dwight")
except NameError:
p.gather_current_exception()
try:
raise KeyError("wilma")
except KeyError:
p.gather_current_exception()
raise p
except PolyStorageError as x:
assert str(x) == "NameError('dwight'),KeyError('wilma')"
def test_poly_crash_storage(self):
n = Namespace()
n.add_option("storage", default=PolyCrashStorage)
n.add_option("logger", default=mock.Mock())
value = {
"storage_namespaces": "A,A2,B",
"A.crashstorage_class": "socorro.unittest.external.test_crashstorage_base.A",
"A2.crashstorage_class": "socorro.unittest.external.test_crashstorage_base.A",
"B.crashstorage_class": "socorro.unittest.external.test_crashstorage_base.B",
"A2.y": 37,
}
cm = ConfigurationManager(n, values_source_list=[value])
with cm.context() as config:
assert config.A.crashstorage_class.foo == "a"
assert config.A2.crashstorage_class.foo == "a"
assert config.A2.y == 37
assert config.B.crashstorage_class.foo == "b"
poly_store = config.storage(config)
assert len(poly_store.storage_namespaces) == 3
assert poly_store.storage_namespaces[0] == "A"
assert poly_store.storage_namespaces[1] == "A2"
assert poly_store.storage_namespaces[2] == "B"<|fim▁hole|> assert poly_store.stores.B.foo == "b"
raw_crash = {"ooid": ""}
dump = "12345"
processed_crash = {"ooid": "", "product": 17}
for v in poly_store.stores.values():
v.save_raw_crash = mock.Mock()
v.save_processed_crash = mock.Mock()
v.close = mock.Mock()
poly_store.save_raw_crash(raw_crash, dump, "")
for v in poly_store.stores.values():
v.save_raw_crash.assert_called_once_with(raw_crash, dump, "")
poly_store.save_processed_crash(raw_crash, processed_crash)
for v in poly_store.stores.values():
v.save_processed_crash.assert_called_once_with(
raw_crash, processed_crash
)
raw_crash = {"ooid": "oaeu"}
dump = "5432"
processed_crash = {"ooid": "aoeu", "product": 33}
expected = Exception("this is messed up")
poly_store.stores["A2"].save_raw_crash = mock.Mock()
poly_store.stores["A2"].save_raw_crash.side_effect = expected
poly_store.stores["B"].save_processed_crash = mock.Mock()
poly_store.stores["B"].save_processed_crash.side_effect = expected
with pytest.raises(PolyStorageError):
poly_store.save_raw_crash(raw_crash, dump, "")
for v in poly_store.stores.values():
v.save_raw_crash.assert_called_with(raw_crash, dump, "")
with pytest.raises(PolyStorageError):
poly_store.save_processed_crash(raw_crash, processed_crash)
for v in poly_store.stores.values():
v.save_processed_crash.assert_called_with(raw_crash, processed_crash)
poly_store.stores["B"].close.side_effect = Exception
with pytest.raises(PolyStorageError):
poly_store.close()
for v in poly_store.stores.values():
v.close.assert_called_with()
class TestRedactor:
def test_redact(self):
d = DotDict()
# these keys survive redaction
d["a.b.c"] = 11
d["sensitive.x"] = 2
d["not_url"] = "not a url"
# these keys do not survive redaction
d["url"] = "http://very.embarassing.com"
d["exploitability"] = "yep"
d["json_dump.sensitive"] = 22
d["upload_file_minidump_flash1.json_dump.sensitive"] = 33
d["upload_file_minidump_flash2.json_dump.sensitive"] = 44
d["upload_file_minidump_browser.json_dump.sensitive.exploitable"] = 55
d["upload_file_minidump_browser.json_dump.sensitive.secret"] = 66
d["memory_info"] = {"incriminating_memory": "call the FBI"}
assert "json_dump" in d
config = DotDict()
config.forbidden_keys = Redactor.required_config.forbidden_keys.default
expected_surviving_keys = [
"a",
"sensitive",
"not_url",
"json_dump",
"upload_file_minidump_flash1",
"upload_file_minidump_flash2",
"upload_file_minidump_browser",
]
expected_surviving_keys.sort()
redactor = Redactor(config)
redactor(d)
actual_surviving_keys = [x for x in d.keys()]
actual_surviving_keys.sort()
assert actual_surviving_keys == expected_surviving_keys
class TestBench:
def test_benchmarking_crashstore(self, caplogpp):
caplogpp.set_level("DEBUG")
required_config = Namespace()
required_config.update(BenchmarkingCrashStorage.get_required_config())
fake_crash_store = mock.Mock()
config_manager = ConfigurationManager(
[required_config],
app_name="testapp",
app_version="1.0",
app_description="app description",
values_source_list=[
{"wrapped_crashstore": fake_crash_store, "benchmark_tag": "test"}
],
argv_source=[],
)
with config_manager.context() as config:
crashstorage = BenchmarkingCrashStorage(config, namespace="")
crashstorage.start_timer = lambda: 0
crashstorage.end_timer = lambda: 1
fake_crash_store.assert_called_with(config, namespace="")
crashstorage.save_raw_crash({}, "payload", "ooid")
crashstorage.wrapped_crashstore.save_raw_crash.assert_called_with(
{}, "payload", "ooid"
)
assert "test save_raw_crash 1" in [rec.message for rec in caplogpp.records]
caplogpp.clear()
crashstorage.save_processed_crash({}, {})
crashstorage.wrapped_crashstore.save_processed_crash.assert_called_with(
{}, {}
)
assert "test save_processed_crash 1" in [
rec.message for rec in caplogpp.records
]
caplogpp.clear()
crashstorage.get_raw_crash("uuid")
crashstorage.wrapped_crashstore.get_raw_crash.assert_called_with("uuid")
assert "test get_raw_crash 1" in [rec.message for rec in caplogpp.records]
caplogpp.clear()
crashstorage.get_raw_dump("uuid")
crashstorage.wrapped_crashstore.get_raw_dump.assert_called_with("uuid")
assert "test get_raw_dump 1" in [rec.message for rec in caplogpp.records]
caplogpp.clear()
crashstorage.get_dumps("uuid")
crashstorage.wrapped_crashstore.get_dumps.assert_called_with("uuid")
assert "test get_dumps 1" in [rec.message for rec in caplogpp.records]
caplogpp.clear()
crashstorage.get_dumps_as_files("uuid")
crashstorage.wrapped_crashstore.get_dumps_as_files.assert_called_with(
"uuid"
)
assert "test get_dumps_as_files 1" in [
rec.message for rec in caplogpp.records
]
caplogpp.clear()
crashstorage.get_unredacted_processed("uuid")
crashstorage.wrapped_crashstore.get_unredacted_processed.assert_called_with(
"uuid"
)
assert "test get_unredacted_processed 1" in [
rec.message for rec in caplogpp.records
]
class TestDumpsMappings:
def test_simple(self):
mdm = MemoryDumpsMapping(
{"upload_file_minidump": b"binary_data", "moar_dump": b"more binary data"}
)
assert mdm.as_memory_dumps_mapping() is mdm
fdm = mdm.as_file_dumps_mapping("a", "/tmp", "dump")
assert fdm.as_file_dumps_mapping() is fdm
assert fdm.as_memory_dumps_mapping() == mdm
class TestMetricsCounter:
def test_count(self, metricsmock):
config_manager = ConfigurationManager(
[MetricsCounter.get_required_config()],
values_source_list=[{"metrics_prefix": "phil", "active_list": "run"}],
argv_source=[],
)
with config_manager.context() as config:
counter = MetricsCounter(config)
with metricsmock as mm:
counter.run()
counter.walk()
mm.assert_incr_once("phil.run", value=1)
class TestMetricsBenchmarkingWrapper:
def test_wrapper(self, metricsmock):
fake_crash_store_class = mock.MagicMock()
fake_crash_store_class.__name__ = "Phil"
config_manager = ConfigurationManager(
[MetricsBenchmarkingWrapper.get_required_config()],
values_source_list=[
{
"wrapped_object_class": fake_crash_store_class,
"metrics_prefix": "phil",
"active_list": "run",
}
],
argv_source=[],
)
with config_manager.context() as config:
mbw = MetricsBenchmarkingWrapper(config)
with metricsmock as mm:
mbw.run()
mbw.walk()
mm.assert_timing_once("phil.Phil.run")
# Assert that the wrapped crash storage class .run() and .walk() were
# called on the instance
fake_crash_store_class.return_value.run.assert_called_with()
fake_crash_store_class.return_value.walk.assert_called_with()<|fim▁end|>
|
assert len(poly_store.stores) == 3
assert poly_store.stores.A.foo == "a"
assert poly_store.stores.A2.foo == "a"
|
<|file_name|>vue-i18n.runtime.esm-bundler.js<|end_file_name|><|fim▁begin|>/*!
* vue-i18n v9.0.0
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
import { getGlobalThis, format, makeSymbol, isPlainObject, isArray, isObject, isBoolean, isString, isRegExp, isFunction, isNumber, warn, isEmptyObject } from '@intlify/shared';
import { ref, getCurrentInstance, computed, watch, createVNode, Text, h, Fragment, inject, onMounted, onUnmounted, isRef } from 'vue';
import { createCompileError, createCoreContext, updateFallbackLocale, resolveValue, clearDateTimeFormat, clearNumberFormat, NOT_REOSLVED, parseTranslateArgs, translate, MISSING_RESOLVE_VALUE, parseDateTimeArgs, datetime, parseNumberArgs, number, DevToolsLabels, DevToolsPlaceholders, DevToolsTimelineColors, createEmitter } from '@intlify/core-base';
import { setupDevtoolsPlugin } from '@vue/devtools-api';
/**
* Vue I18n Version
*
* @remarks
* Semver format. Same format as the package.json `version` field.
*
* @VueI18nGeneral
*/
const VERSION = '9.0.0';
/**
* This is only called in esm-bundler builds.
* istanbul-ignore-next
*/
function initFeatureFlags() {
let needWarn = false;
if (typeof __VUE_I18N_FULL_INSTALL__ !== 'boolean') {
needWarn = true;
getGlobalThis().__VUE_I18N_FULL_INSTALL__ = true;
}
if (typeof __VUE_I18N_LEGACY_API__ !== 'boolean') {
needWarn = true;
getGlobalThis().__VUE_I18N_LEGACY_API__ = true;
}
if (typeof __INTLIFY_PROD_DEVTOOLS__ !== 'boolean') {
needWarn = true;
getGlobalThis().__INTLIFY_PROD_DEVTOOLS__ = false;
}
if ((process.env.NODE_ENV !== 'production') && needWarn) {
console.warn(`You are running the esm-bundler build of vue-i18n. It is recommended to ` +
`configure your bundler to explicitly replace feature flag globals ` +
`with boolean literals to get proper tree-shaking in the final bundle.`);
}
}
/**
* This is only called development env
* istanbul-ignore-next
*/
function initDev() {
const target = getGlobalThis();
target.__INTLIFY__ = true;
{
console.info(`You are running a development build of vue-i18n.\n` +
`Make sure to use the production build (*.prod.js) when deploying for production.`);
}
}
const warnMessages = {
[6 /* FALLBACK_TO_ROOT */]: `Fall back to {type} '{key}' with root locale.`,
[7 /* NOT_SUPPORTED_PRESERVE */]: `Not supported 'preserve'.`,
[8 /* NOT_SUPPORTED_FORMATTER */]: `Not supported 'formatter'.`,
[9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */]: `Not supported 'preserveDirectiveContent'.`,
[10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */]: `Not supported 'getChoiceIndex'.`,
[11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */]: `Component name legacy compatible: '{name}' -> 'i18n'`,
[12 /* NOT_FOUND_PARENT_SCOPE */]: `Not found parent scope. use the global scope.`
};
function getWarnMessage(code, ...args) {
return format(warnMessages[code], ...args);
}
function createI18nError(code, ...args) {
return createCompileError(code, null, (process.env.NODE_ENV !== 'production') ? { messages: errorMessages, args } : undefined);
}
const errorMessages = {
[14 /* UNEXPECTED_RETURN_TYPE */]: 'Unexpected return type in composer',
[15 /* INVALID_ARGUMENT */]: 'Invalid argument',
[16 /* MUST_BE_CALL_SETUP_TOP */]: 'Must be called at the top of a `setup` function',
[17 /* NOT_INSLALLED */]: 'Need to install with `app.use` function',
[22 /* UNEXPECTED_ERROR */]: 'Unexpected error',
[18 /* NOT_AVAILABLE_IN_LEGACY_MODE */]: 'Not available in legacy mode',
[19 /* REQUIRED_VALUE */]: `Required in value: {0}`,
[20 /* INVALID_VALUE */]: `Invalid value`,
[21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */]: `Cannot setup vue-devtools plugin`
};
const TransrateVNodeSymbol = makeSymbol('__transrateVNode');
const DatetimePartsSymbol = makeSymbol('__datetimeParts');
const NumberPartsSymbol = makeSymbol('__numberParts');
const EnableEmitter = makeSymbol('__enableEmitter');
const DisableEmitter = makeSymbol('__disableEmitter');
const SetPluralRulesSymbol = makeSymbol('__setPluralRules');
let composerID = 0;
function defineCoreMissingHandler(missing) {
return ((ctx, locale, key, type) => {
return missing(locale, key, getCurrentInstance() || undefined, type);
});
}
function getLocaleMessages(locale, options) {
const { messages, __i18n } = options;
// prettier-ignore
const ret = isPlainObject(messages)
? messages
: isArray(__i18n)
? {}
: { [locale]: {} };
// merge locale messages of i18n custom block
if (isArray(__i18n)) {
__i18n.forEach(({ locale, resource }) => {
if (locale) {
ret[locale] = ret[locale] || {};
deepCopy(resource, ret[locale]);
}
else {
deepCopy(resource, ret);
}
});
}
return ret;
}
const hasOwnProperty = Object.prototype.hasOwnProperty;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key);
}
const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function deepCopy(src, des) {
// src and des should both be objects, and non of then can be a array
if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) {
throw createI18nError(20 /* INVALID_VALUE */);
}
for (const key in src) {
if (hasOwn(src, key)) {
if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) {
// replace with src[key] when:
// src[key] or des[key] is not a object, or
// src[key] or des[key] is a array
des[key] = src[key];
}
else {
// src[key] and des[key] are both object, merge them
deepCopy(src[key], des[key]);
}
}
}
}
/**
* Create composer interface factory
*
* @internal
*/
function createComposer(options = {}) {
const { __root } = options;
const _isGlobal = __root === undefined;
let _inheritLocale = isBoolean(options.inheritLocale)
? options.inheritLocale
: true;
const _locale = ref(
// prettier-ignore
__root && _inheritLocale
? __root.locale.value
: isString(options.locale)
? options.locale
: 'en-US');
const _fallbackLocale = ref(
// prettier-ignore
__root && _inheritLocale
? __root.fallbackLocale.value
: isString(options.fallbackLocale) ||
isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: _locale.value);
const _messages = ref(getLocaleMessages(_locale.value, options));
const _datetimeFormats = ref(isPlainObject(options.datetimeFormats)
? options.datetimeFormats
: { [_locale.value]: {} });
const _numberFormats = ref(isPlainObject(options.numberFormats)
? options.numberFormats
: { [_locale.value]: {} });
// warning suppress options
// prettier-ignore
let _missingWarn = __root
? __root.missingWarn
: isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
? options.missingWarn
: true;
// prettier-ignore
let _fallbackWarn = __root
? __root.fallbackWarn
: isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
? options.fallbackWarn
: true;
// prettier-ignore
let _fallbackRoot = __root
? __root.fallbackRoot
: isBoolean(options.fallbackRoot)
? options.fallbackRoot
: true;
// configure fall back to root
let _fallbackFormat = !!options.fallbackFormat;
// runtime missing
let _missing = isFunction(options.missing) ? options.missing : null;
let _runtimeMissing = isFunction(options.missing)
? defineCoreMissingHandler(options.missing)
: null;
// postTranslation handler
let _postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: null;
let _warnHtmlMessage = isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
let _escapeParameter = !!options.escapeParameter;
// custom linked modifiers
// prettier-ignore
const _modifiers = __root
? __root.modifiers
: isPlainObject(options.modifiers)
? options.modifiers
: {};
// pluralRules
let _pluralRules = options.pluralRules || (__root && __root.pluralRules);
// runtime context
// eslint-disable-next-line prefer-const
let _context;
function getCoreContext() {
return createCoreContext({
locale: _locale.value,
fallbackLocale: _fallbackLocale.value,
messages: _messages.value,
datetimeFormats: _datetimeFormats.value,
numberFormats: _numberFormats.value,
modifiers: _modifiers,
pluralRules: _pluralRules,
missing: _runtimeMissing === null ? undefined : _runtimeMissing,
missingWarn: _missingWarn,
fallbackWarn: _fallbackWarn,
fallbackFormat: _fallbackFormat,
unresolving: true,
postTranslation: _postTranslation === null ? undefined : _postTranslation,
warnHtmlMessage: _warnHtmlMessage,
escapeParameter: _escapeParameter,
__datetimeFormatters: isPlainObject(_context)
? _context.__datetimeFormatters
: undefined,
__numberFormatters: isPlainObject(_context)
? _context.__numberFormatters
: undefined,
__emitter: isPlainObject(_context)
? _context.__emitter
: undefined
});
}
_context = getCoreContext();
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
// locale
const locale = computed({
get: () => _locale.value,
set: val => {
_locale.value = val;
_context.locale = _locale.value;
}
});
// fallbackLocale
const fallbackLocale = computed({
get: () => _fallbackLocale.value,
set: val => {
_fallbackLocale.value = val;
_context.fallbackLocale = _fallbackLocale.value;
updateFallbackLocale(_context, _locale.value, val);
}
});
// messages
const messages = computed(() => _messages.value);
// datetimeFormats
const datetimeFormats = computed(() => _datetimeFormats.value);
// numberFormats
const numberFormats = computed(() => _numberFormats.value);
// getPostTranslationHandler
function getPostTranslationHandler() {
return isFunction(_postTranslation) ? _postTranslation : null;
}
// setPostTranslationHandler
function setPostTranslationHandler(handler) {
_postTranslation = handler;
_context.postTranslation = handler;
}
// getMissingHandler
function getMissingHandler() {
return _missing;
}
// setMissingHandler
function setMissingHandler(handler) {
if (handler !== null) {
_runtimeMissing = defineCoreMissingHandler(handler);
}
_missing = handler;
_context.missing = _runtimeMissing;
}
function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) {
const context = getCoreContext();
const ret = fn(context); // track reactive dependency, see the getRuntimeContext
if (isNumber(ret) && ret === NOT_REOSLVED) {
const key = argumentParser();
if ((process.env.NODE_ENV !== 'production') && __root) {
if (!_fallbackRoot) {
warn(getWarnMessage(6 /* FALLBACK_TO_ROOT */, {
key,
type: warnType
}));
}
// for vue-devtools timeline event
if ((process.env.NODE_ENV !== 'production')) {
const { __emitter: emitter } = context;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type: warnType,
key,
to: 'global',
groupId: `${warnType}:${key}`
});
}
}
}
return __root && _fallbackRoot
? fallbackSuccess(__root)
: fallbackFail(key);
}
else if (successCondition(ret)) {
return ret;
}
else {
/* istanbul ignore next */
throw createI18nError(14 /* UNEXPECTED_RETURN_TYPE */);
}
}
// t
function t(...args) {
return wrapWithDeps(context => translate(context, ...args), () => parseTranslateArgs(...args)[0], 'translate', root => root.t(...args), key => key, val => isString(val));
}
// d
function d(...args) {
return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args)[0], 'datetime format', root => root.d(...args), () => MISSING_RESOLVE_VALUE, val => isString(val));
}
// n
function n(...args) {
return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args)[0], 'number format', root => root.n(...args), () => MISSING_RESOLVE_VALUE, val => isString(val));
}
// for custom processor
function normalize(values) {
return values.map(val => isString(val) ? createVNode(Text, null, val, 0) : val);
}
const interpolate = (val) => val;
const processor = {
normalize,
interpolate,
type: 'vnode'
};
// __transrateVNode, using for `i18n-t` component
function __transrateVNode(...args) {
return wrapWithDeps(context => {
let ret;
const _context = context;
try {
_context.processor = processor;
ret = translate(_context, ...args);
}
finally {
_context.processor = null;
}
return ret;
}, () => parseTranslateArgs(...args)[0], 'translate',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => root[TransrateVNodeSymbol](...args), key => [createVNode(Text, null, key, 0)], val => isArray(val));
}
// __numberParts, using for `i18n-n` component
function __numberParts(...args) {
return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args)[0], 'number format',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val));
}
// __datetimeParts, using for `i18n-d` component
function __datetimeParts(...args) {
return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args)[0], 'datetime format',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val));
}
function __setPluralRules(rules) {
_pluralRules = rules;
_context.pluralRules = _pluralRules;
}
// te
function te(key, locale) {
const targetLocale = isString(locale) ? locale : _locale.value;
const message = getLocaleMessage(targetLocale);
return resolveValue(message, key) !== null;
}
// tm
function tm(key) {
const messages = _messages.value[_locale.value] || {};
const target = resolveValue(messages, key);
// prettier-ignore
return target != null
? target
: __root
? __root.tm(key) || {}
: {};
}
// getLocaleMessage
function getLocaleMessage(locale) {
return (_messages.value[locale] || {});
}
// setLocaleMessage
function setLocaleMessage(locale, message) {
_messages.value[locale] = message;
_context.messages = _messages.value;
}
// mergeLocaleMessage
function mergeLocaleMessage(locale, message) {
_messages.value[locale] = _messages.value[locale] || {};
deepCopy(message, _messages.value[locale]);
_context.messages = _messages.value;
}
// getDateTimeFormat
function getDateTimeFormat(locale) {
return _datetimeFormats.value[locale] || {};
}
// setDateTimeFormat
function setDateTimeFormat(locale, format) {
_datetimeFormats.value[locale] = format;
_context.datetimeFormats = _datetimeFormats.value;
clearDateTimeFormat(_context, locale, format);
}
// mergeDateTimeFormat
function mergeDateTimeFormat(locale, format) {
_datetimeFormats.value[locale] = Object.assign(_datetimeFormats.value[locale] || {}, format);
_context.datetimeFormats = _datetimeFormats.value;
clearDateTimeFormat(_context, locale, format);
}
// getNumberFormat
function getNumberFormat(locale) {
return _numberFormats.value[locale] || {};
}
// setNumberFormat
function setNumberFormat(locale, format) {
_numberFormats.value[locale] = format;
_context.numberFormats = _numberFormats.value;
clearNumberFormat(_context, locale, format);
}
// mergeNumberFormat
function mergeNumberFormat(locale, format) {
_numberFormats.value[locale] = Object.assign(_numberFormats.value[locale] || {}, format);
_context.numberFormats = _numberFormats.value;
clearNumberFormat(_context, locale, format);
}
// for debug
composerID++;
// watch root locale & fallbackLocale
if (__root) {
watch(__root.locale, (val) => {
if (_inheritLocale) {
_locale.value = val;
_context.locale = val;
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
}
});
watch(__root.fallbackLocale, (val) => {
if (_inheritLocale) {
_fallbackLocale.value = val;
_context.fallbackLocale = val;
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
}
});
}
// export composition API!
const composer = {
id: composerID,
locale,
fallbackLocale,
get inheritLocale() {
return _inheritLocale;
},
set inheritLocale(val) {
_inheritLocale = val;
if (val && __root) {
_locale.value = __root.locale.value;
_fallbackLocale.value = __root.fallbackLocale.value;
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
}
},
get availableLocales() {
return Object.keys(_messages.value).sort();
},
messages,
datetimeFormats,
numberFormats,
get modifiers() {
return _modifiers;
},
get pluralRules() {
return _pluralRules || {};
},
get isGlobal() {
return _isGlobal;
},
get missingWarn() {
return _missingWarn;
},
set missingWarn(val) {
_missingWarn = val;
_context.missingWarn = _missingWarn;
},
get fallbackWarn() {
return _fallbackWarn;
},
set fallbackWarn(val) {
_fallbackWarn = val;
_context.fallbackWarn = _fallbackWarn;
},
get fallbackRoot() {
return _fallbackRoot;
},
set fallbackRoot(val) {
_fallbackRoot = val;
},
get fallbackFormat() {
return _fallbackFormat;
},
set fallbackFormat(val) {
_fallbackFormat = val;
_context.fallbackFormat = _fallbackFormat;
},
get warnHtmlMessage() {
return _warnHtmlMessage;
},
set warnHtmlMessage(val) {
_warnHtmlMessage = val;
_context.warnHtmlMessage = val;
},
get escapeParameter() {
return _escapeParameter;
},
set escapeParameter(val) {
_escapeParameter = val;
_context.escapeParameter = val;
},
t,
d,
n,
te,
tm,
getLocaleMessage,
setLocaleMessage,
mergeLocaleMessage,
getDateTimeFormat,
setDateTimeFormat,
mergeDateTimeFormat,
getNumberFormat,
setNumberFormat,
mergeNumberFormat,
getPostTranslationHandler,
setPostTranslationHandler,
getMissingHandler,
setMissingHandler,
[TransrateVNodeSymbol]: __transrateVNode,
[NumberPartsSymbol]: __numberParts,
[DatetimePartsSymbol]: __datetimeParts,
[SetPluralRulesSymbol]: __setPluralRules
};
// for vue-devtools timeline event
if ((process.env.NODE_ENV !== 'production')) {
composer[EnableEmitter] = (emitter) => {
_context.__emitter = emitter;
};
composer[DisableEmitter] = () => {
_context.__emitter = undefined;
};
}
return composer;
}
/**
* Convert to I18n Composer Options from VueI18n Options
*
* @internal
*/
function convertComposerOptions(options) {
const locale = isString(options.locale) ? options.locale : 'en-US';
const fallbackLocale = isString(options.fallbackLocale) ||
isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: locale;
const missing = isFunction(options.missing) ? options.missing : undefined;
const missingWarn = isBoolean(options.silentTranslationWarn) ||
isRegExp(options.silentTranslationWarn)
? !options.silentTranslationWarn
: true;
const fallbackWarn = isBoolean(options.silentFallbackWarn) ||
isRegExp(options.silentFallbackWarn)
? !options.silentFallbackWarn
: true;
const fallbackRoot = isBoolean(options.fallbackRoot)
? options.fallbackRoot
: true;
const fallbackFormat = !!options.formatFallbackMessages;
const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {};
const pluralizationRules = options.pluralizationRules;
const postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: undefined;
const warnHtmlMessage = isString(options.warnHtmlInMessage)
? options.warnHtmlInMessage !== 'off'
: true;
const escapeParameter = !!options.escapeParameterHtml;
const inheritLocale = isBoolean(options.sync) ? options.sync : true;
if ((process.env.NODE_ENV !== 'production') && options.formatter) {
warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */));
}
if ((process.env.NODE_ENV !== 'production') && options.preserveDirectiveContent) {
warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
}
let messages = options.messages;
if (isPlainObject(options.sharedMessages)) {
const sharedMessages = options.sharedMessages;
const locales = Object.keys(sharedMessages);
messages = locales.reduce((messages, locale) => {
const message = messages[locale] || (messages[locale] = {});
Object.assign(message, sharedMessages[locale]);
return messages;
}, (messages || {}));
}
const { __i18n, __root } = options;
const datetimeFormats = options.datetimeFormats;
const numberFormats = options.numberFormats;
return {
locale,
fallbackLocale,
messages,
datetimeFormats,
numberFormats,
missing,
missingWarn,
fallbackWarn,
fallbackRoot,
fallbackFormat,
modifiers,
pluralRules: pluralizationRules,
postTranslation,
warnHtmlMessage,
escapeParameter,
inheritLocale,
__i18n,
__root
};
}
/**
* create VueI18n interface factory
*
* @internal
*/
function createVueI18n(options = {}) {
const composer = createComposer(convertComposerOptions(options));
// defines VueI18n
const vueI18n = {
// id
id: composer.id,
// locale
get locale() {
return composer.locale.value;
},
set locale(val) {
composer.locale.value = val;
},
// fallbackLocale
get fallbackLocale() {
return composer.fallbackLocale.value;
},
set fallbackLocale(val) {
composer.fallbackLocale.value = val;
},
// messages
get messages() {
return composer.messages.value;
},
// datetimeFormats
get datetimeFormats() {
return composer.datetimeFormats.value;
},
// numberFormats
get numberFormats() {
return composer.numberFormats.value;
},
// availableLocales
get availableLocales() {
return composer.availableLocales;
},
// formatter
get formatter() {
(process.env.NODE_ENV !== 'production') && warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */));
// dummy
return {
interpolate() {
return [];
}
};
},
set formatter(val) {
(process.env.NODE_ENV !== 'production') && warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */));
},
// missing
get missing() {
return composer.getMissingHandler();
},
set missing(handler) {
composer.setMissingHandler(handler);
},
// silentTranslationWarn
get silentTranslationWarn() {
return isBoolean(composer.missingWarn)
? !composer.missingWarn
: composer.missingWarn;
},
set silentTranslationWarn(val) {
composer.missingWarn = isBoolean(val) ? !val : val;
},
// silentFallbackWarn
get silentFallbackWarn() {
return isBoolean(composer.fallbackWarn)
? !composer.fallbackWarn
: composer.fallbackWarn;
},
set silentFallbackWarn(val) {
composer.fallbackWarn = isBoolean(val) ? !val : val;
},
// modifiers
get modifiers() {
return composer.modifiers;
},
// formatFallbackMessages
get formatFallbackMessages() {
return composer.fallbackFormat;
},
set formatFallbackMessages(val) {
composer.fallbackFormat = val;
},
// postTranslation
get postTranslation() {
return composer.getPostTranslationHandler();
},
set postTranslation(handler) {
composer.setPostTranslationHandler(handler);
},
// sync
get sync() {
return composer.inheritLocale;
},
set sync(val) {
composer.inheritLocale = val;
},
// warnInHtmlMessage
get warnHtmlInMessage() {
return composer.warnHtmlMessage ? 'warn' : 'off';
},
set warnHtmlInMessage(val) {
composer.warnHtmlMessage = val !== 'off';
},
// escapeParameterHtml
get escapeParameterHtml() {
return composer.escapeParameter;
},
set escapeParameterHtml(val) {
composer.escapeParameter = val;
},
// preserveDirectiveContent
get preserveDirectiveContent() {
(process.env.NODE_ENV !== 'production') &&
warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
return true;
},
set preserveDirectiveContent(val) {
(process.env.NODE_ENV !== 'production') &&
warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
},
// pluralizationRules
get pluralizationRules() {
return composer.pluralRules || {};
},
// for internal
__composer: composer,
// t
t(...args) {
const [arg1, arg2, arg3] = args;
const options = {};
let list = null;
let named = null;
if (!isString(arg1)) {
throw createI18nError(15 /* INVALID_ARGUMENT */);
}
const key = arg1;
if (isString(arg2)) {
options.locale = arg2;
}
else if (isArray(arg2)) {
list = arg2;
}
else if (isPlainObject(arg2)) {
named = arg2;
}
if (isArray(arg3)) {
list = arg3;
}
else if (isPlainObject(arg3)) {
named = arg3;
}
return composer.t(key, list || named || {}, options);
},
// tc
tc(...args) {
const [arg1, arg2, arg3] = args;
const options = { plural: 1 };
let list = null;
let named = null;
if (!isString(arg1)) {
throw createI18nError(15 /* INVALID_ARGUMENT */);
}
const key = arg1;
if (isString(arg2)) {
options.locale = arg2;
}
else if (isNumber(arg2)) {
options.plural = arg2;
}
else if (isArray(arg2)) {
list = arg2;
}
else if (isPlainObject(arg2)) {
named = arg2;
}
if (isString(arg3)) {
options.locale = arg3;
}
else if (isArray(arg3)) {
list = arg3;
}
else if (isPlainObject(arg3)) {
named = arg3;
}
return composer.t(key, list || named || {}, options);
},
// te
te(key, locale) {
return composer.te(key, locale);
},
// tm
tm(key) {
return composer.tm(key);
},
// getLocaleMessage
getLocaleMessage(locale) {
return composer.getLocaleMessage(locale);
},
// setLocaleMessage
setLocaleMessage(locale, message) {
composer.setLocaleMessage(locale, message);
},
// mergeLocaleMessage
mergeLocaleMessage(locale, message) {
composer.mergeLocaleMessage(locale, message);
},
// d
d(...args) {
return composer.d(...args);
},
// getDateTimeFormat
getDateTimeFormat(locale) {
return composer.getDateTimeFormat(locale);
},
// setDateTimeFormat
setDateTimeFormat(locale, format) {
composer.setDateTimeFormat(locale, format);
},
// mergeDateTimeFormat
mergeDateTimeFormat(locale, format) {
composer.mergeDateTimeFormat(locale, format);
},
// n
n(...args) {
return composer.n(...args);
},
// getNumberFormat
getNumberFormat(locale) {
return composer.getNumberFormat(locale);
},
// setNumberFormat
setNumberFormat(locale, format) {
composer.setNumberFormat(locale, format);
},
// mergeNumberFormat
mergeNumberFormat(locale, format) {
composer.mergeNumberFormat(locale, format);
},
// getChoiceIndex
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getChoiceIndex(choice, choicesLength) {
(process.env.NODE_ENV !== 'production') &&
warn(getWarnMessage(10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */));
return -1;
},
// for internal
__onComponentInstanceCreated(target) {
const { componentInstanceCreatedListener } = options;
if (componentInstanceCreatedListener) {
componentInstanceCreatedListener(target, vueI18n);
}
}
};
// for vue-devtools timeline event
if ((process.env.NODE_ENV !== 'production')) {
vueI18n.__enableEmitter = (emitter) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const __composer = composer;
__composer[EnableEmitter] && __composer[EnableEmitter](emitter);
};
vueI18n.__disableEmitter = () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const __composer = composer;
__composer[DisableEmitter] && __composer[DisableEmitter]();
};
}
return vueI18n;
}
const baseFormatProps = {
tag: {
type: [String, Object]
},
locale: {
type: String
},
scope: {
type: String,
validator: (val) => val === 'parent' || val === 'global',
default: 'parent'
}
};
/**
* Translation Component
*
* @remarks
* See the following items for property about details
*
* @VueI18nSee [TranslationProps](component#translationprops)
* @VueI18nSee [BaseFormatProps](component#baseformatprops)
* @VueI18nSee [Component Interpolation](../../guide/advanced/component)
*
* @example
* ```html
* <div id="app">
* <!-- ... -->
* <i18n path="term" tag="label" for="tos">
* <a :href="url" target="_blank">{{ $t('tos') }}</a>
* </i18n>
* <!-- ... -->
* </div>
* ```
* ```js
* import { createApp } from 'vue'
* import { createI18n } from 'vue-i18n'
*
* const messages = {
* en: {
* tos: 'Term of Service',
* term: 'I accept xxx {0}.'
* },
* ja: {
* tos: '利用規約',
* term: '私は xxx の{0}に同意します。'
* }
* }
*
* const i18n = createI18n({
* locale: 'en',
* messages
* })
*
* const app = createApp({
* data: {
* url: '/term'
* }
* }).use(i18n).mount('#app')
* ```
*
* @VueI18nComponent
*/
const Translation = {
/* eslint-disable */
name: 'i18n-t',
props: {
...baseFormatProps,
keypath: {
type: String,
required: true
},
plural: {
type: [Number, String],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
validator: (val) => isNumber(val) || !isNaN(val)
}
},
/* eslint-enable */
setup(props, context) {
const { slots, attrs } = context;
const i18n = useI18n({ useScope: props.scope });
const keys = Object.keys(slots).filter(key => key !== '_');
return () => {
const options = {};
if (props.locale) {
options.locale = props.locale;
}
if (props.plural !== undefined) {
options.plural = isString(props.plural) ? +props.plural : props.plural;
}
const arg = getInterpolateArg(context, keys);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options);
// prettier-ignore
return isString(props.tag)
? h(props.tag, { ...attrs }, children)
: isObject(props.tag)
? h(props.tag, { ...attrs }, children)
: h(Fragment, { ...attrs }, children);
};
}
};
function getInterpolateArg({ slots }, keys) {
if (keys.length === 1 && keys[0] === 'default') {
// default slot only
return slots.default ? slots.default() : [];
}
else {
// named slots
return keys.reduce((arg, key) => {
const slot = slots[key];
if (slot) {
arg[key] = slot();
}
return arg;
}, {});
}
}
function renderFormatter(props, context, slotKeys, partFormatter) {
const { slots, attrs } = context;
return () => {
const options = { part: true };
let overrides = {};
if (props.locale) {
options.locale = props.locale;
<|fim▁hole|> }
else if (isObject(props.format)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (isString(props.format.key)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options.key = props.format.key;
}
// Filter out number format options only
overrides = Object.keys(props.format).reduce((options, prop) => {
return slotKeys.includes(prop)
? Object.assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any
: options;
}, {});
}
const parts = partFormatter(...[props.value, options, overrides]);
let children = [options.key];
if (isArray(parts)) {
children = parts.map((part, index) => {
const slot = slots[part.type];
return slot
? slot({ [part.type]: part.value, index, parts })
: [part.value];
});
}
else if (isString(parts)) {
children = [parts];
}
// prettier-ignore
return isString(props.tag)
? h(props.tag, { ...attrs }, children)
: isObject(props.tag)
? h(props.tag, { ...attrs }, children)
: h(Fragment, { ...attrs }, children);
};
}
const NUMBER_FORMAT_KEYS = [
'localeMatcher',
'style',
'unit',
'unitDisplay',
'currency',
'currencyDisplay',
'useGrouping',
'numberingSystem',
'minimumIntegerDigits',
'minimumFractionDigits',
'maximumFractionDigits',
'minimumSignificantDigits',
'maximumSignificantDigits',
'notation',
'formatMatcher'
];
/**
* Number Format Component
*
* @remarks
* See the following items for property about details
*
* @VueI18nSee [FormattableProps](component#formattableprops)
* @VueI18nSee [BaseFormatProps](component#baseformatprops)
* @VueI18nSee [Custom Formatting](../../guide/essentials/number#custom-formatting)
*
* @VueI18nDanger
* Not supported IE, due to no support `Intl.NumberFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts)
*
* If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat)
*
* @VueI18nComponent
*/
const NumberFormat = {
/* eslint-disable */
name: 'i18n-n',
props: {
...baseFormatProps,
value: {
type: Number,
required: true
},
format: {
type: [String, Object]
}
},
/* eslint-enable */
setup(props, context) {
const i18n = useI18n({ useScope: 'parent' });
return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
i18n[NumberPartsSymbol](...args));
}
};
const DATETIME_FORMAT_KEYS = [
'dateStyle',
'timeStyle',
'fractionalSecondDigits',
'calendar',
'dayPeriod',
'numberingSystem',
'localeMatcher',
'timeZone',
'hour12',
'hourCycle',
'formatMatcher',
'weekday',
'era',
'year',
'month',
'day',
'hour',
'minute',
'second',
'timeZoneName'
];
/**
* Datetime Format Component
*
* @remarks
* See the following items for property about details
*
* @VueI18nSee [FormattableProps](component#formattableprops)
* @VueI18nSee [BaseFormatProps](component#baseformatprops)
* @VueI18nSee [Custom Formatting](../../guide/essentials/datetime#custom-formatting)
*
* @VueI18nDanger
* Not supported IE, due to no support `Intl.DateTimeFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts)
*
* If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat)
*
* @VueI18nComponent
*/
const DatetimeFormat = {
/* eslint-disable */
name: 'i18n-d',
props: {
...baseFormatProps,
value: {
type: [Number, Date],
required: true
},
format: {
type: [String, Object]
}
},
/* eslint-enable */
setup(props, context) {
const i18n = useI18n({ useScope: 'parent' });
return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
i18n[DatetimePartsSymbol](...args));
}
};
function getComposer(i18n, instance) {
const i18nInternal = i18n;
if (i18n.mode === 'composition') {
return (i18nInternal.__getInstance(instance) || i18n.global);
}
else {
const vueI18n = i18nInternal.__getInstance(instance);
return vueI18n != null
? vueI18n.__composer
: i18n.global.__composer;
}
}
function vTDirective(i18n) {
const bind = (el, { instance, value, modifiers }) => {
/* istanbul ignore if */
if (!instance || !instance.$) {
throw createI18nError(22 /* UNEXPECTED_ERROR */);
}
const composer = getComposer(i18n, instance.$);
if ((process.env.NODE_ENV !== 'production') && modifiers.preserve) {
warn(getWarnMessage(7 /* NOT_SUPPORTED_PRESERVE */));
}
const parsedValue = parseValue(value);
el.textContent = composer.t(...makeParams(parsedValue));
};
return {
beforeMount: bind,
beforeUpdate: bind
};
}
function parseValue(value) {
if (isString(value)) {
return { path: value };
}
else if (isPlainObject(value)) {
if (!('path' in value)) {
throw createI18nError(19 /* REQUIRED_VALUE */, 'path');
}
return value;
}
else {
throw createI18nError(20 /* INVALID_VALUE */);
}
}
function makeParams(value) {
const { path, locale, args, choice, plural } = value;
const options = {};
const named = args || {};
if (isString(locale)) {
options.locale = locale;
}
if (isNumber(choice)) {
options.plural = choice;
}
if (isNumber(plural)) {
options.plural = plural;
}
return [path, named, options];
}
function apply(app, i18n, ...options) {
const pluginOptions = isPlainObject(options[0])
? options[0]
: {};
const useI18nComponentName = !!pluginOptions.useI18nComponentName;
const globalInstall = isBoolean(pluginOptions.globalInstall)
? pluginOptions.globalInstall
: true;
if ((process.env.NODE_ENV !== 'production') && globalInstall && useI18nComponentName) {
warn(getWarnMessage(11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */, {
name: Translation.name
}));
}
if (globalInstall) {
// install components
app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation);
app.component(NumberFormat.name, NumberFormat);
app.component(DatetimeFormat.name, DatetimeFormat);
}
// install directive
app.directive('t', vTDirective(i18n));
}
let devtoolsApi;
async function enableDevTools(app, i18n) {
return new Promise((resolve, reject) => {
try {
setupDevtoolsPlugin({
id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */,
label: DevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */],
app
}, api => {
devtoolsApi = api;
api.on.walkComponentTree((payload, ctx) => {
updateComponentTreeDataTags(ctx.currentAppRecord, payload.componentTreeData, i18n);
});
api.on.inspectComponent(payload => {
const componentInstance = payload.componentInstance;
if (componentInstance.vnode.el.__INTLIFY__ &&
payload.instanceData) {
if (i18n.mode === 'legacy') {
// ignore global scope on legacy mode
if (componentInstance.vnode.el.__INTLIFY__ !==
i18n.global.__composer) {
inspectComposer(payload.instanceData, componentInstance.vnode.el.__INTLIFY__);
}
}
else {
inspectComposer(payload.instanceData, componentInstance.vnode.el.__INTLIFY__);
}
}
});
api.addInspector({
id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */,
label: DevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */],
icon: 'language',
treeFilterPlaceholder: DevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]
});
api.on.getInspectorTree(payload => {
if (payload.app === app &&
payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
registerScope(payload, i18n);
}
});
api.on.getInspectorState(payload => {
if (payload.app === app &&
payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
inspectScope(payload, i18n);
}
});
api.addTimelineLayer({
id: "vue-i18n-timeline" /* TIMELINE */,
label: DevToolsLabels["vue-i18n-timeline" /* TIMELINE */],
color: DevToolsTimelineColors["vue-i18n-timeline" /* TIMELINE */]
});
resolve(true);
});
}
catch (e) {
console.error(e);
reject(false);
}
});
}
function updateComponentTreeDataTags(appRecord, treeData, i18n) {
// prettier-ignore
const global = i18n.mode === 'composition'
? i18n.global
: i18n.global.__composer;
for (const node of treeData) {
const instance = appRecord.instanceMap.get(node.id);
if (instance && instance.vnode.el.__INTLIFY__) {
// add custom tags local scope only
if (instance.vnode.el.__INTLIFY__ !== global) {
const label = instance.type.name ||
instance.type.displayName ||
instance.type.__file;
const tag = {
label: `i18n (${label} Scope)`,
textColor: 0x000000,
backgroundColor: 0xffcd19
};
node.tags.push(tag);
}
}
updateComponentTreeDataTags(appRecord, node.children, i18n);
}
}
function inspectComposer(instanceData, composer) {
const type = 'vue-i18n: composer properties';
instanceData.state.push({
type,
key: 'locale',
editable: false,
value: composer.locale.value
});
instanceData.state.push({
type,
key: 'availableLocales',
editable: false,
value: composer.availableLocales
});
instanceData.state.push({
type,
key: 'fallbackLocale',
editable: false,
value: composer.fallbackLocale.value
});
instanceData.state.push({
type,
key: 'inheritLocale',
editable: false,
value: composer.inheritLocale
});
instanceData.state.push({
type,
key: 'messages',
editable: false,
value: getLocaleMessageValue(composer.messages.value)
});
instanceData.state.push({
type,
key: 'datetimeFormats',
editable: false,
value: composer.datetimeFormats.value
});
instanceData.state.push({
type,
key: 'numberFormats',
editable: false,
value: composer.numberFormats.value
});
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getLocaleMessageValue(messages) {
const value = {};
Object.keys(messages).forEach((key) => {
const v = messages[key];
if (isFunction(v) && 'source' in v) {
value[key] = getMessageFunctionDetails(v);
}
else if (isObject(v)) {
value[key] = getLocaleMessageValue(v);
}
else {
value[key] = v;
}
});
return value;
}
const ESC = {
'<': '<',
'>': '>',
'"': '"',
'&': '&'
};
function escape(s) {
return s.replace(/[<>"&]/g, escapeChar);
}
function escapeChar(a) {
return ESC[a] || a;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getMessageFunctionDetails(func) {
const argString = func.source ? `("${escape(func.source)}")` : `(?)`;
return {
_custom: {
type: 'function',
display: `<span>ƒ</span> ${argString}`
}
};
}
function registerScope(payload, i18n) {
payload.rootNodes.push({
id: 'global',
label: 'Global Scope'
});
// prettier-ignore
const global = i18n.mode === 'composition'
? i18n.global
: i18n.global.__composer;
for (const [keyInstance, instance] of i18n.__instances) {
// prettier-ignore
const composer = i18n.mode === 'composition'
? instance
: instance.__composer;
if (global === composer) {
continue;
}
const label = keyInstance.type.name ||
keyInstance.type.displayName ||
keyInstance.type.__file;
payload.rootNodes.push({
id: composer.id.toString(),
label: `${label} Scope`
});
}
}
function inspectScope(payload, i18n) {
if (payload.nodeId === 'global') {
payload.state = makeScopeInspectState(i18n.mode === 'composition'
? i18n.global
: i18n.global.__composer);
}
else {
const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === payload.nodeId);
if (instance) {
const composer = i18n.mode === 'composition'
? instance
: instance.__composer;
payload.state = makeScopeInspectState(composer);
}
}
}
function makeScopeInspectState(composer) {
const state = {};
const localeType = 'Locale related info';
const localeStates = [
{
type: localeType,
key: 'locale',
editable: false,
value: composer.locale.value
},
{
type: localeType,
key: 'fallbackLocale',
editable: false,
value: composer.fallbackLocale.value
},
{
type: localeType,
key: 'availableLocales',
editable: false,
value: composer.availableLocales
},
{
type: localeType,
key: 'inheritLocale',
editable: false,
value: composer.inheritLocale
}
];
state[localeType] = localeStates;
const localeMessagesType = 'Locale messages info';
const localeMessagesStates = [
{
type: localeMessagesType,
key: 'messages',
editable: false,
value: getLocaleMessageValue(composer.messages.value)
}
];
state[localeMessagesType] = localeMessagesStates;
const datetimeFormatsType = 'Datetime formats info';
const datetimeFormatsStates = [
{
type: datetimeFormatsType,
key: 'datetimeFormats',
editable: false,
value: composer.datetimeFormats.value
}
];
state[datetimeFormatsType] = datetimeFormatsStates;
const numberFormatsType = 'Datetime formats info';
const numberFormatsStates = [
{
type: numberFormatsType,
key: 'numberFormats',
editable: false,
value: composer.numberFormats.value
}
];
state[numberFormatsType] = numberFormatsStates;
return state;
}
function addTimelineEvent(event, payload) {
if (devtoolsApi) {
let groupId;
if (payload && 'groupId' in payload) {
groupId = payload.groupId;
delete payload.groupId;
}
devtoolsApi.addTimelineEvent({
layerId: "vue-i18n-timeline" /* TIMELINE */,
event: {
title: event,
groupId,
time: Date.now(),
meta: {},
data: payload || {},
logType: event === "compile-error" /* COMPILE_ERROR */
? 'error'
: event === "fallback" /* FALBACK */ ||
event === "missing" /* MISSING */
? 'warning'
: 'default'
}
});
}
}
// supports compatibility for legacy vue-i18n APIs
function defineMixin(vuei18n, composer, i18n) {
return {
beforeCreate() {
const instance = getCurrentInstance();
/* istanbul ignore if */
if (!instance) {
throw createI18nError(22 /* UNEXPECTED_ERROR */);
}
const options = this.$options;
if (options.i18n) {
const optionsI18n = options.i18n;
if (options.__i18n) {
optionsI18n.__i18n = options.__i18n;
}
optionsI18n.__root = composer;
if (this === this.$root) {
this.$i18n = mergeToRoot(vuei18n, optionsI18n);
}
else {
this.$i18n = createVueI18n(optionsI18n);
}
}
else if (options.__i18n) {
if (this === this.$root) {
this.$i18n = mergeToRoot(vuei18n, options);
}
else {
this.$i18n = createVueI18n({
__i18n: options.__i18n,
__root: composer
});
}
}
else {
// set global
this.$i18n = vuei18n;
}
vuei18n.__onComponentInstanceCreated(this.$i18n);
i18n.__setInstance(instance, this.$i18n);
// defines vue-i18n legacy APIs
this.$t = (...args) => this.$i18n.t(...args);
this.$tc = (...args) => this.$i18n.tc(...args);
this.$te = (key, locale) => this.$i18n.te(key, locale);
this.$d = (...args) => this.$i18n.d(...args);
this.$n = (...args) => this.$i18n.n(...args);
this.$tm = (key) => this.$i18n.tm(key);
},
mounted() {
/* istanbul ignore if */
if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) && !false) {
this.$el.__INTLIFY__ = this.$i18n.__composer;
const emitter = (this.__emitter = createEmitter());
const _vueI18n = this.$i18n;
_vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
emitter.on('*', addTimelineEvent);
}
},
beforeUnmount() {
const instance = getCurrentInstance();
/* istanbul ignore if */
if (!instance) {
throw createI18nError(22 /* UNEXPECTED_ERROR */);
}
/* istanbul ignore if */
if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) && !false) {
if (this.__emitter) {
this.__emitter.off('*', addTimelineEvent);
delete this.__emitter;
}
const _vueI18n = this.$i18n;
_vueI18n.__disableEmitter && _vueI18n.__disableEmitter();
delete this.$el.__INTLIFY__;
}
delete this.$t;
delete this.$tc;
delete this.$te;
delete this.$d;
delete this.$n;
delete this.$tm;
i18n.__deleteInstance(instance);
delete this.$i18n;
}
};
}
function mergeToRoot(root, options) {
root.locale = options.locale || root.locale;
root.fallbackLocale = options.fallbackLocale || root.fallbackLocale;
root.missing = options.missing || root.missing;
root.silentTranslationWarn =
options.silentTranslationWarn || root.silentFallbackWarn;
root.silentFallbackWarn =
options.silentFallbackWarn || root.silentFallbackWarn;
root.formatFallbackMessages =
options.formatFallbackMessages || root.formatFallbackMessages;
root.postTranslation = options.postTranslation || root.postTranslation;
root.warnHtmlInMessage = options.warnHtmlInMessage || root.warnHtmlInMessage;
root.escapeParameterHtml =
options.escapeParameterHtml || root.escapeParameterHtml;
root.sync = options.sync || root.sync;
root.__composer[SetPluralRulesSymbol](options.pluralizationRules || root.pluralizationRules);
const messages = getLocaleMessages(root.locale, {
messages: options.messages,
__i18n: options.__i18n
});
Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale]));
if (options.datetimeFormats) {
Object.keys(options.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, options.datetimeFormats[locale]));
}
if (options.numberFormats) {
Object.keys(options.numberFormats).forEach(locale => root.mergeNumberFormat(locale, options.numberFormats[locale]));
}
return root;
}
/**
* Vue I18n factory
*
* @param options - An options, see the {@link I18nOptions}
*
* @returns {@link I18n} instance
*
* @remarks
* If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option.
*
* If you use composition API mode, you need to specify {@link ComposerOptions}.
*
* @VueI18nSee [Getting Started](../../guide/)
* @VueI18nSee [Composition API](../../guide/advanced/composition)
*
* @example
* case: for Legacy API
* ```js
* import { createApp } from 'vue'
* import { createI18n } from 'vue-i18n'
*
* // call with I18n option
* const i18n = createI18n({
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
*
* const App = {
* // ...
* }
*
* const app = createApp(App)
*
* // install!
* app.use(i18n)
* app.mount('#app')
* ```
*
* @example
* case: for composition API
* ```js
* import { createApp } from 'vue'
* import { createI18n, useI18n } from 'vue-i18n'
*
* // call with I18n option
* const i18n = createI18n({
* legacy: false, // you must specify 'legacy: false' option
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
*
* const App = {
* setup() {
* // ...
* const { t } = useI18n({ ... })
* return { ... , t }
* }
* }
*
* const app = createApp(App)
*
* // install!
* app.use(i18n)
* app.mount('#app')
* ```
*
* @VueI18nGeneral
*/
function createI18n(options = {}) {
// prettier-ignore
const __legacyMode = __VUE_I18N_LEGACY_API__ && isBoolean(options.legacy)
? options.legacy
: __VUE_I18N_LEGACY_API__;
const __globalInjection = !!options.globalInjection;
const __instances = new Map();
// prettier-ignore
const __global = __VUE_I18N_LEGACY_API__ && __legacyMode
? createVueI18n(options)
: createComposer(options);
const symbol = makeSymbol((process.env.NODE_ENV !== 'production') ? 'vue-i18n' : '');
const i18n = {
// mode
get mode() {
// prettier-ignore
return __VUE_I18N_LEGACY_API__
? __legacyMode
? 'legacy'
: 'composition'
: 'composition';
},
// install plugin
async install(app, ...options) {
if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) && !false) {
app.__VUE_I18N__ = i18n;
}
// setup global provider
app.__VUE_I18N_SYMBOL__ = symbol;
app.provide(app.__VUE_I18N_SYMBOL__, i18n);
// global method and properties injection for Composition API
if (!__legacyMode && __globalInjection) {
injectGlobalFields(app, i18n.global);
}
// install built-in components and directive
if (__VUE_I18N_FULL_INSTALL__) {
apply(app, i18n, ...options);
}
// setup mixin for Legacy API
if (__VUE_I18N_LEGACY_API__ && __legacyMode) {
app.mixin(defineMixin(__global, __global.__composer, i18n));
}
// setup vue-devtools plugin
if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) && !false) {
const ret = await enableDevTools(app, i18n);
if (!ret) {
throw createI18nError(21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */);
}
const emitter = createEmitter();
if (__legacyMode) {
const _vueI18n = __global;
_vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
}
else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = __global;
_composer[EnableEmitter] && _composer[EnableEmitter](emitter);
}
emitter.on('*', addTimelineEvent);
}
},
// global accessor
get global() {
return __global;
},
// @internal
__instances,
// @internal
__getInstance(component) {
return __instances.get(component) || null;
},
// @internal
__setInstance(component, instance) {
__instances.set(component, instance);
},
// @internal
__deleteInstance(component) {
__instances.delete(component);
}
};
return i18n;
}
/**
* Use Composition API for Vue I18n
*
* @param options - An options, see {@link UseI18nOptions}
*
* @returns {@link Composer} instance
*
* @remarks
* This function is mainly used by `setup`.
*
* If options are specified, Composer instance is created for each component and you can be localized on the component.
*
* If options are not specified, you can be localized using the global Composer.
*
* @example
* case: Component resource base localization
* ```html
* <template>
* <form>
* <label>{{ t('language') }}</label>
* <select v-model="locale">
* <option value="en">en</option>
* <option value="ja">ja</option>
* </select>
* </form>
* <p>message: {{ t('hello') }}</p>
* </template>
*
* <script>
* import { useI18n } from 'vue-i18n'
*
* export default {
* setup() {
* const { t, locale } = useI18n({
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
* // Something to do ...
*
* return { ..., t, locale }
* }
* }
* </script>
* ```
*
* @VueI18nComposition
*/
function useI18n(options = {}) {
const instance = getCurrentInstance();
if (instance == null) {
throw createI18nError(16 /* MUST_BE_CALL_SETUP_TOP */);
}
if (!instance.appContext.app.__VUE_I18N_SYMBOL__) {
throw createI18nError(17 /* NOT_INSLALLED */);
}
const i18n = inject(instance.appContext.app.__VUE_I18N_SYMBOL__);
/* istanbul ignore if */
if (!i18n) {
throw createI18nError(22 /* UNEXPECTED_ERROR */);
}
// prettier-ignore
const global = i18n.mode === 'composition'
? i18n.global
: i18n.global.__composer;
// prettier-ignore
const scope = isEmptyObject(options)
? ('__i18n' in instance.type)
? 'local'
: 'global'
: !options.useScope
? 'local'
: options.useScope;
if (scope === 'global') {
let messages = isObject(options.messages) ? options.messages : {};
if ('__i18nGlobal' in instance.type) {
messages = getLocaleMessages(global.locale.value, {
messages,
__i18n: instance.type.__i18nGlobal
});
}
// merge locale messages
const locales = Object.keys(messages);
if (locales.length) {
locales.forEach(locale => {
global.mergeLocaleMessage(locale, messages[locale]);
});
}
// merge datetime formats
if (isObject(options.datetimeFormats)) {
const locales = Object.keys(options.datetimeFormats);
if (locales.length) {
locales.forEach(locale => {
global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);
});
}
}
// merge number formats
if (isObject(options.numberFormats)) {
const locales = Object.keys(options.numberFormats);
if (locales.length) {
locales.forEach(locale => {
global.mergeNumberFormat(locale, options.numberFormats[locale]);
});
}
}
return global;
}
if (scope === 'parent') {
let composer = getComposer$1(i18n, instance);
if (composer == null) {
if ((process.env.NODE_ENV !== 'production')) {
warn(getWarnMessage(12 /* NOT_FOUND_PARENT_SCOPE */));
}
composer = global;
}
return composer;
}
// scope 'local' case
if (i18n.mode === 'legacy') {
throw createI18nError(18 /* NOT_AVAILABLE_IN_LEGACY_MODE */);
}
const i18nInternal = i18n;
let composer = i18nInternal.__getInstance(instance);
if (composer == null) {
const type = instance.type;
const composerOptions = {
...options
};
if (type.__i18n) {
composerOptions.__i18n = type.__i18n;
}
if (global) {
composerOptions.__root = global;
}
composer = createComposer(composerOptions);
setupLifeCycle(i18nInternal, instance, composer);
i18nInternal.__setInstance(instance, composer);
}
return composer;
}
function getComposer$1(i18n, target) {
let composer = null;
const root = target.root;
let current = target.parent;
while (current != null) {
const i18nInternal = i18n;
if (i18n.mode === 'composition') {
composer = i18nInternal.__getInstance(current);
}
else {
const vueI18n = i18nInternal.__getInstance(current);
if (vueI18n != null) {
composer = vueI18n
.__composer;
}
}
if (composer != null) {
break;
}
if (root === current) {
break;
}
current = current.parent;
}
return composer;
}
function setupLifeCycle(i18n, target, composer) {
let emitter = null;
onMounted(() => {
// inject composer instance to DOM for intlify-devtools
if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) &&
!false &&
target.vnode.el) {
target.vnode.el.__INTLIFY__ = composer;
emitter = createEmitter();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = composer;
_composer[EnableEmitter] && _composer[EnableEmitter](emitter);
emitter.on('*', addTimelineEvent);
}
}, target);
onUnmounted(() => {
// remove composer instance from DOM for intlify-devtools
if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) &&
!false &&
target.vnode.el &&
target.vnode.el.__INTLIFY__) {
emitter && emitter.off('*', addTimelineEvent);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = composer;
_composer[DisableEmitter] && _composer[DisableEmitter]();
delete target.vnode.el.__INTLIFY__;
}
i18n.__deleteInstance(target);
}, target);
}
const globalExportProps = [
'locale',
'fallbackLocale',
'availableLocales'
];
const globalExportMethods = ['t', 'd', 'n', 'tm'];
function injectGlobalFields(app, composer) {
const i18n = Object.create(null);
globalExportProps.forEach(prop => {
const desc = Object.getOwnPropertyDescriptor(composer, prop);
if (!desc) {
throw createI18nError(22 /* UNEXPECTED_ERROR */);
}
const wrap = isRef(desc.value) // check computed props
? {
get() {
return desc.value.value;
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
set(val) {
desc.value.value = val;
}
}
: {
get() {
return desc.get && desc.get();
}
};
Object.defineProperty(i18n, prop, wrap);
});
app.config.globalProperties.$i18n = i18n;
globalExportMethods.forEach(method => {
const desc = Object.getOwnPropertyDescriptor(composer, method);
if (!desc) {
throw createI18nError(22 /* UNEXPECTED_ERROR */);
}
Object.defineProperty(app.config.globalProperties, `$${method}`, desc);
});
}
{
initFeatureFlags();
}
(process.env.NODE_ENV !== 'production') && initDev();
export { DatetimeFormat, NumberFormat, Translation, VERSION, createI18n, useI18n, vTDirective };<|fim▁end|>
|
}
if (isString(props.format)) {
options.key = props.format;
|
<|file_name|>config-user.js<|end_file_name|><|fim▁begin|>ig.module(
'plusplus.config-user'
)
.defines(function() {
/**
* User configuration of Impact++.
* <span class="alert alert-info"><strong>Tip:</strong> it is recommended to modify this configuration file!</span>
* @example
* // in order to add your own custom configuration to Impact++
* // edit the file defining ig.CONFIG_USER, 'plusplus/config-user.js'
* // ig.CONFIG_USER is never modified by Impact++ (it is strictly for your use)
* // ig.CONFIG_USER is automatically merged over Impact++'s config
* @static
* @readonly
* @memberof ig
* @namespace ig.CONFIG_USER
* @author Collin Hover - collinhover.com
**/
ig.CONFIG_USER = {
// no need to do force entity extended checks, we won't mess it up
// because we know to have our entities extend ig.EntityExtended
FORCE_ENTITY_EXTENDED: false,
// auto sort
AUTO_SORT_LAYERS: true,
// fullscreen!
GAME_WIDTH_PCT: 1,
GAME_HEIGHT_PCT: 1,
// dynamic scaling based on dimensions in view (resolution independence)
GAME_WIDTH_VIEW: 352,
GAME_HEIGHT_VIEW: 208,
// clamped scaling is still dynamic, but within a range
// so we can't get too big or too small
SCALE_MIN: 1,
SCALE_MAX: 4,
// camera flexibility and smoothness
CAMERA: {
// keep the camera within the level
// (whenever possible)
//KEEP_INSIDE_LEVEL: true,
KEEP_CENTERED: false,
LERP: 0.025,
// trap helps with motion sickness
BOUNDS_TRAP_AS_PCT: true,
BOUNDS_TRAP_PCT_MINX: -0.2,
BOUNDS_TRAP_PCT_MINY: -0.3,
BOUNDS_TRAP_PCT_MAXX: 0.2,
BOUNDS_TRAP_PCT_MAXY: 0.3
},
// font and text settings
FONT: {
MAIN_NAME: "font_helloplusplus_white_16.png",
ALT_NAME: "font_helloplusplus_white_8.png",
CHAT_NAME: "font_helloplusplus_black_8.png",
// we can have the font be scaled relative to system
SCALE_OF_SYSTEM_SCALE: 0.5,
// and force a min / max
SCALE_MIN: 1,
SCALE_MAX: 2
},
// text bubble settings
TEXT_BUBBLE: {
// match the visual style
PIXEL_PERFECT: true
},
UI: {<|fim▁hole|> // sometimes, we want to keep things at a static scale
// for example, UI is a possible target
SCALE: 3,
IGNORE_SYSTEM_SCALE: true
},
/*
// to try dynamic clamped UI scaling
// uncomment below and delete the UI settings above
UI: {
SCALE_MIN: 2,
SCALE_MAX: 4
}
*/
// UI should persist across all levels
UI_LAYER_CLEAR_ON_LOAD: false,
CHARACTER: {
// add some depth using offset
SIZE_OFFSET_X: 8,
SIZE_OFFSET_Y: 4
}
};
});<|fim▁end|>
| |
<|file_name|>0005_course_image.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('studygroups', '0004_studygroupsignup_mobile'),
]
operations = [
migrations.AddField(
model_name='course',
name='image',
field=models.CharField(default=' ', max_length=32),
preserve_default=False,
),<|fim▁hole|><|fim▁end|>
|
]
|
<|file_name|>Forage.ts<|end_file_name|><|fim▁begin|>//convert
/*(ghost.core.Hardware.*/
import {Hardware} from "ghost/core/Hardware";
///<module="ghost/core"/>
//TODO:add mozilla API and converts with Promises
export class FakeLocalStorage
{
public _storage : any;
/**
* Constructor
*/
constructor()
{
// super();
}
public instance():any
{
return this;
}
public getItem(key:string):Promise<any>
{
var promise:Promise<any> = new Promise<any>((resolve:any, reject:any):void=>
{
resolve( null );
});
return promise;
}
public setItem(key:string, value:string):Promise<any>
{
var promise:Promise<any> = new Promise<any>((resolve:any, reject:any):void=>
{
resolve( null );
});
return promise;
}
public key(key:string):Promise<any>
{
var promise:Promise<any> = new Promise<any>((resolve:any, reject:any):void=>
{
resolve( null );
});
return promise;
}
public removeItem(key:string):Promise<any>
{
var promise:Promise<any> = new Promise<any>((resolve:any, reject:any):void=>
{
resolve( null );
});
return promise;
}
public clear():Promise<any>
{
var promise:Promise<any> = new Promise<any>((resolve:any, reject:any):void=>
{
resolve( null );
});
return promise;
}
public keys():Promise<any>
{
var promise:Promise<any> = new Promise<any>((resolve:any, reject:any):void=>
{
resolve( [] );
});
return promise;
}
public iterate( func : any ):Promise<any>
{
var promise:Promise<any> = new Promise<any>((resolve:any, reject:any):void=>
{
resolve( undefined );
});
return promise;
}
}
//convert-import
import {Root} from "ghost/core/Root";
export interface ILocalForageOptions
{
debug?:boolean;
}
var _log:any = function(){};
export class LocalForage
{
protected static _instance: LocalForage;
private _storage:any;
private _name:string;
private _warehouses:any;
private _data:any;
private _keys:string[];
private _sync:any;
private _allSync:boolean;
public static clearAllDebug(): void {
//WARNING only used this on chrome for test
console.warn("WARNING only used this on chrome for test");
try {
if (window.indexedDB && window.indexedDB["webkitGetDatabaseNames"]) {
window.indexedDB["webkitGetDatabaseNames"]().onsuccess = function(sender, args) {
if (!sender || !sender.target || !sender.target.result || !sender.target.result.length) {
return;
}
var len: number = sender.target.result.length;
for (var i = 0; i < len; i++) {
console.log("delete: " + sender.target.result[i]);
window.indexedDB.deleteDatabase(sender.target.result[i]);
}
};
console.log("all database deleted");
}
}catch(error)
{
console.error(error);
}
}
public static config(options:ILocalForageOptions):void
{
if(options.debug === true)
{
_log = LocalForage.consolelog;
}
}
private static consolelog(...args:any[]):void{
console.log(args);
}
public static instance(): LocalForage {
if (!LocalForage._instance) {
LocalForage._instance = new LocalForage({ debug: false });
}
return LocalForage._instance;
}
/**
* Constructor
*/
constructor(config?:any);
constructor(name:string, config?:any);
constructor(name:any = "default", config?:any)
{
if(typeof name != "string")
{
config = name;
name = "default";
}
if(config)
{
LocalForage.config(config);
if(config.name)
{
name = config.name;
}
}
this._name = name;
this._warehouses = {};
if (Hardware.getOS() === 'iOS')
this._storage = new FakeLocalStorage();
else
this._storage = Root.getRoot().localforage.createInstance({name:name});
this._data = {};
this._sync = {};
if (false === Hardware.hasCookieEnable())
{
this._allSync = true;
this._keys = [];
}
else
this._allSync = false;
}
/**
* Gets forage's name
* @return {string} Forage's name
*/
public name():string
{
return this._name;
}
/**
* Gets Item by key
* @param key string key
* @returns {*} Value linked to the key
*/
public getItem(key:string):Promise<any>
{
var promise:Promise<any> = new Promise<any>((resolve:any, reject:any):void=>
{
//no value
if(!this._allSync && !this._sync[key])
{
_log("get item from db:"+key);
this._storage.getItem(key).then((value:any):void=>
{
this.sync(key, value);
resolve(value);
}, reject);
return;
}
_log("has item from cache:"+key);
//value already saved
resolve(this._data[key]);
});
return promise;
}
private sync(key:string, value:any, updateKeys:boolean = true):void
{
_log("sync: "+key+"=", value);
this._data[key] = value;
this._sync[key] = true;
if(this._keys && updateKeys)
{
_log("update keys frmobom "+key);
var index:number = this._keys.indexOf(key);
if(value!=null && index == -1)
{
_log("add key: "+key);
this._keys.push(key);
}else
if(value == null && index !=-1)
{
this._keys.splice(index, 1);
_log("remove key: "+key);
}
}
}
/**
* Gets key at the index id
* @param id
* @returns {string} key
*/
public key(id:string):Promise<string>
{
if(this._allSync)
{
return this._keys[id];
}
else
{
return <any>this._storage.key(id);
}
//TODO: mark as sync key from id
}
public iterate(func:Function):Promise<any[]>
{
return new Promise<any[]>((resolve:any, reject:any):void=>
{
if(this._allSync)
{
_log("iterate from cache");
this._keys.every(function(key, index):boolean
{
var result:any = func(this._data[key], key, index+1);
return result === undefined;
}, this);
resolve();
return;
}
_log("iterate from db");
var keys:string[] = [];
this._storage.iterate((value, key, iterationNumber):any=>{
var result:any = func(value, key, iterationNumber);
this.sync(key, value, false);
keys.push(key);
return result;
}).then((data:any)=>
{
if(data === undefined)
{
this._allSync = true;
this._keys = keys;
_log("all iterate done - no db anymore");
}else
{
_log("iterate broken - still db");
var index:number;
for(var p in keys)
{
index = this._keys.indexOf(keys[p]);
if(index == -1)
{
this._keys.push(keys[p]);
}
}
}
resolve(data);
}, reject);
});
}
/**
* Get Keys
* @returns {Promise<string[]>|string[]|any|*}
*/
public keys():Promise<string[]>
{
return new Promise<string[]>((resolve:any, reject:any):void=>
{
if(this._keys)
{
_log("keys from cache");
resolve(this._keys);
return;
}
_log("keys from db");
this._storage.keys().then((keys:string[]):void=>
{
this._keys = keys;
resolve(keys);
}, reject);
});
}
/**
* Sets an item by key
* @param key key of the item
* @param value new item value
* @returns {void}<|fim▁hole|> {
this.sync(key, value);
return this._storage.setItem(key, value);
}
/**
* Removes an item by key
* @param key key of the item
* @returns {void}
*/
public removeItem(key:string):Promise<any>
{
this.sync(key, null);
return this._storage.removeItem(key);
}
/**
* Clear local storage
* @returns {void}
*/
public clear():Promise<any>
{
this._data = {};
this._sync = {};
this._keys = [];
this._allSync = true;
return <any>this._storage.clear();
}
//not in the W3C standard
/**
* Checks if an item exists with the key given
* @param key item's key
* @returns {boolean}
*/
public hasItem(key:string):Promise<boolean>
{
var promise:Promise<boolean> = new Promise<boolean>((resolve:any, reject:any):void=>
{
if(!this._allSync && !this._sync[key])
{
_log("has item from db:"+key);
//sync is done on getItem
this.getItem(key).then(function(data:any)
{
resolve(data!=null);
}, reject);
return;
}
_log("has item from cache:"+key);
resolve(this._data[key] != null);
});
return promise;
}
public warehouse(name:string):LocalForage
{
return this.war(name);
}
public war(name:string):LocalForage
{
if(!this._warehouses[name])
{
this._warehouses[name] = new LocalForage(this._name+"/"+name);
}
return this._warehouses[name];
}
}
var f = null;
// export var forage:ghost.data.Foragehouse = new ghost.data.Foragehouse("root");
if(Hardware.isBrowser())
{
f = new LocalForage({debug:false});
}
export var forage:LocalForage = f;<|fim▁end|>
|
*/
public setItem(key:string, value:any):Promise<any>
|
<|file_name|>TaxonomyRouter_spec.js<|end_file_name|><|fim▁begin|>const should = require('should'),
sinon = require('sinon'),
_ = require('lodash'),
settingsCache = require('../../../../server/services/settings/cache'),
common = require('../../../../server/lib/common'),
controllers = require('../../../../server/services/routing/controllers'),
TaxonomyRouter = require('../../../../server/services/routing/TaxonomyRouter'),
RESOURCE_CONFIG = require('../../../../server/services/routing/assets/resource-config'),
sandbox = sinon.sandbox.create();
describe('UNIT - services/routing/TaxonomyRouter', function () {
let req, res, next;
beforeEach(function () {
sandbox.stub(settingsCache, 'get').withArgs('permalinks').returns('/:slug/');
sandbox.stub(common.events, 'emit');
sandbox.stub(common.events, 'on');
sandbox.spy(TaxonomyRouter.prototype, 'mountRoute');
sandbox.spy(TaxonomyRouter.prototype, 'mountRouter');
req = sandbox.stub();
res = sandbox.stub();
next = sandbox.stub();
res.locals = {};
});
afterEach(function () {
sandbox.restore();
});
it('instantiate', function () {
const taxonomyRouter = new TaxonomyRouter('tag', '/tag/:slug/');
should.exist(taxonomyRouter.router);
should.exist(taxonomyRouter.rssRouter);
taxonomyRouter.taxonomyKey.should.eql('tag');
taxonomyRouter.getPermalinks().getValue().should.eql('/tag/:slug/');
common.events.emit.calledOnce.should.be.true();
common.events.emit.calledWith('router.created', taxonomyRouter).should.be.true();
taxonomyRouter.mountRouter.callCount.should.eql(1);
taxonomyRouter.mountRouter.args[0][0].should.eql('/tag/:slug/');
taxonomyRouter.mountRouter.args[0][1].should.eql(taxonomyRouter.rssRouter.router());
taxonomyRouter.mountRoute.callCount.should.eql(3);
// permalink route
taxonomyRouter.mountRoute.args[0][0].should.eql('/tag/:slug/');
taxonomyRouter.mountRoute.args[0][1].should.eql(controllers.channel);
// pagination feature
taxonomyRouter.mountRoute.args[1][0].should.eql('/tag/:slug/page/:page(\\d+)');
taxonomyRouter.mountRoute.args[1][1].should.eql(controllers.channel);
<|fim▁hole|>
it('fn: _prepareContext', function () {
const taxonomyRouter = new TaxonomyRouter('tag', '/tag/:slug/');
taxonomyRouter._prepareContext(req, res, next);
next.calledOnce.should.eql(true);
res.locals.routerOptions.should.eql({
name: 'tag',
permalinks: '/tag/:slug/',
type: RESOURCE_CONFIG.QUERY.tag.resource,
data: {tag: _.omit(RESOURCE_CONFIG.QUERY.tag, 'alias')},
filter: RESOURCE_CONFIG.TAXONOMIES.tag.filter,
context: ['tag'],
slugTemplate: true,
identifier: taxonomyRouter.identifier
});
res._route.type.should.eql('channel');
});
});<|fim▁end|>
|
// edit feature
taxonomyRouter.mountRoute.args[2][0].should.eql('/tag/:slug/edit');
taxonomyRouter.mountRoute.args[2][1].should.eql(taxonomyRouter._redirectEditOption.bind(taxonomyRouter));
});
|
<|file_name|>xsky_path45.py<|end_file_name|><|fim▁begin|>import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():
return dict(initial_formation="template5", checking_point=8, path_list=[
[TestAction.create_vm, 'vm1', ],
[TestAction.create_volume, 'volume1', 'flag=scsi'],
[TestAction.attach_volume, 'vm1', 'volume1'],
[TestAction.create_volume, 'volume2', 'flag=scsi'],
[TestAction.attach_volume, 'vm1', 'volume2'],
[TestAction.create_volume, 'volume3', 'flag=scsi'],
[TestAction.attach_volume, 'vm1', 'volume3'],
[TestAction.create_vm_snapshot, 'vm1', 'vm1-snapshot1'],
[TestAction.reboot_vm, 'vm1'],
[TestAction.detach_volume, 'volume3'],
[TestAction.create_vm_snapshot, 'vm1', 'vm1-snapshot5'],
[TestAction.create_vm_backup, 'vm1', 'vm1-backup1'],
[TestAction.create_vm_snapshot, 'vm1', 'vm1-snapshot8'],
[TestAction.stop_vm, 'vm1'],
[TestAction.change_vm_image, 'vm1'],
[TestAction.attach_volume, 'vm1', 'volume3'],
[TestAction.clone_vm, 'vm1', 'vm2'],
[TestAction.delete_vm_snapshot, 'vm1-snapshot1'],
])
'''
The final status:
Running:['vm2']
Stopped:['vm1']
Enadbled:['vm1-snapshot5', 'volume1-snapshot5', 'volume2-snapshot5', 'vm1-snapshot8', 'volume1-snapshot8', 'volume2-snapshot8', 'vm1-backup1', 'volume1-backup1', 'volume2-backup1']
attached:['volume1', 'volume2', 'volume3']
Detached:[]
Deleted:['vm1-snapshot1', 'volume1-snapshot1', 'volume2-snapshot1', 'volume3-snapshot1']
Expunged:[]
Ha:[]<|fim▁hole|>Group:
vm_snap2:['vm1-snapshot5', 'volume1-snapshot5', 'volume2-snapshot5']---vm1volume1_volume2
vm_snap3:['vm1-snapshot8', 'volume1-snapshot8', 'volume2-snapshot8']---vm1volume1_volume2
vm_backup1:['vm1-backup1', 'volume1-backup1', 'volume2-backup1']---vm1_volume1_volume2
'''<|fim▁end|>
| |
<|file_name|>mode.rs<|end_file_name|><|fim▁begin|>// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! Mode type
pub use std::time::Duration;
use client::Mode as ClientMode;
/// IPC-capable shadow-type for `client::config::Mode`
#[derive(Clone, Debug)]
#[cfg_attr(feature = "ipc", binary)]
pub enum Mode {
/// Same as `ClientMode::Off`.
Off,
/// Same as `ClientMode::Dark`; values in seconds.
Dark(u64),
/// Same as `ClientMode::Passive`; values in seconds.
Passive(u64, u64),
/// Same as `ClientMode::Active`.
Active,
}
impl From<ClientMode> for Mode {
fn from(mode: ClientMode) -> Self {
match mode {
ClientMode::Off => Mode::Off,
ClientMode::Dark(timeout) => Mode::Dark(timeout.as_secs()),<|fim▁hole|> ClientMode::Passive(timeout, alarm) => Mode::Passive(timeout.as_secs(), alarm.as_secs()),
ClientMode::Active => Mode::Active,
}
}
}
impl From<Mode> for ClientMode {
fn from(mode: Mode) -> Self {
match mode {
Mode::Off => ClientMode::Off,
Mode::Dark(timeout) => ClientMode::Dark(Duration::from_secs(timeout)),
Mode::Passive(timeout, alarm) => ClientMode::Passive(Duration::from_secs(timeout), Duration::from_secs(alarm)),
Mode::Active => ClientMode::Active,
}
}
}<|fim▁end|>
| |
<|file_name|>Interaction.js<|end_file_name|><|fim▁begin|>/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
/**
* @interface Highcharts.PointEventsOptionsObject
*/ /**
* Fires when the point is selected either programmatically or following a click
* on the point. One parameter, `event`, is passed to the function. Returning
* `false` cancels the operation.
* @name Highcharts.PointEventsOptionsObject#select
* @type {Highcharts.PointSelectCallbackFunction|undefined}
*/ /**
* Fires when the point is unselected either programmatically or following a
* click on the point. One parameter, `event`, is passed to the function.
* Returning `false` cancels the operation.
* @name Highcharts.PointEventsOptionsObject#unselect
* @type {Highcharts.PointUnselectCallbackFunction|undefined}
*/
/**
* Information about the select/unselect event.
*
* @interface Highcharts.PointInteractionEventObject
* @extends global.Event
*/ /**
* @name Highcharts.PointInteractionEventObject#accumulate
* @type {boolean}
*/
/**
* Gets fired when the point is selected either programmatically or following a
* click on the point.
*
* @callback Highcharts.PointSelectCallbackFunction
*
* @param {Highcharts.Point} this
* Point where the event occured.
*
* @param {Highcharts.PointInteractionEventObject} event
* Event that occured.
*/
/**
* Fires when the point is unselected either programmatically or following a
* click on the point.
*
* @callback Highcharts.PointUnselectCallbackFunction
*
* @param {Highcharts.Point} this
* Point where the event occured.
*
* @param {Highcharts.PointInteractionEventObject} event
* Event that occured.
*/
import Legend from './Legend.js';
import Point from './Point.js';
import U from './Utilities.js';
var addEvent = U.addEvent, createElement = U.createElement, css = U.css, defined = U.defined, extend = U.extend, fireEvent = U.fireEvent, isArray = U.isArray, isFunction = U.isFunction, isObject = U.isObject, merge = U.merge, objectEach = U.objectEach, pick = U.pick;
import './Chart.js';
import './Options.js';
import './Series.js';
var Chart = H.Chart, defaultOptions = H.defaultOptions, defaultPlotOptions = H.defaultPlotOptions, hasTouch = H.hasTouch, Series = H.Series, seriesTypes = H.seriesTypes, svg = H.svg, TrackerMixin;
/* eslint-disable valid-jsdoc */
/**
* TrackerMixin for points and graphs.
*
* @private
* @mixin Highcharts.TrackerMixin
*/
TrackerMixin = H.TrackerMixin = {
/**
* Draw the tracker for a point.
*
* @private
* @function Highcharts.TrackerMixin.drawTrackerPoint
* @param {Highcharts.Series} this
* @fires Highcharts.Series#event:afterDrawTracker
*/
drawTrackerPoint: function () {
var series = this, chart = series.chart, pointer = chart.pointer, onMouseOver = function (e) {
var point = pointer.getPointFromEvent(e);
// undefined on graph in scatterchart
if (typeof point !== 'undefined') {
pointer.isDirectTouch = true;
point.onMouseOver(e);
}
}, dataLabels;
// Add reference to the point
series.points.forEach(function (point) {
dataLabels = (isArray(point.dataLabels) ?
point.dataLabels :
(point.dataLabel ? [point.dataLabel] : []));
if (point.graphic) {
point.graphic.element.point = point;
}
dataLabels.forEach(function (dataLabel) {
if (dataLabel.div) {
dataLabel.div.point = point;
}
else {
dataLabel.element.point = point;
}
});
});
// Add the event listeners, we need to do this only once
if (!series._hasTracking) {
series.trackerGroups.forEach(function (key) {
if (series[key]) {
// we don't always have dataLabelsGroup
series[key]
.addClass('highcharts-tracker')
.on('mouseover', onMouseOver)
.on('mouseout', function (e) {
pointer.onTrackerMouseOut(e);
});
if (hasTouch) {
series[key].on('touchstart', onMouseOver);
}
if (!chart.styledMode && series.options.cursor) {
series[key]
.css(css)
.css({ cursor: series.options.cursor });
}
}
});
series._hasTracking = true;
}
fireEvent(this, 'afterDrawTracker');
},
/**
* Draw the tracker object that sits above all data labels and markers to
* track mouse events on the graph or points. For the line type charts
* the tracker uses the same graphPath, but with a greater stroke width
* for better control.
*
* @private
* @function Highcharts.TrackerMixin.drawTrackerGraph
* @param {Highcharts.Series} this
* @fires Highcharts.Series#event:afterDrawTracker
*/
drawTrackerGraph: function () {
var series = this, options = series.options, trackByArea = options.trackByArea, trackerPath = [].concat(trackByArea ?
series.areaPath :
series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, pointer = chart.pointer, renderer = chart.renderer, snap = chart.options.tooltip.snap, tracker = series.tracker, i, onMouseOver = function (e) {
pointer.normalize(e);
if (chart.hoverSeries !== series &&
!pointer.isStickyTooltip(e)) {
series.onMouseOver();
}
},
/*
* Empirical lowest possible opacities for TRACKER_FILL for an
* element to stay invisible but clickable
* IE6: 0.002
* IE7: 0.002
* IE8: 0.002
* IE9: 0.00000000001 (unlimited)
* IE10: 0.0001 (exporting only)
* FF: 0.00000000001 (unlimited)
* Chrome: 0.000001
* Safari: 0.000001
* Opera: 0.00000000001 (unlimited)
*/
TRACKER_FILL = 'rgba(192,192,192,' + (svg ? 0.0001 : 0.002) + ')';
// Extend end points. A better way would be to use round linecaps,
// but those are not clickable in VML.
if (trackerPathLength && !trackByArea) {
i = trackerPathLength + 1;
while (i--) {
if (trackerPath[i] === 'M') {
// extend left side
trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], 'L');
}
if ((i && trackerPath[i] === 'M') ||
i === trackerPathLength) {
// extend right side
trackerPath.splice(i, 0, 'L', trackerPath[i - 2] + snap, trackerPath[i - 1]);
}
}
}
// draw the tracker
if (tracker) {
tracker.attr({ d: trackerPath });
}
else if (series.graph) { // create
series.tracker = renderer.path(trackerPath)
.attr({
visibility: series.visible ? 'visible' : 'hidden',
zIndex: 2
})
.addClass(trackByArea ?
'highcharts-tracker-area' :
'highcharts-tracker-line')
.add(series.group);
if (!chart.styledMode) {
series.tracker.attr({
'stroke-linejoin': 'round',
stroke: TRACKER_FILL,
fill: trackByArea ? TRACKER_FILL : 'none',
'stroke-width': series.graph.strokeWidth() +
(trackByArea ? 0 : 2 * snap)
});
}
// The tracker is added to the series group, which is clipped, but
// is covered by the marker group. So the marker group also needs to
// capture events.
[series.tracker, series.markerGroup].forEach(function (tracker) {
tracker.addClass('highcharts-tracker')
.on('mouseover', onMouseOver)
.on('mouseout', function (e) {
pointer.onTrackerMouseOut(e);
});
if (options.cursor && !chart.styledMode) {
tracker.css({ cursor: options.cursor });
}
if (hasTouch) {
tracker.on('touchstart', onMouseOver);
}
});
}
fireEvent(this, 'afterDrawTracker');
}
};
/* End TrackerMixin */
// Add tracking event listener to the series group, so the point graphics
// themselves act as trackers
if (seriesTypes.column) {
/**
* @private
* @borrows Highcharts.TrackerMixin.drawTrackerPoint as Highcharts.seriesTypes.column#drawTracker
*/
seriesTypes.column.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
}
if (seriesTypes.pie) {
/**
* @private
* @borrows Highcharts.TrackerMixin.drawTrackerPoint as Highcharts.seriesTypes.pie#drawTracker
*/<|fim▁hole|>}
if (seriesTypes.scatter) {
/**
* @private
* @borrows Highcharts.TrackerMixin.drawTrackerPoint as Highcharts.seriesTypes.scatter#drawTracker
*/
seriesTypes.scatter.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
}
// Extend Legend for item events.
extend(Legend.prototype, {
/**
* @private
* @function Highcharts.Legend#setItemEvents
* @param {Highcharts.BubbleLegend|Highcharts.Point|Highcharts.Series} item
* @param {Highcharts.SVGElement} legendItem
* @param {boolean} [useHTML=false]
* @fires Highcharts.Point#event:legendItemClick
* @fires Highcharts.Series#event:legendItemClick
*/
setItemEvents: function (item, legendItem, useHTML) {
var legend = this, boxWrapper = legend.chart.renderer.boxWrapper, isPoint = item instanceof Point, activeClass = 'highcharts-legend-' +
(isPoint ? 'point' : 'series') + '-active', styledMode = legend.chart.styledMode,
// When `useHTML`, the symbol is rendered in other group, so
// we need to apply events listeners to both places
legendItems = useHTML ?
[legendItem, item.legendSymbol] :
[item.legendGroup];
// Set the events on the item group, or in case of useHTML, the item
// itself (#1249)
legendItems.forEach(function (element) {
if (element) {
element
.on('mouseover', function () {
if (item.visible) {
legend.allItems.forEach(function (inactiveItem) {
if (item !== inactiveItem) {
inactiveItem.setState('inactive', !isPoint);
}
});
}
item.setState('hover');
// A CSS class to dim or hide other than the hovered
// series.
// Works only if hovered series is visible (#10071).
if (item.visible) {
boxWrapper.addClass(activeClass);
}
if (!styledMode) {
legendItem.css(legend.options.itemHoverStyle);
}
})
.on('mouseout', function () {
if (!legend.chart.styledMode) {
legendItem.css(merge(item.visible ?
legend.itemStyle :
legend.itemHiddenStyle));
}
legend.allItems.forEach(function (inactiveItem) {
if (item !== inactiveItem) {
inactiveItem.setState('', !isPoint);
}
});
// A CSS class to dim or hide other than the hovered
// series.
boxWrapper.removeClass(activeClass);
item.setState();
})
.on('click', function (event) {
var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function () {
if (item.setVisible) {
item.setVisible();
}
// Reset inactive state
legend.allItems.forEach(function (inactiveItem) {
if (item !== inactiveItem) {
inactiveItem.setState(item.visible ? 'inactive' : '', !isPoint);
}
});
};
// A CSS class to dim or hide other than the hovered
// series. Event handling in iOS causes the activeClass
// to be added prior to click in some cases (#7418).
boxWrapper.removeClass(activeClass);
// Pass over the click/touch event. #4.
event = {
browserEvent: event
};
// click the name or symbol
if (item.firePointEvent) { // point
item.firePointEvent(strLegendItemClick, event, fnLegendItemClick);
}
else {
fireEvent(item, strLegendItemClick, event, fnLegendItemClick);
}
});
}
});
},
/**
* @private
* @function Highcharts.Legend#createCheckboxForItem
* @param {Highcharts.BubbleLegend|Highcharts.Point|Highcharts.Series} item
* @fires Highcharts.Series#event:checkboxClick
*/
createCheckboxForItem: function (item) {
var legend = this;
item.checkbox = createElement('input', {
type: 'checkbox',
className: 'highcharts-legend-checkbox',
checked: item.selected,
defaultChecked: item.selected // required by IE7
}, legend.options.itemCheckboxStyle, legend.chart.container);
addEvent(item.checkbox, 'click', function (event) {
var target = event.target;
fireEvent(item.series || item, 'checkboxClick', {
checked: target.checked,
item: item
}, function () {
item.select();
});
});
}
});
// Extend the Chart object with interaction
extend(Chart.prototype, /** @lends Chart.prototype */ {
/**
* Display the zoom button, so users can reset zoom to the default view
* settings.
*
* @function Highcharts.Chart#showResetZoom
*
* @fires Highcharts.Chart#event:afterShowResetZoom
* @fires Highcharts.Chart#event:beforeShowResetZoom
*/
showResetZoom: function () {
var chart = this, lang = defaultOptions.lang, btnOptions = chart.options.chart.resetZoomButton, theme = btnOptions.theme, states = theme.states, alignTo = (btnOptions.relativeTo === 'chart' ||
btnOptions.relativeTo === 'spaceBox' ?
null :
'plotBox');
/**
* @private
*/
function zoomOut() {
chart.zoomOut();
}
fireEvent(this, 'beforeShowResetZoom', null, function () {
chart.resetZoomButton = chart.renderer
.button(lang.resetZoom, null, null, zoomOut, theme, states && states.hover)
.attr({
align: btnOptions.position.align,
title: lang.resetZoomTitle
})
.addClass('highcharts-reset-zoom')
.add()
.align(btnOptions.position, false, alignTo);
});
fireEvent(this, 'afterShowResetZoom');
},
/**
* Zoom the chart out after a user has zoomed in. See also
* [Axis.setExtremes](/class-reference/Highcharts.Axis#setExtremes).
*
* @function Highcharts.Chart#zoomOut
*
* @fires Highcharts.Chart#event:selection
*/
zoomOut: function () {
fireEvent(this, 'selection', { resetSelection: true }, this.zoom);
},
/**
* Zoom into a given portion of the chart given by axis coordinates.
*
* @private
* @function Highcharts.Chart#zoom
* @param {Highcharts.SelectEventObject} event
*/
zoom: function (event) {
var chart = this, hasZoomed, pointer = chart.pointer, displayButton = false, mouseDownPos = chart.inverted ? pointer.mouseDownX : pointer.mouseDownY, resetZoomButton;
// If zoom is called with no arguments, reset the axes
if (!event || event.resetSelection) {
chart.axes.forEach(function (axis) {
hasZoomed = axis.zoom();
});
pointer.initiated = false; // #6804
}
else { // else, zoom in on all axes
event.xAxis.concat(event.yAxis).forEach(function (axisData) {
var axis = axisData.axis, axisStartPos = chart.inverted ? axis.left : axis.top, axisEndPos = chart.inverted ?
axisStartPos + axis.width : axisStartPos + axis.height, isXAxis = axis.isXAxis, isWithinPane = false;
// Check if zoomed area is within the pane (#1289).
// In case of multiple panes only one pane should be zoomed.
if ((!isXAxis &&
mouseDownPos >= axisStartPos &&
mouseDownPos <= axisEndPos) ||
isXAxis ||
!defined(mouseDownPos)) {
isWithinPane = true;
}
// don't zoom more than minRange
if (pointer[isXAxis ? 'zoomX' : 'zoomY'] && isWithinPane) {
hasZoomed = axis.zoom(axisData.min, axisData.max);
if (axis.displayBtn) {
displayButton = true;
}
}
});
}
// Show or hide the Reset zoom button
resetZoomButton = chart.resetZoomButton;
if (displayButton && !resetZoomButton) {
chart.showResetZoom();
}
else if (!displayButton && isObject(resetZoomButton)) {
chart.resetZoomButton = resetZoomButton.destroy();
}
// Redraw
if (hasZoomed) {
chart.redraw(pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100));
}
},
/**
* Pan the chart by dragging the mouse across the pane. This function is
* called on mouse move, and the distance to pan is computed from chartX
* compared to the first chartX position in the dragging operation.
*
* @private
* @function Highcharts.Chart#pan
* @param {Highcharts.PointerEventObject} e
* @param {string} panning
*/
pan: function (e, panning) {
var chart = this, hoverPoints = chart.hoverPoints, panningOptions, chartOptions = chart.options.chart, doRedraw, type;
if (typeof panning === 'object') {
panningOptions = panning;
}
else {
panningOptions = {
enabled: panning,
type: 'x'
};
}
if (chartOptions && chartOptions.panning) {
chartOptions.panning = panningOptions;
}
type = panningOptions.type;
fireEvent(this, 'pan', { originalEvent: e }, function () {
// remove active points for shared tooltip
if (hoverPoints) {
hoverPoints.forEach(function (point) {
point.setState();
});
}
// panning axis mapping
var xy = [1]; // x
if (type === 'xy') {
xy = [1, 0];
}
else if (type === 'y') {
xy = [0];
}
xy.forEach(function (isX) {
var axis = chart[isX ? 'xAxis' : 'yAxis'][0], axisOpt = axis.options, horiz = axis.horiz, mousePos = e[horiz ? 'chartX' : 'chartY'], mouseDown = horiz ? 'mouseDownX' : 'mouseDownY', startPos = chart[mouseDown], halfPointRange = (axis.pointRange || 0) / 2, pointRangeDirection = (axis.reversed && !chart.inverted) ||
(!axis.reversed && chart.inverted) ?
-1 :
1, extremes = axis.getExtremes(), panMin = axis.toValue(startPos - mousePos, true) +
halfPointRange * pointRangeDirection, panMax = axis.toValue(startPos + axis.len - mousePos, true) -
halfPointRange * pointRangeDirection, flipped = panMax < panMin, newMin = flipped ? panMax : panMin, newMax = flipped ? panMin : panMax, paddedMin = Math.min(extremes.dataMin, halfPointRange ?
extremes.min :
axis.toValue(axis.toPixels(extremes.min) -
axis.minPixelPadding)), paddedMax = Math.max(extremes.dataMax, halfPointRange ?
extremes.max :
axis.toValue(axis.toPixels(extremes.max) +
axis.minPixelPadding)), spill;
// It is not necessary to calculate extremes on ordinal axis,
// because the are already calculated, so we don't want to
// override them.
if (!axisOpt.ordinal) {
// If the new range spills over, either to the min or max,
// adjust the new range.
if (isX) {
spill = paddedMin - newMin;
if (spill > 0) {
newMax += spill;
newMin = paddedMin;
}
spill = newMax - paddedMax;
if (spill > 0) {
newMax = paddedMax;
newMin -= spill;
}
}
// Set new extremes if they are actually new
if (axis.series.length &&
newMin !== extremes.min &&
newMax !== extremes.max &&
isX ? true : (axis.panningState &&
newMin >= axis.panningState
.startMin &&
newMax <= axis.panningState
.startMax //
)) {
axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' });
doRedraw = true;
}
// set new reference for next run:
chart[mouseDown] = mousePos;
}
});
if (doRedraw) {
chart.redraw(false);
}
css(chart.container, { cursor: 'move' });
});
}
});
// Extend the Point object with interaction
extend(Point.prototype, /** @lends Highcharts.Point.prototype */ {
/**
* Toggle the selection status of a point.
*
* @see Highcharts.Chart#getSelectedPoints
*
* @sample highcharts/members/point-select/
* Select a point from a button
* @sample highcharts/chart/events-selection-points/
* Select a range of points through a drag selection
* @sample maps/series/data-id/
* Select a point in Highmaps
*
* @function Highcharts.Point#select
*
* @param {boolean} [selected]
* When `true`, the point is selected. When `false`, the point is
* unselected. When `null` or `undefined`, the selection state is toggled.
*
* @param {boolean} [accumulate=false]
* When `true`, the selection is added to other selected points.
* When `false`, other selected points are deselected. Internally in
* Highcharts, when
* [allowPointSelect](https://api.highcharts.com/highcharts/plotOptions.series.allowPointSelect)
* is `true`, selected points are accumulated on Control, Shift or Cmd
* clicking the point.
*
* @fires Highcharts.Point#event:select
* @fires Highcharts.Point#event:unselect
*/
select: function (selected, accumulate) {
var point = this, series = point.series, chart = series.chart;
selected = pick(selected, !point.selected);
this.selectedStaging = selected;
// fire the event with the default handler
point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () {
/**
* Whether the point is selected or not.
*
* @see Point#select
* @see Chart#getSelectedPoints
*
* @name Highcharts.Point#selected
* @type {boolean}
*/
point.selected = point.options.selected = selected;
series.options.data[series.data.indexOf(point)] =
point.options;
point.setState(selected && 'select');
// unselect all other points unless Ctrl or Cmd + click
if (!accumulate) {
chart.getSelectedPoints().forEach(function (loopPoint) {
var loopSeries = loopPoint.series;
if (loopPoint.selected && loopPoint !== point) {
loopPoint.selected = loopPoint.options.selected =
false;
loopSeries.options.data[loopSeries.data.indexOf(loopPoint)] = loopPoint.options;
// Programatically selecting a point should restore
// normal state, but when click happened on other
// point, set inactive state to match other points
loopPoint.setState(chart.hoverPoints &&
loopSeries.options.inactiveOtherPoints ?
'inactive' : '');
loopPoint.firePointEvent('unselect');
}
});
}
});
delete this.selectedStaging;
},
/**
* Runs on mouse over the point. Called internally from mouse and touch
* events.
*
* @function Highcharts.Point#onMouseOver
*
* @param {Highcharts.PointerEventObject} [e]
* The event arguments.
*/
onMouseOver: function (e) {
var point = this, series = point.series, chart = series.chart, pointer = chart.pointer;
e = e ?
pointer.normalize(e) :
// In cases where onMouseOver is called directly without an event
pointer.getChartCoordinatesFromPoint(point, chart.inverted);
pointer.runPointActions(e, point);
},
/**
* Runs on mouse out from the point. Called internally from mouse and touch
* events.
*
* @function Highcharts.Point#onMouseOut
* @fires Highcharts.Point#event:mouseOut
*/
onMouseOut: function () {
var point = this, chart = point.series.chart;
point.firePointEvent('mouseOut');
if (!point.series.options.inactiveOtherPoints) {
(chart.hoverPoints || []).forEach(function (p) {
p.setState();
});
}
chart.hoverPoints = chart.hoverPoint = null;
},
/**
* Import events from the series' and point's options. Only do it on
* demand, to save processing time on hovering.
*
* @private
* @function Highcharts.Point#importEvents
*/
importEvents: function () {
if (!this.hasImportedEvents) {
var point = this, options = merge(point.series.options.point, point.options), events = options.events;
point.events = events;
objectEach(events, function (event, eventType) {
if (isFunction(event)) {
addEvent(point, eventType, event);
}
});
this.hasImportedEvents = true;
}
},
/**
* Set the point's state.
*
* @function Highcharts.Point#setState
*
* @param {Highcharts.PointStateValue|""} [state]
* The new state, can be one of `'hover'`, `'select'`, `'inactive'`,
* or `''` (an empty string), `'normal'` or `undefined` to set to
* normal state.
* @param {boolean} [move]
* State for animation.
*
* @fires Highcharts.Point#event:afterSetState
*/
setState: function (state, move) {
var point = this, series = point.series, previousState = point.state, stateOptions = (series.options.states[state || 'normal'] ||
{}), markerOptions = (defaultPlotOptions[series.type].marker &&
series.options.marker), normalDisabled = (markerOptions && markerOptions.enabled === false), markerStateOptions = ((markerOptions &&
markerOptions.states &&
markerOptions.states[state || 'normal']) || {}), stateDisabled = markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, pointMarker = point.marker || {}, chart = series.chart, halo = series.halo, haloOptions, markerAttribs, pointAttribs, pointAttribsAnimation, hasMarkers = (markerOptions && series.markerAttribs), newSymbol;
state = state || ''; // empty string
if (
// already has this state
(state === point.state && !move) ||
// selected points don't respond to hover
(point.selected && state !== 'select') ||
// series' state options is disabled
(stateOptions.enabled === false) ||
// general point marker's state options is disabled
(state && (stateDisabled ||
(normalDisabled &&
markerStateOptions.enabled === false))) ||
// individual point marker's state options is disabled
(state &&
pointMarker.states &&
pointMarker.states[state] &&
pointMarker.states[state].enabled === false) // #1610
) {
return;
}
point.state = state;
if (hasMarkers) {
markerAttribs = series.markerAttribs(point, state);
}
// Apply hover styles to the existing point
if (point.graphic) {
if (previousState) {
point.graphic.removeClass('highcharts-point-' + previousState);
}
if (state) {
point.graphic.addClass('highcharts-point-' + state);
}
if (!chart.styledMode) {
pointAttribs = series.pointAttribs(point, state);
pointAttribsAnimation = pick(chart.options.chart.animation, stateOptions.animation);
// Some inactive points (e.g. slices in pie) should apply
// oppacity also for it's labels
if (series.options.inactiveOtherPoints) {
(point.dataLabels || []).forEach(function (label) {
if (label) {
label.animate({
opacity: pointAttribs.opacity
}, pointAttribsAnimation);
}
});
if (point.connector) {
point.connector.animate({
opacity: pointAttribs.opacity
}, pointAttribsAnimation);
}
}
point.graphic.animate(pointAttribs, pointAttribsAnimation);
}
if (markerAttribs) {
point.graphic.animate(markerAttribs, pick(
// Turn off globally:
chart.options.chart.animation, markerStateOptions.animation, markerOptions.animation));
}
// Zooming in from a range with no markers to a range with markers
if (stateMarkerGraphic) {
stateMarkerGraphic.hide();
}
}
else {
// if a graphic is not applied to each point in the normal state,
// create a shared graphic for the hover state
if (state && markerStateOptions) {
newSymbol = pointMarker.symbol || series.symbol;
// If the point has another symbol than the previous one, throw
// away the state marker graphic and force a new one (#1459)
if (stateMarkerGraphic &&
stateMarkerGraphic.currentSymbol !== newSymbol) {
stateMarkerGraphic = stateMarkerGraphic.destroy();
}
// Add a new state marker graphic
if (markerAttribs) {
if (!stateMarkerGraphic) {
if (newSymbol) {
series.stateMarkerGraphic = stateMarkerGraphic =
chart.renderer
.symbol(newSymbol, markerAttribs.x, markerAttribs.y, markerAttribs.width, markerAttribs.height)
.add(series.markerGroup);
stateMarkerGraphic.currentSymbol = newSymbol;
}
// Move the existing graphic
}
else {
stateMarkerGraphic[move ? 'animate' : 'attr']({
x: markerAttribs.x,
y: markerAttribs.y
});
}
}
if (!chart.styledMode && stateMarkerGraphic) {
stateMarkerGraphic.attr(series.pointAttribs(point, state));
}
}
if (stateMarkerGraphic) {
stateMarkerGraphic[state && point.isInside ? 'show' : 'hide'](); // #2450
stateMarkerGraphic.element.point = point; // #4310
}
}
// Show me your halo
haloOptions = stateOptions.halo;
var markerGraphic = (point.graphic || stateMarkerGraphic);
var markerVisibility = (markerGraphic && markerGraphic.visibility || 'inherit');
if (haloOptions &&
haloOptions.size &&
markerGraphic &&
markerVisibility !== 'hidden' &&
!point.isCluster) {
if (!halo) {
series.halo = halo = chart.renderer.path()
// #5818, #5903, #6705
.add(markerGraphic.parentGroup);
}
halo.show()[move ? 'animate' : 'attr']({
d: point.haloPath(haloOptions.size)
});
halo.attr({
'class': 'highcharts-halo highcharts-color-' +
pick(point.colorIndex, series.colorIndex) +
(point.className ? ' ' + point.className : ''),
'visibility': markerVisibility,
'zIndex': -1 // #4929, #8276
});
halo.point = point; // #6055
if (!chart.styledMode) {
halo.attr(extend({
'fill': point.color || series.color,
'fill-opacity': haloOptions.opacity
}, haloOptions.attributes));
}
}
else if (halo && halo.point && halo.point.haloPath) {
// Animate back to 0 on the current halo point (#6055)
halo.animate({ d: halo.point.haloPath(0) }, null,
// Hide after unhovering. The `complete` callback runs in the
// halo's context (#7681).
halo.hide);
}
fireEvent(point, 'afterSetState');
},
/**
* Get the path definition for the halo, which is usually a shadow-like
* circle around the currently hovered point.
*
* @function Highcharts.Point#haloPath
*
* @param {number} size
* The radius of the circular halo.
*
* @return {Highcharts.SVGElement}
* The path definition.
*/
haloPath: function (size) {
var series = this.series, chart = series.chart;
return chart.renderer.symbols.circle(Math.floor(this.plotX) - size, this.plotY - size, size * 2, size * 2);
}
});
// Extend the Series object with interaction
extend(Series.prototype, /** @lends Highcharts.Series.prototype */ {
/**
* Runs on mouse over the series graphical items.
*
* @function Highcharts.Series#onMouseOver
* @fires Highcharts.Series#event:mouseOver
*/
onMouseOver: function () {
var series = this, chart = series.chart, hoverSeries = chart.hoverSeries;
// set normal state to previous series
if (hoverSeries && hoverSeries !== series) {
hoverSeries.onMouseOut();
}
// trigger the event, but to save processing time,
// only if defined
if (series.options.events.mouseOver) {
fireEvent(series, 'mouseOver');
}
// hover this
series.setState('hover');
/**
* Contains the original hovered series.
*
* @name Highcharts.Chart#hoverSeries
* @type {Highcharts.Series|null}
*/
chart.hoverSeries = series;
},
/**
* Runs on mouse out of the series graphical items.
*
* @function Highcharts.Series#onMouseOut
*
* @fires Highcharts.Series#event:mouseOut
*/
onMouseOut: function () {
// trigger the event only if listeners exist
var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint;
// #182, set to null before the mouseOut event fires
chart.hoverSeries = null;
// trigger mouse out on the point, which must be in this series
if (hoverPoint) {
hoverPoint.onMouseOut();
}
// fire the mouse out event
if (series && options.events.mouseOut) {
fireEvent(series, 'mouseOut');
}
// hide the tooltip
if (tooltip &&
!series.stickyTracking &&
(!tooltip.shared || series.noSharedTooltip)) {
tooltip.hide();
}
// Reset all inactive states
chart.series.forEach(function (s) {
s.setState('', true);
});
},
/**
* Set the state of the series. Called internally on mouse interaction
* operations, but it can also be called directly to visually
* highlight a series.
*
* @function Highcharts.Series#setState
*
* @param {Highcharts.SeriesStateValue|""} [state]
* The new state, can be either `'hover'`, `'inactive'`, `'select'`,
* or `''` (an empty string), `'normal'` or `undefined` to set to
* normal state.
* @param {boolean} [inherit]
* Determines if state should be inherited by points too.
*/
setState: function (state, inherit) {
var series = this, options = series.options, graph = series.graph, inactiveOtherPoints = options.inactiveOtherPoints, stateOptions = options.states, lineWidth = options.lineWidth, opacity = options.opacity,
// By default a quick animation to hover/inactive,
// slower to un-hover
stateAnimation = pick((stateOptions[state || 'normal'] &&
stateOptions[state || 'normal'].animation), series.chart.options.chart.animation), attribs, i = 0;
state = state || '';
if (series.state !== state) {
// Toggle class names
[
series.group,
series.markerGroup,
series.dataLabelsGroup
].forEach(function (group) {
if (group) {
// Old state
if (series.state) {
group.removeClass('highcharts-series-' + series.state);
}
// New state
if (state) {
group.addClass('highcharts-series-' + state);
}
}
});
series.state = state;
if (!series.chart.styledMode) {
if (stateOptions[state] &&
stateOptions[state].enabled === false) {
return;
}
if (state) {
lineWidth = (stateOptions[state].lineWidth ||
lineWidth + (stateOptions[state].lineWidthPlus || 0)); // #4035
opacity = pick(stateOptions[state].opacity, opacity);
}
if (graph && !graph.dashstyle) {
attribs = {
'stroke-width': lineWidth
};
// Animate the graph stroke-width.
graph.animate(attribs, stateAnimation);
while (series['zone-graph-' + i]) {
series['zone-graph-' + i].attr(attribs);
i = i + 1;
}
}
// For some types (pie, networkgraph, sankey) opacity is
// resolved on a point level
if (!inactiveOtherPoints) {
[
series.group,
series.markerGroup,
series.dataLabelsGroup,
series.labelBySeries
].forEach(function (group) {
if (group) {
group.animate({
opacity: opacity
}, stateAnimation);
}
});
}
}
}
// Don't loop over points on a series that doesn't apply inactive state
// to siblings markers (e.g. line, column)
if (inherit && inactiveOtherPoints && series.points) {
series.setAllPointsToState(state);
}
},
/**
* Set the state for all points in the series.
*
* @function Highcharts.Series#setAllPointsToState
*
* @private
*
* @param {string} [state]
* Can be either `hover` or undefined to set to normal state.
*/
setAllPointsToState: function (state) {
this.points.forEach(function (point) {
if (point.setState) {
point.setState(state);
}
});
},
/**
* Show or hide the series.
*
* @function Highcharts.Series#setVisible
*
* @param {boolean} [visible]
* True to show the series, false to hide. If undefined, the visibility is
* toggled.
*
* @param {boolean} [redraw=true]
* Whether to redraw the chart after the series is altered. If doing more
* operations on the chart, it is a good idea to set redraw to false and
* call {@link Chart#redraw|chart.redraw()} after.
*
* @fires Highcharts.Series#event:hide
* @fires Highcharts.Series#event:show
*/
setVisible: function (vis, redraw) {
var series = this, chart = series.chart, legendItem = series.legendItem, showOrHide, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible;
// if called without an argument, toggle visibility
series.visible =
vis =
series.options.visible =
series.userOptions.visible =
typeof vis === 'undefined' ? !oldVisibility : vis; // #5618
showOrHide = vis ? 'show' : 'hide';
// show or hide elements
[
'group',
'dataLabelsGroup',
'markerGroup',
'tracker',
'tt'
].forEach(function (key) {
if (series[key]) {
series[key][showOrHide]();
}
});
// hide tooltip (#1361)
if (chart.hoverSeries === series ||
(chart.hoverPoint && chart.hoverPoint.series) === series) {
series.onMouseOut();
}
if (legendItem) {
chart.legend.colorizeItem(series, vis);
}
// rescale or adapt to resized chart
series.isDirty = true;
// in a stack, all other series are affected
if (series.options.stacking) {
chart.series.forEach(function (otherSeries) {
if (otherSeries.options.stacking && otherSeries.visible) {
otherSeries.isDirty = true;
}
});
}
// show or hide linked series
series.linkedSeries.forEach(function (otherSeries) {
otherSeries.setVisible(vis, false);
});
if (ignoreHiddenSeries) {
chart.isDirtyBox = true;
}
fireEvent(series, showOrHide);
if (redraw !== false) {
chart.redraw();
}
},
/**
* Show the series if hidden.
*
* @sample highcharts/members/series-hide/
* Toggle visibility from a button
*
* @function Highcharts.Series#show
* @fires Highcharts.Series#event:show
*/
show: function () {
this.setVisible(true);
},
/**
* Hide the series if visible. If the
* [chart.ignoreHiddenSeries](https://api.highcharts.com/highcharts/chart.ignoreHiddenSeries)
* option is true, the chart is redrawn without this series.
*
* @sample highcharts/members/series-hide/
* Toggle visibility from a button
*
* @function Highcharts.Series#hide
* @fires Highcharts.Series#event:hide
*/
hide: function () {
this.setVisible(false);
},
/**
* Select or unselect the series. This means its
* {@link Highcharts.Series.selected|selected}
* property is set, the checkbox in the legend is toggled and when selected,
* the series is returned by the {@link Highcharts.Chart#getSelectedSeries}
* function.
*
* @sample highcharts/members/series-select/
* Select a series from a button
*
* @function Highcharts.Series#select
*
* @param {boolean} [selected]
* True to select the series, false to unselect. If undefined, the selection
* state is toggled.
*
* @fires Highcharts.Series#event:select
* @fires Highcharts.Series#event:unselect
*/
select: function (selected) {
var series = this;
series.selected =
selected =
this.options.selected = (typeof selected === 'undefined' ?
!series.selected :
selected);
if (series.checkbox) {
series.checkbox.checked = selected;
}
fireEvent(series, selected ? 'select' : 'unselect');
},
/**
* @private
* @borrows Highcharts.TrackerMixin.drawTrackerGraph as Highcharts.Series#drawTracker
*/
drawTracker: TrackerMixin.drawTrackerGraph
});<|fim▁end|>
|
seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
|
<|file_name|>Destroyable.java<|end_file_name|><|fim▁begin|>/* Copyright 2015 Roychoudhury, Abhishek */
<|fim▁hole|>package org.abhishek.fileanalytics.lifecycle;
public interface Destroyable {
void destroy();
boolean destroyed();
}<|fim▁end|>
| |
<|file_name|>rmeta.rs<|end_file_name|><|fim▁begin|>// Copyright 2016 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.
// Test that using rlibs and rmeta dep crates work together. Specifically, that
// there can be both an rmeta and an rlib file and rustc will prefer the rlib.
<|fim▁hole|>
extern crate rmeta_aux;
use rmeta_aux::Foo;
pub fn main() {
let _ = Foo { field: 42 };
}<|fim▁end|>
|
// aux-build:rmeta_rmeta.rs
// aux-build:rmeta_rlib.rs
|
<|file_name|>openpgp.go<|end_file_name|><|fim▁begin|>// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"io"
"time"
_ "crypto/sha256"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/armor"
"golang.org/x/crypto/openpgp/packet"
)
//A fake static time for when key's are (were) created<|fim▁hole|>var config = &packet.Config{
DefaultHash: crypto.SHA256,
DefaultCipher: packet.CipherAES256,
DefaultCompressionAlgo: packet.CompressionZLIB,
CompressionConfig: &packet.CompressionConfig{Level: 7},
}
func prompter(keys []openpgp.Key, symmetric bool) (passphrase []byte, err error) {
return
}
func gpgEncrypt(rsaPubKeys []*rsa.PublicKey, inFile io.Reader, outFile io.Writer) {
aesKey := make([]byte, packet.CipherAES256.KeySize())
rand.Read(aesKey)
outArmor, err := armor.Encode(outFile, "SSH-CRYPT-MESSAGE", make(map[string]string))
if err != nil {
panic(err)
}
defer outArmor.Close()
if len(rsaPubKeys) == 0 {
panic("No keys to use")
}
for _, rsaPubKey := range rsaPubKeys {
pubKey := packet.NewRSAPublicKey(KeyDate, rsaPubKey)
err = packet.SerializeEncryptedKey(outArmor, pubKey, packet.CipherAES256, aesKey, config)
if err != nil {
panic(err)
}
}
encryptedData, err := packet.SerializeSymmetricallyEncrypted(outArmor, packet.CipherAES256, aesKey, config)
if err != nil {
panic(err)
}
defer encryptedData.Close()
hints := &openpgp.FileHints{}
var epochSeconds uint32
if !hints.ModTime.IsZero() {
epochSeconds = uint32(hints.ModTime.Unix())
}
compressedData, err := packet.SerializeCompressed(encryptedData, config.DefaultCompressionAlgo, config.CompressionConfig)
if err != nil {
panic(err)
}
defer compressedData.Close()
writer, err := packet.SerializeLiteral(compressedData, hints.IsBinary, hints.FileName, epochSeconds)
if err != nil {
panic(err)
}
defer writer.Close()
// Copy the input file to the output file, encrypting as we go.
if _, err := io.Copy(writer, inFile); err != nil {
panic(err)
}
// Note that this example is simplistic in that it omits any
// authentication of the encrypted data. It you were actually to use
// StreamReader in this manner, an attacker could flip arbitrary bits in
// the decrypted result.
}
func gpgDecrypt(rsaPrivKey *rsa.PrivateKey, inFile io.Reader, outFile io.Writer) {
privKey := packet.NewRSAPrivateKey(KeyDate, rsaPrivKey)
armorBlock, err := armor.Decode(inFile)
if err != nil {
panic(err)
}
var keyRing openpgp.EntityList
keyRing = append(keyRing, &openpgp.Entity{
PrivateKey: privKey,
PrimaryKey: packet.NewRSAPublicKey(KeyDate, rsaPrivKey.Public().(*rsa.PublicKey)),
})
md, err := openpgp.ReadMessage(armorBlock.Body, keyRing, nil, config)
if err != nil {
panic(err)
}
// Copy the input file to the output file, decrypting as we go.
if _, err := io.Copy(outFile, md.UnverifiedBody); err != nil {
panic(err)
}
// Note that this example is simplistic in that it omits any
// authentication of the encrypted data. It you were actually to use
// StreamReader in this manner, an attacker could flip arbitrary bits in
// the output.
}<|fim▁end|>
|
var KeyDate time.Time = time.Date(1979, time.April, 10, 14, 15, 0, 0, time.FixedZone("VET", -16200))
|
<|file_name|>float_context.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/. */
use geom::point::Point2D;
use geom::size::Size2D;
use geom::rect::Rect;
use gfx::geometry::{Au, max, min};
use std::util::replace;
use std::vec;
use std::i32::max_value;
#[deriving(Clone)]
pub enum FloatType{
FloatLeft,
FloatRight
}
pub enum ClearType {
ClearLeft,
ClearRight,
ClearBoth
}
struct FloatContextBase{
float_data: ~[Option<FloatData>],
floats_used: uint,
max_y : Au,
offset: Point2D<Au>
}
#[deriving(Clone)]
struct FloatData{
bounds: Rect<Au>,
f_type: FloatType
}
/// All information necessary to place a float
pub struct PlacementInfo{
width: Au, // The dimensions of the float
height: Au,
ceiling: Au, // The minimum top of the float, as determined by earlier elements
max_width: Au, // The maximum right of the float, generally determined by the contining block
f_type: FloatType // left or right
}
/// Wrappers around float methods. To avoid allocating data we'll never use,
/// destroy the context on modification.
pub enum FloatContext {
Invalid,
Valid(~FloatContextBase)
}
impl FloatContext {
pub fn new(num_floats: uint) -> FloatContext {
Valid(~FloatContextBase::new(num_floats))
}
#[inline(always)]
pub fn clone(&mut self) -> FloatContext {
match *self {
Invalid => fail!("Can't clone an invalid float context"),
Valid(_) => replace(self, Invalid)
}
}
#[inline(always)]
fn with_mut_base<R>(&mut self, callback: &fn(&mut FloatContextBase) -> R) -> R {
match *self {
Invalid => fail!("Float context no longer available"),
Valid(ref mut base) => callback(&mut **base)
}
}
#[inline(always)]
pub fn with_base<R>(&self, callback: &fn(&FloatContextBase) -> R) -> R {
match *self {
Invalid => fail!("Float context no longer available"),
Valid(ref base) => callback(& **base)
}
}
#[inline(always)]
pub fn translate(&mut self, trans: Point2D<Au>) -> FloatContext {
do self.with_mut_base |base| {
base.translate(trans);
}
replace(self, Invalid)
}
#[inline(always)]
pub fn available_rect(&mut self, top: Au, height: Au, max_x: Au) -> Option<Rect<Au>> {
do self.with_base |base| {
base.available_rect(top, height, max_x)
}
}
#[inline(always)]
pub fn add_float(&mut self, info: &PlacementInfo) -> FloatContext{
do self.with_mut_base |base| {
base.add_float(info);
}
replace(self, Invalid)
}
#[inline(always)]
pub fn place_between_floats(&self, info: &PlacementInfo) -> Rect<Au> {
do self.with_base |base| {
base.place_between_floats(info)
}
}
#[inline(always)]
pub fn last_float_pos(&mut self) -> Point2D<Au> {
do self.with_base |base| {
base.last_float_pos()
}
}
#[inline(always)]
pub fn clearance(&self, clear: ClearType) -> Au {<|fim▁hole|>}
impl FloatContextBase{
fn new(num_floats: uint) -> FloatContextBase {
debug!("Creating float context of size %?", num_floats);
let new_data = vec::from_elem(num_floats, None);
FloatContextBase {
float_data: new_data,
floats_used: 0,
max_y: Au(0),
offset: Point2D(Au(0), Au(0))
}
}
fn translate(&mut self, trans: Point2D<Au>) {
self.offset = self.offset + trans;
}
fn last_float_pos(&self) -> Point2D<Au> {
assert!(self.floats_used > 0, "Error: tried to access FloatContext with no floats in it");
match self.float_data[self.floats_used - 1] {
None => fail!("FloatContext error: floats should never be None here"),
Some(float) => {
debug!("Returning float position: %?", float.bounds.origin + self.offset);
float.bounds.origin + self.offset
}
}
}
/// Returns a rectangle that encloses the region from top to top + height,
/// with width small enough that it doesn't collide with any floats. max_x
/// is the x-coordinate beyond which floats have no effect (generally
/// this is the containing block width).
fn available_rect(&self, top: Au, height: Au, max_x: Au) -> Option<Rect<Au>> {
fn range_intersect(top_1: Au, bottom_1: Au, top_2: Au, bottom_2: Au) -> (Au, Au) {
(max(top_1, top_2), min(bottom_1, bottom_2))
}
let top = top - self.offset.y;
debug!("available_rect: trying to find space at %?", top);
// Relevant dimensions for the right-most left float
let mut max_left = Au(0) - self.offset.x;
let mut l_top = None;
let mut l_bottom = None;
// Relevant dimensions for the left-most right float
let mut min_right = max_x - self.offset.x;
let mut r_top = None;
let mut r_bottom = None;
// Find the float collisions for the given vertical range.
for float in self.float_data.iter() {
debug!("available_rect: Checking for collision against float");
match *float{
None => (),
Some(data) => {
let float_pos = data.bounds.origin;
let float_size = data.bounds.size;
debug!("float_pos: %?, float_size: %?", float_pos, float_size);
match data.f_type {
FloatLeft => {
if(float_pos.x + float_size.width > max_left &&
float_pos.y + float_size.height > top && float_pos.y < top + height) {
max_left = float_pos.x + float_size.width;
l_top = Some(float_pos.y);
l_bottom = Some(float_pos.y + float_size.height);
debug!("available_rect: collision with left float: new max_left is %?",
max_left);
}
}
FloatRight => {
if(float_pos.x < min_right &&
float_pos.y + float_size.height > top && float_pos.y < top + height) {
min_right = float_pos.x;
r_top = Some(float_pos.y);
r_bottom = Some(float_pos.y + float_size.height);
debug!("available_rect: collision with right float: new min_right is %?",
min_right);
}
}
}
}
};
}
// Extend the vertical range of the rectangle to the closest floats.
// If there are floats on both sides, take the intersection of the
// two areas. Also make sure we never return a top smaller than the
// given upper bound.
let (top, bottom) = match (r_top, r_bottom, l_top, l_bottom) {
(Some(r_top), Some(r_bottom), Some(l_top), Some(l_bottom)) =>
range_intersect(max(top, r_top), r_bottom, max(top, l_top), l_bottom),
(None, None, Some(l_top), Some(l_bottom)) => (max(top, l_top), l_bottom),
(Some(r_top), Some(r_bottom), None, None) => (max(top, r_top), r_bottom),
(None, None, None, None) => return None,
_ => fail!("Reached unreachable state when computing float area")
};
// This assertion is too strong and fails in some cases. It is OK to
// return negative widths since we check against that right away, but
// we should still undersrtand why they occur and add a stronger
// assertion here.
//assert!(max_left < min_right);
assert!(top <= bottom, "Float position error");
Some(Rect{
origin: Point2D(max_left, top) + self.offset,
size: Size2D(min_right - max_left, bottom - top)
})
}
fn add_float(&mut self, info: &PlacementInfo) {
debug!("Floats_used: %?, Floats available: %?", self.floats_used, self.float_data.len());
assert!(self.floats_used < self.float_data.len() &&
self.float_data[self.floats_used].is_none());
let new_info = PlacementInfo {
width: info.width,
height: info.height,
ceiling: max(info.ceiling, self.max_y + self.offset.y),
max_width: info.max_width,
f_type: info.f_type
};
debug!("add_float: added float with info %?", new_info);
let new_float = FloatData {
bounds: Rect {
origin: self.place_between_floats(&new_info).origin - self.offset,
size: Size2D(info.width, info.height)
},
f_type: info.f_type
};
self.float_data[self.floats_used] = Some(new_float);
self.max_y = max(self.max_y, new_float.bounds.origin.y);
self.floats_used += 1;
}
/// Returns true if the given rect overlaps with any floats.
fn collides_with_float(&self, bounds: &Rect<Au>) -> bool {
for float in self.float_data.iter() {
match *float{
None => (),
Some(data) => {
if data.bounds.translate(&self.offset).intersects(bounds) {
return true;
}
}
};
}
return false;
}
/// Given the top 3 sides of the rectange, finds the largest height that
/// will result in the rectange not colliding with any floats. Returns
/// None if that height is infinite.
fn max_height_for_bounds(&self, left: Au, top: Au, width: Au) -> Option<Au> {
let top = top - self.offset.y;
let left = left - self.offset.x;
let mut max_height = None;
for float in self.float_data.iter() {
match *float {
None => (),
Some(f_data) => {
if f_data.bounds.origin.y + f_data.bounds.size.height > top &&
f_data.bounds.origin.x + f_data.bounds.size.width > left &&
f_data.bounds.origin.x < left + width {
let new_y = f_data.bounds.origin.y;
max_height = Some(min(max_height.unwrap_or_default(new_y), new_y));
}
}
}
}
max_height.map(|h| h + self.offset.y)
}
/// Given necessary info, finds the closest place a box can be positioned
/// without colliding with any floats.
fn place_between_floats(&self, info: &PlacementInfo) -> Rect<Au>{
debug!("place_float: Placing float with width %? and height %?", info.width, info.height);
// Can't go any higher than previous floats or
// previous elements in the document.
let mut float_y = info.ceiling;
loop {
let maybe_location = self.available_rect(float_y, info.height, info.max_width);
debug!("place_float: Got available rect: %? for y-pos: %?", maybe_location, float_y);
match maybe_location {
// If there are no floats blocking us, return the current location
// TODO(eatknson): integrate with overflow
None => return match info.f_type {
FloatLeft => Rect(Point2D(Au(0), float_y),
Size2D(info.max_width, Au(max_value))),
FloatRight => Rect(Point2D(info.max_width - info.width, float_y),
Size2D(info.max_width, Au(max_value)))
},
Some(rect) => {
assert!(rect.origin.y + rect.size.height != float_y,
"Non-terminating float placement");
// Place here if there is enough room
if (rect.size.width >= info.width) {
let height = self.max_height_for_bounds(rect.origin.x,
rect.origin.y,
rect.size.width);
let height = height.unwrap_or_default(Au(max_value));
return match info.f_type {
FloatLeft => Rect(Point2D(rect.origin.x, float_y),
Size2D(rect.size.width, height)),
FloatRight => {
Rect(Point2D(rect.origin.x + rect.size.width - info.width, float_y),
Size2D(rect.size.width, height))
}
};
}
// Try to place at the next-lowest location.
// Need to be careful of fencepost errors.
float_y = rect.origin.y + rect.size.height;
}
}
}
}
fn clearance(&self, clear: ClearType) -> Au {
let mut clearance = Au(0);
for float in self.float_data.iter() {
match *float {
None => (),
Some(f_data) => {
match (clear, f_data.f_type) {
(ClearLeft, FloatLeft) |
(ClearRight, FloatRight) |
(ClearBoth, _) => {
clearance = max(
clearance,
self.offset.y + f_data.bounds.origin.y + f_data.bounds.size.height);
}
_ => ()
}
}
}
}
clearance
}
}<|fim▁end|>
|
do self.with_base |base| {
base.clearance(clear)
}
}
|
<|file_name|>Anonymous Functions Practice.js<|end_file_name|><|fim▁begin|>// function that finds the sum of two parameters
function findSum(firstnr, secondnr){
return firstnr + secondnr;
}
//function that finds the product of two parameters
function findProduct(firstnr, secondnr){
return firstnr * secondnr;
}
/* threeOperation calls the operation parameter as a function so it's able to run and "do" different things
depending on the global function it takes as a parameter when calling it*/
function threeOperation (x, operation){
/*put console.log here so it doesn't only returns the result but also prints it in the console first:
to check if it gives the right answer when it's called*/
console.log(operation(3, x));
return operation(3, x);
}
//Call "threeOperation" with the values of "4" and "findSum"
threeOperation(4, findSum);
//Call "threeOperation" with the values of "5" and "findSum"<|fim▁hole|>//Call "threeOperation" with the values of "4" and "findProduct"
threeOperation(4, findProduct);
//Call "threeOperation" with the values of "5" and "findProduct"
threeOperation(5, findProduct);<|fim▁end|>
|
threeOperation(5, findSum);
|
<|file_name|>RpAccountCheckBatchServiceImpl.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2015-2102 RonCoo(http://www.roncoo.com) Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.roncoo.pay.reconciliation.service.impl;
<|fim▁hole|>import com.roncoo.pay.common.core.page.PageBean;
import com.roncoo.pay.common.core.page.PageParam;
import com.roncoo.pay.reconciliation.dao.RpAccountCheckBatchDao;
import com.roncoo.pay.reconciliation.entity.RpAccountCheckBatch;
import com.roncoo.pay.reconciliation.service.RpAccountCheckBatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* 对账批次接口实现 .
*
* 龙果学院:www.roncoo.com
*
* @author:shenjialong
*/
@Service("rpAccountCheckBatchService")
public class RpAccountCheckBatchServiceImpl implements RpAccountCheckBatchService {
@Autowired
private RpAccountCheckBatchDao rpAccountCheckBatchDao;
@Override
public void saveData(RpAccountCheckBatch rpAccountCheckBatch) {
rpAccountCheckBatchDao.insert(rpAccountCheckBatch);
}
@Override
public void updateData(RpAccountCheckBatch rpAccountCheckBatch) {
rpAccountCheckBatchDao.update(rpAccountCheckBatch);
}
@Override
public RpAccountCheckBatch getDataById(String id) {
return rpAccountCheckBatchDao.getById(id);
}
@Override
public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap) {
return rpAccountCheckBatchDao.listPage(pageParam, paramMap);
}
/**
* 根据条件查询实体
*
* @param paramMap
*/
public List<RpAccountCheckBatch> listBy(Map<String, Object> paramMap) {
return rpAccountCheckBatchDao.listBy(paramMap);
}
}<|fim▁end|>
| |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import os
from setuptools import setup
def read(fname):
with open(os.path.join(os.path.dirname(__file__), fname)) as f:
return f.read()
setup(name='django-darkknight',
version='0.9.0',
license="BSD",
description="He's a silent guardian, a watchful protector",
long_description=read('README.rst'),
author="Fusionbox, Inc",
author_email="[email protected]",
url='http://github.com/fusionbox/django-darkknight',
packages=['darkknight', 'darkknight_gpg'],
install_requires=[
'django-dotenv',
'Django>=1.5',
'pyOpenSSL',
'django-localflavor',<|fim▁hole|> ],
extras_require = {
'gpg': ['gnupg>=2.0.2,<3', 'django-apptemplates'],
},
classifiers=[
"Development Status :: 4 - Beta",
"Framework :: Django",
"Intended Audience :: Developers",
"Intended Audience :: Information Technology",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
"Topic :: Security :: Cryptography",
],
)<|fim▁end|>
|
'django-countries',
|
<|file_name|>integer-literal-suffix-inference.rs<|end_file_name|><|fim▁begin|>// 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
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn main() {
// the smallest positive values that need these types
let a8: i8 = 8;
let a16: i16 = 128;
let a32: i32 = 32_768;
let a64: i64 = 2_147_483_648;
// the smallest negative values that need these types
let c8: i8 = -9;
let c16: i16 = -129;
let c32: i32 = -32_769;
let c64: i64 = -2_147_483_649;
fn id_i8(n: i8) -> i8 { n }
fn id_i16(n: i16) -> i16 { n }
fn id_i32(n: i32) -> i32 { n }
fn id_i64(n: i64) -> i64 { n }
// the smallest values that need these types
let b8: u8 = 16;
let b16: u16 = 256;
let b32: u32 = 65_536;
let b64: u64 = 4_294_967_296;
fn id_u8(n: u8) -> u8 { n }
fn id_u16(n: u16) -> u16 { n }
fn id_u32(n: u32) -> u32 { n }
fn id_u64(n: u64) -> u64 { n }
id_i8(a8); // ok
id_i8(a16);
//~^ ERROR mismatched types
//~| expected `i8`
//~| found `i16`
//~| expected i8
//~| found i16
id_i8(a32);
//~^ ERROR mismatched types
//~| expected `i8`
//~| found `i32`
//~| expected i8
//~| found i32
id_i8(a64);
//~^ ERROR mismatched types
//~| expected `i8`
//~| found `i64`
//~| expected i8
//~| found i64
id_i16(a8);
//~^ ERROR mismatched types
//~| expected `i16`
//~| found `i8`
//~| expected i16
//~| found i8
id_i16(a16); // ok
id_i16(a32);
//~^ ERROR mismatched types
//~| expected `i16`
//~| found `i32`
//~| expected i16
//~| found i32
id_i16(a64);
//~^ ERROR mismatched types
//~| expected `i16`
//~| found `i64`
//~| expected i16
//~| found i64
id_i32(a8);
//~^ ERROR mismatched types
//~| expected `i32`
//~| found `i8`
//~| expected i32
//~| found i8
id_i32(a16);
//~^ ERROR mismatched types
//~| expected `i32`
//~| found `i16`
//~| expected i32
//~| found i16
id_i32(a32); // ok
id_i32(a64);
//~^ ERROR mismatched types
//~| expected `i32`
//~| found `i64`
//~| expected i32
//~| found i64
id_i64(a8);
//~^ ERROR mismatched types
//~| expected `i64`
//~| found `i8`
//~| expected i64
//~| found i8
id_i64(a16);
//~^ ERROR mismatched types
//~| expected `i64`
//~| found `i16`
//~| expected i64
//~| found i16
id_i64(a32);
//~^ ERROR mismatched types
//~| expected `i64`
//~| found `i32`
//~| expected i64
//~| found i32
id_i64(a64); // ok
id_i8(c8); // ok
id_i8(c16);
//~^ ERROR mismatched types
//~| expected `i8`
//~| found `i16`
//~| expected i8
//~| found i16
id_i8(c32);
//~^ ERROR mismatched types
//~| expected `i8`
//~| found `i32`
//~| expected i8
//~| found i32
id_i8(c64);
//~^ ERROR mismatched types
//~| expected `i8`
//~| found `i64`
//~| expected i8
//~| found i64
id_i16(c8);
//~^ ERROR mismatched types
//~| expected `i16`
//~| found `i8`
//~| expected i16
//~| found i8
id_i16(c16); // ok
id_i16(c32);
//~^ ERROR mismatched types
//~| expected `i16`
//~| found `i32`<|fim▁hole|> //~| expected `i16`
//~| found `i64`
//~| expected i16
//~| found i64
id_i32(c8);
//~^ ERROR mismatched types
//~| expected `i32`
//~| found `i8`
//~| expected i32
//~| found i8
id_i32(c16);
//~^ ERROR mismatched types
//~| expected `i32`
//~| found `i16`
//~| expected i32
//~| found i16
id_i32(c32); // ok
id_i32(c64);
//~^ ERROR mismatched types
//~| expected `i32`
//~| found `i64`
//~| expected i32
//~| found i64
id_i64(a8);
//~^ ERROR mismatched types
//~| expected `i64`
//~| found `i8`
//~| expected i64
//~| found i8
id_i64(a16);
//~^ ERROR mismatched types
//~| expected `i64`
//~| found `i16`
//~| expected i64
//~| found i16
id_i64(a32);
//~^ ERROR mismatched types
//~| expected `i64`
//~| found `i32`
//~| expected i64
//~| found i32
id_i64(a64); // ok
id_u8(b8); // ok
id_u8(b16);
//~^ ERROR mismatched types
//~| expected `u8`
//~| found `u16`
//~| expected u8
//~| found u16
id_u8(b32);
//~^ ERROR mismatched types
//~| expected `u8`
//~| found `u32`
//~| expected u8
//~| found u32
id_u8(b64);
//~^ ERROR mismatched types
//~| expected `u8`
//~| found `u64`
//~| expected u8
//~| found u64
id_u16(b8);
//~^ ERROR mismatched types
//~| expected `u16`
//~| found `u8`
//~| expected u16
//~| found u8
id_u16(b16); // ok
id_u16(b32);
//~^ ERROR mismatched types
//~| expected `u16`
//~| found `u32`
//~| expected u16
//~| found u32
id_u16(b64);
//~^ ERROR mismatched types
//~| expected `u16`
//~| found `u64`
//~| expected u16
//~| found u64
id_u32(b8);
//~^ ERROR mismatched types
//~| expected `u32`
//~| found `u8`
//~| expected u32
//~| found u8
id_u32(b16);
//~^ ERROR mismatched types
//~| expected `u32`
//~| found `u16`
//~| expected u32
//~| found u16
id_u32(b32); // ok
id_u32(b64);
//~^ ERROR mismatched types
//~| expected `u32`
//~| found `u64`
//~| expected u32
//~| found u64
id_u64(b8);
//~^ ERROR mismatched types
//~| expected `u64`
//~| found `u8`
//~| expected u64
//~| found u8
id_u64(b16);
//~^ ERROR mismatched types
//~| expected `u64`
//~| found `u16`
//~| expected u64
//~| found u16
id_u64(b32);
//~^ ERROR mismatched types
//~| expected `u64`
//~| found `u32`
//~| expected u64
//~| found u32
id_u64(b64); // ok
}<|fim▁end|>
|
//~| expected i16
//~| found i32
id_i16(c64);
//~^ ERROR mismatched types
|
<|file_name|>lee_lineas.cc<|end_file_name|><|fim▁begin|><|fim▁hole|>/* ---------------------------------------------------------------------------
* Programa: lee_lineas
* Entradas: Una serie de líneas de texto
* Salidas: - La línea más larga (si no se introduce ninguna se muestra una cadena vacía)
* - La línea menor lexicográficamente (si no se introduce ninguna se
* muestra la cadena FIN)
* --------------------------------------------------------------------------- */
#include <iostream>
#include <string>
using namespace std;
int main ()
{
const string CENTINELA = "FIN";
string masLarga = ""; // tiene longitud 0
string linea;
cout << "Introduzca una línea (" << CENTINELA << " para acabar): ";
getline (cin, linea);
string menor = linea; // se inicia la menor a la primera línea leída
while (linea != CENTINELA) {
if (linea.length () > masLarga.length ())
masLarga = linea;
if (linea < menor)
menor = linea;
cout << "Introduzca una línea (" << CENTINELA << " para acabar): ";
getline (cin, linea);
}
cout << "Línea más larga: " << masLarga << endl;
cout << "Línea menor lexicográficamente: " << menor << endl;
return 0;
}<|fim▁end|>
| |
<|file_name|>QsbkFragment.java<|end_file_name|><|fim▁begin|>package io.github.marktony.reader.qsbk;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import io.github.marktony.reader.R;
import io.github.marktony.reader.adapter.QsbkArticleAdapter;
import io.github.marktony.reader.data.Qiushibaike;
import io.github.marktony.reader.interfaze.OnRecyclerViewClickListener;
import io.github.marktony.reader.interfaze.OnRecyclerViewLongClickListener;
/**
* Created by Lizhaotailang on 2016/8/4.
*/
public class QsbkFragment extends Fragment
implements QsbkContract.View {
private QsbkContract.Presenter presenter;
private QsbkArticleAdapter adapter;
private RecyclerView recyclerView;
private SwipeRefreshLayout refreshLayout;
public QsbkFragment() {
// requires empty constructor
}
public static QsbkFragment newInstance(int page) {
return new QsbkFragment();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.joke_list_fragment, container, false);
initViews(view);
presenter.loadArticle(true);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override<|fim▁hole|> presenter.loadArticle(true);
adapter.notifyDataSetChanged();
if (refreshLayout.isRefreshing()){
refreshLayout.setRefreshing(false);
}
}
});
recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
boolean isSlidingToLast = false;
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
// 当不滚动时
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
// 获取最后一个完全显示的itemposition
int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
int totalItemCount = manager.getItemCount();
// 判断是否滚动到底部并且是向下滑动
if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
presenter.loadMore();
}
}
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
isSlidingToLast = dy > 0;
}
});
return view;
}
@Override
public void setPresenter(QsbkContract.Presenter presenter) {
if (presenter != null) {
this.presenter = presenter;
}
}
@Override
public void initViews(View view) {
recyclerView = (RecyclerView) view.findViewById(R.id.qsbk_rv);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
}
@Override
public void showResult(ArrayList<Qiushibaike.Item> articleList) {
if (adapter == null) {
adapter = new QsbkArticleAdapter(getActivity(), articleList);
recyclerView.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
adapter.setOnItemClickListener(new OnRecyclerViewClickListener() {
@Override
public void OnClick(View v, int position) {
presenter.shareTo(position);
}
});
adapter.setOnItemLongClickListener(new OnRecyclerViewLongClickListener() {
@Override
public void OnLongClick(View view, int position) {
presenter.copyToClipboard(position);
}
});
}
@Override
public void startLoading() {
refreshLayout.post(new Runnable() {
@Override
public void run() {
refreshLayout.setRefreshing(true);
}
});
}
@Override
public void stopLoading() {
refreshLayout.post(new Runnable() {
@Override
public void run() {
refreshLayout.setRefreshing(false);
}
});
}
@Override
public void showLoadError() {
Snackbar.make(recyclerView, "加载失败", Snackbar.LENGTH_SHORT)
.setAction("重试", new View.OnClickListener() {
@Override
public void onClick(View view) {
presenter.loadArticle(false);
}
}).show();
}
@Override
public void onResume() {
super.onResume();
presenter.start();
}
}<|fim▁end|>
|
public void onRefresh() {
|
<|file_name|>test_maxout_op.py<|end_file_name|><|fim▁begin|># Copyright (c) 2018 PaddlePaddle Authors. 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.
from __future__ import print_function
import unittest
import numpy as np
import paddle
import paddle.fluid as fluid
import paddle.fluid.core as core
import paddle.nn.functional as F
from op_test import OpTest
paddle.enable_static()
np.random.seed(1)
def maxout_forward_naive(x, groups, channel_axis):
s0, s1, s2, s3 = x.shape
if channel_axis == 1:
return np.ndarray([s0, s1 // groups, groups, s2, s3], \
buffer = x, dtype=x.dtype).max(axis=2)
return np.ndarray([s0, s1, s2, s3 // groups, groups], \
buffer = x, dtype=x.dtype).max(axis=4)
class TestMaxOutOp(OpTest):
def setUp(self):
self.op_type = "maxout"
self.dtype = 'float64'
self.shape = [3, 6, 2, 4]
self.groups = 2
self.axis = 1
self.set_attrs()
x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
out = maxout_forward_naive(x, self.groups, self.axis)
self.inputs = {'X': x}
self.attrs = {'groups': self.groups, 'axis': self.axis}
self.outputs = {'Out': out}
def set_attrs(self):
pass
def test_check_output(self):
self.check_output()
def test_check_grad(self):
self.check_grad(['X'], 'Out')
class TestMaxOutOpAxis0(TestMaxOutOp):
def set_attrs(self):
self.axis = -1
class TestMaxOutOpAxis1(TestMaxOutOp):
def set_attrs(self):
self.axis = 3
class TestMaxOutOpFP32(TestMaxOutOp):
def set_attrs(self):
self.dtype = 'float32'
class TestMaxOutOpGroups(TestMaxOutOp):
def set_attrs(self):
self.groups = 3
class TestMaxoutAPI(unittest.TestCase):
# test paddle.nn.Maxout, paddle.nn.functional.maxout
def setUp(self):
self.x_np = np.random.uniform(-1, 1, [2, 6, 5, 4]).astype(np.float64)
self.groups = 2
self.axis = 1
self.place=paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
else paddle.CPUPlace()
def test_static_api(self):
with paddle.static.program_guard(paddle.static.Program()):
x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
out1 = F.maxout(x, self.groups, self.axis)
m = paddle.nn.Maxout(self.groups, self.axis)
out2 = m(x)
exe = paddle.static.Executor(self.place)
res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
out_ref = maxout_forward_naive(self.x_np, self.groups, self.axis)
for r in res:
self.assertTrue(np.allclose(out_ref, r))<|fim▁hole|> x = paddle.to_tensor(self.x_np)
out1 = F.maxout(x, self.groups, self.axis)
m = paddle.nn.Maxout(self.groups, self.axis)
out2 = m(x)
out_ref = maxout_forward_naive(self.x_np, self.groups, self.axis)
for r in [out1, out2]:
self.assertTrue(np.allclose(out_ref, r.numpy()))
out3 = F.maxout(x, self.groups, -1)
out3_ref = maxout_forward_naive(self.x_np, self.groups, -1)
self.assertTrue(np.allclose(out3_ref, out3.numpy()))
paddle.enable_static()
def test_fluid_api(self):
with fluid.program_guard(fluid.Program()):
x = fluid.data('X', self.x_np.shape, self.x_np.dtype)
out = fluid.layers.maxout(x, groups=self.groups, axis=self.axis)
exe = fluid.Executor(self.place)
res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
out_ref = maxout_forward_naive(self.x_np, self.groups, self.axis)
self.assertTrue(np.allclose(out_ref, res[0]))
paddle.disable_static(self.place)
x = paddle.to_tensor(self.x_np)
out = paddle.fluid.layers.maxout(x, groups=self.groups, axis=self.axis)
self.assertTrue(np.allclose(out_ref, out.numpy()))
paddle.enable_static()
def test_errors(self):
with paddle.static.program_guard(paddle.static.Program()):
# The input type must be Variable.
self.assertRaises(TypeError, F.maxout, 1)
# The input dtype must be float16, float32, float64.
x_int32 = paddle.fluid.data(
name='x_int32', shape=[2, 4, 6, 8], dtype='int32')
self.assertRaises(TypeError, F.maxout, x_int32)
x_float32 = paddle.fluid.data(name='x_float32', shape=[2, 4, 6, 8])
self.assertRaises(ValueError, F.maxout, x_float32, 2, 2)
if __name__ == '__main__':
unittest.main()<|fim▁end|>
|
def test_dygraph_api(self):
paddle.disable_static(self.place)
|
<|file_name|>test_stats_routes.py<|end_file_name|><|fim▁begin|>from .routes_test_fixture import app # noqa<|fim▁hole|> assert client.get("/stats/enwiki/1")._status_code == 200
# test archived campaign
assert client.get("/stats/enwiki/7")._status_code == 200
def test_stats(client):
assert client.get("/stats/")._status_code == 200<|fim▁end|>
|
def test_stats_wiki_campaign(client):
# test active campaign
|
<|file_name|>QuoteEntity.java<|end_file_name|><|fim▁begin|>package mobi.qubits.tradingapp.query;
import java.util.Date;
import org.springframework.data.annotation.Id;
public class QuoteEntity {
@Id
private String id;
private String symbol;
private String name;
private float open;
private float prevClose;
private float currentQuote;
private float high;
private float low;
<|fim▁hole|>
private Date timestamp;
public QuoteEntity() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getOpen() {
return open;
}
public void setOpen(float open) {
this.open = open;
}
public float getPrevClose() {
return prevClose;
}
public void setPrevClose(float prevClose) {
this.prevClose = prevClose;
}
public float getCurrentQuote() {
return currentQuote;
}
public void setCurrentQuote(float currentQuote) {
this.currentQuote = currentQuote;
}
public float getHigh() {
return high;
}
public void setHigh(float high) {
this.high = high;
}
public float getLow() {
return low;
}
public void setLow(float low) {
this.low = low;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getQuoteTime() {
return quoteTime;
}
public void setQuoteTime(String quoteTime) {
this.quoteTime = quoteTime;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
}<|fim▁end|>
|
private String date;
private String quoteTime;
|
<|file_name|>main.go<|end_file_name|><|fim▁begin|>package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"github.com/hashicorp/go-plugin"
"github.com/hashicorp/go-plugin/examples/grpc/shared"
)
func main() {
// We don't want to see the plugin logs.
log.SetOutput(ioutil.Discard)
// We're a host. Start by launching the plugin process.
client := plugin.NewClient(&plugin.ClientConfig{
HandshakeConfig: shared.Handshake,
Plugins: shared.PluginMap,
Cmd: exec.Command("sh", "-c", os.Getenv("KV_PLUGIN")),
AllowedProtocols: []plugin.Protocol{
plugin.ProtocolNetRPC, plugin.ProtocolGRPC},
})
defer client.Kill()
// Connect via RPC
rpcClient, err := client.Client()
if err != nil {
fmt.Println("Error:", err.Error())
os.Exit(1)
}
// Request the plugin
raw, err := rpcClient.Dispense("kv")
if err != nil {
fmt.Println("Error:", err.Error())
os.Exit(1)
}
// We should have a KV store now! This feels like a normal interface
// implementation but is in fact over an RPC connection.
kv := raw.(shared.KV)
os.Args = os.Args[1:]
switch os.Args[0] {
case "get":
result, err := kv.Get(os.Args[1])
if err != nil {
fmt.Println("Error:", err.Error())
os.Exit(1)
}
fmt.Println(string(result))
case "put":
err := kv.Put(os.Args[1], []byte(os.Args[2]))
if err != nil {<|fim▁hole|> }
default:
fmt.Println("Please only use 'get' or 'put'")
os.Exit(1)
}
}<|fim▁end|>
|
fmt.Println("Error:", err.Error())
os.Exit(1)
|
<|file_name|>test_nxos_bfd_global.py<|end_file_name|><|fim▁begin|># (c) 2019 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.nxos import nxos_bfd_global
from ansible.module_utils.network.nxos.nxos import NxosCmdRef
from .nxos_module import TestNxosModule, load_fixture, set_module_args
# TBD: These imports / import checks are only needed as a workaround for
# shippable, which fails this test due to import yaml & import ordereddict.
import pytest
from ansible.module_utils.network.nxos.nxos import nxosCmdRef_import_check
msg = nxosCmdRef_import_check()
@pytest.mark.skipif(len(msg), reason=msg)
class TestNxosBfdGlobalModule(TestNxosModule):
module = nxos_bfd_global
def setUp(self):
super(TestNxosBfdGlobalModule, self).setUp()
self.mock_load_config = patch('ansible.modules.network.nxos.nxos_bfd_global.load_config')
self.load_config = self.mock_load_config.start()
self.mock_execute_show_command = patch('ansible.module_utils.network.nxos.nxos.NxosCmdRef.execute_show_command')
self.execute_show_command = self.mock_execute_show_command.start()
self.mock_get_platform_shortname = patch('ansible.module_utils.network.nxos.nxos.NxosCmdRef.get_platform_shortname')
self.get_platform_shortname = self.mock_get_platform_shortname.start()
def tearDown(self):
super(TestNxosBfdGlobalModule, self).tearDown()
self.mock_load_config.stop()
self.execute_show_command.stop()
self.get_platform_shortname.stop()
def load_fixtures(self, commands=None, device=''):
self.load_config.return_value = None
def test_bfd_defaults_n9k(self):
# feature bfd is enabled, no non-defaults are set.
self.execute_show_command.return_value = "feature bfd"
self.get_platform_shortname.return_value = 'N9K'
set_module_args(dict(
echo_interface='deleted',
echo_rx_interval=50,
interval={'tx': 50, 'min_rx': 50, 'multiplier': 3},
slow_timer=2000,
startup_timer=5,
ipv4_echo_rx_interval=50,
ipv4_interval={'tx': 50, 'min_rx': 50, 'multiplier': 3},
ipv4_slow_timer=2000,
ipv6_echo_rx_interval=50,
ipv6_interval={'tx': 50, 'min_rx': 50, 'multiplier': 3},
ipv6_slow_timer=2000
))
self.execute_module(changed=False)
def test_bfd_defaults_n3k(self):
# feature bfd is enabled, no non-defaults are set.
self.execute_show_command.return_value = "feature bfd"
self.get_platform_shortname.return_value = 'N3K'
set_module_args(dict(
echo_interface='deleted',
echo_rx_interval=250,
interval={'tx': 250, 'min_rx': 250, 'multiplier': 3},
slow_timer=2000,
startup_timer=5,
ipv4_echo_rx_interval=250,
ipv4_interval={'tx': 250, 'min_rx': 250, 'multiplier': 3},
ipv4_slow_timer=2000,
ipv6_echo_rx_interval=250,
ipv6_interval={'tx': 250, 'min_rx': 250, 'multiplier': 3},
ipv6_slow_timer=2000
))
self.execute_module(changed=False)
def test_bfd_defaults_n35(self):
# feature bfd is enabled, no non-defaults are set.
self.execute_show_command.return_value = "feature bfd"
self.get_platform_shortname.return_value = 'N35'
set_module_args(dict(
echo_interface='deleted',
echo_rx_interval=50,
interval={'tx': 50, 'min_rx': 50, 'multiplier': 3},
slow_timer=2000,
startup_timer=5,
ipv4_echo_rx_interval=50,
ipv4_interval={'tx': 50, 'min_rx': 50, 'multiplier': 3},
ipv4_slow_timer=2000,
))
self.execute_module(changed=False)
def test_bfd_defaults_n6k(self):
# feature bfd is enabled, no non-defaults are set.
self.execute_show_command.return_value = "feature bfd"
self.get_platform_shortname.return_value = 'N6K'
set_module_args(dict(
echo_interface='deleted',
interval={'tx': 50, 'min_rx': 50, 'multiplier': 3},
slow_timer=2000,
fabricpath_interval={'tx': 50, 'min_rx': 50, 'multiplier': 3},
fabricpath_slow_timer=2000,
fabricpath_vlan=1
))
self.execute_module(changed=False)
def test_bfd_defaults_n7k(self):
# feature bfd is enabled, no non-defaults are set.
self.execute_show_command.return_value = "feature bfd"
self.get_platform_shortname.return_value = 'N7K'
set_module_args(dict(
echo_interface='deleted',
echo_rx_interval=50,
interval={'tx': 50, 'min_rx': 50, 'multiplier': 3},
slow_timer=2000,
ipv4_echo_rx_interval=50,
ipv4_interval={'tx': 50, 'min_rx': 50, 'multiplier': 3},
ipv4_slow_timer=2000,
ipv6_echo_rx_interval=50,
ipv6_interval={'tx': 50, 'min_rx': 50, 'multiplier': 3},
ipv6_slow_timer=2000,
fabricpath_interval={'tx': 50, 'min_rx': 50, 'multiplier': 3},
fabricpath_slow_timer=2000,
fabricpath_vlan=1
))
self.execute_module(changed=False)
def test_bfd_existing_n9k(self):
module_name = self.module.__name__.rsplit('.', 1)[1]
self.execute_show_command.return_value = load_fixture(module_name, 'N9K.cfg')
self.get_platform_shortname.return_value = 'N9K'
set_module_args(dict(
echo_interface='deleted',<|fim▁hole|> ipv4_echo_rx_interval=50,
ipv4_interval={'tx': 51, 'min_rx': 51, 'multiplier': 3},
ipv4_slow_timer=2000,
ipv6_echo_rx_interval=50,
ipv6_interval={'tx': 51, 'min_rx': 51, 'multiplier': 3},
ipv6_slow_timer=2000
))
self.execute_module(changed=True, commands=[
'no bfd echo-interface loopback2',
'bfd echo-rx-interval 51',
'bfd interval 51 min_rx 51 multiplier 3',
'bfd slow-timer 2000',
'bfd startup-timer 5',
'bfd ipv4 echo-rx-interval 50',
'bfd ipv4 interval 51 min_rx 51 multiplier 3',
'bfd ipv4 slow-timer 2000',
'bfd ipv6 echo-rx-interval 50',
'bfd ipv6 interval 51 min_rx 51 multiplier 3',
'bfd ipv6 slow-timer 2000',
])
def test_bfd_idempotence_n9k(self):
module_name = self.module.__name__.rsplit('.', 1)[1]
self.execute_show_command.return_value = load_fixture(module_name, 'N9K.cfg')
self.get_platform_shortname.return_value = 'N9K'
set_module_args(dict(
echo_interface='loopback2',
echo_rx_interval=56,
interval={'tx': 51, 'min_rx': 52, 'multiplier': 4},
slow_timer=2001,
startup_timer=6,
ipv4_echo_rx_interval=54,
ipv4_interval={'tx': 54, 'min_rx': 54, 'multiplier': 4},
ipv4_slow_timer=2004,
ipv6_echo_rx_interval=56,
ipv6_interval={'tx': 56, 'min_rx': 56, 'multiplier': 6},
ipv6_slow_timer=2006
))
self.execute_module(changed=False)
def test_bfd_existing_n7k(self):
module_name = self.module.__name__.rsplit('.', 1)[1]
self.execute_show_command.return_value = load_fixture(module_name, 'N7K.cfg')
self.get_platform_shortname.return_value = 'N7K'
set_module_args(dict(
echo_interface='deleted',
echo_rx_interval=51,
interval={'tx': 51, 'min_rx': 51, 'multiplier': 3},
slow_timer=2002,
ipv4_echo_rx_interval=51,
ipv4_interval={'tx': 51, 'min_rx': 51, 'multiplier': 3},
ipv4_slow_timer=2002,
ipv6_echo_rx_interval=51,
ipv6_interval={'tx': 51, 'min_rx': 51, 'multiplier': 3},
ipv6_slow_timer=2002,
fabricpath_interval={'tx': 51, 'min_rx': 51, 'multiplier': 3},
fabricpath_slow_timer=2003,
fabricpath_vlan=3,
))
self.execute_module(changed=True, commands=[
'no bfd echo-interface loopback2',
'bfd echo-rx-interval 51',
'bfd interval 51 min_rx 51 multiplier 3',
'bfd slow-timer 2002',
'bfd ipv4 echo-rx-interval 51',
'bfd ipv4 interval 51 min_rx 51 multiplier 3',
'bfd ipv4 slow-timer 2002',
'bfd ipv6 echo-rx-interval 51',
'bfd ipv6 interval 51 min_rx 51 multiplier 3',
'bfd ipv6 slow-timer 2002',
'bfd fabricpath interval 51 min_rx 51 multiplier 3',
'bfd fabricpath slow-timer 2003',
'bfd fabricpath vlan 3',
])
def test_bfd_idempotence_n7k(self):
module_name = self.module.__name__.rsplit('.', 1)[1]
self.execute_show_command.return_value = load_fixture(module_name, 'N7K.cfg')
self.get_platform_shortname.return_value = 'N7K'
set_module_args(dict(
echo_interface='loopback2',
echo_rx_interval=56,
interval={'tx': 51, 'min_rx': 52, 'multiplier': 4},
slow_timer=2001,
ipv4_echo_rx_interval=54,
ipv4_interval={'tx': 54, 'min_rx': 54, 'multiplier': 4},
ipv4_slow_timer=2004,
ipv6_echo_rx_interval=56,
ipv6_interval={'tx': 56, 'min_rx': 56, 'multiplier': 6},
ipv6_slow_timer=2006,
fabricpath_interval={'tx': 58, 'min_rx': 58, 'multiplier': 8},
fabricpath_slow_timer=2008,
fabricpath_vlan=2,
))
self.execute_module(changed=False)<|fim▁end|>
|
echo_rx_interval=51,
interval={'tx': 51, 'min_rx': 51, 'multiplier': 3},
slow_timer=2000,
startup_timer=5,
|
<|file_name|>test_overview_example.py<|end_file_name|><|fim▁begin|>__author__ = 'mpetyx'
from unittest import TestCase
import unittest
import logging
import sys
from pyapi import API
class TestpyAPI(TestCase):
def setUp(self):<|fim▁hole|> # print "Setting up the coverage unit test for pyapi"
self.document = API()
self.api = API().parse(location="url", language="raml")
def test_swagger_serialise(self):
self.assertEqual(self.api.serialise(language="swagger"), {}, "Swagger could not be serialised properly")
def test_raml_serialise(self):
self.assertEqual(self.api.serialise(language="raml"), {}, "RAML could not be serialised properly")
def test_hydra_serialise(self):
self.assertEqual(self.api.serialise(language="hydra"), {}, "Hydra could not be serialised properly")
def test_blueprint_serialise(self):
self.assertEqual(self.api.serialise(language="blueprint"), {},
"API blueprint could not be serialised properly")
def test_query(self):
# print "sample"
self.assertEqual(1, 2, "There are not equal at all!")
# ending the test
def tearDown(self):
"""Cleaning up after the test"""
self.log.debug("finalising the test")
if __name__ == '__main__':
logging.basicConfig(stream=sys.stderr)
logging.getLogger("SomeTest.testSomething").setLevel(logging.DEBUG)
unittest.main()<|fim▁end|>
| |
<|file_name|>mod_sesamstrasse.py<|end_file_name|><|fim▁begin|>import datetime, re
from mod_helper import *
debug = True
def sesamstrasseShow():
mediaList = ObjectContainer(no_cache=True)
if debug == True: Log("Running sesamstrasseShow()...")
try:
urlMain = "http://www.sesamstrasse.de"
content = getURL(urlMain+"/home/homepage1077.html")
spl = content.split('<div class="thumb">')
for i in range(1, len(spl), 1):
entry = spl[i]
match = re.compile('title="(.+?)"', re.DOTALL).findall(entry)
title = match[0]
match = re.compile('href="(.+?)"', re.DOTALL).findall(entry)
url = urlMain+match[0]
match = re.compile('src="(.+?)"', re.DOTALL).findall(entry)
thumb = urlMain+match[0]
thumb = thumb[:thumb.find("_")]+"_v-original.jpg"
match = re.compile('<div class="subline">(.+?) \\| (.+?):', re.DOTALL).findall(entry)
date = ""
duration = ""
if match:
date = match[0][0]
date = date[:date.rfind('.')].strip()
duration = match[0][1]<|fim▁hole|>
item = {
'title':title,
'url':url,
'thumb':thumb,
'duration':int(duration)*60000
}
if debug == True: Log("Adding: " + title)
vo = sesamstrasseCreateVideoObject(item)
mediaList.add(vo)
return mediaList
except Exception as e:
if debug == True: Log("ERROR: " + str(e))
def sesamstrasseCreateVideoObject(item, container = False):
if debug == True: Log("Running sesamstrasseCreateVideoObject()...")
if debug == True: Log("Creating VideoObject: " + str(item))
try:
vo = VideoClipObject(
key = Callback(sesamstrasseCreateVideoObject, item = item, container = True),
title = item['title'],
thumb = item['thumb'],
duration = item['duration'],
rating_key = item['url'],
items = []
)
# Lookup URL and create MediaObject.
mo = MediaObject(parts = [PartObject(key = Callback(sesamstrasseGetStreamingUrl, url = item['url']))])
# Append mediaobject to clipobject.
vo.items.append(mo)
if container:
return ObjectContainer(objects = [vo])
else:
return vo
except Exception as e:
if debug == True: Log("ERROR: " + str(e))
def sesamstrasseGetStreamingUrl(url):
if debug == True: Log("Running sesamstrasseGetStreamingUrl()...")
try:
quality = 'hd'
if ',sesamstrasse' in url:
regex_suffix_id = ',sesamstrasse(.+?).html'
try: suffix_id = re.findall(regex_suffix_id, url)[0]
except: suffix_id = '3000'
else: suffix_id = '3000'
content = getURL(url)
json_uuid = re.findall('player_image-(.+?)_', content)[0]
json_url = 'http://www.sesamstrasse.de/sendungsinfos/sesamstrasse%s-ppjson_image-%s.json' % (suffix_id, json_uuid)
json = getURL(json_url)
regex_qualities = '\.,(.+?),\.'
qualities = re.findall(regex_qualities, json)[-1].split(',')
if not (quality in qualities): quality = qualities[-1]
regex_url = '"src": "http://(.+?)"'
urls = re.findall(regex_url, json)
stream_url = ''
for url in urls:
if url.endswith('.mp4'):
stream_url = 'http://' + url[:-6] + quality + '.mp4'
break
if not stream_url: return
if debug == True: Log("Playing video URL: " + stream_url)
return Redirect(stream_url)
except Exception as e:
if debug == True: Log("ERROR: " + str(e))<|fim▁end|>
|
title = date+" - "+title
|
<|file_name|>get-all-users.js<|end_file_name|><|fim▁begin|><|fim▁hole|>
module.exports = function(req, res) {
var result = User.find ({})
.where('loginName').ne('root')
.select('id loginName name claims')
.exec(function(err, users) {
res.json(users);
});
};<|fim▁end|>
|
var User = require('../../models/user');
|
<|file_name|>args.py<|end_file_name|><|fim▁begin|>from webargs import fields
<|fim▁hole|>
user_args = {
'email': fields.Str(validate=Email, required=True),
'password': fields.Str(validate=password, required=True)
}
role_args = {
'name': fields.Str(required=True),
'description': fields.Str(required=True)
}<|fim▁end|>
|
from ..api.validators import Email, password
|
<|file_name|>test_weather.py<|end_file_name|><|fim▁begin|>"""Test for the smhi weather entity."""
import asyncio
from datetime import datetime
import logging
from unittest.mock import AsyncMock, Mock, patch
from smhi.smhi_lib import APIURL_TEMPLATE, SmhiForecastException
from homeassistant.components.smhi import weather as weather_smhi
from homeassistant.components.smhi.const import ATTR_SMHI_CLOUDINESS
from homeassistant.components.weather import (
ATTR_FORECAST_CONDITION,
ATTR_FORECAST_PRECIPITATION,
ATTR_FORECAST_TEMP,
ATTR_FORECAST_TEMP_LOW,
ATTR_FORECAST_TIME,
ATTR_WEATHER_ATTRIBUTION,
ATTR_WEATHER_HUMIDITY,
ATTR_WEATHER_PRESSURE,
ATTR_WEATHER_TEMPERATURE,
ATTR_WEATHER_VISIBILITY,
ATTR_WEATHER_WIND_BEARING,
ATTR_WEATHER_WIND_SPEED,
DOMAIN as WEATHER_DOMAIN,
)
from homeassistant.const import TEMP_CELSIUS
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry, load_fixture
_LOGGER = logging.getLogger(__name__)
TEST_CONFIG = {"name": "test", "longitude": "17.84197", "latitude": "59.32624"}
async def test_setup_hass(hass: HomeAssistant, aioclient_mock) -> None:
"""Test for successfully setting up the smhi platform.
This test are deeper integrated with the core. Since only
config_flow is used the component are setup with
"async_forward_entry_setup". The actual result are tested
with the entity state rather than "per function" unity tests
"""
uri = APIURL_TEMPLATE.format(TEST_CONFIG["longitude"], TEST_CONFIG["latitude"])
api_response = load_fixture("smhi.json")
aioclient_mock.get(uri, text=api_response)
entry = MockConfigEntry(domain="smhi", data=TEST_CONFIG)
await hass.config_entries.async_forward_entry_setup(entry, WEATHER_DOMAIN)
await hass.async_block_till_done()
assert aioclient_mock.call_count == 1
# Testing the actual entity state for
# deeper testing than normal unity test
state = hass.states.get("weather.smhi_test")
assert state.state == "sunny"
assert state.attributes[ATTR_SMHI_CLOUDINESS] == 50
assert state.attributes[ATTR_WEATHER_ATTRIBUTION].find("SMHI") >= 0
assert state.attributes[ATTR_WEATHER_HUMIDITY] == 55
assert state.attributes[ATTR_WEATHER_PRESSURE] == 1024<|fim▁hole|> assert state.attributes[ATTR_WEATHER_WIND_SPEED] == 7
assert state.attributes[ATTR_WEATHER_WIND_BEARING] == 134
_LOGGER.error(state.attributes)
assert len(state.attributes["forecast"]) == 4
forecast = state.attributes["forecast"][1]
assert forecast[ATTR_FORECAST_TIME] == "2018-09-02T12:00:00"
assert forecast[ATTR_FORECAST_TEMP] == 21
assert forecast[ATTR_FORECAST_TEMP_LOW] == 6
assert forecast[ATTR_FORECAST_PRECIPITATION] == 0
assert forecast[ATTR_FORECAST_CONDITION] == "partlycloudy"
def test_properties_no_data(hass: HomeAssistant) -> None:
"""Test properties when no API data available."""
weather = weather_smhi.SmhiWeather("name", "10", "10")
weather.hass = hass
assert weather.name == "name"
assert weather.should_poll is True
assert weather.temperature is None
assert weather.humidity is None
assert weather.wind_speed is None
assert weather.wind_bearing is None
assert weather.visibility is None
assert weather.pressure is None
assert weather.cloudiness is None
assert weather.condition is None
assert weather.forecast is None
assert weather.temperature_unit == TEMP_CELSIUS
# pylint: disable=protected-access
def test_properties_unknown_symbol() -> None:
"""Test behaviour when unknown symbol from API."""
hass = Mock()
data = Mock()
data.temperature = 5
data.mean_precipitation = 0.5
data.total_precipitation = 1
data.humidity = 5
data.wind_speed = 10
data.wind_direction = 180
data.horizontal_visibility = 6
data.pressure = 1008
data.cloudiness = 52
data.symbol = 100 # Faulty symbol
data.valid_time = datetime(2018, 1, 1, 0, 1, 2)
data2 = Mock()
data2.temperature = 5
data2.mean_precipitation = 0.5
data2.total_precipitation = 1
data2.humidity = 5
data2.wind_speed = 10
data2.wind_direction = 180
data2.horizontal_visibility = 6
data2.pressure = 1008
data2.cloudiness = 52
data2.symbol = 100 # Faulty symbol
data2.valid_time = datetime(2018, 1, 1, 12, 1, 2)
data3 = Mock()
data3.temperature = 5
data3.mean_precipitation = 0.5
data3.total_precipitation = 1
data3.humidity = 5
data3.wind_speed = 10
data3.wind_direction = 180
data3.horizontal_visibility = 6
data3.pressure = 1008
data3.cloudiness = 52
data3.symbol = 100 # Faulty symbol
data3.valid_time = datetime(2018, 1, 2, 12, 1, 2)
testdata = [data, data2, data3]
weather = weather_smhi.SmhiWeather("name", "10", "10")
weather.hass = hass
weather._forecasts = testdata
assert weather.condition is None
forecast = weather.forecast[0]
assert forecast[ATTR_FORECAST_CONDITION] is None
# pylint: disable=protected-access
async def test_refresh_weather_forecast_exceeds_retries(hass) -> None:
"""Test the refresh weather forecast function."""
with patch.object(
hass.helpers.event, "async_call_later"
) as call_later, patch.object(
weather_smhi.SmhiWeather,
"get_weather_forecast",
side_effect=SmhiForecastException(),
):
weather = weather_smhi.SmhiWeather("name", "17.0022", "62.0022")
weather.hass = hass
weather._fail_count = 2
await weather.async_update()
assert weather._forecasts is None
assert not call_later.mock_calls
async def test_refresh_weather_forecast_timeout(hass) -> None:
"""Test timeout exception."""
weather = weather_smhi.SmhiWeather("name", "17.0022", "62.0022")
weather.hass = hass
with patch.object(
hass.helpers.event, "async_call_later"
) as call_later, patch.object(
weather_smhi.SmhiWeather, "retry_update"
), patch.object(
weather_smhi.SmhiWeather,
"get_weather_forecast",
side_effect=asyncio.TimeoutError,
):
await weather.async_update()
assert len(call_later.mock_calls) == 1
# Assert we are going to wait RETRY_TIMEOUT seconds
assert call_later.mock_calls[0][1][0] == weather_smhi.RETRY_TIMEOUT
async def test_refresh_weather_forecast_exception() -> None:
"""Test any exception."""
hass = Mock()
weather = weather_smhi.SmhiWeather("name", "17.0022", "62.0022")
weather.hass = hass
with patch.object(
hass.helpers.event, "async_call_later"
) as call_later, patch.object(
weather,
"get_weather_forecast",
side_effect=SmhiForecastException(),
):
await weather.async_update()
assert len(call_later.mock_calls) == 1
# Assert we are going to wait RETRY_TIMEOUT seconds
assert call_later.mock_calls[0][1][0] == weather_smhi.RETRY_TIMEOUT
async def test_retry_update():
"""Test retry function of refresh forecast."""
hass = Mock()
weather = weather_smhi.SmhiWeather("name", "17.0022", "62.0022")
weather.hass = hass
with patch.object(weather, "async_update", AsyncMock()) as update:
await weather.retry_update(None)
assert len(update.mock_calls) == 1
def test_condition_class():
"""Test condition class."""
def get_condition(index: int) -> str:
"""Return condition given index."""
return [k for k, v in weather_smhi.CONDITION_CLASSES.items() if index in v][0]
# SMHI definitions as follows, see
# http://opendata.smhi.se/apidocs/metfcst/parameters.html
# 1. Clear sky
assert get_condition(1) == "sunny"
# 2. Nearly clear sky
assert get_condition(2) == "sunny"
# 3. Variable cloudiness
assert get_condition(3) == "partlycloudy"
# 4. Halfclear sky
assert get_condition(4) == "partlycloudy"
# 5. Cloudy sky
assert get_condition(5) == "cloudy"
# 6. Overcast
assert get_condition(6) == "cloudy"
# 7. Fog
assert get_condition(7) == "fog"
# 8. Light rain showers
assert get_condition(8) == "rainy"
# 9. Moderate rain showers
assert get_condition(9) == "rainy"
# 18. Light rain
assert get_condition(18) == "rainy"
# 19. Moderate rain
assert get_condition(19) == "rainy"
# 10. Heavy rain showers
assert get_condition(10) == "pouring"
# 20. Heavy rain
assert get_condition(20) == "pouring"
# 21. Thunder
assert get_condition(21) == "lightning"
# 11. Thunderstorm
assert get_condition(11) == "lightning-rainy"
# 15. Light snow showers
assert get_condition(15) == "snowy"
# 16. Moderate snow showers
assert get_condition(16) == "snowy"
# 17. Heavy snow showers
assert get_condition(17) == "snowy"
# 25. Light snowfall
assert get_condition(25) == "snowy"
# 26. Moderate snowfall
assert get_condition(26) == "snowy"
# 27. Heavy snowfall
assert get_condition(27) == "snowy"
# 12. Light sleet showers
assert get_condition(12) == "snowy-rainy"
# 13. Moderate sleet showers
assert get_condition(13) == "snowy-rainy"
# 14. Heavy sleet showers
assert get_condition(14) == "snowy-rainy"
# 22. Light sleet
assert get_condition(22) == "snowy-rainy"
# 23. Moderate sleet
assert get_condition(23) == "snowy-rainy"
# 24. Heavy sleet
assert get_condition(24) == "snowy-rainy"<|fim▁end|>
|
assert state.attributes[ATTR_WEATHER_TEMPERATURE] == 17
assert state.attributes[ATTR_WEATHER_VISIBILITY] == 50
|
<|file_name|>ob_equality.py<|end_file_name|><|fim▁begin|># Copyright (C) 2013-2021 Roland Lutz
#
# 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.<|fim▁hole|># 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.
import xorn.storage
rev = xorn.storage.Revision()
ob0 = rev.add_object(xorn.storage.Line())
ob1, = rev.get_objects()
ob2 = rev.add_object(xorn.storage.Line())
assert ob0 is not ob1
assert ob0 == ob1
assert hash(ob0) == hash(ob1)
assert ob0 is not ob2
assert ob0 != ob2
assert hash(ob0) != hash(ob2)
assert ob1 is not ob2
assert ob1 != ob2
assert hash(ob1) != hash(ob2)<|fim▁end|>
|
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
<|file_name|>BenchmarkTest11613.java<|end_file_name|><|fim▁begin|>/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark 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
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest11613")
public class BenchmarkTest11613 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request );
String param = scr.getTheParameter("foo");
String bar = new Test().doSomething(param);
try {
java.util.Properties Benchmarkprops = new java.util.Properties();
Benchmarkprops.load(this.getClass().getClassLoader().getResourceAsStream("Benchmark.properties"));
String algorithm = Benchmarkprops.getProperty("cryptoAlg1", "DESede/ECB/PKCS5Padding");
javax.crypto.Cipher c = javax.crypto.Cipher.getInstance(algorithm);
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case");
throw new ServletException(e);
} catch (javax.crypto.NoSuchPaddingException e) {
System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case");
throw new ServletException(e);
}
response.getWriter().println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String) executed");
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar;<|fim▁hole|>
// Simple ? condition that assigns constant to bar on true condition
int i = 106;
bar = (7*18) + i > 200 ? "This_should_always_happen" : param;
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass<|fim▁end|>
| |
<|file_name|>table6.py<|end_file_name|><|fim▁begin|>from parameter import *
from parse_digit import *
from os import system
cmd = "make -C tools >/dev/null 2>/dev/null;mkdir log model 2>/dev/null"
system(cmd)
#remove those method/data you are not interested in its result
methodlist = ['random-forest','gbdt']
data = ['MQ2007','MQ2008','MSLR','YAHOO_SET1','YAHOO_SET2','MQ2007-list','MQ2008-list']
print "\\begin{tabular}{l"+"|rrr"*len(methodlist) +"}"
if 'random-forest' in methodlist:
print "& \\multicolumn{3}{|c}{Random forests}",
if 'gbdt' in methodlist:
print "& \\multicolumn{3}{|c}{GBDT}",
print "\\\\"
print "& Training & Pairwise & "*len(methodlist), "\\\\"
print "Data set "+"& time (s) & accuracy & NDCG "*len(methodlist) +"\\\\"
print "\\hline"
for d in data:
o = []
for method in methodlist:
dp = log_path + d + '.' + method+ '.fewtrees.log'
try:
tmp_data = open(dp,'r').readlines()
except:
traindata = path + data_path[d]
testdata = path + test_path[d]
if method == 'random-forest':
cmd = "%s -f %s -F -z -p %s -k %s -t %s %s %s ./tmp_file >> %s 2>/dev/null"%(tree_exe,num_feature[d],num_processors, num_sampled_feature[d], tree_num_few[method],traindata,testdata,dp)
elif method == 'gbdt':
model = model_path + d + '.' + method + '.' + 'fewtrees.model'
cmd = "mpirun -np %s %s %s %s %s 4 100 0.1 -m >%s 2>> %s"%(8,gbrt_exe,traindata,num_instance[d],num_feature[d]+1,model,dp)
system('echo \'%s\' >> %s'%(cmd, dp))
system(cmd)
cmd = "cat %s|python %s ./tmp_exe"%(model,gbrt_compile_test)
system('echo \'%s\' >> %s'%(cmd, dp))
system(cmd)
cmd = "cat %s|./tmp_exe > ./tmp_file"%testdata
system('echo \'%s\' >> %s'%(cmd, dp))
system(cmd)
cmd = "tools/eval ./tmp_file %s >> %s;rm -f tmp_file ./tmp_exe*"%(testdata, dp)
system('echo \'%s\' >> %s'%(cmd, dp))
system(cmd)
tmp_data = open(dp,'r').readlines()
for l in tmp_data:
if 'time' in l:
time = l.split(' ')[-1].strip()
digit = FormatWithCommas("%5.1f",float(time))
digit = "$"+digit+"$"
o.append(digit)
if 'accuracy' in l:
acc = l.split(' ')[-2].strip().strip('%')
digit = "$%5.2f$"%float(acc)+"\\%"
o.append(digit)
if d == 'YAHOO_SET1' or d == 'YAHOO_SET2':
if '(YAHOO)' in l:
ndcg = l.split(' ')[-2].strip()
digit = "$%1.4f$"%float(ndcg)
o.append(digit)
else:
if 'Mean' in l:<|fim▁hole|> digit = "$%1.4f$"%float(ndcg)
o.append(digit)
print output_name[d],
for l in o:
print "& %s "%l,
print "\\\\"
print "\\end{tabular}"<|fim▁end|>
|
if d == 'MQ2007-list' or d == 'MQ2008-list':
digit = "NA"
else:
ndcg = l.split(' ')[-2].strip()
|
<|file_name|>windows.rs<|end_file_name|><|fim▁begin|>#![cfg(windows)]
use std::{ptr, thread, time};
use std::sync::mpsc::{channel, Sender};
use winapi::{self, KEY_EVENT_RECORD};
use kernel32;
use user32;
use tvis_util::Handle;
use input::{Event, InputEvent, Key, Mods};
use {Error, Result};
const SHUTDOWN_KEY: u16 = 0x1111;
const SIGINT_KEY: u16 = 0x2222;
const SIGQUIT_KEY: u16 = 0x3333;
// winapi-rs omits these.
const EVENT_CONSOLE_LAYOUT: winapi::DWORD = 0x4005;
const WINEVENT_OUTOFCONTEXT: winapi::DWORD = 0;
const WINEVENT_SKIPOWNTHREAD: winapi::DWORD = 1;
pub(crate) fn start_threads(tx: Sender<Box<Event>>) -> Result<()> {
register_ctrl_handler()?;
let (init_tx, init_rx) = channel();
thread::spawn(move || unsafe {
create_session_wnd()
.and_then(|_| register_layout_hook())
.and_then(|_| {
init_tx.send(Ok(())).unwrap();
run_message_pump();
Ok(())
})
.or_else(|e| init_tx.send(Err(e)))
.unwrap();
});
init_rx.recv().unwrap()?;
thread::spawn(move || raw_event_loop(tx));
Ok(())
}
fn register_ctrl_handler() -> Result<()> {
extern "system" fn handler(ctrl_type: winapi::DWORD) -> winapi::BOOL {
match ctrl_type {
winapi::CTRL_C_EVENT => {
write_fake_key(SIGINT_KEY);
1
}
winapi::CTRL_BREAK_EVENT => {
write_fake_key(SIGQUIT_KEY);
1
}
winapi::CTRL_CLOSE_EVENT => {
write_fake_key(SHUTDOWN_KEY);
thread::sleep(time::Duration::from_secs(5));
0
}
_ => 0,
}
}
match unsafe { kernel32::SetConsoleCtrlHandler(Some(handler), 1) } {
0 => Error::ffi_err("SetConsoleCtrlHandler failed"),
_ => Ok(()),
}
}
// winapi-rs omits this.
#[allow(non_snake_case)]
#[repr(C)]
struct WNDCLASS {
pub style: winapi::UINT,
pub lpfnWndProc: winapi::WNDPROC,
pub cbClsExtra: winapi::c_int,
pub cbWndExtra: winapi::c_int,
pub instance: winapi::HINSTANCE,
pub hIcon: winapi::HICON,
pub hCursor: winapi::HCURSOR,
pub hbrBackground: winapi::HBRUSH,
pub lpszMenuName: winapi::LPCSTR,
pub lpszClassName: winapi::LPCSTR,
}
// winapi-rs omits this.
extern "system" {
fn RegisterClassA(lpWndClass: *const WNDCLASS) -> winapi::ATOM;
}
unsafe fn create_session_wnd() -> Result<()> {
extern "system" fn wnd_proc(
hwnd: winapi::HWND,
msg: winapi::UINT,
wparam: winapi::WPARAM,
lparam: winapi::LPARAM,
) -> winapi::LRESULT {
match msg {
winapi::WM_ENDSESSION => {
write_fake_key(SHUTDOWN_KEY);
thread::sleep(time::Duration::from_secs(5));
0
}
_ => unsafe {
user32::DefWindowProcA(hwnd, msg, wparam, lparam)
},
}
}
let mut wnd_class: WNDCLASS = ::std::mem::zeroed();
wnd_class.lpfnWndProc = Some(wnd_proc);
wnd_class.instance = kernel32::GetModuleHandleA(ptr::null());
if wnd_class.instance.is_null() {
return Error::ffi_err("GetModuleHandle failed");
}
wnd_class.lpszClassName =
"HiddenShutdownClass\x00".as_ptr() as *const _ as winapi::LPCSTR;
if 0 == RegisterClassA(&wnd_class) {
return Error::ffi_err("RegisterClass failed");
}
let hwnd = user32::CreateWindowExA(
0,
"HiddenShutdownClass\x00".as_ptr() as *const _ as winapi::LPCSTR,
ptr::null(),
0,
0,
0,
0,
0,
ptr::null_mut(),
ptr::null_mut(),
kernel32::GetModuleHandleA(ptr::null()),
ptr::null_mut(),
);
if hwnd.is_null() {
return Error::ffi_err("CreateWindowEx failed");
}
Ok(())
}
fn register_layout_hook() -> Result<()> {
extern "system" fn layout_hook(
_: winapi::HWINEVENTHOOK,
_: winapi::DWORD,
hwnd: winapi::HWND,
_: winapi::LONG,
_: winapi::LONG,
_: winapi::DWORD,
_: winapi::DWORD,
) {
// Filter out events from consoles in other processes.
if hwnd != unsafe { kernel32::GetConsoleWindow() } {
return;
}
// Use an "empty" window buffer size event as a resize
// notification.
let mut ir: winapi::INPUT_RECORD =
unsafe { ::std::mem::uninitialized() };
ir.EventType = winapi::WINDOW_BUFFER_SIZE_EVENT;
{
let ir = unsafe { ir.WindowBufferSizeEvent_mut() };
ir.dwSize.X = 0;
ir.dwSize.Y = 0;
}
let con_hndl = Handle::Stdin.win_handle();
let mut write_count: winapi::DWORD = 0;
unsafe {
kernel32::WriteConsoleInputW(con_hndl, &ir, 1, &mut write_count);
}
}
let hook = unsafe {
user32::SetWinEventHook(
EVENT_CONSOLE_LAYOUT,
EVENT_CONSOLE_LAYOUT,
ptr::null_mut(),
Some(layout_hook),
// Listen for events from all threads/processes and filter
// in the callback, because there doesn't seem to be a way
// to get the id for the thread that actually delivers
// WinEvents for the console (it's not the thread returned
// by GetWindowThreadProcessId(GetConsoleWindow())).
0,
0,
WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNTHREAD,
)
};
if hook.is_null() {
return Error::ffi_err("SetWinEventHook failed");
}
Ok(())
}
// Windows events and WinEvents require a thread with a message pump.
unsafe fn run_message_pump() {
let mut msg: winapi::MSG = ::std::mem::uninitialized();
while 0 != user32::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) {
user32::TranslateMessage(&msg);
user32::DispatchMessageW(&msg);
}
}
fn write_fake_key(key_code: u16) -> winapi::BOOL {
let mut key: winapi::INPUT_RECORD =
unsafe { ::std::mem::uninitialized() };
key.EventType = winapi::KEY_EVENT;
{
let key = unsafe { key.KeyEvent_mut() };
key.bKeyDown = 1;
key.wVirtualKeyCode = key_code;
}
let con_hndl = Handle::Stdin.win_handle();
let mut write_count: winapi::DWORD = 0;
unsafe {
kernel32::WriteConsoleInputW(con_hndl, &key, 1, &mut write_count)
}
}
fn raw_event_loop(tx: Sender<Box<Event>>) {
// TODO: Handle FFI errors/channel send errors (until then, just
// exit when the event loop exits).
let _ = event_loop(tx);
}
#[cfg_attr(feature = "cargo-clippy",
allow(needless_range_loop, needless_pass_by_value))]
fn event_loop(tx: Sender<Box<Event>>) -> Result<()> {
let mut resizer = Resizer::from_conout()?;
let in_hndl = Handle::Stdin.win_handle();
let mut buffer: [winapi::INPUT_RECORD; 128] =
unsafe { ::std::mem::uninitialized() };
let mut key_reader = KeyReader::new(tx.clone());
let mut mouse_reader = MouseReader::new(tx.clone());
loop {
let mut read_count: winapi::DWORD = 0;
unsafe {
if kernel32::ReadConsoleInputW(
in_hndl,
buffer.as_mut_ptr(),
128,
&mut read_count,
) == 0
{
return Error::ffi_err("ReadConsoleInputW failed");
}
}
for i in 0..read_count as usize {
let input = buffer[i];
if input.EventType == winapi::FOCUS_EVENT
|| input.EventType == winapi::MENU_EVENT
{
continue;
}
match input.EventType {
winapi::MOUSE_EVENT => {
let mevt = unsafe { input.MouseEvent() };
mouse_reader.read(mevt)?
}
winapi::KEY_EVENT => {
let kevt = unsafe { input.KeyEvent() };
match kevt.wVirtualKeyCode {
SHUTDOWN_KEY => return Ok(()),
SIGINT_KEY => tx.send(Box::new(InputEvent::Interrupt))?,
SIGQUIT_KEY => tx.send(Box::new(InputEvent::Break))?,
_ => key_reader.read(kevt)?,
}
}
winapi::WINDOW_BUFFER_SIZE_EVENT => if resizer.update()? {
tx.send(Box::new(InputEvent::Repaint))?;
},
_ => unreachable!(),
};
}
}
}
struct KeyReader {
surrogate: Option<u16>,
tx: Sender<Box<Event>>,
}
impl KeyReader {<|fim▁hole|> }
}
fn send(&self, event: InputEvent) -> Result<()> {
self.tx.send(Box::new(event))?;
Ok(())
}
fn read(&mut self, evt: &KEY_EVENT_RECORD) -> Result<()> {
if self.surrogate_pair(evt)? {
return Ok(());
}
if evt.bKeyDown == 0 {
return Ok(());
}
if self.special_key(evt)? {
return Ok(());
}
self.key(evt)
}
fn surrogate_pair(&mut self, evt: &KEY_EVENT_RECORD) -> Result<bool> {
let s2 = u32::from(evt.UnicodeChar);
if let Some(s1) = self.surrogate.take() {
if s2 >= 0xdc00 && s2 <= 0xdfff {
let s1 = u32::from(s1);
let mut utf8 = [0u8; 4];
let c: u32 = 0x1_0000 | ((s1 - 0xd800) << 10) | (s2 - 0xdc00);
let c = ::std::char::from_u32(c).unwrap();
let len = c.encode_utf8(&mut utf8).len();
let kevt = InputEvent::Key(
Key::Char(c, utf8, len),
Mods::win32(evt.dwControlKeyState),
);
self.send(kevt)?;
return Ok(true);
} else {
let err = Key::Err(
[
0xe0 | (s2 >> 12) as u8,
0x80 | ((s2 >> 6) & 0x3f) as u8,
0x80 | (s2 & 0x3f) as u8,
0,
],
3,
);
self.send(InputEvent::Key(err, Mods::empty()))?;
}
}
if s2 >= 0xd800 && s2 <= 0xdbff {
self.surrogate = Some(s2 as u16);
return Ok(true);
}
Ok(false)
}
fn special_key(&self, evt: &KEY_EVENT_RECORD) -> Result<bool> {
let skey = match evt.wVirtualKeyCode {
0x08 => Key::BS,
0x09 => Key::Tab,
0x0d => Key::Enter,
0x1b => Key::Esc,
0x21 => Key::PgUp,
0x22 => Key::PgDn,
0x23 => Key::End,
0x24 => Key::Home,
0x25 => Key::Left,
0x26 => Key::Up,
0x27 => Key::Right,
0x28 => Key::Down,
0x2d => Key::Ins,
0x2e => Key::Del,
0x70 => Key::F1,
0x71 => Key::F2,
0x72 => Key::F3,
0x73 => Key::F4,
0x74 => Key::F5,
0x75 => Key::F6,
0x76 => Key::F7,
0x77 => Key::F8,
0x78 => Key::F9,
0x79 => Key::F10,
0x7a => Key::F11,
0x7b => Key::F12,
_ => return Ok(false),
};
self.send(InputEvent::Key(skey, Mods::win32(evt.dwControlKeyState)))?;
Ok(true)
}
fn key(&self, evt: &KEY_EVENT_RECORD) -> Result<()> {
use std::char;
use input::Mods;
let uc = evt.UnicodeChar;
let mods = Mods::win32(evt.dwControlKeyState);
let (key, mods) = if uc == 0 {
return Ok(());
} else if uc < 0x80 {
match uc {
3 => return self.send(InputEvent::Interrupt),
8 => (Key::BS, mods - Mods::CTRL),
9 => (Key::Tab, mods - Mods::CTRL),
13 => (Key::Enter, mods - Mods::CTRL),
27 => (Key::Esc, mods - Mods::CTRL),
b if b < 32 => (Key::ascii(b as u8 + 64), mods | Mods::CTRL),
_ => (Key::ascii(uc as u8), mods),
}
} else if uc < 0x800 {
(
Key::Char(
unsafe { char::from_u32_unchecked(uc as u32) },
[0xc0 | (uc >> 6) as u8, 0x80 | (uc & 0x3f) as u8, 0, 0],
2,
),
mods,
)
} else {
// Surrogate pairs have already been handled.
(
Key::Char(
unsafe { char::from_u32_unchecked(uc as u32) },
[
0xe0 | (uc >> 12) as u8,
0x80 | ((uc >> 6) & 0x3f) as u8,
0x80 | (uc & 0x3f) as u8,
0,
],
3,
),
mods,
)
};
self.send(InputEvent::Key(key, mods))?;
Ok(())
}
}
bitflags! {
#[derive(Default)]
pub struct Btn: u32 {
const LEFT = 0x01;
const RIGHT = 0x02;
const MIDDLE = 0x04;
}
}
pub struct MouseReader {
tx: Sender<Box<Event>>,
coords: (i32, i32),
btns: Btn,
}
impl MouseReader {
fn new(tx: Sender<Box<Event>>) -> MouseReader {
MouseReader {
tx,
coords: (-1, -1),
btns: Btn::empty(),
}
}
fn send(&self, event: InputEvent) -> Result<()> {
self.tx.send(Box::new(event))?;
Ok(())
}
fn read(&mut self, evt: &winapi::MOUSE_EVENT_RECORD) -> Result<()> {
use input::ButtonMotion::*;
use input::MouseButton::*;
use input::WheelMotion::*;
let coords = (
(evt.dwMousePosition.X as u16),
(evt.dwMousePosition.Y as u16),
);
let mods = Mods::win32(evt.dwControlKeyState);
match evt.dwEventFlags {
0 | 2 => {
let new_btns = Btn::from_bits(evt.dwButtonState & 0x7).unwrap();
let presses = new_btns - self.btns;
let releases = self.btns - new_btns;
self.btns = new_btns;
if presses.contains(Btn::LEFT) {
let mevt = InputEvent::Mouse(Press, Left, mods, coords);
self.send(mevt)?;
}
if presses.contains(Btn::MIDDLE) {
let mevt = InputEvent::Mouse(Press, Middle, mods, coords);
self.send(mevt)?;
}
if presses.contains(Btn::RIGHT) {
let mevt = InputEvent::Mouse(Press, Right, mods, coords);
self.send(mevt)?;
}
if releases.contains(Btn::LEFT) {
let mevt = InputEvent::Mouse(Release, Left, mods, coords);
self.send(mevt)?;
}
if releases.contains(Btn::MIDDLE) {
let mevt = InputEvent::Mouse(Release, Middle, mods, coords);
self.send(mevt)?;
}
if releases.contains(Btn::RIGHT) {
let mevt = InputEvent::Mouse(Release, Right, mods, coords);
self.send(mevt)?;
}
}
1 => if (i32::from(coords.0), i32::from(coords.1)) != self.coords {
let mevt = InputEvent::MouseMove(mods, coords);
self.send(mevt)?;
},
4 => {
let mevt = if (evt.dwButtonState >> 16) < 0x8000 {
InputEvent::MouseWheel(Up, mods, coords)
} else {
InputEvent::MouseWheel(Down, mods, coords)
};
self.send(mevt)?;
}
_ => (),
}
self.coords = (i32::from(coords.0), i32::from(coords.1));
Ok(())
}
}
pub(crate) struct Resizer {
hndl: winapi::HANDLE,
size: winapi::COORD,
}
impl Resizer {
fn from_conout() -> Result<Resizer> {
let hndl = unsafe {
kernel32::CreateFileA(
"CONOUT$\x00".as_ptr() as *const _ as winapi::LPCSTR,
winapi::GENERIC_READ | winapi::GENERIC_WRITE,
winapi::FILE_SHARE_READ | winapi::FILE_SHARE_WRITE,
ptr::null_mut(),
winapi::OPEN_EXISTING,
0,
ptr::null_mut(),
)
};
if hndl == winapi::INVALID_HANDLE_VALUE {
return Error::ffi_err("CreateFileA failed");
}
Resizer::from_hndl(hndl)
}
pub(crate) fn from_hndl(hndl: winapi::HANDLE) -> Result<Resizer> {
let mut resizer = Resizer {
hndl,
size: winapi::COORD { X: -1, Y: -1 },
};
resizer.update()?;
Ok(resizer)
}
fn update(&mut self) -> Result<bool> {
let mut csbi: winapi::CONSOLE_SCREEN_BUFFER_INFO =
unsafe { ::std::mem::uninitialized() };
if 0 == unsafe {
kernel32::GetConsoleScreenBufferInfo(self.hndl, &mut csbi)
} {
return Error::ffi_err("GetConsoleScreenBufferInfo failed");
}
let init_size = winapi::COORD {
X: csbi.srWindow.Right - csbi.srWindow.Left + 1,
Y: csbi.srWindow.Bottom - csbi.srWindow.Top + 1,
};
let window_offset = winapi::COORD {
X: csbi.srWindow.Left,
Y: csbi.srWindow.Top,
};
// Set the origin of the window to the origin of the buffer.
if window_offset.X != 0 || window_offset.Y != 0 {
let pos = winapi::SMALL_RECT {
Left: 0,
Top: 0,
Right: init_size.X - 1,
Bottom: init_size.Y - 1,
};
if 0 == unsafe {
kernel32::SetConsoleWindowInfo(self.hndl, 1, &pos)
} {
return Error::ffi_err("SetConsoleWindowInfo failed");
}
}
// Set the buffer size to (window width+1, window height+1).
// This allows resizing to a larger size, while minimizing the
// potential for layout changes caused by scrolling.
let max_win =
unsafe { kernel32::GetLargestConsoleWindowSize(self.hndl) };
if max_win.X == 0 && max_win.Y == 0 {
return Error::ffi_err("GetLargestConsoleWindowSize failed");
}
let size = winapi::COORD {
X: ::std::cmp::min(init_size.X + 1, max_win.X),
Y: ::std::cmp::min(init_size.Y + 1, max_win.Y),
};
if size.X != self.size.X || size.Y != self.size.Y {
if 0 == unsafe {
kernel32::SetConsoleScreenBufferSize(self.hndl, size)
} {
return Error::ffi_err("SetConsoleScreenBufferSize failed");
}
self.size = size;
return Ok(true);
}
Ok(false)
}
}<|fim▁end|>
|
fn new(tx: Sender<Box<Event>>) -> KeyReader {
KeyReader {
surrogate: None,
tx,
|
<|file_name|>parser.rs<|end_file_name|><|fim▁begin|>use expr::{Expr, BinOp, UnOp, Dec};
use parser::lexer::Lexer;
use parser::token::Token;
use parser::parser_error::ParserError;
use std::result;
pub type Result<T> = result::Result<T, ParserError>;
struct Parser {
lexer: Lexer,
current_token: Token,
}
impl Parser {
pub fn new(lexer: Lexer, token: Token) -> Parser {
Parser {
lexer: lexer,
current_token: token,
}
}
fn current_token(&self) -> Token {
self.current_token.clone()
}
fn eat(&mut self, expected: Token) -> Result<()> {
let actual = self.current_token();
if expected != actual {
return Err(ParserError::UnexpectedToken(expected, actual))
}
self.current_token = self.lexer.get_next_token()?;
debug!("new current token: {:?}", self.current_token);
Ok(())
}
fn ternary(&mut self, e1: Expr, e2: Expr, e3: Expr) -> Expr {
Expr::Ternary(Box::new(e1), Box::new(e2), Box::new(e3))
}
fn binop(&mut self, bop: BinOp, e1: Expr, e2: Expr) -> Expr {
Expr::Bop(bop, Box::new(e1), Box::new(e2))
}
fn parse_fn_params(&mut self) -> Result<Vec<Expr>> {
let mut params = Vec::new();
let mut token = self.current_token();
while token != Token::RParen {
debug!("getting fn params");
let term = self.binop_expr()?;
params.push(term);
if self.current_token == Token::Comma {
self.eat(Token::Comma)?;
}
token = self.current_token();
}
Ok(params)
}
fn parse_fn_decl_params(&mut self) -> Result<Vec<Expr>> {
let mut params = Vec::new();
let mut token = self.current_token();
while token != Token::RParen {
debug!("getting fn decl params");
match token.clone() {
Token::Var(s) => {
self.eat(Token::Var(s.clone()))?;
params.push(Expr::Var(s));
},
Token::Comma => self.eat(Token::Comma)?,
_ => return Err(ParserError::InvalidToken(token, String::from("parsing fn decl params")))
}
token = self.current_token();
}
Ok(params)
}
fn parse_print(&mut self) -> Result<Expr> {
self.eat(Token::Print)?;
let term = self.binop_expr()?;
Ok(Expr::Print(Box::new(term)))
}
fn parse_print_var_name(&mut self) -> Result<Expr> {
self.eat(Token::PrintVarName)?;
self.eat(Token::LParen)?;
match self.current_token() {
Token::Var(s) => {
self.eat(Token::Var(s.clone()))?;
self.eat(Token::RParen)?;
Ok(Expr::PrintVarName(Box::new(Expr::Var(s))))
},
t => Err(ParserError::InvalidToken(t, String::from("parsing name for PrintVarName")))
}
}
fn parse_fn(&mut self) -> Result<Expr> {
debug!("parsing named fn...");
self.eat(Token::FnDecl)?;
let var = match self.current_token() {
Token::Var(s) => {
self.eat(Token::Var(s.clone()))?;
Some(Expr::Var(s))
},
_ => None,
};
self.eat(Token::LParen)?;
let params = self.parse_fn_decl_params()?;<|fim▁hole|> self.eat(Token::RBracket)?;
match var {
Some(v) => {
self.eat(Token::Seq)?;
let e3 = self.block()?;
let func = Expr::Func(Some(Box::new(v.clone())), Box::new(body.clone()), params);
Ok(Expr::Decl(Dec::DConst, Box::new(v), Box::new(func), Box::new(e3)))
},
None => {
let func = Expr::Func(None, Box::new(body.clone()), params);
// fn call rule
if self.current_token == Token::LParen {
self.eat(Token::LParen)?;
let params = self.parse_fn_params()?;
self.eat(Token::RParen)?;
Ok(Expr::FnCall(Box::new(func), params))
} else {
Ok(func)
}
}
}
}
fn parse_while(&mut self) -> Result<Expr> {
self.eat(Token::While)?;
self.eat(Token::LParen)?;
let e1 = self.statement()?;
self.eat(Token::RParen)?;
let e2 = self.factor()?;
self.eat(Token::Seq)?;
let e3 = self.block()?;
return Ok(Expr::While(
Box::new(e1.clone()),
Box::new(e1),
Box::new(e2.clone()),
Box::new(e2),
Box::new(e3)
));
}
fn parse_if(&mut self) -> Result<Expr> {
self.eat(Token::If)?;
let e1 = self.binop_expr()?;
let e2 = self.block()?;
let e3 = self.statement()?;
return Ok(self.ternary(e1, e2, e3));
}
fn factor(&mut self) -> Result<Expr> {
let e = match self.current_token() {
Token::Int(n) => {
self.eat(Token::Int(n.clone()))?;
Expr::Int(n)
},
Token::Bool(b) => {
self.eat(Token::Bool(b.clone()))?;
Expr::Bool(b)
},
Token::Var(s) => {
self.eat(Token::Var(s.clone()))?;
// fn call rule
if self.current_token == Token::LParen {
self.eat(Token::LParen)?;
let params = self.parse_fn_params()?;
self.eat(Token::RParen)?;
Expr::FnCall(Box::new(Expr::Var(s)), params)
} else {
Expr::Var(s)
}
},
Token::Give => {
self.eat(Token::Give)?;
self.eat(Token::LParen)?;
match self.current_token() {
Token::Var(s) => {
self.eat(Token::Var(s.clone()))?;
self.eat(Token::RParen)?;
Ok(Expr::Give(Box::new(Expr::Var(s))))
},
t => Err(ParserError::InvalidToken(t, String::from("parsing name for give")))
}?
},
Token::Print => {
self.parse_print()?
},
Token::PrintVarName => {
self.parse_print_var_name()?
},
Token::FnDecl => {
self.parse_fn()?
},
Token::VarDecl => {
self.eat(Token::VarDecl)?;
let var = self.term()?;
self.eat(Token::Assign)?;
let e2 = self.statement()?;
self.eat(Token::Seq)?;
let e3 = self.block()?;
Expr::Decl(Dec::DVar, Box::new(var), Box::new(e2), Box::new(e3))
},
Token::Let => {
self.eat(Token::Let)?;
let var = self.term()?;
self.eat(Token::Assign)?;
let e2 = self.statement()?;
self.eat(Token::Seq)?;
let e3 = self.block()?;
Expr::Decl(Dec::DConst, Box::new(var), Box::new(e2), Box::new(e3))
},
Token::If => {
self.parse_if()?
},
Token::Rebattle => {
self.eat(Token::Rebattle)?;
let e1 = self.binop_expr()?;
let e2 = self.block()?;
let e3 = self.statement()?;
self.ternary(e1, e2, e3)
},
Token::Else => {
self.eat(Token::Else)?;
self.statement()?
},
Token::While => {
self.parse_while()?
},
Token::LParen => {
self.eat(Token::LParen)?;
let node = self.statement()?;
self.eat(Token::RParen)?;
node
},
Token::LBracket => {
self.eat(Token::LBracket)?;
let node = self.block()?;
self.eat(Token::RBracket)?;
node
},
Token::Not => {
self.eat(Token::Not)?;
Expr::Uop(UnOp::Not, Box::new(self.factor()?))
},
Token::Minus => {
self.eat(Token::Minus)?;
Expr::Uop(UnOp::Neg, Box::new(self.factor()?))
},
Token::EOF => {
self.eat(Token::EOF)?;
Expr::Undefined
},
_ => {
return Err(ParserError::InvalidToken(self.current_token(), String::from("parsing factor")))
}
};
Ok(e)
}
pub fn term(&mut self) -> Result<Expr> {
let mut node = self.factor()?;
let mut op = self.current_token();
while op.is_term_op() {
self.eat(op.clone())?;
let right_node = self.term()?;
node = match op {
Token::Times => self.binop(BinOp::Times, node, right_node),
Token::Div => self.binop(BinOp::Div, node, right_node),
_ => return Err(ParserError::InvalidToken(op, String::from("parsing term")))
};
op = self.current_token();
}
Ok(node)
}
pub fn binop_expr(&mut self) -> Result<Expr> {
let mut node = self.term()?;
let mut op = self.current_token();
while op.is_expr_op() {
debug!("expr looping on op {:?}", op);
self.eat(op.clone())?;
let right_node = self.term()?;
node = match op {
Token::Plus => self.binop(BinOp::Plus, node, right_node),
Token::Minus => self.binop(BinOp::Minus, node, right_node),
Token::Eq => self.binop(BinOp::Eq, node, right_node),
Token::Ne => self.binop(BinOp::Ne, node, right_node),
Token::Leq => self.binop(BinOp::Leq, node, right_node),
Token::Geq => self.binop(BinOp::Geq, node, right_node),
Token::Lt => self.binop(BinOp::Lt, node, right_node),
Token::Gt => self.binop(BinOp::Gt, node, right_node),
Token::And => self.binop(BinOp::And, node, right_node),
Token::Or => self.binop(BinOp::Or, node, right_node),
Token::Mod => self.binop(BinOp::Mod, node, right_node),
_ => return Err(ParserError::InvalidToken(op, String::from("parsing binop expression")))
};
op = self.current_token();
}
Ok(node)
}
pub fn statement(&mut self) -> Result<Expr> {
let mut node = self.binop_expr()?;
let mut op = self.current_token();
while op.is_statement_op() {
self.eat(op.clone())?;
node = match op {
Token::Ternary => {
let e2 = self.block()?;
self.eat(Token::Else)?;
let e3 = self.statement()?;
self.ternary(node, e2, e3)
},
Token::Assign => {
let e2 = self.statement()?;
self.binop(BinOp::Assign, node, e2)
},
_ => return Err(ParserError::InvalidToken(op, String::from("parsing statement")))
};
op = self.current_token();
}
Ok(node)
}
pub fn block(&mut self) -> Result<Expr> {
let mut node = self.statement()?;
let mut op = self.current_token();
while op.is_block_op() {
self.eat(op.clone())?;
node = match op {
Token::Seq => {
let e2 = match self.current_token() {
Token::RBracket => Expr::Undefined,
_ => self.statement()?,
};
self.binop(BinOp::Seq, node, e2)
},
_ => return Err(ParserError::InvalidToken(op, String::from("parsing block")))
};
op = self.current_token();
}
Ok(node)
}
pub fn program(&mut self) -> Result<Expr> {
self.block()
}
}
pub fn parse(input: &str) -> Result<Expr> {
let mut lexer = Lexer::new(input.to_string());
let token = lexer.get_next_token()?;
let mut parser = Parser::new(lexer, token);
let expr = parser.program();
debug!("parsed expr: {:#?}", expr);
debug!("original: {:#?}", input);
expr
}<|fim▁end|>
|
self.eat(Token::RParen)?;
self.eat(Token::LBracket)?;
let body = self.block()?;
|
<|file_name|>django_settings.py<|end_file_name|><|fim▁begin|>from holodeck.settings import *
import os
import sys
# Django settings for Holodeck project.
PATH = os.path.split(os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]))))[0]
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '[email protected]'),
)
MANAGERS = ADMINS
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = False
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(PATH, 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(PATH, 'static')
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'nj1p6t#2(fe(e=e_96o05fhti6p#@^mwaqioq=(f(ma_unqvt='
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages"
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'holodeck.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'holodeck.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)<|fim▁hole|>
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'holodeck',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}<|fim▁end|>
| |
<|file_name|>models.py<|end_file_name|><|fim▁begin|>##-*-coding: utf-8 -*-
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Usage(models.Model):
ip = models.CharField(max_length=50)
method = models.CharField(max_length=3)
path = models.CharField(max_length=100)
params = models.CharField(max_length=255)
def __str__(self):
return self.ip
@python_2_unicode_compatible
class Element(models.Model):
name = models.CharField(max_length=10)
code = models.CharField(max_length=10)
def __str__(self):
return self.name
class Meta:
verbose_name = "ธาตุ"
verbose_name_plural = "ธาตุต่างๆ"
db_table = 'element'
@python_2_unicode_compatible
class Disease(models.Model):
name = models.CharField(max_length=100, unique=True)
description = models.CharField(max_length=255, null=True)
is_congenital = models.BooleanField(default=False)
created_by = models.CharField(max_length=50, null=True)
created_date = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True, null=True)
last_modified_by = models.CharField(max_length=30, null=True, blank=True)
def __str__(self):
return self.name
class Meta:
verbose_name = "เชื้อโรค"
verbose_name_plural = "กลุ่มเชื้อโรค"
db_table = 'disease'
class Nutrient(models.Model):
water = models.DecimalField(max_digits=14, decimal_places=4)
protein = models.DecimalField(max_digits=14, decimal_places=4)
fat = models.DecimalField(max_digits=14, decimal_places=4)
carbohydrate = models.DecimalField(max_digits=14, decimal_places=4)
dietary_fiber = models.DecimalField(max_digits=14, decimal_places=4)
ash = models.DecimalField(max_digits=14, decimal_places=4)
calcium = models.DecimalField(max_digits=14, decimal_places=4)
phosphorus = models.DecimalField(max_digits=14, decimal_places=4)
iron = models.DecimalField(max_digits=14, decimal_places=4)
retinol = models.DecimalField(max_digits=14, decimal_places=4)
beta_carotene = models.DecimalField(max_digits=14, decimal_places=4)
vitamin_a = models.DecimalField(max_digits=14, decimal_places=4)
vitamin_e = models.DecimalField(max_digits=14, decimal_places=4)
thiamin = models.DecimalField(max_digits=14, decimal_places=4)
riboflavin = models.DecimalField(max_digits=14, decimal_places=4)
niacin = models.DecimalField(max_digits=14, decimal_places=4)
vitamin_c = models.DecimalField(max_digits=14, decimal_places=4)
def __str__(self):
return 'id: ' + str(self._get_pk_val())
class Meta:
verbose_name = "สารอาหาร"
verbose_name_plural = "กลุ่มสารอาหาร"
db_table = 'nutrient'
@python_2_unicode_compatible
class IngredientCategory(models.Model):
name = models.CharField(max_length=50, unique=True)
created_by = models.CharField(max_length=50)
created_date = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True, null=True)
last_modified_by = models.CharField(max_length=30, null=True, blank=True)
def __str__(self):
return self.name
class Meta:
verbose_name = "หมวดหมู่วัตถุดิบ"
verbose_name_plural = "กลุ่มหมวดหมู่วัตถุดิบ"
db_table = 'ingredient_type'
@python_2_unicode_compatible
class FoodCategory(models.Model):
name = models.CharField(max_length=50, unique=True)
created_by = models.CharField(max_length=50)
created_date = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True, null=True)
last_modified_by = models.CharField(max_length=30, null=True, blank=True)
def __str__(self):
return self.name
class Meta:
verbose_name = "หมวดหมู่อาหาร"
verbose_name_plural = "กลุ่มหมวดหมู่อาหาร"
db_table = 'food_type'
@python_2_unicode_compatible
class Ingredient(models.Model):
name = models.CharField(max_length=100, unique=True)
description = models.CharField(max_length=255, blank=True, null=True)
calories = models.IntegerField(default=0)
nutrient = models.ForeignKey(Nutrient,
on_delete=models.SET_NULL,
blank=True,
null=True)
element = models.ForeignKey(Element,
on_delete=models.SET_NULL,
blank=True,
null=True)
category = models.ManyToManyField(IngredientCategory, blank=True)
healing = models.ManyToManyField(Disease, related_name="healing", blank=True)
affect = models.ManyToManyField(Disease, related_name="affect", blank=True)
code = models.IntegerField(default=0)
def __str__(self):
return self.name
class Meta:
verbose_name = "วัตถุดิบ"
verbose_name_plural = "กลุ่มวัตถุดิบ"
db_table = 'ingredient'
@python_2_unicode_compatible
class Food(models.Model):
name = models.CharField(max_length=100, unique=True)
description = models.CharField(max_length=255, blank=True, null=True, default="")
calories = models.IntegerField(default=0)
nutrient = models.ForeignKey(Nutrient,
on_delete=models.SET_NULL,
blank=True,
null=True)
ingredients = models.ManyToManyField(Ingredient, through='Menu')
category = models.ManyToManyField(FoodCategory)
created_by = models.CharField(max_length=50, default="")
created_date = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True, null=True)
last_modified_by = models.CharField(max_length=30, null=True, blank=True)
code = models.IntegerField(default=0)
def __str__(self):
return self.name
<|fim▁hole|> class Meta:
verbose_name = "อาหาร"
verbose_name_plural = "กลุ่มอาหาร"
db_table = 'food'
class Menu(models.Model):
food = models.ForeignKey(Food, on_delete=models.CASCADE)
ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
weight = models.DecimalField(max_digits=14, decimal_places=4)
name = models.CharField(max_length=100, blank=True, default="")
class Meta:
db_table = 'menu'<|fim▁end|>
| |
<|file_name|>fields.py<|end_file_name|><|fim▁begin|>from django.conf import settings
if 'django_select2' in settings.INSTALLED_APPS:
from django_select2.fields import AutoModelSelect2Field
class PageSearchField(AutoModelSelect2Field):<|fim▁hole|> search_fields = [
'title_set__title__icontains',
'title_set__menu_title__icontains',
'title_set__slug__icontains'
]
def get_queryset(self):
queryset = super(PageSearchField, self).get_queryset()
return queryset.distinct()
def security_check(self, request, *args, **kwargs):
user = request.user
if user and not user.is_anonymous() and user.is_staff:
return True
return False
class UserSearchField(AutoModelSelect2Field):
search_fields = ['username__icontains', 'firstname__icontains', 'lastname__icontains']
def security_check(self, request, *args, **kwargs):
user = request.user
if user and not user.is_anonymous() and user.is_staff:
return True
return False
def prepare_value(self, value):
if not value:
return None
return super(UserSearchField, self).prepare_value(value)<|fim▁end|>
| |
<|file_name|>syncgroups.go<|end_file_name|><|fim▁begin|>package storagesync
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// SyncGroupsClient is the microsoft Storage Sync Service API
type SyncGroupsClient struct {
BaseClient
}
// NewSyncGroupsClient creates an instance of the SyncGroupsClient client.
func NewSyncGroupsClient(subscriptionID string) SyncGroupsClient {
return NewSyncGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewSyncGroupsClientWithBaseURI creates an instance of the SyncGroupsClient client using a custom endpoint. Use this
// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
func NewSyncGroupsClientWithBaseURI(baseURI string, subscriptionID string) SyncGroupsClient {
return SyncGroupsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Create create a new SyncGroup.
// Parameters:
// resourceGroupName - the name of the resource group. The name is case insensitive.
// storageSyncServiceName - name of Storage Sync Service resource.
// syncGroupName - name of Sync Group resource.
// parameters - sync Group Body
func (client SyncGroupsClient) Create(ctx context.Context, resourceGroupName string, storageSyncServiceName string, syncGroupName string, parameters SyncGroupCreateParameters) (result SyncGroup, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/SyncGroupsClient.Create")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: client.SubscriptionID,
Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("storagesync.SyncGroupsClient", "Create", err.Error())
}
req, err := client.CreatePreparer(ctx, resourceGroupName, storageSyncServiceName, syncGroupName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "storagesync.SyncGroupsClient", "Create", nil, "Failure preparing request")
return
}
resp, err := client.CreateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storagesync.SyncGroupsClient", "Create", resp, "Failure sending request")
return
}
result, err = client.CreateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storagesync.SyncGroupsClient", "Create", resp, "Failure responding to request")
return
}
return
}
// CreatePreparer prepares the Create request.
func (client SyncGroupsClient) CreatePreparer(ctx context.Context, resourceGroupName string, storageSyncServiceName string, syncGroupName string, parameters SyncGroupCreateParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"storageSyncServiceName": autorest.Encode("path", storageSyncServiceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"syncGroupName": autorest.Encode("path", syncGroupName),
}
const APIVersion = "2018-04-02"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}/syncGroups/{syncGroupName}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateSender sends the Create request. The method will close the
// http.Response Body if it receives an error.
func (client SyncGroupsClient) CreateSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))<|fim▁hole|>// CreateResponder handles the response to the Create request. The method always
// closes the http.Response Body.
func (client SyncGroupsClient) CreateResponder(resp *http.Response) (result SyncGroup, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete delete a given SyncGroup.
// Parameters:
// resourceGroupName - the name of the resource group. The name is case insensitive.
// storageSyncServiceName - name of Storage Sync Service resource.
// syncGroupName - name of Sync Group resource.
func (client SyncGroupsClient) Delete(ctx context.Context, resourceGroupName string, storageSyncServiceName string, syncGroupName string) (result autorest.Response, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/SyncGroupsClient.Delete")
defer func() {
sc := -1
if result.Response != nil {
sc = result.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: client.SubscriptionID,
Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("storagesync.SyncGroupsClient", "Delete", err.Error())
}
req, err := client.DeletePreparer(ctx, resourceGroupName, storageSyncServiceName, syncGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "storagesync.SyncGroupsClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "storagesync.SyncGroupsClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storagesync.SyncGroupsClient", "Delete", resp, "Failure responding to request")
return
}
return
}
// DeletePreparer prepares the Delete request.
func (client SyncGroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, storageSyncServiceName string, syncGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"storageSyncServiceName": autorest.Encode("path", storageSyncServiceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"syncGroupName": autorest.Encode("path", syncGroupName),
}
const APIVersion = "2018-04-02"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}/syncGroups/{syncGroupName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client SyncGroupsClient) DeleteSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client SyncGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get get a given SyncGroup.
// Parameters:
// resourceGroupName - the name of the resource group. The name is case insensitive.
// storageSyncServiceName - name of Storage Sync Service resource.
// syncGroupName - name of Sync Group resource.
func (client SyncGroupsClient) Get(ctx context.Context, resourceGroupName string, storageSyncServiceName string, syncGroupName string) (result SyncGroup, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/SyncGroupsClient.Get")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: client.SubscriptionID,
Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("storagesync.SyncGroupsClient", "Get", err.Error())
}
req, err := client.GetPreparer(ctx, resourceGroupName, storageSyncServiceName, syncGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "storagesync.SyncGroupsClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storagesync.SyncGroupsClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storagesync.SyncGroupsClient", "Get", resp, "Failure responding to request")
return
}
return
}
// GetPreparer prepares the Get request.
func (client SyncGroupsClient) GetPreparer(ctx context.Context, resourceGroupName string, storageSyncServiceName string, syncGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"storageSyncServiceName": autorest.Encode("path", storageSyncServiceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"syncGroupName": autorest.Encode("path", syncGroupName),
}
const APIVersion = "2018-04-02"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}/syncGroups/{syncGroupName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client SyncGroupsClient) GetSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client SyncGroupsClient) GetResponder(resp *http.Response) (result SyncGroup, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListByStorageSyncService get a SyncGroup List.
// Parameters:
// resourceGroupName - the name of the resource group. The name is case insensitive.
// storageSyncServiceName - name of Storage Sync Service resource.
func (client SyncGroupsClient) ListByStorageSyncService(ctx context.Context, resourceGroupName string, storageSyncServiceName string) (result SyncGroupArray, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/SyncGroupsClient.ListByStorageSyncService")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: client.SubscriptionID,
Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("storagesync.SyncGroupsClient", "ListByStorageSyncService", err.Error())
}
req, err := client.ListByStorageSyncServicePreparer(ctx, resourceGroupName, storageSyncServiceName)
if err != nil {
err = autorest.NewErrorWithError(err, "storagesync.SyncGroupsClient", "ListByStorageSyncService", nil, "Failure preparing request")
return
}
resp, err := client.ListByStorageSyncServiceSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storagesync.SyncGroupsClient", "ListByStorageSyncService", resp, "Failure sending request")
return
}
result, err = client.ListByStorageSyncServiceResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storagesync.SyncGroupsClient", "ListByStorageSyncService", resp, "Failure responding to request")
return
}
return
}
// ListByStorageSyncServicePreparer prepares the ListByStorageSyncService request.
func (client SyncGroupsClient) ListByStorageSyncServicePreparer(ctx context.Context, resourceGroupName string, storageSyncServiceName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"storageSyncServiceName": autorest.Encode("path", storageSyncServiceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-04-02"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}/syncGroups", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByStorageSyncServiceSender sends the ListByStorageSyncService request. The method will close the
// http.Response Body if it receives an error.
func (client SyncGroupsClient) ListByStorageSyncServiceSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListByStorageSyncServiceResponder handles the response to the ListByStorageSyncService request. The method always
// closes the http.Response Body.
func (client SyncGroupsClient) ListByStorageSyncServiceResponder(resp *http.Response) (result SyncGroupArray, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}<|fim▁end|>
|
}
|
<|file_name|>qmanager-agent.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
import signal
import pickle
import platform
import socket
import time
from pika import BasicProperties
import portbuild.qthreads as qthreads
import portbuild.torrent as torrent
import portbuild.util as util
ready = []
class AgentProducer(qthreads.QueueProducerThread):
def __init__(self):
qthreads.QueueProducerThread.__init__(self)
def setup(self):
"""Set up AgentProducer."""
self.channel = self.connection.channel()
self.channel.add_on_return_callback(self.notify_return)
util.debug("AgentProducer is all set!")
<|fim▁hole|> def teardown(self):
"""Clean up AgentProducer."""
self.channel.close()
def notify(self, queue):
"""Send notification back to the head node."""
message = "Finished" # FIXME
util.log("Sending notification on {0}".format(queue))
props = BasicProperties(content_type="text/plain", delivery_mode=1)
self.channel.basic_publish(exchange="",
routing_key=queue,
mandatory=True,
immediate=True,
body=pickle.dumps(message),
properties=props)
def notify_return(self, method, header, body):
"""Notification was returned. Head node isn't listening anymore."""
# This actually is only triggered when the exchange doesn't exists,
# not when the queue doesn't exist.
print "Message returned!"
class AgentConsumer(qthreads.QueueConsumerThread):
def __init__(self):
qthreads.QueueConsumerThread.__init__(self)
def setup(self):
"""Set up AgentConsumer."""
self.arch = platform.machine()
self.hostname = socket.gethostname()
self.channel = self.connection.channel()
self.channel.queue_declare(queue=self.arch, durable=True, exclusive=False, auto_delete=False)
self.channel.basic_qos(prefetch_count=1)
self.channel.basic_consume(self.handle_delivery, queue=self.arch)
util.debug("AgentConsumer is all set!")
util.debug("AgentConsumer listening on queue {0}...".format(self.arch))
def teardown(self):
"""Clean up AgentConsumer."""
self.channel.close()
def handle_delivery(self, channel, method, header, body):
"""Message received callback."""
global producer
message = pickle.loads(body)
p = message["package"]
arch = message["arch"]
branch = message["branch"]
buildid = message["buildid"]
torrents = message["torrents"]
reply_to = message["reply_to"]
self.buildname = "{0}/{1}/{2}".format(arch, branch, buildid)
if buildid in ready:
util.log("Building {0} for build {1}".format(p.name, self.buildname))
channel.basic_ack(delivery_tag=method.delivery_tag)
else:
time.sleep(5)
channel.basic_reject(delivery_tag=method.delivery_tag)
util.log("Setting up build {0}".format(self.buildname))
ts = torrent.TorrentSession()
for t in torrents:
t.dest="." # XXX - Temporary while I'm testing locally.
ts.add(t)
while not ts.all_seeding():
ts.status()
time.sleep(1)
util.debug("Finished downloading components.")
ts.terminate()
producer.notify(reply_to)
ready.append(buildid)
consumer = AgentConsumer()
consumer.start()
producer = AgentProducer()
producer.start()
def shutdown(signum, stack):
global loop
loop = False
signal.signal(signal.SIGINT, shutdown)
loop = True
while loop:
time.sleep(3)
consumer.stop()
producer.stop()
# vim: tabstop=2 shiftwidth=2 softtabstop=2 expandtab<|fim▁end|>
| |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>pub mod number_value;<|fim▁end|>
|
pub mod boolean_value;
|
<|file_name|>globalconnect.d.ts<|end_file_name|><|fim▁begin|>declare module "diagram-js/lib/features/global-connect/GlobalConnect" {
import EventBus from "diagram-js/lib/core/EventBus";
import { Base } from "diagram-js/lib/model";
import Canvas from "diagram-js/lib/core/Canvas";
import Dragging from "diagram-js/lib/features/dragging/Dragging";
export default class GlobalConnect {
public _dragging: Dragging;
constructor(eventBus: EventBus, dragging: {}, connect: {}, canvas: Canvas, toolManager: {});
public registerProvider(provider: IGlobalConnectProvider): void;
public isActive(): boolean;
public toggle(): void;
/**
* Initiates tool activity.
*/
public start(): void;
/**
* Check if source shape can initiate connection.
*
* @param {Base} startTarget
* @return {Boolean}
*/
public canStartConnect(startTarget: Base): boolean;
}
export interface IGlobalConnectProvider {
/**
* Check if source shape can initiate connection.
*
* @param {Base} startTarget
* @return {Boolean}
*/
canStartConnect(startTarget: Base): boolean;
}<|fim▁hole|>
}<|fim▁end|>
| |
<|file_name|>lc767-reorganize-string.go<|end_file_name|><|fim▁begin|>package main
import (
"fmt"
)
/*767. Reorganize String
https://leetcode.com/problems/reorganize-string/description/
Given a string `S`, check if the letters can be rearranged so that two
characters that are adjacent to each other are not the same.
If possible, output any possible result. If not possible, return the empty
string.
**Example 1:**
<|fim▁hole|>
**Example 2:**
**Input:** S = "aaab"
**Output:** ""
**Note:**
* `S` will consist of lowercase letters and have length in range `[1, 500]`.
Similar Questions:
Rearrange String k Distance Apart (rearrange-string-k-distance-apart)
Task Scheduler (task-scheduler)
*/
func reorganizeString(S string) string {
}
func main() {
fmt.Println()
}<|fim▁end|>
|
**Input:** S = "aab"
**Output:** "aba"
|
<|file_name|>TaskCreateFragment.java<|end_file_name|><|fim▁begin|>package pg.autyzm.friendly_plans.manager_app.view.task_create;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import database.repository.StepTemplateRepository;
import javax.inject.Inject;
import database.entities.Asset;
import database.entities.TaskTemplate;
import database.repository.TaskTemplateRepository;
import pg.autyzm.friendly_plans.ActivityProperties;
import pg.autyzm.friendly_plans.App;
import pg.autyzm.friendly_plans.AppComponent;
import pg.autyzm.friendly_plans.R;
import pg.autyzm.friendly_plans.asset.AssetType;
import pg.autyzm.friendly_plans.databinding.FragmentTaskCreateBinding;
import pg.autyzm.friendly_plans.manager_app.validation.TaskValidation;
import pg.autyzm.friendly_plans.manager_app.validation.Utils;
import pg.autyzm.friendly_plans.manager_app.validation.ValidationResult;
import pg.autyzm.friendly_plans.manager_app.view.components.SoundComponent;
import pg.autyzm.friendly_plans.manager_app.view.main_screen.MainActivity;
import pg.autyzm.friendly_plans.manager_app.view.step_list.StepListFragment;
import pg.autyzm.friendly_plans.manager_app.view.task_type_enum.TaskType;
import pg.autyzm.friendly_plans.manager_app.view.view_fragment.CreateFragment;
public class TaskCreateFragment extends CreateFragment implements TaskCreateActivityEvents {
private static final String REGEX_TRIM_NAME = "_([\\d]*)(?=\\.)";
@Inject
TaskValidation taskValidation;
@Inject
TaskTemplateRepository taskTemplateRepository;
@Inject
StepTemplateRepository stepTemplateRepository;
private TextView labelTaskName;
private EditText taskName;
private EditText taskDurationTime;
private Long taskId;
private Integer typeId;
private Button steps;
private RadioGroup types;
private TaskType taskType = TaskType.TASK;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
FragmentTaskCreateBinding binding = DataBindingUtil.inflate(
inflater, R.layout.fragment_task_create, container, false);
binding.setEvents(this);
View view = binding.getRoot();
ImageButton playSoundIcon = (ImageButton) view.findViewById(R.id.id_btn_play_sound);
AppComponent appComponent = ((App) getActivity().getApplication()).getAppComponent();
soundComponent = SoundComponent.getSoundComponent(
soundId, playSoundIcon, getActivity().getApplicationContext(), appComponent);
appComponent.inject(this);
binding.setSoundComponent(soundComponent);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
registerViews(view);
view.post(new Runnable() { // Set assets only when the layout is completely built
@Override
public void run() {
Bundle arguments = getArguments();
if (arguments != null) {
Long taskId = (Long) arguments.get(ActivityProperties.TASK_ID);
if (taskId != null) {
initTaskForm(taskId);
}
}
}
});
}
private void registerViews(View view) {
labelTaskName = (TextView) view.findViewById(R.id.id_tv_task_name_label);
Utils.markFieldMandatory(labelTaskName);
taskName = (EditText) view.findViewById(R.id.id_et_task_name);
pictureFileName = (EditText) view.findViewById(R.id.id_et_task_picture);
soundFileName = (EditText) view.findViewById(R.id.id_et_task_sound);
taskDurationTime = (EditText) view.findViewById(R.id.id_et_task_duration_time);
picturePreview = (ImageView) view.findViewById(R.id.iv_picture_preview);
clearSound = (ImageButton) view.findViewById(R.id.id_ib_clear_sound_btn);
clearPicture = (ImageButton) view.findViewById(R.id.id_ib_clear_img_btn);
steps = (Button) view.findViewById(R.id.id_btn_steps);
types = (RadioGroup) view.findViewById(R.id.id_rg_types);
RadioButton typeTask = (RadioButton) view.findViewById(R.id.id_rb_type_task);
typeTask.setChecked(true);
taskType = TaskType.TASK;
}
private Long saveOrUpdate() {
soundComponent.stopActions();
try {
if (taskId != null) {
if (validateName(taskId, taskName) && validateDuration(taskDurationTime)) {
typeId = taskType.getId();
Integer duration = getDuration();
clearSteps(typeId, taskId);
taskTemplateRepository.update(taskId,
taskName.getText().toString(),
duration,
pictureId,
soundId,
typeId);
showToastMessage(R.string.task_saved_message);
return taskId;
}
} else {
if (validateName(taskName) && validateDuration(taskDurationTime)) {
Integer duration = getDuration();
typeId = taskType.getId();
long taskId = taskTemplateRepository.create(taskName.getText().toString(),
duration,
pictureId,
soundId,
typeId);
showToastMessage(R.string.task_saved_message);
return taskId;
}
}
} catch (RuntimeException exception) {
Log.e("Task Create View", "Error saving task", exception);
showToastMessage(R.string.save_task_error_message);
}
return null;
}
private void clearSteps(Integer typeId, Long taskId) {
if (typeId != 1) {
stepTemplateRepository.deleteAllStepsForTask(taskId);
}
}
private boolean validateName(Long taskId, EditText taskName) {
ValidationResult validationResult = taskValidation
.isUpdateNameValid(taskId, taskName.getText().toString());
return handleInvalidResult(taskName, validationResult);
}
private boolean validateName(EditText taskName) {
ValidationResult validationResult = taskValidation
.isNewNameValid(taskName.getText().toString());
return handleInvalidResult(taskName, validationResult);
}
private boolean validateDuration(EditText duration) {
ValidationResult validationResult = taskValidation
.isDurationValid(duration.getText().toString());
return handleInvalidResult(duration, validationResult);
}
private void initTaskForm(long taskId) {
this.taskId = taskId;
TaskTemplate task = taskTemplateRepository.get(taskId);
taskName.setText(task.getName());
if (task.getDurationTime() != null) {
taskDurationTime.setText(String.valueOf(task.getDurationTime()));
}
Asset picture = task.getPicture();
Asset sound = task.getSound();
if (picture != null) {
setAssetValue(AssetType.PICTURE, picture.getFilename(), picture.getId());
}
if (sound != null) {
setAssetValue(AssetType.SOUND, sound.getFilename(), sound.getId());
}
typeId = task.getTypeId();
((RadioButton) types.getChildAt(typeId - 1)).setChecked(true);
setVisibilityStepButton(Integer.valueOf(task.getTypeId().toString()));
}
private void setVisibilityStepButton(int typeIdValue) {
if (typeIdValue == 1) {
steps.setVisibility(View.VISIBLE);
} else {
steps.setVisibility(View.INVISIBLE);
}
}
private void showStepsList(final long taskId) {
StepListFragment fragment = new StepListFragment();
Bundle args = new Bundle();
args.putLong(ActivityProperties.TASK_ID, taskId);
fragment.setArguments(args);
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
transaction.replace(R.id.task_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
private void showMainMenu() {
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
@Override
protected void setAssetValue(AssetType assetType, String assetName, Long assetId) {
String assetNameTrimmed = assetName.replaceAll(REGEX_TRIM_NAME, "");
if (assetType.equals(AssetType.PICTURE)) {
pictureFileName.setText(assetNameTrimmed);
clearPicture.setVisibility(View.VISIBLE);
pictureId = assetId;
showPreview(pictureId, picturePreview);
} else {
soundFileName.setText(assetNameTrimmed);
clearSound.setVisibility(View.VISIBLE);
soundId = assetId;
soundComponent.setSoundId(soundId);
}
}
private Integer getDuration() {
if (!taskDurationTime.getText().toString().isEmpty() &&
!taskDurationTime.getText().toString().equals("0")) {
return Integer.valueOf(taskDurationTime.getText().toString());
}
return null;
}
@Override
public void eventListStep(View view) {
taskId = saveOrUpdate();
if (taskId != null) {
showStepsList(taskId);
}
}
@Override
public void eventSelectPicture(View view) {
filePickerProxy.openFilePicker(TaskCreateFragment.this, AssetType.PICTURE);<|fim▁hole|> filePickerProxy.openFilePicker(TaskCreateFragment.this, AssetType.SOUND);
}
@Override
public void eventClearPicture(View view) {
clearPicture();
}
@Override
public void eventClearSound(View view) {
clearSound();
}
@Override
public void eventClickPreviewPicture(View view) {
showPicture(pictureId);
}
@Override
public void eventChangeButtonStepsVisibility(View view, int id) {
if (id == R.id.id_rb_type_task) {
steps.setVisibility(View.VISIBLE);
taskType = TaskType.TASK;
} else {
steps.setVisibility(View.INVISIBLE);
if (id == R.id.id_rb_type_interaction) {
taskType = TaskType.INTERACTION;
} else {
taskType = TaskType.PRIZE;
}
}
}
@Override
public void eventSaveAndFinish(View view) {
Long taskId = saveOrUpdate();
if (taskId != null) {
showMainMenu();
}
}
}<|fim▁end|>
|
}
@Override
public void eventSelectSound(View view) {
|
<|file_name|>mva-w15.js<|end_file_name|><|fim▁begin|>/**
*
* STREAM: MVA (window: 15)
*
*
*
* DESCRIPTION:
* -
*
*
* API:
* -
*
*
* NOTES:
* [1]
*
*
* TODO:
* [1]
*
*
* HISTORY:
* - 2014/05/28: Created. [AReines].
*
*
* DEPENDENCIES:
* [1]
*
*
* LICENSE:
* MIT
*
* Copyright (c) 2014. Athan Reines.
*
*
* AUTHOR:<|fim▁hole|>* Athan Reines. [email protected]. 2014.
*
*/
(function() {
'use strict';
// MODULES //
var // Stream combiner:
pipeline = require( 'stream-combiner' ),
// Flow streams:
flow = require( 'flow.io' );
// FUNCTIONS //
/**
* FUNCTION: map( fcn )
* Returns a data transformation function.
*
* @private
* @param {function} fcn - function which performs the map transform
* @returns {function} data transformation function
*/
function map( fcn ) {
/**
* FUNCTION: map( data )
* Defines the data transformation.
*
* @private
* @param {*} data - stream data
* @returns {number} transformed data
*/
return function map( data ) {
return fcn( data );
};
} // end FUNCTION map()
// STREAM //
/**
* FUNCTION: Stream()
* Stream constructor.
*
* @returns {Stream} Stream instance
*/
function Stream() {
this.name = '';
this._window = 15;
// ACCESSORS:
this._value = function( d ) {
return d.y;
};
return this;
} // end FUNCTION Stream()
/**
* ATTRIBUTE: type
* Defines the stream type.
*/
Stream.prototype.type = 'mva-w15';
/**
* METHOD: metric( metric )
* Metric setter and getter. If a metric instance is supplied, sets the metric. If no metric is supplied, returns the instance metric value function.
*
* @param {object} metric - an object with a 'value' method; see constructor for basic example. If the metric has a name property, sets the transform name.
* @returns {Stream|object} Stream instance or instance metric
*/
Stream.prototype.metric = function ( metric ) {
if ( !arguments.length ) {
return this._value;
}
if ( !metric.value ) {
throw new Error( 'metric()::invalid input argument. Metric must be an object with a \'value\' method.' );
}
// Extract the method to calculate the metric value and bind the metric context:
this._value = metric.value.bind( metric );
// If the metric has a name, set the transform name:
this.name = ( metric.name ) ? metric.name : '';
// Return the stream instance:
return this;
}; // end METHOD metric()
/**
* METHOD: stream()
* Returns a JSON data transform stream for performing MVA.
*
* @returns {stream} transform stream
*/
Stream.prototype.stream = function() {
var mTransform, tStream, mva, mStream, pStream;
// Create the input transform stream:
mTransform = flow.map()
.map( map( this._value ) );
// Create the input transform stream:
tStream = mTransform.stream();
// Create an MVA stream generator and configure:
mva = flow.mva()
.window( this._window );
// Create an MVA stream:
mStream = mva.stream();
// Create a stream pipeline:
pStream = pipeline(
tStream,
mStream
);
// Return the pipeline:
return pStream;
}; // end METHOD stream()
// EXPORTS //
module.exports = function createStream() {
return new Stream();
};
})();<|fim▁end|>
| |
<|file_name|>aql_linker.py<|end_file_name|><|fim▁begin|>import re
import os.path
import datetime
import base64
import aql
# ==============================================================================
info = aql.get_aql_info()
HEADER = """#!/usr/bin/env python
#
# THIS FILE WAS AUTO-GENERATED. DO NOT EDIT!
#
# Copyright (c) 2011-{year} of the {name} project, site: {url}
#
# 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.
""".format(year=datetime.date.today().year,
name=info.name, url=info.url)
# ==============================================================================
AQL_DATE = '_AQL_VERSION_INFO.date = "{date}"'.format(
date=datetime.date.today().isoformat())
# ==============================================================================
MAIN = """
if __name__ == '__main__':
aql_module_globals = globals().copy()
aql_module_name = "aql"
aql_module = imp.new_module(aql_module_name)
aql_module_globals.update( aql_module.__dict__)
aql_module.__dict__.update(aql_module_globals)
sys.modules[aql_module_name] = aql_module
{embedded_tools}
sys.exit(main())
"""
# ==============================================================================<|fim▁hole|># ==============================================================================
class AqlPreprocess (aql.FileBuilder):
split = aql.FileBuilder.split_single
# ----------------------------------------------------------
def get_trace_name(self, source_entities, brief):
return "Preprocess file"
# ----------------------------------------------------------
def get_trace_targets(self, target_entities, brief):
return None
# -----------------------------------------------------------
def build(self, source_entities, targets):
src_file = source_entities[0].get()
empty_re = re.compile(r'^\s*\r*\n', re.MULTILINE)
slash_re = re.compile(r'\\\r*\n', re.MULTILINE)
comments_re = re.compile(r"^\s*#.*$", re.MULTILINE)
all_stmt_re = re.compile(
r"^__all__\s*=\s*\(.+?\)", re.MULTILINE | re.DOTALL)
content = aql.read_text_file(src_file)
content = slash_re.sub("", content)
content = comments_re.sub("", content)
content = all_stmt_re.sub("", content)
# -----------------------------------------------------------
import_re = re.compile(r"^import\s+(.+)$", re.MULTILINE)
std_imports = set()
def import_handler(match, _std_imports=std_imports):
module_name = match.group(1)
_std_imports.add(module_name)
return ""
content = import_re.sub(import_handler, content)
# -----------------------------------------------------------
aql_import_re = re.compile(r"^\s*from\s+(\.?aql.+)\s+import\s+.+$",
re.MULTILINE)
aql_imports = set()
def aql_import_handler(match, _aql_imports=aql_imports):
module_name = match.group(1)
if module_name.startswith('.'):
module_name = os.sep + module_name[1:] + '.py'
else:
module_name = os.sep + \
module_name.replace('.', os.sep) + os.sep
_aql_imports.add(module_name)
return ""
content = aql_import_re.sub(aql_import_handler, content)
# -----------------------------------------------------------
content = empty_re.sub("", content)
target = aql.SimpleEntity(name=src_file,
data=(std_imports, aql_imports, content))
targets.add_target_entity(target)
# ==============================================================================
class AqlLinkCore (aql.FileBuilder):
def __init__(self, options, target):
self.target = self.get_target_path(target, ext='.py')
def get_trace_name(self, source_entities, brief):
return "Link AQL Module"
# ----------------------------------------------------------
def get_target_entities(self, source_entities):
return self.target
# ----------------------------------------------------------
def get_trace_sources(self, source_entities, brief):
return (os.path.basename(src.name) for src in source_entities)
# -----------------------------------------------------------
def replace(self, options, source_entities):
finder = aql.FindFilesBuilder(options,
mask='*.py',
exclude_mask="__init__.py")
core_files = aql.Node(finder, source_entities)
return aql.Node(AqlPreprocess(options), core_files)
# -----------------------------------------------------------
@staticmethod
def _mod_to_files(file2deps, modules):
mod2files = {}
for mod in modules:
files = set()
for file in file2deps:
if file.find(mod) != -1:
files.add(file)
mod2files[mod] = files
return mod2files
# -----------------------------------------------------------
@staticmethod
def _get_dep_to_files(file2deps, mod2files):
dep2files = {}
tmp_file2deps = {}
for file, mods in file2deps.items():
for mod in mods:
files = mod2files[mod]
tmp_file2deps.setdefault(file, set()).update(files)
for f in files:
dep2files.setdefault(f, set()).add(file)
return dep2files, tmp_file2deps
# -----------------------------------------------------------
@staticmethod
def _get_content(files_content, dep2files, file2deps, tails):
content = ""
while tails:
tail = tails.pop(0)
content += files_content[tail]
files = dep2files.pop(tail, [])
for file in files:
deps = file2deps[file]
deps.remove(tail)
if not deps:
tails.append(file)
del file2deps[file]
return content
# -----------------------------------------------------------
def build(self, source_entities, targets):
file2deps = {}
files_content = {}
modules = set()
tails = []
std_modules = set()
for entity in source_entities:
file_name = entity.name
mod_std_imports, mod_deps, mod_content = entity.data
if not mod_content:
continue
if not mod_deps:
tails.append(file_name)
files_content[file_name] = mod_content
file2deps[file_name] = mod_deps
std_modules.update(mod_std_imports)
modules.update(mod_deps)
mod2files = self._mod_to_files(file2deps, modules)
dep2files, file2deps = self._get_dep_to_files(file2deps, mod2files)
content = self._get_content(files_content, dep2files, file2deps, tails)
imports_content = '\n'.join(
"import %s" % module for module in sorted(std_modules))
content = '\n'.join([HEADER, imports_content, content, AQL_DATE])
aql.write_text_file(self.target, data=content)
targets.add_target_files(self.target)
# ==============================================================================
class AqlPackTools (aql.FileBuilder):
NAME_ATTRS = ['target']
def __init__(self, options, target):
self.target = target
self.build_target = self.get_target_path(target, ext='.b64')
# ----------------------------------------------------------
def get_trace_name(self, source_entities, brief):
return "Pack Tools"
# ----------------------------------------------------------
def get_target_entities(self, source_values):
return self.build_target
# ----------------------------------------------------------
def replace(self, options, source_entities):
tools_path = [source.get() for source in source_entities]
if not tools_path:
return None
finder = aql.FindFilesBuilder(options, '*.py')
zipper = aql.ZipFilesBuilder(options,
target=self.target,
basedir=tools_path)
tool_files = aql.Node(finder, source_entities)
zip = aql.Node(zipper, tool_files)
return zip
# -----------------------------------------------------------
def build(self, source_entities, targets):
target = self.build_target
with aql.open_file(target, write=True,
binary=True, truncate=True) as output:
for source in source_entities:
zip_file = source.get()
with aql.open_file(zip_file, read=True, binary=True) as input:
base64.encode(input, output)
targets.add_target_files(target, tags="embedded_tools")
# ==============================================================================
class AqlLinkStandalone (aql.FileBuilder):
def __init__(self, options, target):
self.target = self.get_target_path(target)
# -----------------------------------------------------------
def get_trace_name(self, source_entities, brief):
return "Link AQL standalone script"
# ----------------------------------------------------------
def get_target_entities(self, source_values):
return self.target
# ----------------------------------------------------------
def build(self, source_entities, targets):
content = []
embedded_tools = ""
for source in source_entities:
data = aql.read_text_file(source.get())
if not data:
continue
if "embedded_tools" in source.tags:
embedded_tools = EMBEDDED_TOOLS % data
else:
content.append(data)
content.append(MAIN.format(embedded_tools=embedded_tools))
content = '\n'.join(content)
aql.write_text_file(self.target, content)
targets.add_target_files(self.target)
# ==============================================================================
class AqlBuildTool(aql.Tool):
def pack_tools(self, options, target):
return AqlPackTools(options, target)
def link_module(self, options, target):
return AqlLinkCore(options, target)
def link_standalone(self, options, target):
return AqlLinkStandalone(options, target)
PackTools = pack_tools
LinkModule = link_module
LinkStandalone = link_standalone<|fim▁end|>
|
EMBEDDED_TOOLS = '\n _EMBEDDED_TOOLS.append(b"""\n%s""")\n'
|
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Misc helper functions.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import logging as log
import tensorflow as tf
def optimistic_restorer(save_file, vars_all=None):
"""Restores the variables which are present in save_file.
Args:
save_file: checkpoint file
vars_all: optional list of the variable superset
Returns:
restorer: object on which we should call restore(sess, save_file)
"""
if vars_all is None:
vars_all = tf.global_variables()
reader = tf.train.NewCheckpointReader(save_file)
saved_shapes = reader.get_variable_to_shape_map()
var_names = sorted([(var.name, var.name.split(':')[0])
for var in vars_all
if var.name.split(':')[0] in saved_shapes])
var_names_new = sorted([
var.name for var in vars_all if var.name.split(':')[0] not in saved_shapes
])
log.info('Number of new variables: %d', len(var_names_new))
log.info(var_names_new)
restore_vars = []
name2var = dict(
zip([x.name.split(':')[0] for x in tf.global_variables()],
tf.global_variables()))
with tf.variable_scope('', reuse=True):
for var_name, saved_var_name in var_names:
curr_var = name2var[saved_var_name]
var_shape = curr_var.get_shape().as_list()
if var_shape == saved_shapes[saved_var_name]:
restore_vars.append(curr_var)
else:
log.info('Different shape than saved: %s', var_name)
restorer = tf.train.Saver(restore_vars)
return restorer
def transpose(rot):
"""Transposes last two dimensions.
Args:
rot: relative rotation, are [...] X M X N matrices
Returns:
rot_t: [...] X N X M matrices
"""
with tf.name_scope('transpose'):
n_inp_dim = len(rot.get_shape())
perm = range(n_inp_dim)
perm[-1] = n_inp_dim - 2
perm[-2] = n_inp_dim - 1
rot_t = tf.transpose(rot, perm=perm)
return rot_t
def divide_safe(num, den, name=None):
eps = 1e-8
den += eps * tf.cast(tf.equal(den, 0), 'float32')
return tf.divide(num, den, name=name)
def pixel_coords(bs, h, w):
"""Creates a bs X h X w X 3 tensor with (x,y,1) coord at each pixel.
Args:
bs: batch_size (number of meshgrid repetitions)
h: number of rows
w: number of columns
Returns:
bs X h X w X 3 tensor with (x,y,1) coord at each pixel.
Note : these coordinates are 0.5 indexed
"""
with tf.name_scope('pixel_coords'):
ones_w = tf.ones((1, 1, w))
ones_h = tf.ones((1, h, 1))
ones_b = tf.ones((bs, 1, 1))
range_h = tf.cast(tf.reshape(tf.range(h) + 1, (1, h, 1)), 'float32')
range_w = tf.cast(tf.reshape(tf.range(w) + 1, (1, 1, w)), 'float32')
# subtracting 0.5 so that pixel centres correspond to 0.5
# for example, the top left pixel centre is at (0.5, 0.5)
ys = ones_b * range_h * ones_w - 0.5
xs = ones_b * ones_h * range_w - 0.5
ones = ones_b * ones_h * ones_w
return tf.stack([xs, ys, ones], axis=3)
def transform_pts(pts_coords_init, tform_mat):
"""Transforms input points according to the transformation.
Args:
pts_coords_init : [...] X H X W X D; pixelwise coordinates.
tform_mat : [...] X D X D; desired matrix transformation
Returns:
pts_coords : [...] X H X W X D; transformed coordinates.
"""
with tf.name_scope('transform_pts'):
tform_mat_size = tform_mat.get_shape().as_list()
n_dims_t = len(tform_mat_size)
pts_init_size = pts_coords_init.get_shape().as_list()
pts_transform_size = [tform_mat_size[ix] for ix in range(n_dims_t)]
pts_transform_size[-2] = -1
pts_coords_init_reshape = tf.reshape(pts_coords_init, pts_transform_size)
tform_mat_transpose = transpose(tform_mat)
pts_mul = tf.matmul(pts_coords_init_reshape, tform_mat_transpose)
pts_coords_transformed = tf.reshape(pts_mul, pts_init_size)
return pts_coords_transformed
def soft_z_buffering(layer_masks, layer_disps, depth_softmax_temp=1):
"""Computes pixelwise probability for belonging to each layer.
Args:
layer_masks: L X [...] X 1, indicating which layer pixels are valid
layer_disps: L X [...] X 1, laywewise per pixel disparity
depth_softmax_temp: Denominator for exponentiation of negative depths
Returns:
layer_probs: L X [...] X 1, indicating prob. of layer assignment
"""
eps = 1e-8
layer_disps = tf.nn.relu(layer_disps)
layer_depths = divide_safe(1, layer_disps)
log_depth_probs = -layer_depths / depth_softmax_temp
log_layer_probs = tf.log(layer_masks + eps) + log_depth_probs<|fim▁hole|> return layer_probs
def enforce_bg_occupied(ldi_masks):
"""Enforce that the last layer's mask has all ones.
Args:
ldi_masks: L X [...] masks
Returns:
ldi_masks: L X [..], masks with last layer set as 1
"""
n_layers = ldi_masks.get_shape().as_list()[0]
if n_layers == 1:
return ldi_masks * 0 + 1
else:
masks_fg, masks_bg = tf.split(ldi_masks, [n_layers - 1, 1], axis=0)
masks_bg = masks_bg * 0 + 1
return tf.concat([masks_fg, masks_bg], axis=0)
def zbuffer_weights(disps, scale=50):
"""Compute decreasing, non-negative inverse depths based on disparity deltas.
Args:
disps: [...] inverse depths, between 0 (far) and 1 (closest possible depth)
scale: multiplicative factor before exponentiation
Returns:
z_buf_wts: [..], higher weights for closer things
"""
pos_disps = tf.cast(tf.greater(disps, 0), tf.float32)
disps = tf.clip_by_value(disps, 0, 1)
disps -= 0.5 # subtracting a constant just divides all weights by a fraction
wts = tf.exp(disps * scale) * pos_disps
return wts<|fim▁end|>
|
log_layer_probs -= tf.reduce_max(log_layer_probs, axis=0, keep_dims=True)
layer_probs = tf.exp(log_layer_probs)
probs_sum = tf.reduce_sum(layer_probs, axis=0, keep_dims=True)
layer_probs = tf.divide(layer_probs, probs_sum)
|
<|file_name|>extension.go<|end_file_name|><|fim▁begin|><|fim▁hole|>
import (
"github.com/markdaws/gohome/pkg/cmd"
"github.com/markdaws/gohome/pkg/gohome"
)
type extension struct {
gohome.NullExtension
}
func (e *extension) Name() string {
return "testing"
}
func (e *extension) BuilderForDevice(sys *gohome.System, d *gohome.Device) cmd.Builder {
switch d.ModelNumber {
case "testing.hardware":
return &cmdBuilder{ModelNumber: d.ModelNumber, Device: d}
default:
// This device is not one that we know how to control, return nil
return nil
}
}
func (e *extension) NetworkForDevice(sys *gohome.System, d *gohome.Device) gohome.Network {
return nil
}
func (e *extension) EventsForDevice(sys *gohome.System, d *gohome.Device) *gohome.ExtEvents {
switch d.ModelNumber {
case "testing.hardware":
evts := &gohome.ExtEvents{}
evts.Producer = &producer{
Device: d,
System: sys,
}
evts.Consumer = &consumer{
Device: d,
System: sys,
}
return evts
default:
return nil
}
}
func (e *extension) Discovery(sys *gohome.System) gohome.Discovery {
return &discovery{}
}
func NewExtension() *extension {
return &extension{}
}<|fim▁end|>
|
package testing
|
<|file_name|>account_test_classes.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from odoo.tests.common import HttpCase
from odoo.exceptions import ValidationError<|fim▁hole|> the installation of all modules, and will SKIP TESTS ifit cannot find an already
configured accounting (which means no localization module has been installed).
"""
post_install = True
at_install = False
def setUp(self):
super(AccountingTestCase, self).setUp()
domain = [('company_id', '=', self.env.ref('base.main_company').id)]
if not self.env['account.account'].search_count(domain):
self.skipTest("No Chart of account found")
def check_complete_move(self, move, theorical_lines):
for aml in move.line_ids:
line = (aml.name, round(aml.debit, 2), round(aml.credit, 2))
if line in theorical_lines:
theorical_lines.remove(line)
else:
raise ValidationError('Unexpected journal item. (label: %s, debit: %s, credit: %s)' % (aml.name, round(aml.debit, 2), round(aml.credit, 2)))
if theorical_lines:
raise ValidationError('Remaining theorical line (not found). %s)' % ([(aml[0], aml[1], aml[2]) for aml in theorical_lines]))
return True
def ensure_account_property(self, property_name):
'''Ensure the ir.property targetting an account.account passed as parameter exists.
In case it's not: create it with a random account. This is useful when testing with
partially defined localization (missing stock properties for example)
:param property_name: The name of the property.
'''
company_id = self.env.user.company_id
field_id = self.env['ir.model.fields'].search(
[('model', '=', 'product.template'), ('name', '=', property_name)], limit=1)
property_id = self.env['ir.property'].search([
('company_id', '=', company_id.id),
('name', '=', property_name),
('res_id', '=', None),
('fields_id', '=', field_id.id)], limit=1)
account_id = self.env['account.account'].search([('company_id', '=', company_id.id)], limit=1)
value_reference = 'account.account,%d' % account_id.id
if property_id and not property_id.value_reference:
property_id.value_reference = value_reference
else:
self.env['ir.property'].create({
'name': property_name,
'company_id': company_id.id,
'fields_id': field_id.id,
'value_reference': value_reference,
})<|fim▁end|>
|
class AccountingTestCase(HttpCase):
""" This class extends the base TransactionCase, in order to test the
accounting with localization setups. It is configured to run the tests after
|
<|file_name|>protractor-ci.conf.js<|end_file_name|><|fim▁begin|>const config = require('./protractor.conf').config;
config.capabilities = {
browserName: 'chrome',
chromeOptions: {<|fim▁hole|>
exports.config = config;<|fim▁end|>
|
args: ['--headless', '--no-sandbox', '--disable-gpu'],
},
};
|
<|file_name|>help.go<|end_file_name|><|fim▁begin|>// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package etcdmain
var (
usageline = `usage: etcd [flags]
start an etcd server
etcd --version
show the version of etcd
etcd -h | --help
show the help information about etcd
`
flagsline = `
member flags:
--name 'default'
human-readable name for this member.
--data-dir '${name}.etcd'
path to the data directory.
--wal-dir ''
path to the dedicated wal directory.
--snapshot-count '10000'
number of committed transactions to trigger a snapshot to disk.
--heartbeat-interval '100'
time (in milliseconds) of a heartbeat interval.
--election-timeout '1000'
time (in milliseconds) for an election to timeout. See tuning documentation for details.
--listen-peer-urls 'http://localhost:2380,http://localhost:7001'
list of URLs to listen on for peer traffic.
--listen-client-urls 'http://localhost:2379,http://localhost:4001'
list of URLs to listen on for client traffic.
-cors ''
comma-separated whitelist of origins for CORS (cross-origin resource sharing).
<|fim▁hole|> --initial-advertise-peer-urls 'http://localhost:2380,http://localhost:7001'
list of this member's peer URLs to advertise to the rest of the cluster.
--initial-cluster 'default=http://localhost:2380,default=http://localhost:7001'
initial cluster configuration for bootstrapping.
--initial-cluster-state 'new'
initial cluster state ('new' or 'existing').
--initial-cluster-token 'etcd-cluster'
initial cluster token for the etcd cluster during bootstrap.
--advertise-client-urls 'http://localhost:2379,http://localhost:4001'
list of this member's client URLs to advertise to the public.
The client URLs advertised should be accessible to machines that talk to etcd cluster. etcd client libraries parse these URLs to connect to the cluster.
--discovery ''
discovery URL used to bootstrap the cluster.
--discovery-fallback 'proxy'
expected behavior ('exit' or 'proxy') when discovery services fails.
--discovery-proxy ''
HTTP proxy to use for traffic to discovery service.
--discovery-srv ''
dns srv domain used to bootstrap the cluster.
--strict-reconfig-check
reject reconfiguration requests that would cause quorum loss.
proxy flags:
--proxy 'off'
proxy mode setting ('off', 'readonly' or 'on').
--proxy-failure-wait 5000
time (in milliseconds) an endpoint will be held in a failed state.
--proxy-refresh-interval 30000
time (in milliseconds) of the endpoints refresh interval.
--proxy-dial-timeout 1000
time (in milliseconds) for a dial to timeout.
--proxy-write-timeout 5000
time (in milliseconds) for a write to timeout.
--proxy-read-timeout 0
time (in milliseconds) for a read to timeout.
security flags:
--ca-file '' [DEPRECATED]
path to the client server TLS CA file. '-ca-file ca.crt' could be replaced by '-trusted-ca-file ca.crt -client-cert-auth' and etcd will perform the same.
--cert-file ''
path to the client server TLS cert file.
--key-file ''
path to the client server TLS key file.
--client-cert-auth 'false'
enable client cert authentication.
--trusted-ca-file ''
path to the client server TLS trusted CA key file.
--peer-ca-file '' [DEPRECATED]
path to the peer server TLS CA file. '-peer-ca-file ca.crt' could be replaced by '-peer-trusted-ca-file ca.crt -peer-client-cert-auth' and etcd will perform the same.
--peer-cert-file ''
path to the peer server TLS cert file.
--peer-key-file ''
path to the peer server TLS key file.
--peer-client-cert-auth 'false'
enable peer client cert authentication.
--peer-trusted-ca-file ''
path to the peer server TLS trusted CA file.
logging flags
--debug 'false'
enable debug-level logging for etcd.
--log-package-levels ''
specify a particular log level for each etcd package (eg: 'etcdmain=CRITICAL,etcdserver=DEBUG').
unsafe flags:
Please be CAUTIOUS when using unsafe flags because it will break the guarantees
given by the consensus protocol.
--force-new-cluster 'false'
force to create a new one-member cluster.
experimental flags:
--experimental-v3demo 'false'
enable experimental v3 demo API.
--experimental-gRPC-addr '127.0.0.1:2378'
gRPC address for experimental v3 demo API.
`
)<|fim▁end|>
|
clustering flags:
|
<|file_name|>dummy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import logging
from moulinette.utils.text import random_ascii
from moulinette.core import MoulinetteError, MoulinetteAuthenticationError
from moulinette.authentication import BaseAuthenticator
logger = logging.getLogger("moulinette.authenticator.yoloswag")
# Dummy authenticator implementation
session_secret = random_ascii()
class Authenticator(BaseAuthenticator):
"""Dummy authenticator used for tests"""
name = "dummy"
def __init__(self, *args, **kwargs):
pass
def _authenticate_credentials(self, credentials=None):
if not credentials == self.name:
raise MoulinetteError("invalid_password", raw_msg=True)
return
def set_session_cookie(self, infos):
from bottle import response
assert isinstance(infos, dict)
# This allows to generate a new session id or keep the existing one
current_infos = self.get_session_cookie(raise_if_no_session_exists=False)
new_infos = {"id": current_infos["id"]}
new_infos.update(infos)
response.set_cookie(
"moulitest",
new_infos,
secure=True,
secret=session_secret,
httponly=True,
# samesite="strict", # Bottle 0.12 doesn't support samesite, to be added in next versions
)
def get_session_cookie(self, raise_if_no_session_exists=True):
from bottle import request
try:
infos = request.get_cookie("moulitest", secret=session_secret, default={})
except Exception:<|fim▁hole|> raise MoulinetteAuthenticationError("unable_authenticate")
if not infos and raise_if_no_session_exists:
raise MoulinetteAuthenticationError("unable_authenticate")
if "id" not in infos:
infos["id"] = random_ascii()
return infos
def delete_session_cookie(self):
from bottle import response
response.set_cookie("moulitest", "", max_age=-1)
response.delete_cookie("moulitest")<|fim▁end|>
|
if not raise_if_no_session_exists:
return {"id": random_ascii()}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.