prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>ActionWithdrawTest.java<|end_file_name|><|fim▁begin|>package com.simplyian.superplots.actions; import static org.mockito.Matchers.contains; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; import java.util.Arrays; import java.util.List; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.simplyian.superplots.EconHook; import com.simplyian.superplots.SPSettings; import com.simplyian.superplots.SuperPlotsPlugin; import com.simplyian.superplots.plot.Plot; import com.simplyian.superplots.plot.PlotManager; public class ActionWithdrawTest { private SuperPlotsPlugin main; private ActionWithdraw action; private PlotManager plotManager; private Player player; private EconHook econ; @Before public void setup() { main = mock(SuperPlotsPlugin.class); action = new ActionWithdraw(main); econ = mock(EconHook.class); when(main.getEconomy()).thenReturn(econ); plotManager = mock(PlotManager.class); when(main.getPlotManager()).thenReturn(plotManager); SPSettings settings = mock(SPSettings.class); when(main.getSettings()).thenReturn(settings); when(settings.getInfluenceMultiplier()).thenReturn(1.5); when(settings.getInitialPlotSize()).thenReturn(10); player = mock(Player.class); when(player.getName()).thenReturn("albireox"); } @After public void tearDown() { main = null; action = null; plotManager = null; player = null; } @Test public void test_perform_notInPlot() { World world = mock(World.class); Location playerLoc = new Location(world, 0, 0, 0); when(plotManager.getPlotAt(playerLoc)).thenReturn(null); List<String> args = Arrays.asList("asdf"); action.perform(player, args); verify(player).sendMessage(contains("not in a plot")); } @Test public void test_perform_mustBeAdministrator() { World world = mock(World.class); Location playerLoc = new Location(world, 0, 0, 0); when(player.getLocation()).thenReturn(playerLoc); Plot plot = mock(Plot.class); when(plotManager.getPlotAt(playerLoc)).thenReturn(plot); when(plot.isAdministrator("albireox")).thenReturn(false); when(player.getName()).thenReturn("albireox"); List<String> args = Arrays.asList(); action.perform(player, args); <|fim▁hole|> @Test public void test_perform_noAmount() { World world = mock(World.class); Location playerLoc = new Location(world, 0, 0, 0); when(player.getLocation()).thenReturn(playerLoc); Plot plot = mock(Plot.class); when(plotManager.getPlotAt(playerLoc)).thenReturn(plot); when(plot.isAdministrator("albireox")).thenReturn(true); when(player.getName()).thenReturn("albireox"); List<String> args = Arrays.asList(); action.perform(player, args); verify(player).sendMessage(contains("did not specify")); } @Test public void test_perform_notANumber() { World world = mock(World.class); Location playerLoc = new Location(world, 0, 0, 0); when(player.getLocation()).thenReturn(playerLoc); Plot plot = mock(Plot.class); when(plotManager.getPlotAt(playerLoc)).thenReturn(plot); when(plot.isAdministrator("albireox")).thenReturn(true); when(player.getName()).thenReturn("albireox"); when(econ.getBalance("albireox")).thenReturn(200.0); List<String> args = Arrays.asList("400x"); action.perform(player, args); verify(player).sendMessage(contains("not a valid amount")); } @Test public void test_perform_notEnoughMoney() { World world = mock(World.class); Location playerLoc = new Location(world, 0, 0, 0); when(player.getLocation()).thenReturn(playerLoc); Plot plot = mock(Plot.class); when(plotManager.getPlotAt(playerLoc)).thenReturn(plot); when(plot.isAdministrator("albireox")).thenReturn(true); when(player.getName()).thenReturn("albireox"); when(plot.getFunds()).thenReturn(200); List<String> args = Arrays.asList("400"); action.perform(player, args); verify(player).sendMessage(contains("doesn't have that much money")); } @Test public void test_perform_success() { World world = mock(World.class); Location playerLoc = new Location(world, 0, 0, 0); when(player.getLocation()).thenReturn(playerLoc); Plot plot = mock(Plot.class); when(plotManager.getPlotAt(playerLoc)).thenReturn(plot); when(plot.isAdministrator("albireox")).thenReturn(true); when(player.getName()).thenReturn("albireox"); when(plot.getFunds()).thenReturn(400); List<String> args = Arrays.asList("400"); action.perform(player, args); verify(player).sendMessage(contains("has been withdrawn")); verify(plot).subtractFunds(400); verify(econ).addBalance("albireox", 400); } }<|fim▁end|>
verify(player).sendMessage(contains("must be an administrator")); }
<|file_name|>test_log.py<|end_file_name|><|fim▁begin|>from chimera.core.chimeraobject import ChimeraObject from chimera.core.manager import Manager from chimera.core.exceptions import ChimeraException from nose.tools import assert_raises import chimera.core.log import logging log = logging.getLogger("chimera.test_log") class TestLog (object): def test_log (self): class Simple (ChimeraObject): def __init__ (self): ChimeraObject.__init__(self) def answer (self): try:<|fim▁hole|> raise ChimeraException("I'm an Exception, sorry.") except ChimeraException: self.log.exception("from except: wow, exception caught.") raise ChimeraException("I'm a new Exception, sorry again") manager = Manager() manager.addClass(Simple, "simple") simple = manager.getProxy(Simple) try: simple.answer() except ChimeraException, e: assert e.cause != None log.exception("wow, something wrong") manager.shutdown()<|fim▁end|>
<|file_name|>login.js<|end_file_name|><|fim▁begin|>window.onload=function() { var start = document.getElementById('start');<|fim▁hole|> if (name == "") { alert("请输入名字"); return false; } if (!isName(name)) { alert("请输入正确的姓名") return false; } if (id =="") { alert("请输入学号"); return false; } if (!isId(id)) { alert("请输入正确学号"); return false; } if (tel == "") { alert("请输入电话号码"); return false; } if (!isTelephone(tel)) { alert("请输入正确的手机号码"); return false; } else { start.submit(); // document.getElementById("myform").submit(); // window.open("answer.html","_self"); } } function isName(obj) { var nameReg = /[\u4E00-\u9FA5]+$/; return nameReg.test(obj); } function isId(obj) { var emailReg = /^2017\d{8}$/; return emailReg.test(obj); } function isTelephone(obj) { reg = /^1[34578]\d{9}$/; return reg.test(obj); } }<|fim▁end|>
start.onclick = function () { var name = document.getElementById('Name').value; var id = document.getElementById('Id').value; var tel = document.getElementById("Tel").value;
<|file_name|>events.js<|end_file_name|><|fim▁begin|>function runTest(config,qualifier) { var testname = testnamePrefix( qualifier, config.keysystem ) + ', basic events'; var configuration = getSimpleConfigurationForContent( config.content ); if ( config.initDataType && config.initData ) configuration.initDataTypes = [ config.initDataType ] async_test(function(test) { var initDataType; var initData; var mediaKeySession; function processMessage(event) { assert_true(event instanceof window.MediaKeyMessageEvent); assert_equals(event.target, mediaKeySession); assert_equals(event.type, 'message'); assert_any( assert_equals, event.messageType, [ 'license-request', 'individualization-request' ] ); config.messagehandler( event.messageType, event.message ).then( function( response ) { waitForEventAndRunStep('keystatuseschange', mediaKeySession, test.step_func(processKeyStatusesChange), test); mediaKeySession.update( response ).catch(function(error) { forceTestFailureFromPromise(test, error); }); }); } function processKeyStatusesChange(event) { assert_true(event instanceof Event); assert_equals(event.target, mediaKeySession); assert_equals(event.type, 'keystatuseschange'); test.done(); } navigator.requestMediaKeySystemAccess( config.keysystem, [ configuration ] ).then(function(access) { initDataType = access.getConfiguration().initDataTypes[0]; if ( config.initDataType && config.initData ) { initData = config.initData; } else {<|fim▁hole|> }).then(test.step_func(function(mediaKeys) { mediaKeySession = mediaKeys.createSession(); waitForEventAndRunStep('message', mediaKeySession, test.step_func(processMessage), test); return mediaKeySession.generateRequest(initDataType, initData); })).catch(test.step_func(function(error) { forceTestFailureFromPromise(test, error); })); }, testname ); }<|fim▁end|>
initData = getInitData(config.content, initDataType); } return access.createMediaKeys();
<|file_name|>pet-add.component.spec.ts<|end_file_name|><|fim▁begin|>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { PetAddComponent } from './pet-add.component'; describe('PetAddComponent', () => { let component: PetAddComponent;<|fim▁hole|> let fixture: ComponentFixture<PetAddComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ PetAddComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(PetAddComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });<|fim▁end|>
<|file_name|>Battery.cpp<|end_file_name|><|fim▁begin|>/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2014 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #include "Battery.hpp" #ifdef HAVE_BATTERY #if (defined(_WIN32_WCE) && !defined(GNAV)) #include <windows.h> namespace Power { namespace Battery{ unsigned Temperature = 0; unsigned RemainingPercent = 0; bool RemainingPercentValid = false; batterystatus Status = UNKNOWN; }; namespace External{ externalstatus Status = UNKNOWN; }; }; void UpdateBatteryInfo() { SYSTEM_POWER_STATUS_EX2 sps; // request the power status DWORD result = GetSystemPowerStatusEx2(&sps, sizeof(sps), TRUE);<|fim▁hole|> Power::Battery::RemainingPercentValid = true; } else Power::Battery::RemainingPercentValid = false; switch (sps.BatteryFlag) { case BATTERY_FLAG_HIGH: Power::Battery::Status = Power::Battery::HIGH; break; case BATTERY_FLAG_LOW: Power::Battery::Status = Power::Battery::LOW; break; case BATTERY_FLAG_CRITICAL: Power::Battery::Status = Power::Battery::CRITICAL; break; case BATTERY_FLAG_CHARGING: Power::Battery::Status = Power::Battery::CHARGING; break; case BATTERY_FLAG_NO_BATTERY: Power::Battery::Status = Power::Battery::NOBATTERY; break; case BATTERY_FLAG_UNKNOWN: default: Power::Battery::Status = Power::Battery::UNKNOWN; } switch (sps.ACLineStatus) { case AC_LINE_OFFLINE: Power::External::Status = Power::External::OFF; break; case AC_LINE_BACKUP_POWER: case AC_LINE_ONLINE: Power::External::Status = Power::External::ON; break; case AC_LINE_UNKNOWN: default: Power::External::Status = Power::External::UNKNOWN; } } else { Power::Battery::Status = Power::Battery::UNKNOWN; Power::External::Status = Power::External::UNKNOWN; } } #endif #ifdef KOBO #include "OS/FileUtil.hpp" #include <string.h> #include <stdlib.h> namespace Power { namespace Battery{ unsigned Temperature = 0; unsigned RemainingPercent = 0; bool RemainingPercentValid = false; batterystatus Status = UNKNOWN; }; namespace External{ externalstatus Status = UNKNOWN; }; }; void UpdateBatteryInfo() { // assume failure at entry Power::Battery::RemainingPercentValid = false; Power::Battery::Status = Power::Battery::UNKNOWN; Power::External::Status = Power::External::UNKNOWN; // code shamelessly copied from OS/SystemLoad.cpp char line[256]; if (!File::ReadString("/sys/bus/platform/drivers/pmic_battery/pmic_battery.1/power_supply/mc13892_bat/uevent", line, sizeof(line))) return; char field[80], value[80]; int n; char* ptr = line; while (sscanf(ptr, "%[^=]=%[^\n]\n%n", field, value, &n)==2) { ptr += n; if (!strcmp(field,"POWER_SUPPLY_STATUS")) { if (!strcmp(value,"Not charging") || !strcmp(value,"Charging")) { Power::External::Status = Power::External::ON; } else if (!strcmp(value,"Discharging")) { Power::External::Status = Power::External::OFF; } } else if (!strcmp(field,"POWER_SUPPLY_CAPACITY")) { int rem = atoi(value); Power::Battery::RemainingPercentValid = true; Power::Battery::RemainingPercent = rem; if (Power::External::Status == Power::External::OFF) { if (rem>30) { Power::Battery::Status = Power::Battery::HIGH; } else if (rem>10) { Power::Battery::Status = Power::Battery::LOW; } else if (rem<10) { Power::Battery::Status = Power::Battery::CRITICAL; } } else { Power::Battery::Status = Power::Battery::CHARGING; } } } } #endif #endif<|fim▁end|>
if (result >= sizeof(sps)) { if (sps.BatteryLifePercent != BATTERY_PERCENTAGE_UNKNOWN){ Power::Battery::RemainingPercent = sps.BatteryLifePercent;
<|file_name|>builder.py<|end_file_name|><|fim▁begin|># This program is free software; you can redistribute it and/or modify # it under the terms of the (LGPL) GNU Lesser General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library Lesser General Public License for more details at # ( http://www.gnu.org/licenses/lgpl.html ). # # You should have received a copy of the GNU Lesser General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # written by: Jeff Ortel ( [email protected] ) """ The I{builder} module provides an wsdl/xsd defined types factory """ from logging import getLogger from suds import * from suds.sudsobject import Factory log = getLogger(__name__) class Builder: """ Builder used to construct an object for types defined in the schema """ def __init__(self, resolver): """ @param resolver: A schema object name resolver. @type resolver: L{resolver.Resolver} """ self.resolver = resolver def build(self, name): """ build a an object for the specified typename as defined in the schema """ if isinstance(name, str): type = self.resolver.find(name) if type is None: raise TypeNotFound(name) else: type = name cls = type.name if type.mixed(): data = Factory.property(cls) else: data = Factory.object(cls) resolved = type.resolve() md = data.__metadata__ md.sxtype = resolved md.ordering = self.ordering(resolved) history = [] self.add_attributes(data, resolved) for child, ancestry in type.children(): if self.skip_child(child, ancestry): continue self.process(data, child, history[:]) return data def process(self, data, type, history): """ process the specified type then process its children """ if type in history: return if type.enum(): return history.append(type) resolved = type.resolve() value = None if type.unbounded(): value = [] else:<|fim▁hole|> md.sxtype = resolved else: value = Factory.object(resolved.name) md = value.__metadata__ md.sxtype = resolved md.ordering = self.ordering(resolved) setattr(data, type.name, value) if value is not None: data = value if not isinstance(data, list): self.add_attributes(data, resolved) for child, ancestry in resolved.children(): if self.skip_child(child, ancestry): continue self.process(data, child, history[:]) def add_attributes(self, data, type): """ add required attributes """ for attr, ancestry in type.attributes(): name = '_%s' % attr.name value = attr.get_default() setattr(data, name, value) def skip_child(self, child, ancestry): """ get whether or not to skip the specified child """ if child.any(): return True for x in ancestry: if x.choice(): return True return False def ordering(self, type): """ get the ordering """ result = [] for child, ancestry in type.resolve(): name = child.name if child.name is None: continue if child.isattr(): name = '_%s' % child.name result.append(name) return result<|fim▁end|>
if len(resolved) > 0: if resolved.mixed(): value = Factory.property(resolved.name) md = value.__metadata__
<|file_name|>parse_version.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. ## this functions are taken from the setuptools package (version 0.6c8) ## http://peak.telecommunity.com/DevCenter/PkgResources#parsing-utilities from __future__ import print_function import re from odoo.tools import pycompat component_re = re.compile(r'(\d+ | [a-z]+ | \.| -)', re.VERBOSE) replace = {'pre':'c', 'preview':'c','-':'final-','_':'final-','rc':'c','dev':'@','saas':'','~':''}.get def _parse_version_parts(s): for part in component_re.split(s): part = replace(part,part) if not part or part=='.': continue if part[:1] in '0123456789': yield part.zfill(8) # pad for numeric comparison else: yield '*'+part yield '*final' # ensure that alpha/beta/candidate are before final def parse_version(s): """Convert a version string to a chronologically-sortable key This is a rough cross between distutils' StrictVersion and LooseVersion; if you give it versions that would work with StrictVersion, then it behaves the same; otherwise it acts like a slightly-smarter LooseVersion. It is *possible* to create pathological version coding schemes that will fool this parser, but they should be very rare in practice. The returned value will be a tuple of strings. Numeric portions of the version are padded to 8 digits so they will compare numerically, but without relying on how numbers compare relative to strings. Dots are dropped, but dashes are retained. Trailing zeros between alpha segments or dashes are suppressed, so that e.g. "2.4.0" is considered the same as "2.4". Alphanumeric parts are lower-cased. The algorithm assumes that strings like "-" and any alpha string that<|fim▁hole|> Strings like "a", "b", "c", "alpha", "beta", "candidate" and so on (that come before "final" alphabetically) are assumed to be pre-release versions, so that the version "2.4" is considered newer than "2.4a1". Finally, to handle miscellaneous cases, the strings "pre", "preview", and "rc" are treated as if they were "c", i.e. as though they were release candidates, and therefore are not as new as a version string that does not contain them. """ parts = [] for part in _parse_version_parts((s or '0.1').lower()): if part.startswith('*'): if part<'*final': # remove '-' before a prerelease tag while parts and parts[-1]=='*final-': parts.pop() # remove trailing zeros from each series of numeric parts while parts and parts[-1]=='00000000': parts.pop() parts.append(part) return tuple(parts) if __name__ == '__main__': def chk(lst, verbose=False): pvs = [] for v in lst: pv = parse_version(v) pvs.append(pv) if verbose: print(v, pv) for a, b in pycompat.izip(pvs, pvs[1:]): assert a < b, '%s < %s == %s' % (a, b, a < b) chk(('0', '4.2', '4.2.3.4', '5.0.0-alpha', '5.0.0-rc1', '5.0.0-rc1.1', '5.0.0_rc2', '5.0.0_rc3', '5.0.0'), False) chk(('5.0.0-0_rc3', '5.0.0-1dev', '5.0.0-1'), False)<|fim▁end|>
alphabetically follows "final" represents a "patch level". So, "2.4-1" is assumed to be a branch or patch of "2.4", and therefore "2.4.1" is considered newer than "2.4-1", whic in turn is newer than "2.4".
<|file_name|>function.rs<|end_file_name|><|fim▁begin|>use std::borrow::ToOwned; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::ops::Index; use std::{error,fmt,iter}; use sxd_document::XmlChar; use super::{EvaluationContext,Functions,Value}; use super::nodeset::Nodeset; pub trait Function { fn evaluate<'a, 'd>(&self, context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error>; } #[derive(Copy,Clone,Debug,PartialEq,Hash)] pub enum ArgumentType { Nodeset, Boolean, Number, String, } #[derive(Copy,Clone,Debug,PartialEq,Hash)] pub enum Error { TooManyArguments{ expected: usize, actual: usize }, NotEnoughArguments{ expected: usize, actual: usize }, WrongType{ expected: ArgumentType, actual: ArgumentType }, } impl Error { fn wrong_type(actual: &Value, expected: ArgumentType) -> Error { let actual = match *actual { Value::Nodeset(..) => ArgumentType::Nodeset, Value::String(..) => ArgumentType::String, Value::Number(..) => ArgumentType::Number, Value::Boolean(..) => ArgumentType::Boolean, }; Error::WrongType { expected: expected, actual: actual } } } impl error::Error for Error { fn description(&self) -> &str { use self::Error::*; match *self { TooManyArguments{..} => "too many arguments", NotEnoughArguments{..} => "not enough arguments", WrongType{..} => "argument of wrong type", } } } impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { use self::Error::*; match *self { TooManyArguments{expected, actual} => { write!(fmt, "too many arguments, expected {} but had {}", expected, actual) }, NotEnoughArguments{expected, actual} => { write!(fmt, "not enough arguments, expected {} but had {}", expected, actual) }, WrongType{expected, actual} => { write!(fmt, "argument was the wrong type, expected {:?} but had {:?}", expected, actual) }, } } } struct Args<'d>(Vec<Value<'d>>); impl<'d> Args<'d> { fn len(&self) -> usize { self.0.len() } fn at_least(&self, minimum: usize) -> Result<(), Error> { let actual = self.0.len(); if actual < minimum { Err(Error::NotEnoughArguments{expected: minimum, actual: actual}) } else { Ok(()) } } fn at_most(&self, maximum: usize) -> Result<(), Error> { let actual = self.0.len(); if actual > maximum { Err(Error::TooManyArguments{expected: maximum, actual: actual}) } else { Ok(()) } } fn exactly(&self, expected: usize) -> Result<(), Error> { let actual = self.0.len(); if actual < expected { Err(Error::NotEnoughArguments{ expected: expected, actual: actual }) } else if actual > expected { Err(Error::TooManyArguments{ expected: expected, actual: actual }) } else { Ok(()) } } fn into_strings(self) -> Result<Vec<String>, Error> { fn string_arg(v: Value) -> Result<String, Error> { match v { Value::String(s) => Ok(s), _ => Err(Error::wrong_type(&v, ArgumentType::String)), } } self.0.into_iter().map(string_arg).collect() } fn pop_boolean(&mut self) -> Result<bool, Error> { match self.0.pop().unwrap() { Value::Boolean(v) => Ok(v), a => Err(Error::wrong_type(&a, ArgumentType::Boolean)), } } fn pop_number(&mut self) -> Result<f64, Error> { match self.0.pop().unwrap() { Value::Number(v) => Ok(v), a => Err(Error::wrong_type(&a, ArgumentType::Number)), } } fn pop_string(&mut self) -> Result<String, Error> { match self.0.pop().unwrap() { Value::String(v) => Ok(v), a => Err(Error::wrong_type(&a, ArgumentType::String)), } } fn pop_nodeset(&mut self) -> Result<Nodeset<'d>, Error> { match self.0.pop().unwrap() { Value::Nodeset(v) => Ok(v), a => Err(Error::wrong_type(&a, ArgumentType::Nodeset)), } } fn pop_value_or_context_node<'_>(&mut self, context: &EvaluationContext<'_, 'd>) -> Value<'d> { self.0.pop() .unwrap_or_else(|| Value::Nodeset(nodeset![context.node])) } fn pop_string_value_or_context_node(&mut self, context: &EvaluationContext) -> Result<String, Error> { match self.0.pop() { Some(Value::String(s)) => Ok(s), Some(arg) => Err(Error::wrong_type(&arg, ArgumentType::String)), None => Ok(context.node.string_value()), } } fn pop_nodeset_or_context_node<'_>(&mut self, context: &EvaluationContext<'_, 'd>) -> Result<Nodeset<'d>, Error> { match self.0.pop() { Some(Value::Nodeset(ns)) => Ok(ns), Some(arg) => Err(Error::wrong_type(&arg, ArgumentType::Nodeset)), None => Ok(nodeset![context.node]), } } } impl<'d> Index<usize> for Args<'d> { type Output = Value<'d>; fn index(&self, index: usize) -> &Value<'d> { self.0.index(index) } } struct Last; impl Function for Last { fn evaluate<'a, 'd>(&self, context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let args = Args(args); try!(args.exactly(0)); Ok(Value::Number(context.size() as f64)) } } struct Position; impl Function for Position { fn evaluate<'a, 'd>(&self, context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let args = Args(args); try!(args.exactly(0)); Ok(Value::Number(context.position() as f64)) } } struct Count; impl Function for Count { fn evaluate<'a, 'd>(&self, _context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let mut args = Args(args); try!(args.exactly(1)); let arg = try!(args.pop_nodeset()); Ok(Value::Number(arg.size() as f64)) } } struct LocalName; impl Function for LocalName { fn evaluate<'a, 'd>(&self, context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let mut args = Args(args); try!(args.at_most(1)); let arg = try!(args.pop_nodeset_or_context_node(context)); let name = arg.document_order_first() .and_then(|n| n.expanded_name()) .map(|q| q.local_part()) .unwrap_or(""); Ok(Value::String(name.to_owned())) } } struct NamespaceUri; impl Function for NamespaceUri { fn evaluate<'a, 'd>(&self, context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let mut args = Args(args); try!(args.at_most(1)); let arg = try!(args.pop_nodeset_or_context_node(context)); let name = arg.document_order_first() .and_then(|n| n.expanded_name()) .and_then(|q| q.namespace_uri()) .unwrap_or(""); Ok(Value::String(name.to_owned())) } } struct Name; impl Function for Name { fn evaluate<'a, 'd>(&self, context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let mut args = Args(args); try!(args.at_most(1)); let arg = try!(args.pop_nodeset_or_context_node(context)); let name = arg.document_order_first() .and_then(|n| n.prefixed_name()) .unwrap_or("".to_owned()); Ok(Value::String(name)) } } struct StringFn; impl Function for StringFn { fn evaluate<'a, 'd>(&self, context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let mut args = Args(args); try!(args.at_most(1)); let arg = args.pop_value_or_context_node(context); Ok(Value::String(arg.string())) } } struct Concat; impl Function for Concat { fn evaluate<'a, 'd>(&self, _context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let args = Args(args); try!(args.at_least(2)); let args = try!(args.into_strings()); Ok(Value::String(args.concat())) } } struct TwoStringPredicate(fn(&str, &str) -> bool); impl Function for TwoStringPredicate { fn evaluate<'a, 'd>(&self, _context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let args = Args(args); try!(args.exactly(2)); let args = try!(args.into_strings()); let v = self.0(&args[0], &args[1]); Ok(Value::Boolean(v)) } } fn starts_with() -> TwoStringPredicate { fn imp(a: &str, b: &str) -> bool { str::starts_with(a, b) }; TwoStringPredicate(imp) } fn contains() -> TwoStringPredicate { fn imp(a: &str, b: &str) -> bool { str::contains(a, b) }; TwoStringPredicate(imp) } struct SubstringCommon(for<'s> fn(&'s str, &'s str) -> &'s str); impl Function for SubstringCommon { fn evaluate<'a, 'd>(&self, _context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let args = Args(args); try!(args.exactly(2)); let args = try!(args.into_strings()); let s = self.0(&*args[0], &*args[1]); Ok(Value::String(s.to_owned())) } } fn substring_before() -> SubstringCommon { fn inner<'a>(haystack: &'a str, needle: &'a str) -> &'a str { match haystack.find(needle) { Some(pos) => &haystack[..pos], None => "", } } SubstringCommon(inner) } fn substring_after() -> SubstringCommon { fn inner<'a>(haystack: &'a str, needle: &'a str) -> &'a str { match haystack.find(needle) { Some(pos) => &haystack[pos + needle.len()..], None => "", } } SubstringCommon(inner) } struct Substring; impl Function for Substring { fn evaluate<'a, 'd>(&self, _context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let mut args = Args(args); try!(args.at_least(2)); try!(args.at_most(3)); let len = if args.len() == 3 { let len = try!(args.pop_number()); round_ties_to_positive_infinity(len) } else { ::std::f64::INFINITY }; let start = try!(args.pop_number()); let start = round_ties_to_positive_infinity(start); let s = try!(args.pop_string()); <|fim▁hole|> Some(s) } else { None } }).collect() ; Ok(Value::String(selected_chars)) } } struct StringLength; impl Function for StringLength { fn evaluate<'a, 'd>(&self, context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let mut args = Args(args); try!(args.at_most(1)); let arg = try!(args.pop_string_value_or_context_node(context)); Ok(Value::Number(arg.chars().count() as f64)) } } struct NormalizeSpace; impl Function for NormalizeSpace { fn evaluate<'a, 'd>(&self, context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let mut args = Args(args); try!(args.at_most(1)); let arg = try!(args.pop_string_value_or_context_node(context)); // TODO: research itertools or another pure-iterator solution let s: Vec<_> = arg.split(XmlChar::is_space_char).filter(|s| !s.is_empty()).collect(); let s = s.connect(" "); Ok(Value::String(s)) } } struct Translate; impl Function for Translate { fn evaluate<'a, 'd>(&self, _context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let mut args = Args(args); try!(args.exactly(3)); let to = try!(args.pop_string()); let from = try!(args.pop_string()); let s = try!(args.pop_string()); let mut replacements = HashMap::new(); let pairs = from.chars().zip(to.chars().map(|c| Some(c)).chain(iter::repeat(None))); for (from, to) in pairs { if let Entry::Vacant(entry) = replacements.entry(from) { entry.insert(to); } } let s = s.chars().filter_map(|c| { replacements.get(&c).map(|&s| s).unwrap_or(Some(c)) }).collect(); Ok(Value::String(s)) } } struct BooleanFn; impl Function for BooleanFn { fn evaluate<'a, 'd>(&self, _context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let args = Args(args); try!(args.exactly(1)); Ok(Value::Boolean(args[0].boolean())) } } struct Not; impl Function for Not { fn evaluate<'a, 'd>(&self, _context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let mut args = Args(args); try!(args.exactly(1)); let arg = try!(args.pop_boolean()); Ok(Value::Boolean(!arg)) } } struct BooleanLiteral(bool); impl Function for BooleanLiteral { fn evaluate<'a, 'd>(&self, _context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let args = Args(args); try!(args.exactly(0)); Ok(Value::Boolean(self.0)) } } fn true_fn() -> BooleanLiteral { BooleanLiteral(true) } fn false_fn() -> BooleanLiteral { BooleanLiteral(false) } struct NumberFn; impl Function for NumberFn { fn evaluate<'a, 'd>(&self, context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let mut args = Args(args); try!(args.at_most(1)); let arg = args.pop_value_or_context_node(context); Ok(Value::Number(arg.number())) } } struct Sum; impl Function for Sum { fn evaluate<'a, 'd>(&self, _context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let mut args = Args(args); try!(args.exactly(1)); let arg = try!(args.pop_nodeset()); let r = arg.iter().map(|n| super::str_to_num(&n.string_value())).fold(0.0, |acc, i| acc + i); Ok(Value::Number(r)) } } struct NumberConvert(fn(f64) -> f64); impl Function for NumberConvert { fn evaluate<'a, 'd>(&self, _context: &EvaluationContext<'a, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> { let mut args = Args(args); try!(args.exactly(1)); let arg = try!(args.pop_number()); Ok(Value::Number(self.0(arg))) } } fn floor() -> NumberConvert { NumberConvert(f64::floor) } fn ceiling() -> NumberConvert { NumberConvert(f64::ceil) } // http://stackoverflow.com/a/28124775/155423 fn round_ties_to_positive_infinity(x: f64) -> f64 { let y = x.floor(); if x == y { x } else { let z = (2.0*x-y).floor(); z * x.signum() // Should use copysign } } fn round() -> NumberConvert { NumberConvert(round_ties_to_positive_infinity) } pub fn register_core_functions(functions: &mut Functions) { functions.insert("last".to_owned(), Box::new(Last)); functions.insert("position".to_owned(), Box::new(Position)); functions.insert("count".to_owned(), Box::new(Count)); functions.insert("local-name".to_owned(), Box::new(LocalName)); functions.insert("namespace-uri".to_owned(), Box::new(NamespaceUri)); functions.insert("name".to_owned(), Box::new(Name)); functions.insert("string".to_owned(), Box::new(StringFn)); functions.insert("concat".to_owned(), Box::new(Concat)); functions.insert("starts-with".to_owned(), Box::new(starts_with())); functions.insert("contains".to_owned(), Box::new(contains())); functions.insert("substring-before".to_owned(), Box::new(substring_before())); functions.insert("substring-after".to_owned(), Box::new(substring_after())); functions.insert("substring".to_owned(), Box::new(Substring)); functions.insert("string-length".to_owned(), Box::new(StringLength)); functions.insert("normalize-space".to_owned(), Box::new(NormalizeSpace)); functions.insert("translate".to_owned(), Box::new(Translate)); functions.insert("boolean".to_owned(), Box::new(BooleanFn)); functions.insert("not".to_owned(), Box::new(Not)); functions.insert("true".to_owned(), Box::new(true_fn())); functions.insert("false".to_owned(), Box::new(false_fn())); functions.insert("number".to_owned(), Box::new(NumberFn)); functions.insert("sum".to_owned(), Box::new(Sum)); functions.insert("floor".to_owned(), Box::new(floor())); functions.insert("ceiling".to_owned(), Box::new(ceiling())); functions.insert("round".to_owned(), Box::new(round())); } #[cfg(test)] mod test { use std::borrow::ToOwned; use std::collections::HashMap; use sxd_document::Package; use super::super::{EvaluationContext,LiteralValue,Value,Functions,Variables,Namespaces}; use super::super::nodeset::Node; use super::{ Function, Error, Last, Position, Count, LocalName, NamespaceUri, Name, StringFn, Concat, Substring, StringLength, NormalizeSpace, Translate, BooleanFn, NumberFn, Sum, }; struct Setup<'d> { functions: Functions, variables: Variables<'d>, namespaces: Namespaces, } impl<'d> Setup<'d> { fn new() -> Setup<'d> { Setup { functions: HashMap::new(), variables: HashMap::new(), namespaces: HashMap::new(), } } fn evaluate<N, F>(&self, node: N, f: F, args: Vec<Value<'d>>) -> Result<Value<'d>, Error> where N: Into<Node<'d>>, F: Function { let context = EvaluationContext::new( node, &self.functions, &self.variables, &self.namespaces ); f.evaluate(&context, args) } } fn evaluate_literal<F>(f: F, args: Vec<LiteralValue>) -> Result<LiteralValue, Error> where F: Function { let package = Package::new(); let doc = package.as_document(); let setup = Setup::new(); let args = args.into_iter().map(|a| a.into_value()).collect(); let r = setup.evaluate(doc.root(), f, args); r.map(|r| r.into_literal_value()) } #[test] fn last_returns_context_size() { let r = evaluate_literal(Last, vec![]); assert_eq!(Ok(LiteralValue::Number(1.0)), r); } #[test] fn position_returns_context_position() { let r = evaluate_literal(Position, vec![]); assert_eq!(Ok(LiteralValue::Number(1.0)), r); } #[test] fn count_counts_nodes_in_nodeset() { let package = Package::new(); let doc = package.as_document(); let setup = Setup::new(); let nodeset = nodeset![doc.root()]; let r = setup.evaluate(doc.root(), Count, vec![Value::Nodeset(nodeset)]); assert_eq!(Ok(Value::Number(1.0)), r); } #[test] fn local_name_gets_name_of_element() { let package = Package::new(); let doc = package.as_document(); let setup = Setup::new(); let e = doc.create_element(("uri", "wow")); doc.root().append_child(e); let nodeset = nodeset![e]; let r = setup.evaluate(doc.root(), LocalName, vec![Value::Nodeset(nodeset)]); assert_eq!(Ok(Value::String("wow".to_owned())), r); } #[test] fn local_name_is_empty_for_empty_nodeset() { let package = Package::new(); let doc = package.as_document(); let setup = Setup::new(); let nodeset = nodeset![]; let r = setup.evaluate(doc.root(), LocalName, vec![Value::Nodeset(nodeset)]); assert_eq!(Ok(Value::String("".to_owned())), r); } #[test] fn namespace_uri_gets_uri_of_element() { let package = Package::new(); let doc = package.as_document(); let setup = Setup::new(); let e = doc.create_element(("uri", "wow")); doc.root().append_child(e); let nodeset = nodeset![e]; let r = setup.evaluate(doc.root(), NamespaceUri, vec![Value::Nodeset(nodeset)]); assert_eq!(Ok(Value::String("uri".to_owned())), r); } #[test] fn name_uses_declared_prefix() { let package = Package::new(); let doc = package.as_document(); let setup = Setup::new(); let e = doc.create_element(("uri", "wow")); e.register_prefix("prefix", "uri"); doc.root().append_child(e); let nodeset = nodeset![e]; let r = setup.evaluate(doc.root(), Name, vec![Value::Nodeset(nodeset)]); assert_eq!(Ok(Value::String("prefix:wow".to_owned())), r); } #[test] fn string_converts_to_string() { let args = vec![LiteralValue::Boolean(true)]; let r = evaluate_literal(StringFn, args); assert_eq!(Ok(LiteralValue::String("true".to_owned())), r); } #[test] fn concat_combines_strings() { let args = vec![LiteralValue::String("hello".to_owned()), LiteralValue::String(" ".to_owned()), LiteralValue::String("world".to_owned())]; let r = evaluate_literal(Concat, args); assert_eq!(Ok(LiteralValue::String("hello world".to_owned())), r); } #[test] fn starts_with_checks_prefixes() { let args = vec![LiteralValue::String("hello".to_owned()), LiteralValue::String("he".to_owned())]; let r = evaluate_literal(super::starts_with(), args); assert_eq!(Ok(LiteralValue::Boolean(true)), r); } #[test] fn contains_looks_for_a_needle() { let args = vec![LiteralValue::String("astronomer".to_owned()), LiteralValue::String("ono".to_owned())]; let r = evaluate_literal(super::contains(), args); assert_eq!(Ok(LiteralValue::Boolean(true)), r); } #[test] fn substring_before_slices_before() { let args = vec![LiteralValue::String("1999/04/01".to_owned()), LiteralValue::String("/".to_owned())]; let r = evaluate_literal(super::substring_before(), args); assert_eq!(Ok(LiteralValue::String("1999".to_owned())), r); } #[test] fn substring_after_slices_after() { let args = vec![LiteralValue::String("1999/04/01".to_owned()), LiteralValue::String("/".to_owned())]; let r = evaluate_literal(super::substring_after(), args); assert_eq!(Ok(LiteralValue::String("04/01".to_owned())), r); } #[test] fn substring_is_one_indexed() { let args = vec![LiteralValue::String("あいうえお".to_owned()), LiteralValue::Number(2.0)]; let r = evaluate_literal(Substring, args); assert_eq!(Ok(LiteralValue::String("いうえお".to_owned())), r); } #[test] fn substring_has_optional_length() { let args = vec![LiteralValue::String("あいうえお".to_owned()), LiteralValue::Number(2.0), LiteralValue::Number(3.0)]; let r = evaluate_literal(Substring, args); assert_eq!(Ok(LiteralValue::String("いうえ".to_owned())), r); } fn substring_test(s: &str, start: f64, len: f64) -> String { let args = vec![LiteralValue::String(s.to_owned()), LiteralValue::Number(start), LiteralValue::Number(len)]; match evaluate_literal(Substring, args) { Ok(LiteralValue::String(s)) => s, r => panic!("substring failed: {:?}", r), } } #[test] fn substring_rounds_values() { assert_eq!("いうえ", substring_test("あいうえお", 1.5, 2.6)); } #[test] fn substring_is_a_window_of_the_characters() { assert_eq!("あい", substring_test("あいうえお", 0.0, 3.0)); } #[test] fn substring_with_nan_start_is_empty() { assert_eq!("", substring_test("あいうえお", ::std::f64::NAN, 3.0)); } #[test] fn substring_with_nan_len_is_empty() { assert_eq!("", substring_test("あいうえお", 1.0, ::std::f64::NAN)); } #[test] fn substring_with_infinite_len_goes_to_end_of_string() { assert_eq!("あいうえお", substring_test("あいうえお", -42.0, ::std::f64::INFINITY)); } #[test] fn substring_with_negative_infinity_start_is_empty() { assert_eq!("", substring_test("あいうえお", ::std::f64::NEG_INFINITY, ::std::f64::INFINITY)); } #[test] fn string_length_counts_characters() { let args = vec![LiteralValue::String("日本語".to_owned())]; let r = evaluate_literal(StringLength, args); assert_eq!(Ok(LiteralValue::Number(3.0)), r); } #[test] fn normalize_space_removes_leading_space() { let args = vec![LiteralValue::String("\t hello".to_owned())]; let r = evaluate_literal(NormalizeSpace, args); assert_eq!(Ok(LiteralValue::String("hello".to_owned())), r); } #[test] fn normalize_space_removes_trailing_space() { let args = vec![LiteralValue::String("hello\r\n".to_owned())]; let r = evaluate_literal(NormalizeSpace, args); assert_eq!(Ok(LiteralValue::String("hello".to_owned())), r); } #[test] fn normalize_space_squashes_intermediate_space() { let args = vec![LiteralValue::String("hello\t\r\n world".to_owned())]; let r = evaluate_literal(NormalizeSpace, args); assert_eq!(Ok(LiteralValue::String("hello world".to_owned())), r); } fn translate_test(s: &str, from: &str, to: &str) -> String { let args = vec![LiteralValue::String(s.to_owned()), LiteralValue::String(from.to_owned()), LiteralValue::String(to.to_owned())]; match evaluate_literal(Translate, args) { Ok(LiteralValue::String(s)) => s, r => panic!("translate failed: {:?}", r) } } #[test] fn translate_replaces_characters() { assert_eq!("イエ", translate_test("いえ", "あいうえお", "アイウエオ")); } #[test] fn translate_removes_characters_without_replacement() { assert_eq!("イ", translate_test("いえ", "あいうえお", "アイ")); } #[test] fn translate_replaces_each_char_only_once() { assert_eq!("b", translate_test("a", "ab", "bc")); } #[test] fn translate_uses_first_replacement() { assert_eq!("b", translate_test("a", "aa", "bc")); } #[test] fn translate_ignores_extra_replacements() { assert_eq!("b", translate_test("a", "a", "bc")); } #[test] fn boolean_converts_to_boolean() { let args = vec![LiteralValue::String("false".to_owned())]; let r = evaluate_literal(BooleanFn, args); assert_eq!(Ok(LiteralValue::Boolean(true)), r); } #[test] fn number_converts_to_number() { let args = vec![LiteralValue::String(" -1.2 ".to_owned())]; let r = evaluate_literal(NumberFn, args); assert_eq!(Ok(LiteralValue::Number(-1.2)), r); } #[test] fn sum_adds_up_nodeset() { let package = Package::new(); let doc = package.as_document(); let setup = Setup::new(); let c = doc.create_comment("-32.0"); let t = doc.create_text("98.7"); let nodeset = nodeset![c, t]; let r = setup.evaluate(doc.root(), Sum, vec![Value::Nodeset(nodeset)]); assert_eq!(Ok(Value::Number(66.7)), r); } fn assert_number<F>(f: F, val: f64, expected: f64) where F: Function { let r = evaluate_literal(f, vec![LiteralValue::Number(val)]); if expected.is_nan() { match r { Ok(LiteralValue::Number(a)) => assert!(a.is_nan(), "{} should be NaN", a), _ => assert!(false, "{:?} did not evaluate correctly", r), } } else { assert_eq!(Ok(LiteralValue::Number(expected)), r); } } #[test] fn floor_rounds_down() { assert_number(super::floor(), 199.99, 199.0); } #[test] fn ceiling_rounds_up() { assert_number(super::ceiling(), 199.99, 200.0); } #[test] fn round_nan_to_nan() { assert_number(super::round(), ::std::f64::NAN, ::std::f64::NAN); } #[test] fn round_pos_inf_to_pos_inf() { assert_number(super::round(), ::std::f64::INFINITY, ::std::f64::INFINITY); } #[test] fn round_neg_inf_to_neg_inf() { assert_number(super::round(), ::std::f64::NEG_INFINITY, ::std::f64::NEG_INFINITY); } #[test] fn round_pos_zero_to_pos_zero() { assert_number(super::round(), 0.0, 0.0); } #[test] fn round_neg_zero_to_neg_zero() { assert_number(super::round(), -0.0, -0.0); } #[test] fn round_neg_zero_point_five_to_neg_zero() { assert_number(super::round(), -0.5, -0.0); } #[test] fn round_pos_zero_point_five_to_pos_one() { assert_number(super::round(), 0.5, 1.0); } }<|fim▁end|>
let chars = s.chars().enumerate(); let selected_chars = chars.filter_map(|(p, s)| { let p = (p+1) as f64; // 1-based indexing if p >= start && p < start + len {
<|file_name|>compile.py<|end_file_name|><|fim▁begin|>from sys import stdout from collections import defaultdict from .parse import main, HTMLTag def maybe_call(f, *args, **kwargs): if callable(f): return f(*args, **kwargs) return f class Compiler(object): def __init__(self, stream): self.stream = stream self.blocks = [] self.deferred_endif = () self.tmpvar_count = 0 def start(self, parser): """ Called by the parser to start compiling. """ self.parser = parser def put_tmpvar(self, val): """ Allocate a temporary variable, output assignment, and return the variable name. """ name = '_jade_%d' % self.tmpvar_count self.tmpvar_count += 1 self.stream.write(u'{%% set %s = %s %%}' % (name, val)) return name def dismiss_endif(self): """ Dismiss an endif, only outputting the newlines. The parser doesn't take care of if-elif-else matching. Instead, it will try to close the if block before opening a new elif or else block. Thus the endif block needs to be deferred, along with the newlines after it. When non-empty, self.deferred_endif is a list [endif, newlines]. """ if self.deferred_endif: self.stream.write(self.deferred_endif[1]) self.deferred_endif = () def put_endif(self): """ Output an endif. """ if self.deferred_endif: self.stream.write(''.join(self.deferred_endif)) self.deferred_endif = () def start_block(self, tag): """ Called by the parser to start a block. `tag` can be either an HTMLTag or a ControlTag. """ if tag.name in ('elif', 'else'): self.dismiss_endif() else: self.put_endif() self.blocks.append(tag) if isinstance(tag, HTMLTag): self.stream.write(u'<%s' % tag.name) for a in tag.attr: if isinstance(a, basestring): self.literal(a) continue k, v = a if k == 'id':<|fim▁hole|> self.stream.write( u' class="%s{{ _jade_class(%s) |escape}}"' % (tag.class_ and tag.class_ + u' ' or u'', v)) tag.class_ = None continue self.stream.write(u' %s="{{ %s |escape}}"' % (k, v)) if tag.id_: self.stream.write(u' id="%s"' % tag.id_) if tag.class_: self.stream.write(u' class="%s"' % tag.class_) self.stream.write('>') elif tag.name == 'case': tag.var = self.put_tmpvar(tag.head) tag.seen_when = tag.seen_default = False elif tag.name in ('when', 'default'): case_tag = len(self.blocks) >= 2 and self.blocks[-2] if not case_tag or case_tag.name != 'case': raise self.parser.error( '%s tag not child of case tag' % tag.name) if tag.name == 'when': if case_tag.seen_default: raise self.parser.error('when tag after default tag') self.stream.write(u'{%% %s %s == %s %%}' % ( 'elif' if case_tag.seen_when else 'if', case_tag.var, tag.head)) case_tag.seen_when = True else: if case_tag.seen_default: raise self.parser.error('duplicate default tag') if not case_tag.seen_when: raise self.parser.error('default tag before when tag') self.stream.write(u'{% else %}') case_tag.seen_default = True else: self.stream.write(maybe_call(control_blocks[tag.name][0], tag)) def end_block(self): """ Called by the parser to end a block. The parser doesn't keep track of active blocks. """ tag = self.blocks.pop() if isinstance(tag, HTMLTag): self.stream.write('</%s>' % tag.name) elif tag.name in ('if', 'elif'): self.deferred_endif = [u'{% endif %}', ''] elif tag.name == 'case': if not tag.seen_when: raise self.parser.error('case tag has no when child') self.stream.write('{% endif %}') elif tag.name in ('when', 'default'): pass else: self.stream.write(maybe_call(control_blocks[tag.name][1], tag)) def literal(self, text): """ Called by the parser to output literal text. The parser doesn't keep track of active blocks. """ self.put_endif() self.stream.write(text) def newlines(self, text): """ Called by the parser to output newlines that are part of the indent. """ if self.deferred_endif: self.deferred_endif[1] = text else: self.literal(text) def end(self): """ Called by the parser to terminate compiling. """ self.put_endif() doctypes = { '5': '<!DOCTYPE html>', 'default': '<!DOCTYPE html>', 'xml': '<?xml version="1.0" encoding="utf-8" ?>', 'transitional': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ' 'Transitional//EN" "http://www.w3.org/TR/xhtml1/' 'DTD/xhtml1-transitional.dtd">', 'strict': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ' 'Strict//EN" "http://www.w3.org/TR/xhtml1/' 'DTD/xhtml1-strict.dtd">', 'frameset': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ' 'Frameset//EN" "http://www.w3.org/TR/xhtml1/' 'DTD/xhtml1-frameset.dtd">', '1.1': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" ' '"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">', 'basic': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic ' '1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">', 'mobile': '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" ' '"http://www.openmobilealliance.org/tech/DTD/' 'xhtml-mobile12.dtd">' } def default_start(tag): return '{%% %s %s %%}' % (tag.name, tag.head) def default_end(tag): return '{%% end%s %%}' % tag.name def doctype(tag): return doctypes.get(tag.head.lower() or 'default', '<!DOCTYPE %s>' % tag.head) control_blocks = defaultdict( lambda: (default_start, default_end), { '=': ('{{ ', ' }}'), '!=': ('{{ ', ' |safe}}'), '-': ('{% ', ' %}'), '|': ('', ''), '//': (lambda tag: '<!--%s' % tag.head, '-->'), '//-': ('{#', '#}'), ':': (lambda tag: '{%% filter %s %%}' % tag.head, '{% endfilter %}'), 'mixin': (lambda tag: '{%% macro %s %%}' % tag.head, '{% endmacro %}'), 'prepend': (lambda tag: '{%% block %s %%}' % tag.head, '{{ super() }} {% endblock %}'), 'append': (lambda tag: '{%% block %s %%} {{ super() }}' % tag.head, '{% endblock %}'), 'extends': (default_start, ''), 'doctype': (doctype, ''), 'else': ('{% else %}', '{% endif %}'), }) if __name__ == '__main__': main(Compiler(stdout))<|fim▁end|>
# tag(id=xxx) takes precedence over tag#xxx tag.id_ = None elif k == 'class': # merge tag(class=xxx) with tag.xxx
<|file_name|>base.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 std::vec; use stb_image = stb_image::image; // FIXME: Images must not be copied every frame. Instead we should atomically // reference count them. pub type Image = stb_image::Image<u8>; pub fn Image(width: uint, height: uint, depth: uint, data: ~[u8]) -> Image { stb_image::new_image(width, height, depth, data) } static TEST_IMAGE: [u8, ..4962] = include_bin!("test.jpeg"); pub fn test_image_bin() -> ~[u8] { return vec::from_fn(4962, |i| TEST_IMAGE[i]); } pub fn load_from_memory(buffer: &[u8]) -> Option<Image> { // Can't remember why we do this. Maybe it's what cairo wants static FORCE_DEPTH: uint = 4; match stb_image::load_from_memory_with_depth(buffer, FORCE_DEPTH, true) { stb_image::ImageU8(image) => { assert!(image.depth == 4); // Do color space conversion :( let data = do vec::from_fn(image.width * image.height * 4) |i| { let color = i % 4; let pixel = i / 4; match color { 0 => image.data[pixel * 4 + 2],<|fim▁hole|> 3 => 0xffu8, _ => fail!() } }; assert!(image.data.len() == data.len()); Some(Image(image.width, image.height, image.depth, data)) } stb_image::ImageF32(_image) => fail!(~"HDR images not implemented"), stb_image::Error => None } }<|fim▁end|>
1 => image.data[pixel * 4 + 1], 2 => image.data[pixel * 4 + 0],
<|file_name|>enums.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, division, print_function, unicode_literals CASH_TRANSACTION_TYPES = {'Cashflow', 'Coupon', 'Dividend', 'Payment'} TRANSACTION_TYPES = {'Allocation', 'Block', 'Exercise', 'Expiry', 'Journal', 'Maturity', 'Net', 'Novation', 'Split', 'Trade', 'Transfer'} | CASH_TRANSACTION_TYPES TRANSACTION_INVESTOR_ACTIONS = {'Subscription', 'Redemption'}<|fim▁hole|>TRANSACTION_LIFECYCLE_ACTIONS = {'Acquire', 'Remove'} TRANSACTION_ACTIONS = {'Buy', 'Sell', 'Short Sell', 'Deliver', 'Receive'} | TRANSACTION_LIFECYCLE_ACTIONS | \ TRANSACTION_INVESTOR_ACTIONS TRANSACTION_CANCEL_STATUSES = {'Cancelled', 'Netted', 'Novated'} TRANSACTION_STATUSES = {'New', 'Amended', 'Superseded'} | TRANSACTION_CANCEL_STATUSES<|fim▁end|>
<|file_name|>school-competencies-list.js<|end_file_name|><|fim▁begin|>import Component from '@ember/component'; export default Component.extend({ domains: null<|fim▁hole|><|fim▁end|>
});
<|file_name|>count.py<|end_file_name|><|fim▁begin|>""" count number of reads mapping to features of transcripts """ import os import sys import itertools import pandas as pd import gffutils from bcbio.utils import file_exists from bcbio.distributed.transaction import file_transaction from bcbio.log import logger from bcbio import bam import bcbio.pipeline.datadict as dd def combine_count_files(files, out_file=None, ext=".fpkm"): """ combine a set of count files into a single combined file """ assert all([file_exists(x) for x in files]), \ "Some count files in %s do not exist." % files for f in files: assert file_exists(f), "%s does not exist or is empty." % f col_names = [os.path.basename(x.replace(ext, "")) for x in files] if not out_file: out_dir = os.path.join(os.path.dirname(files[0])) out_file = os.path.join(out_dir, "combined.counts") if file_exists(out_file): return out_file for i, f in enumerate(files): if i == 0: df = pd.io.parsers.read_table(f, sep="\t", index_col=0, header=None, names=[col_names[0]]) else: df = df.join(pd.io.parsers.read_table(f, sep="\t", index_col=0, header=None, names=[col_names[i]])) df.to_csv(out_file, sep="\t", index_label="id") return out_file def annotate_combined_count_file(count_file, gtf_file, out_file=None): dbfn = gtf_file + ".db"<|fim▁hole|> return None if not gffutils: return None db = gffutils.FeatureDB(dbfn, keep_order=True) if not out_file: out_dir = os.path.dirname(count_file) out_file = os.path.join(out_dir, "annotated_combined.counts") # if the genes don't have a gene_id or gene_name set, bail out try: symbol_lookup = {f['gene_id'][0]: f['gene_name'][0] for f in db.features_of_type('exon')} except KeyError: return None df = pd.io.parsers.read_table(count_file, sep="\t", index_col=0, header=0) df['symbol'] = df.apply(lambda x: symbol_lookup.get(x.name, ""), axis=1) df.to_csv(out_file, sep="\t", index_label="id") return out_file<|fim▁end|>
if not file_exists(dbfn):
<|file_name|>SerialExecutor.cpp<|end_file_name|><|fim▁begin|>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "SerialExecutor.h" namespace facebook { namespace hermes { namespace inspector { namespace detail { SerialExecutor::SerialExecutor(const std::string &name) : finish_(false), thread_(name, [this]() { runLoop(); }) {} SerialExecutor::~SerialExecutor() { { std::lock_guard<std::mutex> lock(mutex_); finish_ = true; wakeup_.notify_one(); } thread_.join(); } void SerialExecutor::add(folly::Func func) { std::lock_guard<std::mutex> lock(mutex_); funcs_.push(std::move(func));<|fim▁hole|> wakeup_.notify_one(); } void SerialExecutor::runLoop() { bool shouldExit = false; while (!shouldExit) { folly::Func func; { std::unique_lock<std::mutex> lock(mutex_); wakeup_.wait(lock, [this] { return finish_ || !funcs_.empty(); }); if (!funcs_.empty()) { func = std::move(funcs_.front()); funcs_.pop(); } shouldExit = funcs_.empty() && finish_; } if (func) { func(); } } } } // namespace detail } // namespace inspector } // namespace hermes } // namespace facebook<|fim▁end|>
<|file_name|>SearchPage.tsx<|end_file_name|><|fim▁begin|>import * as React from 'react'; import { Menu, Container, Checkbox, Icon } from 'semantic-ui-react'; import * as SelectRP from 'react-select-plus'; import SearchPageState from '../State/Pages/SearchPageState'; import MealSearchFilter from '../State/Meal/Filters/MealSearchFilter'; import { MealTime } from '../State/Meal/Filters/MealTime'; import CeraonDispatcher from '../Store/CeraonDispatcher'; import * as Actions from '../Actions/Index'; import LoadingSpinner from '../Components/LoadingSpinner'; import Meal from '../State/Meal/Meal'; import Tag from '../State/Meal/Tag'; import MealCard, { MealCardMode } from '../Components/MealCard'; export interface SearchPageProps extends SearchPageState, React.Props<SearchPage> { } interface SearchPageInternalState { searchValue: string; tagsFilter: Tag; } export default class SearchPage extends React.Component<SearchPageProps, SearchPageInternalState> { constructor() { super(); this.onMealTimeClicked = this.onMealTimeClicked.bind(this); this.onSearchTextInput = this.onSearchTextInput.bind(this); this.onSearchTextEnter = this.onSearchTextEnter.bind(this); this.onTagFilterChange = this.onTagFilterChange .bind(this); this.removeTextFilter = this.removeTextFilter.bind(this); this.viewMeal = this.viewMeal.bind(this); CeraonDispatcher(Actions.createFetchTagsAction()); this.state = {searchValue: '', tagsFilter: {id: null, title: null, alias: null}}; } viewMeal(id: string) { CeraonDispatcher(Actions.createViewMealAction(id)); } removeTextFilter(filter: string) { let newFilters = Object.assign({}, this.props.filters); let index = newFilters.textFilter.findIndex((txtFilter) => {<|fim▁hole|> if (index > -1) { newFilters.textFilter.splice(index, 1); } CeraonDispatcher(Actions.createMealSearchAction(newFilters)); } onSearchTextEnter(event: any) { let searchValue = this.state.searchValue; if (searchValue.length > 0 && event.keyCode === 13) { this.setState({searchValue: ''}); let newFilters = Object.assign({}, this.props.filters); newFilters.textFilter.push(searchValue); CeraonDispatcher(Actions.createMealSearchAction(newFilters)); } } onSearchTextInput(event: any) { let searchValue = event.target.value; this.setState({searchValue: searchValue}); } onTagFilterChange(tag: Tag) { this.setState({tagsFilter: tag}); let newFilters = Object.assign({}, this.props.filters); if(tag.id === null) { newFilters.tagsFilter = []; } else { newFilters.tagsFilter = [tag]; } CeraonDispatcher(Actions.createMealSearchAction(newFilters)); } onMealTimeClicked(event: any, data: any) { let newFilters = Object.assign({}, this.props.filters); newFilters.mealTime = data.value as MealTime; CeraonDispatcher(Actions.createMealSearchAction(newFilters)); } render() { let textFilters = []; let i = 0; for (let filter of this.props.filters.textFilter) { textFilters.push(( <Menu.Item key={i++}> <a onClick={()=>this.removeTextFilter(filter)}><Icon name='remove'/></a> {filter} </Menu.Item> )); } let resultCards = []; for (let result of this.props.results) { resultCards.push( <MealCard key={result.id} meal={result} mealCardMode={MealCardMode.Full} onClick={(result: Meal)=>{ this.viewMeal(result.id)} }/> ); } return ( <div className='ui stackable grid'> <div className='column search-page-filters'> <div className='ui menu vertical stackable left'> <Menu.Item> <div className="ui input"> <input className='prompt' type='text' placeholder='Filter by name' value={this.state.searchValue} onChange={this.onSearchTextInput} onKeyUp={this.onSearchTextEnter}/> </div> {textFilters} </Menu.Item> <Menu.Item> <Menu.Header>Meal Time</Menu.Header> <Menu.Item> <Checkbox radio name='mealTime' label='Breakfast' onChange={this.onMealTimeClicked} checked={this.props.filters.mealTime == MealTime.Breakfast} value={MealTime.Breakfast}/> </Menu.Item> <Menu.Item> <Checkbox radio name='mealTime' label='Lunch' onChange={this.onMealTimeClicked} checked={this.props.filters.mealTime == MealTime.Lunch} value={MealTime.Lunch}/> </Menu.Item> <Menu.Item> <Checkbox radio name='mealTime' label='Dinner' onChange={this.onMealTimeClicked} checked={this.props.filters.mealTime == MealTime.Dinner} value={MealTime.Dinner}/> </Menu.Item> <Menu.Item> <Checkbox radio name='mealTime' label='Any Time' onChange={this.onMealTimeClicked} checked={this.props.filters.mealTime == MealTime.Any} value={MealTime.Any}/> </Menu.Item> </Menu.Item> <Menu.Item> <Menu.Header>Food Type</Menu.Header> <SelectRP multi={false} valueKey='id' labelKey='title' options={this.props.mealTags} onChange={this.onTagFilterChange} label={this.state.tagsFilter.title} value={this.state.tagsFilter.id} resetValue={{id: null, title: 'Select a type', alias: null}} /> </Menu.Item> </div> </div> <div className='column search-results-wrapper'> {this.props.isLoading ? <LoadingSpinner loadingStatusMessage={'Searching through thousands of meals..'}/> : resultCards } </div> </div> ) } }<|fim▁end|>
return txtFilter == filter; });
<|file_name|>rakibolanamalagasy.py<|end_file_name|><|fim▁begin|>from threading import Lock import requests from api.decorator import critical_section from api.importer import AdditionalDataImporter from api.importer import AdditionalDataImporterError from api.importer.wiktionary import dyn_backend rmi_lock = Lock() class DictionaryImporter(AdditionalDataImporter): def populate_cache(self, language): rq_params = { 'language': 'eq.' + language } response = requests.get(dyn_backend.backend + '/word', rq_params) query = response.json() for json in query: self.word_id_cache[(json['word'], json['language'])] = json['id'] class TenyMalagasyImporter(DictionaryImporter): data_type = 'tenymalagasy/definition' class RakibolanaMalagasyImporter(DictionaryImporter): data_type = 'rakibolana/definition' @critical_section(rmi_lock) def write_tif(self, title, language, additional_data): temp = self.data_type self.data_type = 'rakibolana/derived' try: self.write_additional_data(title, language, additional_data) except AdditionalDataImporterError as exc: pass self.data_type = temp @critical_section(rmi_lock) def write_raw(self, title, language, additional_data): temp = self.data_type<|fim▁hole|> self.write_additional_data(title, language, additional_data) except AdditionalDataImporterError as exc: pass self.data_type = temp def get_data(self, template_title: str, wikipage: str, language: str): pass<|fim▁end|>
self.data_type = 'rakibolana/raw' try:
<|file_name|>threads.rs<|end_file_name|><|fim▁begin|>//! Threading code. use std::mem; use remacs_macros::lisp_fn; use remacs_sys::{current_thread, thread_state}; use buffers::LispBufferRef; use lisp::{ExternalPtr, LispObject}; use lisp::defsubr; pub type ThreadStateRef = ExternalPtr<thread_state>; pub struct ThreadState {} impl ThreadState { pub fn current_buffer() -> LispBufferRef { unsafe { mem::transmute((*current_thread).m_current_buffer) } } } impl ThreadStateRef { #[inline] pub fn name(self) -> LispObject { LispObject::from_raw(self.name) }<|fim▁hole|> } } /// Return the name of the THREAD. /// The name is the same object that was passed to `make-thread'. #[lisp_fn] pub fn thread_name(thread: ThreadStateRef) -> LispObject { thread.name() } /// Return t if THREAD is alive, or nil if it has exited. #[lisp_fn] pub fn thread_alive_p(thread: ThreadStateRef) -> bool { thread.is_alive() } include!(concat!(env!("OUT_DIR"), "/threads_exports.rs"));<|fim▁end|>
#[inline] pub fn is_alive(self) -> bool { !self.m_specpdl.is_null()
<|file_name|>client.js<|end_file_name|><|fim▁begin|>var nock = require('nock'); var Mockaroo = require('../lib/mockaroo'); require('chai').should(); describe('Client', function() { describe('constructor', function() { it('should require an api key', function() { (function() { new Mockaroo.Client({}); }).should.throw('apiKey is required'); }); }); describe('convertError', function() { var client = new Mockaroo.Client({ apiKey: 'xxx' }); it('should convert Invalid API Key to InvalidApiKeyError', function() { client.convertError({ data: { error: 'Invalid API Key' }}).should.be.a.instanceOf(Mockaroo.errors.InvalidApiKeyError) }); it('should convert errors containing "limited" to UsageLimitExceededError', function() { client.convertError({ data: { error: 'Silver plans are limited to 1,000,000 records per day.' }}).should.be.a.instanceOf(Mockaroo.errors.UsageLimitExceededError) });<|fim▁hole|> }); describe('getUrl', function() { it('should default to https://mockaroo.com', function() { var client = new Mockaroo.Client({ apiKey: 'xxx' }); client.getUrl().should.equal('https://mockaroo.com/api/generate.json?client=node&key=xxx&count=1') }); it('should allow you to change the port', function() { var client = new Mockaroo.Client({ apiKey: 'xxx', secure: false, port: 3000 }); client.getUrl().should.equal('http://mockaroo.com:3000/api/generate.json?client=node&key=xxx&count=1'); }); it('should use http when secure:false', function() { var client = new Mockaroo.Client({ apiKey: 'xxx', secure: false }); client.getUrl().should.equal('http://mockaroo.com/api/generate.json?client=node&key=xxx&count=1'); }); it('should allow you to set a count > 1', function() { var client = new Mockaroo.Client({ apiKey: 'xxx', }); client.getUrl({count: 10}).should.equal('https://mockaroo.com/api/generate.json?client=node&key=xxx&count=10'); }); it('should allow you to customize the host', function() { var client = new Mockaroo.Client({ apiKey: 'xxx', host: 'foo' }); client.getUrl().should.equal('https://foo/api/generate.json?client=node&key=xxx&count=1'); }); it('should include schema', function() { var client = new Mockaroo.Client({ apiKey: 'xxx' }); client.getUrl({schema: 'MySchema'}).should.equal('https://mockaroo.com/api/generate.json?client=node&key=xxx&count=1&schema=MySchema'); }); it('should allow you to generate csv', function() { var client = new Mockaroo.Client({ apiKey: 'xxx' }); client.getUrl({format: 'csv'}).should.equal('https://mockaroo.com/api/generate.csv?client=node&key=xxx&count=1'); }); it('should allow you to remove the header from csv', function() { var client = new Mockaroo.Client({ apiKey: 'xxx' }); client.getUrl({format: 'csv', header: false}).should.equal('https://mockaroo.com/api/generate.csv?client=node&key=xxx&count=1&header=false'); }) }); describe('generate', function() { var client = new Mockaroo.Client({ secure: false, apiKey: 'xxx' }); it('should require fields or schema', function() { (function() { client.generate() }).should.throw('Either fields or schema option must be specified'); }); describe('when successful', function() { var api = nock('http://mockaroo.com') .post('/api/generate.json?client=node&key=xxx&count=1') .reply(200, JSON.stringify([{ foo: 'bar' }])) it('should resolve', function() { return client.generate({ fields: [{ name: 'foo', type: 'Custom List', values: ['bar'] }] }).then(function(records) { records.should.deep.equal([{ foo: 'bar' }]); }) }); }) describe('when unsuccessful', function() { var api = nock('http://mockaroo.com') .post('/api/generate.json?client=node&key=xxx&count=1') .reply(500, JSON.stringify({ error: 'Invalid API Key' })) it('should handle errors', function() { return client.generate({ fields: [] }).catch(function(error) { error.should.be.instanceOf(Mockaroo.errors.InvalidApiKeyError) }) }); }); it('should required fields to be an array', function() { (function() { client.generate({ fields: 'foo' }) }).should.throw('fields must be an array'); }); it('should required a name for each field', function() { (function() { client.generate({ fields: [{ type: 'Row Number' }] }) }).should.throw('each field must have a name'); }); it('should required a type for each field', function() { (function() { client.generate({ fields: [{ name: 'ID' }] }) }).should.throw('each field must have a type'); }); }); });<|fim▁end|>
<|file_name|>IADSR.cpp<|end_file_name|><|fim▁begin|>//////////////////////////////////////////////////////////////////////// // This file is part of the SndObj library // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright (c)Victor Lazzarini, 1997-2004 // See License.txt for a disclaimer of all warranties // and licensing information //************************************************************// // IADSR.cpp: implementation of the IADSR class // // ADSR with init and end values // // // // // //************************************************************// #include "IADSR.h" //////////////// CONSTRUCTION / DESTRUCTION //////////////////// IADSR::IADSR(){ m_init = m_end = 0.f; AddMsg("init", 31); AddMsg("end", 32); } IADSR::IADSR(float init, float att, float maxamp, float dec, float sus, float rel, float end, float dur, SndObj* InObj, int vecsize, float sr) : ADSR(att, maxamp, dec, sus, rel,dur,InObj, vecsize, sr) { m_init = init; m_end = end; AddMsg("init", 31); AddMsg("end", 32); } IADSR::~IADSR(){ } ////////////////// OPERATIONS /////////////////////////////// int IADSR::Set(char* mess, float value){ switch (FindMsg(mess)){ case 31: SetInit(value); return 1; case 32: SetEnd(value); return 1; default: return ADSR::Set(mess,value); } } short IADSR::DoProcess() {<|fim▁hole|> if(m_count == m_dur)m_count=0; if(m_count < m_att) a = ((m_maxamp - m_init)/m_att)*m_count + m_init; if(m_count >= m_att && m_count < (m_att+m_dec)) a = ((m_sus - m_maxamp)/m_dec)*(m_count - m_att) + m_maxamp; if(m_count >= (m_att+m_dec) && m_count <= (m_dur - m_rel)) a = m_sus; if (m_count > (m_dur - m_rel)) { if( !m_sustain){ a = ((m_end - m_sus)/m_rel)*(m_count - (m_dur - m_rel)) + m_sus; m_count++; } else a = m_sus; } else m_count++; if(m_input) m_output[m_vecpos] = m_input->Output(m_vecpos)*a; else m_output[m_vecpos] = a; } else m_output[m_vecpos] = 0.f ; } return 1; } else return 0; }<|fim▁end|>
if(!m_error){ float a = 0.f; for(m_vecpos=0; m_vecpos < m_vecsize; m_vecpos++){ if(m_enable){
<|file_name|>useful.py<|end_file_name|><|fim▁begin|># # This file is part of pyasn1 software. # # Copyright (c) 2005-2017, Ilya Etingof <[email protected]> # License: http://pyasn1.sf.net/license.html #<|fim▁hole|> NoValue = univ.NoValue noValue = univ.noValue class ObjectDescriptor(char.GraphicString): __doc__ = char.GraphicString.__doc__ #: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects tagSet = char.GraphicString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 7) ) class GeneralizedTime(char.VisibleString): __doc__ = char.GraphicString.__doc__ #: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects tagSet = char.VisibleString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 24) ) class UTCTime(char.VisibleString): __doc__ = char.GraphicString.__doc__ #: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects tagSet = char.VisibleString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 23) )<|fim▁end|>
from pyasn1.type import univ, char, tag __all__ = ['ObjectDescriptor', 'GeneralizedTime', 'UTCTime']
<|file_name|>build.rs<|end_file_name|><|fim▁begin|>// Copyright © 2015, Peter Atashian<|fim▁hole|> println!("cargo:rustc-link-lib=comctl32"); }<|fim▁end|>
// Licensed under the MIT License <LICENSE.md> fn main() {
<|file_name|>create.js<|end_file_name|><|fim▁begin|>;(function(){ 'use strict' const express = require('express'); const router = express.Router(); router.post('/', function(req, res){ console.error('route: /create, ip: %s, time: %s', req.ip, new Date().toTimeString().substr(0,9)); console.error(Object.keys(req)); console.error(req.body); res.status(200).json('user created!'); }); module.exports = router;<|fim▁hole|><|fim▁end|>
})();
<|file_name|>grunt-iconv.js<|end_file_name|><|fim▁begin|>/* * y * * * Copyright (c) 2013 ssddi456 * Licensed under the MIT license. */ 'use strict'; var iconvLite = require('iconv-lite'); var _ = require('underscore'); var path = require('path'); module.exports = function(grunt) { function detectDestType (dest) { if (grunt.util._.endsWith(dest, path.sep)) { return 'directory'; } else { return 'file'; } }; function unixifyPath (filepath) { if (process.platform === 'win32') { return filepath.replace(/\\/g, '/'); } else { return filepath; } }; grunt.registerMultiTask('grunt-iconv-lite', 'trans encoding', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ fromEncoding : 'utf8', toEncoding : 'gb2312' }); // Iterate over all specified file groups. this.files.forEach(function(f) { var isExpandedPair = f.orig.expand || false; // Concat specified files. f.src.filter(function(src) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(src)) { grunt.log.warn('Source file "' + src + '" not found.'); return false; } else { return true; } }).forEach(function(src) { var dest; if (detectDestType(f.dest) === 'directory') { dest = (isExpandedPair) ? f.dest : unixifyPath(path.join(f.dest, src)); } else { dest = f.dest; } if (grunt.file.isDir(src)) { // grunt.log.writeln('Creating ' + dest.cyan); grunt.file.mkdir(dest); } else { // grunt.log.writeln('Copying ' + src.cyan + ' -> ' + dest.cyan); // Read file source.<|fim▁hole|> grunt.file.copy(src, dest, { encoding : options.fromEncoding, process : function( content ){ return iconvLite.encode(new Buffer(content),options.toEncoding); } }); // Print a success message. grunt.log.writeln('File "' + f.dest + '" transed.'); } }); }); }); };<|fim▁end|>
<|file_name|>StmtNodes.py<|end_file_name|><|fim▁begin|>from .Child import Child from .Node import Node # noqa: I201 STMT_NODES = [ # continue-stmt -> 'continue' label? ';'? Node('ContinueStmt', kind='Stmt', children=[ Child('ContinueKeyword', kind='ContinueToken'), Child('Label', kind='IdentifierToken', is_optional=True), ]), # while-stmt -> label? ':'? 'while' condition-list code-block ';'? Node('WhileStmt', kind='Stmt', traits=['WithCodeBlock', 'Labeled'], children=[ Child('LabelName', kind='IdentifierToken', is_optional=True), Child('LabelColon', kind='ColonToken', is_optional=True), Child('WhileKeyword', kind='WhileToken'), Child('Conditions', kind='ConditionElementList', collection_element_name='Condition'), Child('Body', kind='CodeBlock'), ]), # defer-stmt -> 'defer' code-block ';'? Node('DeferStmt', kind='Stmt', traits=['WithCodeBlock'], children=[ Child('DeferKeyword', kind='DeferToken'), Child('Body', kind='CodeBlock'), ]), # expr-stmt -> expression ';'? Node('ExpressionStmt', kind='Stmt', children=[ Child('Expression', kind='Expr'), ]), # switch-case-list -> switch-case switch-case-list? Node('SwitchCaseList', kind='SyntaxCollection', element='Syntax', element_name='SwitchCase', element_choices=['SwitchCase', 'IfConfigDecl']), # repeat-while-stmt -> label? ':'? 'repeat' code-block 'while' expr ';'? Node('RepeatWhileStmt', kind='Stmt', traits=['WithCodeBlock', 'Labeled'], children=[ Child('LabelName', kind='IdentifierToken', is_optional=True), Child('LabelColon', kind='ColonToken', is_optional=True), Child('RepeatKeyword', kind='RepeatToken'), Child('Body', kind='CodeBlock'), Child('WhileKeyword', kind='WhileToken'), Child('Condition', kind='Expr'), ]), # guard-stmt -> 'guard' condition-list 'else' code-block ';'? Node('GuardStmt', kind='Stmt', traits=['WithCodeBlock'], children=[ Child('GuardKeyword', kind='GuardToken'), Child('Conditions', kind='ConditionElementList', collection_element_name='Condition'), Child('ElseKeyword', kind='ElseToken'), Child('Body', kind='CodeBlock'), ]), Node('WhereClause', kind='Syntax', children=[ Child('WhereKeyword', kind='WhereToken'), Child('GuardResult', kind='Expr'), ]), # for-in-stmt -> label? ':'? # 'for' 'try'? 'await'? 'case'? pattern 'in' expr 'where'? # expr code-block ';'? Node('ForInStmt', kind='Stmt', traits=['WithCodeBlock', 'Labeled'], children=[ Child('LabelName', kind='IdentifierToken', is_optional=True), Child('LabelColon', kind='ColonToken', is_optional=True), Child('ForKeyword', kind='ForToken'), Child('TryKeyword', kind='TryToken', is_optional=True), Child('AwaitKeyword', kind='IdentifierToken', classification='Keyword', text_choices=['await'], is_optional=True), Child('CaseKeyword', kind='CaseToken', is_optional=True), Child('Pattern', kind='Pattern'), Child('TypeAnnotation', kind='TypeAnnotation', is_optional=True), Child('InKeyword', kind='InToken'), Child('SequenceExpr', kind='Expr'), Child('WhereClause', kind='WhereClause', is_optional=True), Child('Body', kind='CodeBlock'), ]), # switch-stmt -> identifier? ':'? 'switch' expr '{' # switch-case-list '}' ';'? Node('SwitchStmt', kind='Stmt', traits=['Braced', 'Labeled'], children=[ Child('LabelName', kind='IdentifierToken', is_optional=True), Child('LabelColon', kind='ColonToken', is_optional=True), Child('SwitchKeyword', kind='SwitchToken'), Child('Expression', kind='Expr'), Child('LeftBrace', kind='LeftBraceToken'), Child('Cases', kind='SwitchCaseList', collection_element_name='Case'), Child('RightBrace', kind='RightBraceToken'), ]), # catch-clause-list -> catch-clause catch-clause-list? Node('CatchClauseList', kind='SyntaxCollection', element='CatchClause'), # do-stmt -> identifier? ':'? 'do' code-block catch-clause-list ';'? Node('DoStmt', kind='Stmt', traits=['WithCodeBlock', 'Labeled'], children=[ Child('LabelName', kind='IdentifierToken', is_optional=True), Child('LabelColon', kind='ColonToken', is_optional=True), Child('DoKeyword', kind='DoToken'), Child('Body', kind='CodeBlock'), Child('CatchClauses', kind='CatchClauseList', collection_element_name='CatchClause', is_optional=True), ]), # return-stmt -> 'return' expr? ';'? Node('ReturnStmt', kind='Stmt', children=[ Child('ReturnKeyword', kind='ReturnToken'), Child('Expression', kind='Expr', is_optional=True), ]), # yield-stmt -> 'yield' '('? expr-list? ')'? Node('YieldStmt', kind='Stmt', children=[ Child('YieldKeyword', kind='YieldToken'), Child('Yields', kind='Syntax', node_choices=[ Child('YieldList', kind='YieldList'), Child('SimpleYield', kind='Expr'), ]), ]), Node('YieldList', kind='Syntax', children=[ Child('LeftParen', kind='LeftParenToken'), Child('ElementList', kind='ExprList', collection_element_name='Element'), Child('TrailingComma', kind='CommaToken', is_optional=True), Child('RightParen', kind='RightParenToken'), ]), # fallthrough-stmt -> 'fallthrough' ';'? Node('FallthroughStmt', kind='Stmt', children=[ Child('FallthroughKeyword', kind='FallthroughToken'), ]), # break-stmt -> 'break' identifier? ';'? Node('BreakStmt', kind='Stmt', children=[ Child('BreakKeyword', kind='BreakToken'), Child('Label', kind='IdentifierToken', is_optional=True), ]), # case-item-list -> case-item case-item-list? Node('CaseItemList', kind='SyntaxCollection', element='CaseItem'), # catch-item-list -> catch-item catch-item-list? Node('CatchItemList', kind='SyntaxCollection', element='CatchItem'), # condition -> expression # | availability-condition # | case-condition # | optional-binding-condition Node('ConditionElement', kind='Syntax', traits=['WithTrailingComma'], children=[ Child('Condition', kind='Syntax', node_choices=[ Child('Expression', kind='Expr'), Child('Availablity', kind='AvailabilityCondition'), Child('Unavailablity', kind='UnavailabilityCondition'), Child('MatchingPattern', kind='MatchingPatternCondition'), Child('OptionalBinding', kind='OptionalBindingCondition'), ]), Child('TrailingComma', kind='CommaToken', is_optional=True), ]), # availability-condition -> '#available' '(' availability-spec ')' Node('AvailabilityCondition', kind='Syntax', children=[ Child('PoundAvailableKeyword', kind='PoundAvailableToken'), Child('LeftParen', kind='LeftParenToken'), Child('AvailabilitySpec', kind='AvailabilitySpecList', collection_element_name='AvailabilityArgument'), Child('RightParen', kind='RightParenToken'), ]), Node('MatchingPatternCondition', kind='Syntax', children=[ Child('CaseKeyword', kind='CaseToken'), Child('Pattern', kind='Pattern'), Child('TypeAnnotation', kind='TypeAnnotation', is_optional=True), Child('Initializer', kind='InitializerClause'), ]), Node('OptionalBindingCondition', kind='Syntax', children=[ Child('LetOrVarKeyword', kind='Token', token_choices=[ 'LetToken', 'VarToken', ]), Child('Pattern', kind='Pattern'), Child('TypeAnnotation', kind='TypeAnnotation', is_optional=True), Child('Initializer', kind='InitializerClause'), ]), # unavailability-condition -> '#unavailable' '(' availability-spec ')'<|fim▁hole|> Node('UnavailabilityCondition', kind='Syntax', children=[ Child('PoundUnavailableKeyword', kind='PoundUnavailableToken'), Child('LeftParen', kind='LeftParenToken'), Child('AvailabilitySpec', kind='AvailabilitySpecList', collection_element_name='AvailabilityArgument'), Child('RightParen', kind='RightParenToken'), ]), # condition-list -> condition # | condition ','? condition-list Node('ConditionElementList', kind='SyntaxCollection', element='ConditionElement'), # A declaration in statement position. # struct Foo {}; Node('DeclarationStmt', kind='Stmt', children=[ Child('Declaration', kind='Decl'), ]), # throw-stmt -> 'throw' expr ';'? Node('ThrowStmt', kind='Stmt', children=[ Child('ThrowKeyword', kind='ThrowToken'), Child('Expression', kind='Expr'), ]), # if-stmt -> identifier? ':'? 'if' condition-list code-block # else-clause ';'? Node('IfStmt', kind='Stmt', traits=['WithCodeBlock', 'Labeled'], children=[ Child('LabelName', kind='IdentifierToken', is_optional=True), Child('LabelColon', kind='ColonToken', is_optional=True), Child('IfKeyword', kind='IfToken'), Child('Conditions', kind='ConditionElementList', collection_element_name='Condition'), Child('Body', kind='CodeBlock'), Child('ElseKeyword', kind='ElseToken', is_optional=True), Child('ElseBody', kind='Syntax', node_choices=[ Child('IfStmt', kind='IfStmt'), Child('CodeBlock', kind='CodeBlock'), ], is_optional=True), ]), # else-if-continuation -> label? ':'? 'while' condition-list code-block ';' Node('ElseIfContinuation', kind='Syntax', children=[ Child('IfStatement', kind='IfStmt'), ]), # else-clause -> 'else' code-block Node('ElseBlock', kind='Syntax', traits=['WithCodeBlock'], children=[ Child('ElseKeyword', kind='ElseToken'), Child('Body', kind='CodeBlock'), ]), # switch-case -> unknown-attr? switch-case-label stmt-list # | unknown-attr? switch-default-label stmt-list Node('SwitchCase', kind='Syntax', traits=['WithStatements'], children=[ Child('UnknownAttr', kind='Attribute', is_optional=True), Child('Label', kind='Syntax', node_choices=[ Child('Default', kind='SwitchDefaultLabel'), Child('Case', kind='SwitchCaseLabel'), ]), Child('Statements', kind='CodeBlockItemList', collection_element_name='Statement'), ]), # switch-default-label -> 'default' ':' Node('SwitchDefaultLabel', kind='Syntax', children=[ Child('DefaultKeyword', kind='DefaultToken'), Child('Colon', kind='ColonToken'), ]), # case-item -> pattern where-clause? ','? Node('CaseItem', kind='Syntax', traits=['WithTrailingComma'], children=[ Child('Pattern', kind='Pattern'), Child('WhereClause', kind='WhereClause', is_optional=True), Child('TrailingComma', kind='CommaToken', is_optional=True), ]), # catch-item -> pattern? where-clause? ','? Node('CatchItem', kind='Syntax', traits=['WithTrailingComma'], children=[ Child('Pattern', kind='Pattern', is_optional=True), Child('WhereClause', kind='WhereClause', is_optional=True), Child('TrailingComma', kind='CommaToken', is_optional=True), ]), # switch-case-label -> 'case' case-item-list ':' Node('SwitchCaseLabel', kind='Syntax', children=[ Child('CaseKeyword', kind='CaseToken'), Child('CaseItems', kind='CaseItemList', collection_element_name='CaseItem'), Child('Colon', kind='ColonToken'), ]), # catch-clause 'catch' case-item-list? code-block Node('CatchClause', kind='Syntax', traits=['WithCodeBlock'], children=[ Child('CatchKeyword', kind='CatchToken'), Child('CatchItems', kind='CatchItemList', collection_element_name='CatchItem', is_optional=True), Child('Body', kind='CodeBlock'), ]), # e.g. #assert(1 == 2) Node('PoundAssertStmt', kind='Stmt', children=[ Child('PoundAssert', kind='PoundAssertToken'), Child('LeftParen', kind='LeftParenToken'), Child('Condition', kind='Expr', description='The assertion condition.'), Child('Comma', kind='CommaToken', is_optional=True, description='The comma after the assertion condition.'), Child('Message', kind='StringLiteralToken', is_optional=True, description='The assertion message.'), Child('RightParen', kind='RightParenToken'), ]), ]<|fim▁end|>
<|file_name|>test_functional.py<|end_file_name|><|fim▁begin|># # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os import time import uuid import concurrent.futures from oslo_config import cfg import six.moves from testtools import matchers import oslo_messaging from oslo_messaging.tests.functional import utils class CallTestCase(utils.SkipIfNoTransportURL): def setUp(self): super(CallTestCase, self).setUp(conf=cfg.ConfigOpts()) if self.url.startswith("kafka://"): self.skipTest("kafka does not support RPC API") self.conf.prog = "test_prog" self.conf.project = "test_project" self.config(heartbeat_timeout_threshold=0, group='oslo_messaging_rabbit') def test_specific_server(self): group = self.useFixture(utils.RpcServerGroupFixture( self.conf, self.url) ) client = group.client(1) client.append(text='open') self.assertEqual('openstack', client.append(text='stack')) client.add(increment=2) self.assertEqual(12, client.add(increment=10)) self.assertEqual(9, client.subtract(increment=3)) self.assertEqual('openstack', group.servers[1].endpoint.sval) self.assertEqual(9, group.servers[1].endpoint.ival) for i in [0, 2]: self.assertEqual('', group.servers[i].endpoint.sval) self.assertEqual(0, group.servers[i].endpoint.ival) def test_server_in_group(self): group = self.useFixture( utils.RpcServerGroupFixture(self.conf, self.url) ) client = group.client() data = [c for c in 'abcdefghijklmn'] for i in data: client.append(text=i) for s in group.servers: self.assertThat(len(s.endpoint.sval), matchers.GreaterThan(0)) actual = [[c for c in s.endpoint.sval] for s in group.servers] self.assertThat(actual, utils.IsValidDistributionOf(data)) def test_different_exchanges(self): # If the different exchanges are not honoured, then the # teardown may hang unless we broadcast all control messages # to each server group1 = self.useFixture( utils.RpcServerGroupFixture(self.conf, self.url, use_fanout_ctrl=True)) group2 = self.useFixture( utils.RpcServerGroupFixture(self.conf, self.url, exchange="a", use_fanout_ctrl=True)) group3 = self.useFixture( utils.RpcServerGroupFixture(self.conf, self.url, exchange="b", use_fanout_ctrl=True)) client1 = group1.client(1) data1 = [c for c in 'abcdefghijklmn'] for i in data1: client1.append(text=i) client2 = group2.client() data2 = [c for c in 'opqrstuvwxyz'] for i in data2: client2.append(text=i) actual1 = [[c for c in s.endpoint.sval] for s in group1.servers] self.assertThat(actual1, utils.IsValidDistributionOf(data1)) actual1 = [c for c in group1.servers[1].endpoint.sval] self.assertThat([actual1], utils.IsValidDistributionOf(data1)) for s in group1.servers: expected = len(data1) if group1.servers.index(s) == 1 else 0 self.assertEqual(expected, len(s.endpoint.sval)) self.assertEqual(0, s.endpoint.ival) actual2 = [[c for c in s.endpoint.sval] for s in group2.servers] for s in group2.servers: self.assertThat(len(s.endpoint.sval), matchers.GreaterThan(0)) self.assertEqual(0, s.endpoint.ival) self.assertThat(actual2, utils.IsValidDistributionOf(data2)) for s in group3.servers: self.assertEqual(0, len(s.endpoint.sval)) self.assertEqual(0, s.endpoint.ival) def test_timeout(self): transport = self.useFixture( utils.TransportFixture(self.conf, self.url) ) target = oslo_messaging.Target(topic="no_such_topic") c = utils.ClientStub(transport.transport, target, timeout=1) self.assertThat(c.ping, matchers.raises(oslo_messaging.MessagingTimeout)) def test_exception(self): group = self.useFixture( utils.RpcServerGroupFixture(self.conf, self.url) ) client = group.client(1) client.add(increment=2) self.assertRaises(ValueError, client.subtract, increment=3) def test_timeout_with_concurrently_queues(self): transport = self.useFixture( utils.TransportFixture(self.conf, self.url) ) target = oslo_messaging.Target(topic="topic_" + str(uuid.uuid4()), server="server_" + str(uuid.uuid4())) server = self.useFixture( utils.RpcServerFixture(self.conf, self.url, target, executor="threading")) client = utils.ClientStub(transport.transport, target, cast=False, timeout=5) def short_periodical_tasks(): for i in range(10): client.add(increment=1) time.sleep(1) with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor: future = executor.submit(client.long_running_task, seconds=10) executor.submit(short_periodical_tasks) self.assertRaises(oslo_messaging.MessagingTimeout, future.result) self.assertEqual(10, server.endpoint.ival) class CastTestCase(utils.SkipIfNoTransportURL): # Note: casts return immediately, so these tests utilise a special # internal sync() cast to ensure prior casts are complete before # making the necessary assertions. def setUp(self): super(CastTestCase, self).setUp() if self.url.startswith("kafka://"): self.skipTest("kafka does not support RPC API") def test_specific_server(self): group = self.useFixture( utils.RpcServerGroupFixture(self.conf, self.url) ) client = group.client(1, cast=True) client.append(text='open') client.append(text='stack') client.add(increment=2) client.add(increment=10) time.sleep(0.3) client.sync() group.sync(1) self.assertIn(group.servers[1].endpoint.sval, ["openstack", "stackopen"]) self.assertEqual(12, group.servers[1].endpoint.ival) for i in [0, 2]: self.assertEqual('', group.servers[i].endpoint.sval) self.assertEqual(0, group.servers[i].endpoint.ival) def test_server_in_group(self): if self.url.startswith("amqp:"): self.skipTest("QPID-6307") group = self.useFixture( utils.RpcServerGroupFixture(self.conf, self.url) ) client = group.client(cast=True) for i in range(20): client.add(increment=1) for i in range(len(group.servers)): # expect each server to get a sync client.sync() group.sync(server="all") total = 0 for s in group.servers: ival = s.endpoint.ival self.assertThat(ival, matchers.GreaterThan(0)) self.assertThat(ival, matchers.LessThan(20)) total += ival self.assertEqual(20, total) def test_fanout(self): group = self.useFixture( utils.RpcServerGroupFixture(self.conf, self.url) ) client = group.client('all', cast=True) client.append(text='open') client.append(text='stack') client.add(increment=2) client.add(increment=10) time.sleep(0.3) client.sync() group.sync(server='all') for s in group.servers: self.assertIn(s.endpoint.sval, ["openstack", "stackopen"]) self.assertEqual(12, s.endpoint.ival) class NotifyTestCase(utils.SkipIfNoTransportURL): # NOTE(sileht): Each test must not use the same topics # to be run in parallel def test_simple(self): listener = self.useFixture( utils.NotificationFixture(self.conf, self.url, ['test_simple'])) notifier = listener.notifier('abc') notifier.info({}, 'test', 'Hello World!') event = listener.events.get(timeout=1) self.assertEqual('info', event[0]) self.assertEqual('test', event[1]) self.assertEqual('Hello World!', event[2]) self.assertEqual('abc', event[3]) def test_multiple_topics(self): listener = self.useFixture( utils.NotificationFixture(self.conf, self.url, ['a', 'b'])) a = listener.notifier('pub-a', topic='a') b = listener.notifier('pub-b', topic='b') sent = { 'pub-a': [a, 'test-a', 'payload-a'], 'pub-b': [b, 'test-b', 'payload-b'] } for e in sent.values(): e[0].info({}, e[1], e[2]) received = {} while len(received) < len(sent): e = listener.events.get(timeout=1) received[e[3]] = e for key in received: actual = received[key] expected = sent[key] self.assertEqual('info', actual[0]) self.assertEqual(expected[1], actual[1]) self.assertEqual(expected[2], actual[2]) def test_multiple_servers(self): if self.url.startswith("amqp:"): self.skipTest("QPID-6307") if self.url.startswith("zmq"): self.skipTest("ZeroMQ-PUB-SUB") if self.url.startswith("kafka"): self.skipTest("Kafka: Need to be fixed") listener_a = self.useFixture( utils.NotificationFixture(self.conf, self.url, ['test-topic'])) listener_b = self.useFixture( utils.NotificationFixture(self.conf, self.url, ['test-topic'])) n = listener_a.notifier('pub') events_out = [('test-%s' % c, 'payload-%s' % c) for c in 'abcdefgh'] for event_type, payload in events_out: n.info({}, event_type, payload) events_in = [[(e[1], e[2]) for e in listener_a.get_events()], [(e[1], e[2]) for e in listener_b.get_events()]] self.assertThat(events_in, utils.IsValidDistributionOf(events_out)) for stream in events_in: self.assertThat(len(stream), matchers.GreaterThan(0)) def test_independent_topics(self): listener_a = self.useFixture( utils.NotificationFixture(self.conf, self.url, ['1'])) listener_b = self.useFixture( utils.NotificationFixture(self.conf, self.url, ['2'])) a = listener_a.notifier('pub-1', topic='1') b = listener_b.notifier('pub-2', topic='2') a_out = [('test-1-%s' % c, 'payload-1-%s' % c) for c in 'abcdefgh'] for event_type, payload in a_out: a.info({}, event_type, payload) b_out = [('test-2-%s' % c, 'payload-2-%s' % c) for c in 'ijklmnop'] for event_type, payload in b_out: b.info({}, event_type, payload) def check_received(listener, publisher, messages): actuals = sorted([listener.events.get(timeout=0.5) for __ in range(len(a_out))]) expected = sorted([['info', m[0], m[1], publisher] for m in messages]) self.assertEqual(expected, actuals) check_received(listener_a, "pub-1", a_out) check_received(listener_b, "pub-2", b_out) def test_all_categories(self): listener = self.useFixture(utils.NotificationFixture( self.conf, self.url, ['test_all_categories']))<|fim▁hole|> n = listener.notifier('abc') cats = ['debug', 'audit', 'info', 'warn', 'error', 'critical'] events = [(getattr(n, c), c, 'type-' + c, c + '-data') for c in cats] for e in events: e[0]({}, e[2], e[3]) # order between events with different categories is not guaranteed received = {} for expected in events: e = listener.events.get(timeout=1) received[e[0]] = e for expected in events: actual = received[expected[1]] self.assertEqual(expected[1], actual[0]) self.assertEqual(expected[2], actual[1]) self.assertEqual(expected[3], actual[2]) def test_simple_batch(self): if self.url.startswith("amqp:"): backend = os.environ.get("AMQP1_BACKEND") if backend == "qdrouterd": # end-to-end acknowledgement with router intermediary # sender pends until batch_size or timeout reached self.skipTest("qdrouterd backend") listener = self.useFixture( utils.BatchNotificationFixture(self.conf, self.url, ['test_simple_batch'], batch_size=100, batch_timeout=2)) notifier = listener.notifier('abc') for i in six.moves.range(0, 205): notifier.info({}, 'test%s' % i, 'Hello World!') events = listener.get_events(timeout=3) self.assertEqual(3, len(events)) self.assertEqual(100, len(events[0][1])) self.assertEqual(100, len(events[1][1])) self.assertEqual(5, len(events[2][1]))<|fim▁end|>
<|file_name|>bitcoin.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <QApplication> #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h"<|fim▁hole|>#include "paymentserver.h" #include "splashscreen.h" #include <QMessageBox> #if QT_VERSION < 0x050000 #include <QTextCodec> #endif #include <QLocale> #include <QTimer> #include <QTranslator> #include <QLibraryInfo> #ifdef Q_OS_MAC #include "macdockiconhandler.h" #endif #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Declare meta types used for QMetaObject::invokeMethod Q_DECLARE_METATYPE(bool*) // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static SplashScreen *splashref; static bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); bool ret = false; // In case of modal message, use blocking connection to wait for user to click a button QMetaObject::invokeMethod(guiref, "message", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(unsigned int, style), Q_ARG(bool*, &ret)); return ret; } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); return false; } } static bool ThreadSafeAskFee(int64 nFeeRequired) { if(!guiref) return false; if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55)); qApp->processEvents(); } printf("init message: %s\n", message.c_str()); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Amerios can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { // Command-line options take precedence: ParseParameters(argc, argv); #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Register meta types used for QMetaObject::invokeMethod qRegisterMetaType< bool* >(); // Do this early as we don't want to bother initializing if we are just calling IPC // ... but do it after creating app, so QCoreApplication::arguments is initialized: if (PaymentServer::ipcSendCommandLine()) exit(0); PaymentServer* paymentServer = new PaymentServer(&app); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { // This message can not be translated, as translation is not initialized yet // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) QMessageBox::critical(0, "Amerios", QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) QApplication::setOrganizationName("Amerios"); QApplication::setOrganizationDomain("amerios.org"); if(GetBoolArg("-testnet")) // Separate UI settings for testnet QApplication::setApplicationName("Amerios-Qt-testnet"); else QApplication::setApplicationName("Amerios-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.InitMessage.connect(InitMessage); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } #ifdef Q_OS_MAC // on mac, also change the icon now because it would look strange to have a testnet splash (green) and a std app icon (orange) if(GetBoolArg("-testnet")) { MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet")); } #endif SplashScreen splash(QPixmap(), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splash.setAutoFillBackground(true); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { #ifndef Q_OS_MAC // Regenerate startup link, to fix links to old versions // OSX: makes no sense on mac and might also scan/mount external (and sleeping) volumes (can take up some secs) if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); #endif boost::thread_group threadGroup; BitcoinGUI window; guiref = &window; QTimer* pollShutdownTimer = new QTimer(guiref); QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown())); pollShutdownTimer->start(200); if(AppInit2(threadGroup)) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). optionsModel.Upgrade(); // Must be done after AppInit2 if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel *walletModel = 0; if(pwalletMain) walletModel = new WalletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); if(walletModel) { window.addWallet("~Default", walletModel); window.setCurrentWallet("~Default"); } // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Now that initialization/startup is done, process any command-line // bitcoin: URIs QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString))); QTimer::singleShot(100, paymentServer, SLOT(uiReady())); app.exec(); window.hide(); window.setClientModel(0); window.removeAllWallets(); guiref = 0; delete walletModel; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); } else { threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST<|fim▁end|>
#include "guiconstants.h" #include "init.h" #include "util.h" #include "ui_interface.h"
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>import http = require('http'); import path = require('path'); import fs = require('fs'); import request = require('request'); import express = require('express'); import calais = require('calais-entity-extractor'); interface IGeoJsonGeometry { type: string; coordinates: number[] | number[][] | number[][][]; } interface IFeature { geometry: IGeoJsonGeometry; properties?: { [id: string]: any[] }; sensors?: { [id: string]: any[]; }; id: string; }; /** Options */ export class NewsSourceOptions { /** If true, set headers to enable CORRS. */ corrs: boolean = true; /** source folder. If not set, uses ./newsfeatures */ newsFolder: string = path.join(__dirname, 'newsfeatures'); calaisApi: string = ''; alchemyApi: string = ''; keywords: string[] = []; updateInterval: number = 3600; }; export class NewsSource { private options: NewsSourceOptions; private alchemyFeed: AlchemyFeed; private calaisSource: CalaisSource; constructor(app: express.Express, options?: NewsSourceOptions) { var defaultOptions = new NewsSourceOptions(); if (!options) options = defaultOptions; this.options = options; if (!this.options.updateInterval || this.options.updateInterval < 2) this.options.updateInterval = 600; // enable corrs if ((options && typeof options.corrs !== 'undefined' && options.corrs) || defaultOptions.corrs) { app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); }); } this.alchemyFeed = new AlchemyFeed(app, options.alchemyApi); this.calaisSource = new CalaisSource(app, options.calaisApi, { minConfidence: 0.3, parseData: false }); // Update on api call app.get('/api/newsfeatures', (req, res) => { this.alchemyFeed.getNewsText(options.keywords, 3, (data) => { this.processNews(data); }); res.statusCode = 200; res.end(); }); // Update on api call with nr of items specified app.get('/api/newsfeatures/:numberofitems', (req, res) => { var n = req.params.numberofitems; if (n <= 0) { n = 1; } else if (n > 100) { n = 100; } n = Math.round(n); this.alchemyFeed.getNewsText(options.keywords, n, (data) => { this.processNews(data); }); res.statusCode = 200; res.end(); }); // Update with interval setInterval(() => { this.alchemyFeed.getNewsText(options.keywords, 2, (data) => { this.processNews(data); }); }, this.options.updateInterval * 1000); } /** Processes a data object containing news items */ private processNews(data: Object) { console.log('Processing news...'); var items = []; if (data && data.hasOwnProperty('docs')) { data['docs'].forEach((item) => { // Skip items that already exist if (fs.existsSync(path.join(this.options.newsFolder, item.id + '.json'))) return; items.push(item); }); // Throttle the OpenCalais calls to 1Hz to prevent exceeding the limit setTimeout(() => this.contactCalais(items), 1000); } else { console.log('No docs found in result'); } } /** Adds (geographic) information to news items using the OpenCalais source*/ private contactCalais(items: any[]) { console.log('Contacting calais...'); var item = items.shift(); if (item && item.source && item.source.enriched && item.source.enriched.url) { this.calaisSource.getNewsFeatures(item.source.enriched.url.title + ' \n ' + item.source.enriched.url.text, ((fts: any[]) => { console.log('Nr. items: ' + fts.length); fts = fts.sort((a, b) => { if (!a.properties.hasOwnProperty('relevance')) return -1; if (!b.properties.hasOwnProperty('relevance')) return 1; return (a.properties.relevance - b.properties.relevance); }); if (fts.length === 0) fs.writeFileSync(path.join(this.options.newsFolder, item.id + '.json'), null); fts.some((f) => { if (f.geometry.coordinates.length > 0) { f.properties['news_title'] = item.source.enriched.url.title; f.properties['news_text'] = item.source.enriched.url.text; f.properties['news_date'] = item.timestamp * 1000; //Timestamp is in seconds, convert to ms f.properties['news_url'] = '[url=' + item.source.enriched.url.url + ']Source[/url]'; f.properties['news_author'] = item.source.enriched.url.author; f.id = item.id; f.type = 'Feature'; fs.writeFileSync(path.join(this.options.newsFolder, item.id + '.json'), JSON.stringify(f)); return true; } return false; }); })); } if (items.length === 0) { console.log('Calais queue empty'); return; } setTimeout(() => this.contactCalais(items), 1000); } } // export class NYTimesFeed { // private apiKey; // private keywords: string[]; // constructor(app: express.Express, apiKey: string) { // if (!apiKey || apiKey === '') { // console.log('Error: no api-key found for NYTimesFeed. Exiting...'); // return; // } // this.apiKey = apiKey; // app.use(function(req, res, next) { // res.header('Access-Control-Allow-Origin', '*'); // res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); // next(); // }); // } // public getNewsText(keywords: string | string[], clbk: Function): void { // var keys: string[]; // if (typeof keywords === 'string') { // keys = [keywords]; // } else if (Array.isArray(keywords)) { // keys = keywords; // } else { // console.log('Warning: no valid keyword(s)'); // clbk(null, 'No valid keyword(s)'); // return; // } // var url = ['http://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=' + this.apiKey]; // url.push('fq=headline:("' + keys.join('" "') + '") AND type_of_material:("News")'); // url.push('begin_date=20140101'); // url.push('sort=newest'); // var urlString = url.join('&'); // this.performRequest(urlString, (data, errText) => { // console.log('News request status: ' + urlString); // clbk(data, errText); // }); // } // private performRequest(url: string, cb: Function) { // var options = { // uri: url, // method: 'GET', // body: null, // headers: {} // }; // //Send the response // request(options, function(error, response, data) { // if (error) { // return cb({}, error); // } // if (response === undefined) { // return cb({}, 'Undefined NYtimes response'); // } else if (response.statusCode === 200) { // if (!data) { // return cb({}, 'No data received'); // } else { // try { // var parsed = JSON.parse(data); // if (parsed.hasOwnProperty('response')) { // cb(parsed['response'], 'OK'); // } else { // console.log(parsed); // cb({}, 'No result received'); // } // } catch (error) { // cb({}, 'JSON parsing error'); // } // } // } else { // cb({}, 'Undefined response: ' + response.statusCode); // } // }); // } // } export class AlchemyFeed { private apiKey; private keywords: string[]; constructor(app: express.Express, apiKey: string) { if (!apiKey || apiKey === '') { console.log('Error: no api-key found for AlchemyFeed. Exiting...'); return; } this.apiKey = apiKey; app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); }); } public getNewsText(keywords: string | string[], count: number, clbk: Function): void { var keys: string[]; if (typeof keywords === 'string') { keys = [keywords]; } else if (Array.isArray(keywords)) { keys = keywords; } else { console.log('Warning: no valid keyword(s)'); clbk(null, 'No valid keyword(s)'); return; } if (typeof count !== 'number') count = 5; var url = ['https://gateway-a.watsonplatform.net/calls/data/GetNews?apikey=' + this.apiKey]; url.push('outputMode=json'); url.push('start=now-14d'); url.push('end=now'); url.push('count=' + count); url.push('q.enriched.url.enrichedTitle.keywords.keyword.text=O[' + keys.join('^') + ']'); url.push('q.enriched.url.text=-[cookies]'); url.push('return=enriched.url.url,enriched.url.title,enriched.url.text,enriched.url.author'); var urlString = url.join('&'); this.performRequest(urlString, (data, errText) => { console.log('News request status: ' + errText); clbk(data, errText); }); } private performRequest(url: string, cb: Function) { var options = { uri: url, method: 'GET', body: null, headers: {} }; //Send the response request(options, function(error, response, data) { if (error) { return cb({}, error); } if (response === undefined) { return cb({}, 'Undefined Alchemy response'); } else if (response.statusCode === 200) { if (!data) { return cb({}, 'No data received'); } else { try { var parsed = JSON.parse(data); if (parsed.hasOwnProperty('result')) { cb(parsed['result'], 'OK'); } else { console.log(parsed); cb({}, 'No result received'); } } catch (error) { cb({}, 'JSON parsing error'); } } } else { cb({}, 'Undefined response: ' + response.statusCode); } }); } } export class CalaisSource { private oc: calais.Calais; constructor(app: express.Express, apiKey: string, options?: calais.ICalaisOptions) { if (!apiKey || apiKey === '') { console.log('Error: no api-key found for OpenCalais. Exiting...'); return; } app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); }); this.oc = new calais.Calais(apiKey, options); this.oc.set('content', ''); } public getNewsFeatures(content: string, cb: Function): void { if (!content || content === '') { console.log('Error: no valid content.'); cb([]); } this.oc.set('content', content); this.oc.extractFromText((result, err) => { if (err) { console.log('OpenCalais returned an error! : ' + err); cb([]); } var features = this.parseResult(result); cb(features); }); } private parseResult(res: string | JSON): any[] { var features: any[] = []; var json = {}; if (typeof res === 'string') { try { console.log('Parsing...'); json = JSON.parse(res); } catch (error) { console.log('Error parsing string: ' + res); return; } } else if (typeof res !== 'object') { console.log('Unknown type: ' + typeof res); return; } else { json = res; } <|fim▁hole|> var f; switch ((item['_typeGroup'])) { case 'entities': f = this.parseEntity(item); break; case 'relations': f = this.parseRelation(item); break; default: break; } if (f) { features.push(f); } } return features; } private parseEntity(item: any) { var f = <IFeature>{ properties: {}, geometry: { type: 'Point', coordinates: [] }, sensors: null, id: item.id }; if (item.hasOwnProperty('resolutions')) { var r = item['resolutions'].pop(); if (r.hasOwnProperty('latitude') && r.hasOwnProperty('longitude')) { f.geometry.coordinates = [parseFloat(r['longitude']), parseFloat(r['latitude'])]; } f.properties = r; } if (item.hasOwnProperty('name')) f.properties['Name'] = item['name']; if (item.hasOwnProperty('_type')) f.properties['Type'] = item['_type']; if (item.hasOwnProperty('relevance')) f.properties['Relevance'] = item['relevance']; return f; } private parseRelation(item: any) { var f = <IFeature>{}; f.properties = {}; f.properties['Name'] = item['name']; return f; } }<|fim▁end|>
for (var key in json) { if (!json.hasOwnProperty(key)) continue; var item = json[key]; if (!item.hasOwnProperty('_typeGroup') || !item.hasOwnProperty('name')) continue;
<|file_name|>beanbot-client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import sys, re from socket import * serve_addr = ('localhost', 47701) if __name__ == '__main__':<|fim▁hole|> IRC_ULINE = '\x1f' IRC_NORMAL = '\x0f' IRC_RED = '\x034' IRC_LIME = '\x039' IRC_BLUE = '\x0312' repo, branch, author, rev, description = sys.argv[1:6] match = re.search(r'^\s*(.*?)\s*<.*>\s*$', author) if match: author = match.group(1) data = ( "%(IRC_RED)s%(repo)s" "%(IRC_NORMAL)s[%(branch)s] " "%(IRC_NORMAL)s%(IRC_BOLD)s%(author)s " "%(IRC_NORMAL)s%(IRC_ULINE)s%(rev)s%(IRC_NORMAL)s " "%(description)s" % locals() ) if len(data) > 400: data = data[:400] + "..." sock = socket(AF_INET, SOCK_DGRAM) sock.sendto(data, serve_addr) sock.sendto("https://hg.adblockplus.org/%(repo)s/rev/%(rev)s" % locals(), serve_addr) sock.close()<|fim▁end|>
IRC_BOLD = '\x02'
<|file_name|>ZabbixHelper.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- ''' Created on 2015/04/17 @author: 2015 AIST ''' import time from django.conf import settings from zbxsend import Metric, send_to_zabbix import logging import json from vt_manager_kvm.communication.geni.v3.configurators.handlerconfigurator import HandlerConfigurator class ZabbixHelper(): logger = logging.getLogger("ZabbixHelper") @staticmethod def sendAgentStatus(server, available): if available == True: status = 1 # UP else: status = 2 # DOWN timestamp = int(time.time()) driver = HandlerConfigurator.get_vt_am_driver() server_urn = driver.generate_component_id(server) itemname = settings.ZBX_ITEM_HOSTSTATUS + '[' + str(server_urn) + ']' metric = Metric(server.name, str(itemname), status, timestamp) ZabbixHelper.sendZabbix(metric) return @staticmethod def sendVMDiscovery(server, vms): timestamp = int(time.time()) discoveryList = [] for vm in vms: discovery = {"{#USERVM.NAME}": vm.name} discoveryList.append(discovery) tmpobj = {"data": discoveryList} discoveryStr = json.dumps(tmpobj) metric = Metric(server.name, settings.ZBX_ITEM_DISCOVERY_USERVM, str(discoveryStr), timestamp) ZabbixHelper.sendZabbix(metric) return @staticmethod def sendVMStatusDiscovery(vms): timestamp = int(time.time()) driver = HandlerConfigurator.get_vt_am_driver() for vm in vms: discoveryList = [] vm_urn = driver.generate_sliver_urn(vm) discovery = {"{#USERVM.URN}": vm_urn} discoveryList.append(discovery)<|fim▁hole|> return @staticmethod def sendVMStatus(vm, isUp): if isUp == True: status = 1 # UP else: status = 2 # DOWN driver = HandlerConfigurator.get_vt_am_driver() vm_urn = driver.generate_sliver_urn(vm) timestamp = int(time.time()) itemname = settings.ZBX_ITEM_USERVMSTATUS + '[' + str(vm_urn) + ']' metric = Metric(vm.name, str(itemname), status, timestamp) ZabbixHelper.sendZabbix(metric) return @staticmethod def sendZabbix(metric): ZabbixHelper.logger.debug("send Zabbix " + str(metric)) result = send_to_zabbix([metric], settings.ZBX_SERVER_IP, settings.ZBX_SERVER_PORT) if(result == False): ZabbixHelper.logger.warn("cannot send VM status to Zabbix, continue anyway") return<|fim▁end|>
tmpobj = {"data": discoveryList} discoveryStr = json.dumps(tmpobj) metric = Metric(vm.name, settings.ZBX_ITEM_DISCOVERY_USERVMSTATUS, str(discoveryStr), timestamp) ZabbixHelper.sendZabbix(metric)
<|file_name|>recovered-block.rs<|end_file_name|><|fim▁begin|>use std::env; pub struct Foo {<|fim▁hole|>} pub fn foo() -> Foo { let args: Vec<String> = env::args().collect(); let text = args[1].clone(); pub Foo { text } } //~^^ ERROR missing `struct` for struct definition pub fn bar() -> Foo { fn Foo { text: "".to_string() } } //~^^ ERROR expected one of `(` or `<`, found `{` fn main() {}<|fim▁end|>
text: String
<|file_name|>kikidocs.py<|end_file_name|><|fim▁begin|>from celery.app.task import BaseTask from sphinx.ext import autodoc class TaskDocumenter(autodoc.DataDocumenter): @classmethod def can_document_member(cls, member, membername, isattr, parent): if isinstance(member, BaseTask): return True<|fim▁hole|> def setup(app): app.add_autodocumenter(TaskDocumenter)<|fim▁end|>
<|file_name|>DefinitionFormalParametersImpl.java<|end_file_name|><|fim▁begin|>// This is a generated file. Not intended for manual editing. package org.modula.parsing.definition.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static org.modula.parsing.definition.psi.ModulaTypes.*; import com.intellij.extapi.psi.ASTWrapperPsiElement; import org.modula.parsing.definition.psi.*; public class DefinitionFormalParametersImpl extends ASTWrapperPsiElement implements DefinitionFormalParameters { public DefinitionFormalParametersImpl(ASTNode node) { super(node); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof DefinitionVisitor) ((DefinitionVisitor)visitor).visitFormalParameters(this); else super.accept(visitor); } @Override @NotNull public List<DefinitionFPSection> getFPSectionList() { return PsiTreeUtil.getChildrenOfTypeAsList(this, DefinitionFPSection.class); } @Override @Nullable public DefinitionQualident getQualident() { return findChildByClass(DefinitionQualident.class); } <|fim▁hole|><|fim▁end|>
}
<|file_name|>treeMultiSelectorCtrl.js<|end_file_name|><|fim▁begin|>/* * Copyright (C) 2021 Inera AB (http://www.inera.se) * * This file is part of sklintyg (https://github.com/sklintyg). * * sklintyg 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. * * sklintyg 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/>. */ angular.module('StatisticsApp.treeMultiSelector.controller', []) .controller('treeMultiSelectorCtrl', ['$scope', '$uibModal', function($scope, $uibModal) { 'use strict'; $scope.openDialogClicked = function() { if (angular.isFunction($scope.onOpen)) { $scope.onOpen(); } var modalInstance = $uibModal.open({ animation: false, templateUrl: '/app/shared/treemultiselector/modal/modal.html', controller: 'TreeMultiSelectorModalCtrl', windowTopClass: 'tree-multi-selector', size: 'lg', backdrop: 'true', resolve: { directiveScope: $scope } }); <|fim▁hole|> $scope.doneClicked(); }, function() { }); }; }]);<|fim▁end|>
modalInstance.result.then(function() {
<|file_name|>HomeController.js<|end_file_name|><|fim▁begin|>(function() { 'use strict'; function HomeController($scope, $q, $timeout) { var self = this; self.time = 50; self.message = "Mensagem para mostrar"; var promiseTimeout; var deferredToast; self.mostrarToast = function() { esconderToast(); deferredToast = $q.defer();<|fim▁hole|> self.mensagemAtual = self.message; promiseTimeout = $timeout(timeoutToast, self.time * 1000); }; function timeoutToast() { deferredToast.reject(); esconderToast(); } function esconderToast() { if (promiseTimeout) { $timeout.cancel(promiseTimeout); promiseTimeout = undefined; } self.activeShow = false; } self.clickBotaoFechar = function() { if (deferredToast) { // verifica pra evitar problema com duplo clique rápido deferredToast.resolve(); deferredToast = undefined; } esconderToast(); }; self.clickNoToast = function() { if (deferredToast) { timeoutToast(); // clicar no toast equivale ao timeout } }; function toastResolved() { console.log('Resolved'); self.ultimaResposta = 'Resolved'; } function toastRejected() { console.log('Rejected'); self.ultimaResposta = 'Rejected'; } } angular .module('hotMilhasApp') .controller('HomeController', ['$scope', '$q', '$timeout', HomeController]); })();<|fim▁end|>
deferredToast.promise.then(toastResolved, toastRejected); self.activeShow = true;
<|file_name|>trazabilidad_articulos.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright (C) 2005-2008 Francisco José Rodríguez Bogado, # # Diego Muñoz Escalante. # # ([email protected], [email protected]) # # # # This file is part of GeotexInn. # # # # GeotexInn 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. # # # # GeotexInn 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 GeotexInn; if not, write to the Free Software # # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # ############################################################################### ################################################################### ## trazabilidad_articulos.py - Trazabilidad de rollo, bala o bigbag ################################################################### ## NOTAS: ## ## ---------------------------------------------------------------- ## ################################################################### ## Changelog: ## 24 de mayo de 2006 -> Inicio ## 24 de mayo de 2006 -> It's alive! ################################################################### ## DONE: Imprimir toda la información en PDF sería lo suyo. ################################################################### from ventana import Ventana import utils import pygtk pygtk.require('2.0') import gtk, gtk.glade, time, sqlobject import sys, os try: import pclases except ImportError: sys.path.append(os.path.join('..', 'framework')) import pclases import mx, mx.DateTime sys.path.append(os.path.join('..', 'informes')) from barcode import code39 from barcode.EANBarCode import EanBarCode from reportlab.lib.units import cm class TrazabilidadArticulos(Ventana): def __init__(self, objeto = None, usuario = None): self.usuario = usuario Ventana.__init__(self, 'trazabilidad_articulos.glade', objeto, self.usuario) connections = {'b_salir/clicked': self.salir, 'b_buscar/clicked': self.buscar, 'b_imprimir/clicked': self.imprimir } self.add_connections(connections) #self.wids['e_num'].connect("key_press_event", self.pasar_foco) self.wids['ventana'].resize(800, 600) self.wids['ventana'].set_position(gtk.WIN_POS_CENTER) if objeto != None: self.rellenar_datos(objeto) self.wids['e_num'].grab_focus() gtk.main() def imprimir(self, boton): """ Vuelca toda la información de pantalla en bruto a un PDF. """ import informes, geninformes datos = "Código de trazabilidad: %s\n\n"%self.wids['e_num'].get_text() for desc, txt in (("Producto:\n", self.wids['txt_producto']), ("Lote/Partida:\n", self.wids['txt_lp']), ("Albarán de salida:\n", self.wids['txt_albaran']), ("Producción:\n", self.wids['txt_produccion'])): buffer = txt.get_buffer() texto = buffer.get_text(buffer.get_start_iter(), buffer.get_end_iter()) datos += desc + texto + "\n\n" informes.abrir_pdf(geninformes.trazabilidad(datos)) def pasar_foco(self, widget, event): if event.keyval == 65293 or event.keyval == 65421: self.wids['b_buscar'].grab_focus() def chequear_cambios(self): pass def buscar_bigbag(self, txt): ar = None if isinstance(txt, str): txt = utils.parse_numero(txt) ars = pclases.Bigbag.select(pclases.Bigbag.q.numbigbag == txt) if ars.count() == 1: ar = ars[0] elif ars.count() > 1: filas = [(a.id, a.numbigbag, a.codigo) for a in ars] idbigbag = utils.dialogo_resultado(filas, titulo = "Seleccione bigbag", cabeceras = ('ID', 'Número de bigbag', 'Código'), padre = self.wids['ventana']) if idbigbag > 0: ar = pclases.Bigbag.get(idbigbag) return ar def buscar_bala(self, txt): ar = None if isinstance(txt, str): txt = utils.parse_numero(txt) ars = pclases.Bala.select(pclases.Bala.q.numbala == txt) if ars.count() == 1: ar = ars[0] elif ars.count() > 1: filas = [(a.id, a.numbala, a.codigo) for a in ars] idbala = utils.dialogo_resultado(filas, titulo = "Seleccione bala", cabeceras = ('ID', 'Número de bala', 'Código'), padre = self.wids['ventana']) if idbala > 0: ar = pclases.Bala.get(idbala) return ar def buscar_rollo(self, txt): ar = None if isinstance(txt, str): txt = utils.parse_numero(txt) ars = pclases.Rollo.select(pclases.Rollo.q.numrollo == txt) if ars.count() == 1: ar = ars[0] elif ars.count() > 1: filas = [(a.id, a.numrollo, a.codigo) for a in ars] idrollo = utils.dialogo_resultado(filas, titulo = "Seleccione rollo", cabeceras = ('ID', 'Número de rollo', 'Código'), padre = self.wids['ventana']) if idrollo > 0: ar = pclases.Rollo.get(idrollo) return ar def buscar_articulo(self, txt): ar = None if isinstance(txt, str): txt = utils.parse_numero(txt) ars = pclases.Rollo.select(pclases.Rollo.q.numrollo == txt) if ars.count() == 0: ar = self.buscar_bala(txt) elif ars.count() == 1: ar = ars[0] else: ar = self.buscar_rollo(txt) return ar def buscar(self, b): a_buscar = self.wids['e_num'].get_text().strip().upper() if a_buscar.startswith(pclases.PREFIJO_ROLLO): try: objeto = pclases.Rollo.select( pclases.Rollo.q.codigo == a_buscar)[0] except IndexError: objeto = self.buscar_rollo(a_buscar[1:]) elif a_buscar.startswith(pclases.PREFIJO_BALA): try: objeto = pclases.Bala.select( pclases.Bala.q.codigo == a_buscar)[0] except IndexError: objeto = self.buscar_bala(a_buscar[1:]) elif a_buscar.startswith(pclases.PREFIJO_LOTECEM): try: loteCem = pclases.LoteCem.select( pclases.LoteCem.q.codigo == a_buscar)[0] except IndexError: utils.dialogo_info(titulo = "LOTE NO ENCONTRADO", texto = "El lote de fibra de cemento %s no se encontró." % (a_buscar), padre = self.wids['ventana']) loteCem = None objeto = loteCem elif a_buscar.startswith(pclases.PREFIJO_LOTE): try: lote = pclases.Lote.select( pclases.Lote.q.numlote == int(a_buscar[2:]))[0] except IndexError: try: lote = pclases.Lote.select( pclases.Lote.q.codigo == a_buscar)[0] except IndexError: utils.dialogo_info(titulo = "LOTE NO ENCONTRADO", texto = "El lote de fibra %s no se encontró." % ( a_buscar), padre = self.wids['ventana']) lote = None except ValueError: utils.dialogo_info(titulo = "ERROR BUSCANDO LOTE", texto = "El texto %s provocó un error en la búsqueda." % ( a_buscar), padre = self.wids['ventana']) lote = None objeto = lote elif a_buscar.startswith(pclases.PREFIJO_PARTIDA): try: partida = pclases.Partida.select( pclases.Partida.q.numpartida == int(a_buscar[2:]))[0] except IndexError: try: partida = pclases.Partida.select( pclases.Partida.q.codigo == a_buscar)[0] except IndexError: utils.dialogo_info(titulo = "PARTIDA NO ENCONTRADA", texto = "La partida de geotextiles %s " "no se encontró." % (a_buscar), padre = self.wids['ventana']) partida = None except ValueError: utils.dialogo_info(titulo = "ERROR BUSCANDO PARTIDA", texto = "El texto %s provocó un error en la búsqueda." % ( a_buscar), padre = self.wids['ventana']) partida = None objeto = partida elif a_buscar.startswith(pclases.PREFIJO_PARTIDACEM): try: partidaCem = pclases.PartidaCem.select( pclases.PartidaCem.q.numpartida == int(a_buscar[2:]))[0] except IndexError: try: partidaCem = pclases.PartidaCem.select( pclases.PartidaCem.q.codigo == a_buscar)[0] except IndexError: utils.dialogo_info( titulo = "PARTIDA DE FIBRA EMBOLSADA NO ENCONTRADA", texto = "La partida de fibra embolsada %s " "no se encontró." % (a_buscar), padre = self.wids['ventana']) partidaCem = None except ValueError: utils.dialogo_info( titulo = "ERROR BUSCANDO PARTIDA DE FIBRA EMBOLSADA", texto = "El texto %s provocó un error en la búsqueda." % ( a_buscar), padre = self.wids['ventana']) partidaCem = None objeto = partidaCem elif a_buscar.startswith(pclases.PREFIJO_PARTIDACARGA): try: partidacarga = pclases.PartidaCarga.select( pclases.PartidaCarga.q.numpartida == int(a_buscar[2:]))[0] except IndexError: try: partidacarga = pclases.PartidaCarga.select( pclases.PartidaCarga.q.codigo == a_buscar)[0] except IndexError: utils.dialogo_info(titulo="PARTIDA DE CARGA NO ENCONTRADA", texto = "La partida de carga %s no se encontró." % ( a_buscar), padre = self.wids['ventana']) partidacarga = None except ValueError: utils.dialogo_info(titulo = "ERROR BUSCANDO PARTIDA DE CARGA", texto = "El texto %s provocó un error en la búsqueda." % ( a_buscar), padre = self.wids['ventana']) partidacarga = None objeto = partidacarga elif a_buscar.startswith(pclases.PREFIJO_BIGBAG): try: objeto = pclases.Bigbag.select( pclases.Bigbag.q.codigo == a_buscar)[0] except IndexError: objeto = self.buscar_bigbag(a_buscar[1:]) elif a_buscar.startswith(pclases.PREFIJO_ROLLODEFECTUOSO): try: objeto = pclases.RolloDefectuoso.select( pclases.RolloDefectuoso.q.codigo == a_buscar)[0] except IndexError: objeto = None # O lo busca bien o que se vaya a "puirla". elif a_buscar.startswith(pclases.PREFIJO_BALACABLE): try: objeto = pclases.BalaCable.select( pclases.BalaCable.q.codigo == a_buscar)[0] except IndexError: objeto = None # O lo busca bien o que se vaya a "puirla". elif a_buscar.startswith(pclases.PREFIJO_ROLLOC): try: objeto = pclases.RolloC.select( pclases.RolloC.q.codigo == a_buscar)[0] except IndexError: objeto = None # O lo busca bien o que se vaya a "puirla". elif a_buscar.startswith(pclases.PREFIJO_PALE): try: objeto = pclases.Pale.select( pclases.Pale.q.codigo == a_buscar)[0] except IndexError: objeto = None # O lo busca bien o que se vaya a "puirla". elif a_buscar.startswith(pclases.PREFIJO_CAJA): try: objeto = pclases.Caja.select( pclases.Caja.q.codigo == a_buscar)[0] except IndexError: objeto = None # O lo busca bien o que se vaya a "puirla". elif a_buscar.startswith(pclases.PREFIJO_BOLSA): # No more bolsas como tal. # try: # objeto = pclases.Bolsa.select( # pclases.Bolsa.q.codigo == a_buscar.upper())[0] # except IndexError: # objeto = None # O lo busca bien o que se vaya a "puirla". # Voy a buscar la caja a la que pertenece la bolsa: objeto = pclases.Caja.get_caja_from_bolsa(a_buscar) else: objeto = self.buscar_articulo(a_buscar) if objeto != None: objeto.sync() if hasattr(objeto, "codigo"): self.wids['e_num'].set_text(objeto.codigo) else: self.wids['e_num'].set_text("DEBUG: __hash__ %s" % ( objeto.__hash__())) self.rellenar_datos(objeto) else: utils.dialogo_info(titulo = "NO ENCONTRADO", texto = "Producto no encontrado", padre = self.wids['ventana']) def rellenar_datos(self, objeto): """ "objeto" es el objeto sobre el que se va a mostar la información. """ objeto.sync() if isinstance(objeto, (pclases.Bala, pclases.Rollo, pclases.Bigbag, pclases.RolloDefectuoso, pclases.BalaCable, pclases.RolloC, pclases.Pale, pclases.Caja, )): # pclases.Bolsa)): try: objeto.articulo.sync() except AttributeError: pass # Es una caja o un palé. No tiene artículo concreto # que sincronizar. self.rellenar_producto(objeto) self.rellenar_lotepartida(objeto) self.rellenar_albaran(objeto) self.rellenar_produccion(objeto) self.wids['e_num'].set_text(objeto.codigo) elif isinstance(objeto, pclases.PartidaCarga): from ventana_progreso import VentanaActividad, VentanaProgreso vpro = VentanaProgreso(padre = self.wids['ventana']) vpro.mostrar() i = 0.0 tot = 5 vpro.set_valor(i/tot, "Buscando..."); i += 1 import time; time.sleep(0.5) vpro.set_valor(i/tot, "Producto..."); i += 1 self.rellenar_producto_partida_carga(objeto) vpro.set_valor(i/tot, "Lote/Partida..."); i += 1 self.rellenar_partida_carga(objeto) vpro.set_valor(i/tot, "Albarán de salida..."); i += 1 self.rellenar_albaran_partida_carga(objeto) vpro.set_valor(i/tot, "Producción..."); i += 1 self.rellenar_produccion_partida_carga(objeto) self.wids['e_num'].set_text(objeto.codigo) vpro.ocultar() elif isinstance(objeto,(pclases.Lote, pclases.LoteCem, pclases.Partida, pclases.PartidaCem)): from ventana_progreso import VentanaActividad, VentanaProgreso vpro = VentanaProgreso(padre = self.wids['ventana']) vpro.mostrar() i = 0.0 tot = 5 vpro.set_valor(i/tot, "Buscando..."); i += 1 import time; time.sleep(0.5) vpro.set_valor(i/tot, "Producto..."); i += 1 self.rellenar_producto_lote_o_partida(objeto) vpro.set_valor(i/tot, "Lote/Partida..."); i += 1 self.rellenar_lote_o_partida(objeto) vpro.set_valor(i/tot, "Albarán de salida..."); i += 1 self.rellenar_albaran_lote_o_partida(objeto) vpro.set_valor(i/tot, "Producción..."); i += 1 self.rellenar_produccion_lote_o_partida(objeto) self.wids['e_num'].set_text(objeto.codigo) vpro.ocultar() def rellenar_producto_partida_carga(self, pcarga): """ Muestra los productos de fibra que componen la partida de carga. """ txtvw = self.wids['txt_producto'] borrar_texto(txtvw) prodsfibra = {} total = 0.0 for bala in pcarga.balas: a = bala.articulo pv = a.productoVenta l = bala.lote if pv not in prodsfibra: prodsfibra[pv] = {} if bala.lote not in prodsfibra[pv]: prodsfibra[pv][l] = {'balas': [], 'total': 0.0} prodsfibra[pv][l]['balas'].append(bala) prodsfibra[pv][l]['total'] += bala.pesobala total += bala.pesobala for pv in prodsfibra: escribir(txtvw, "%s kg de %s\n" % (utils.float2str(sum( [prodsfibra[pv][l]['total'] for l in prodsfibra[pv]])), pv.descripcion), ("negrita")) for l in prodsfibra[pv]: escribir(txtvw, "\t%d balas del lote %s; %s kg\n" % ( len(prodsfibra[pv][l]['balas']), l.codigo, utils.float2str(prodsfibra[pv][l]['total']))) escribir(txtvw, "Total cargado: %s kg\n" % (utils.float2str(total)), ("negrita", "grande")) def rellenar_partida_carga(self, pcarga): """ Muestra la partida de carga, fecha y partidas de geotextiles relacionados con ella. """ txtvw = self.wids['txt_lp'] borrar_texto(txtvw) escribir(txtvw, "Partida de carga %s (%s)\n" % ( pcarga.numpartida, pcarga.codigo), ("negrita")) escribir(txtvw, "Fecha y hora de creación: %s %s\n" % ( utils.str_fecha(pcarga.fecha), utils.str_hora_corta(pcarga.fecha)), ("cursiva")) escribir(txtvw, "Partidas de geotextiles relacionados:\n") for partida in pcarga.partidas: escribir(txtvw, "\tPartida %s (%s)\n" % (partida.numpartida, partida.codigo)) def rellenar_albaran_partida_carga(self, pcarga): """ Muestra los albaranes internos relacionados con las balas de la partida de carga. """ txtvw = self.wids['txt_albaran'] borrar_texto(txtvw) albs = [] for bala in pcarga.balas: alb = bala.articulo.albaranSalida if alb != None and alb not in albs: albs.append(alb) escribir(txtvw, "Albarán %s (%s): %s\n" % (alb.numalbaran, utils.str_fecha(alb.fecha), alb.cliente and alb.cliente.nombre or "-")) def rellenar_produccion_partida_carga(self, pcarga): """ Muestra los rollos fabricados, metros cuadrados y kilos reales por parte de produccion. """ txtvw = self.wids['txt_produccion'] borrar_texto(txtvw) fab = {} for partida in pcarga.partidas: for rollo in partida.rollos: pv = rollo.productoVenta metros = pv.camposEspecificosRollo.get_metros_cuadrados() if pv not in fab: fab[pv] = {'rollos': [rollo], 'peso_real': rollo.peso, 'peso_sin': rollo.peso_sin, 'peso_teorico': rollo.peso_teorico, 'metros': metros} else: fab[pv]['rollos'].append(rollo) fab[pv]['peso_real'] += rollo.peso fab[pv]['peso_sin'] += rollo.peso_sin fab[pv]['peso_teorico'] += rollo.peso_teorico fab[pv]['metros'] += metros total_peso_real=total_peso_sin=total_peso_teorico=total_metros=0.0 total_rollos = 0 for pv in fab: escribir(txtvw, "%s:\n" % (pv.descripcion), ("negrita")) escribir(txtvw, "\t%d rollos.\n" % (len(fab[pv]['rollos']))) total_rollos += len(fab[pv]['rollos']) escribir(txtvw, "\t%s kg peso real.\n" % ( utils.float2str(fab[pv]['peso_real']))) total_peso_real += fab[pv]['peso_real'] escribir(txtvw, "\t%s kg peso sin embalaje.\n" % ( utils.float2str(fab[pv]['peso_sin']))) total_peso_sin += fab[pv]['peso_sin'] escribir(txtvw, "\t%s kg peso teórico.\n" % ( utils.float2str(fab[pv]['peso_teorico']))) total_peso_teorico += fab[pv]['peso_teorico'] escribir(txtvw, "\t%s m².\n" % utils.float2str(fab[pv]['metros'])) total_metros += fab[pv]['metros'] escribir(txtvw, "Total fabricado:\n", ("negrita", "grande")) escribir(txtvw, "\t%d rollos.\n" % (total_rollos), ("negrita")) escribir(txtvw, "\t%s kg peso real.\n" % ( utils.float2str(total_peso_real)), ("negrita")) escribir(txtvw, "\t%s kg peso sin embalaje.\n" % ( utils.float2str(total_peso_sin)), ("negrita")) escribir(txtvw, "\t%s kg peso teórico.\n" % ( utils.float2str(total_peso_teorico)), ("negrita")) escribir(txtvw, "\t%s m².\n" % (utils.float2str(total_metros)), ("negrita")) def rellenar_producto_lote_o_partida(self, objeto): """ Determina el producto (o productos, para lotes antiguos) al que pertenece el lote, lote de cemento o partida y lo muestra en el cuadro correspondiente. """ txtvw = self.wids['txt_producto'] borrar_texto(txtvw)<|fim▁hole|> for bala in objeto.balas: if (bala.articulo and bala.articulo.productoVenta and bala.articulo.productoVenta not in productos): productos.append(bala.articulo.productoVenta) elif isinstance(objeto, pclases.LoteCem): for bigbag in objeto.bigbags: if (bigbag.articulo and bigbag.articulo.productoVenta and bigbag.articulo.productoVenta not in productos): productos.append(bigbag.articulo.productoVenta) elif isinstance(objeto, pclases.Partida): for rollo in objeto.rollos: if (rollo.articulo and rollo.articulo.productoVenta and rollo.articulo.productoVenta not in productos): productos.append(rollo.articulo.productoVenta) elif isinstance(objeto, pclases.PartidaCem): for pale in objeto.pales: if (pale.productoVenta and pale.productoVenta not in productos): productos.append(pale.productoVenta) for producto in productos: self.rellenar_info_producto_venta(producto, txtvw) def rellenar_lote_o_partida(self, objeto): """ Muestra la información del lote o partida """ txtvw = self.wids['txt_lp'] borrar_texto(txtvw) if isinstance(objeto, pclases.Lote): self.rellenar_info_lote(objeto, txtvw) elif isinstance(objeto, pclases.LoteCem): self.rellenar_info_lote_cemento(objeto, txtvw) elif isinstance(objeto, pclases.Partida): self.rellenar_info_partida(objeto, txtvw) elif isinstance(objeto, pclases.PartidaCem): self.rellenar_info_partidaCem(objeto, txtvw) def rellenar_albaran_lote_o_partida(self, objeto): """ Busca los artículos que siguen en almacén del lote o partida y muestra también la relación de albaranes de los que han salido. """ txtvw = self.wids['txt_albaran'] borrar_texto(txtvw) albs = {} en_almacen = 0 if isinstance(objeto, pclases.LoteCem): bultos = objeto.bigbags elif isinstance(objeto, pclases.Lote): bultos = objeto.balas elif isinstance(objeto, pclases.Partida): bultos = objeto.rollos elif isinstance(objeto, pclases.PartidaCem): bultos = [] for pale in objeto.pales: for caja in pale.cajas: bultos.append(caja) for bulto in bultos: albaran = bulto.articulo.albaranSalida if albaran == None: en_almacen += 1 else: if albaran not in albs: albs[albaran] = 1 else: albs[albaran] += 1 self.mostrar_info_albaranes_lote_o_partida(txtvw, bultos, albs, en_almacen) def mostrar_info_albaranes_lote_o_partida(self, txtvw, bultos, albs, en_almacen): """ Introduce la información en sí en el TextView. """ escribir(txtvw, "Bultos en almacén: %d\n" % (en_almacen)) escribir(txtvw, "Bultos vendidos: %d\n" % (len(bultos) - en_almacen)) for albaran in albs: escribir(txtvw, "\t%d en el albarán %s.\n" % (albs[albaran], albaran.numalbaran)) def rellenar_produccion_lote_o_partida(self, objeto): """ Muestra el número de bultos y kg o metros fabricados para el lote, loteCem o partida en cuestión. Si el objeto es una partida, muestra además el consumo de materia prima. """ txtvw = self.wids['txt_produccion'] borrar_texto(txtvw) if isinstance(objeto, pclases.LoteCem): self.mostrar_produccion_lote_cemento(objeto, txtvw) elif isinstance(objeto, pclases.Lote): self.mostrar_produccion_lote(objeto, txtvw) elif isinstance(objeto, pclases.Partida): self.mostrar_produccion_partida(objeto, txtvw) elif isinstance(objeto, pclases.PartidaCem): self.mostrar_produccion_partidaCem(objeto, txtvw) def mostrar_produccion_lote(self, objeto, txtvw): """ Muestra las balas del lote producidas, desglosadas en clase A y clase B; y los partes donde se fabricaron. """ ba = {'bultos': 0, 'peso': 0.0} bb = {'bultos': 0, 'peso': 0.0} partes = [] for b in objeto.balas: if (b.articulo.parteDeProduccion != None and b.articulo.parteDeProduccion not in partes): partes.append(b.articulo.parteDeProduccion) if b.claseb: bb['bultos'] += 1 bb['peso'] += b.pesobala else: ba['bultos'] += 1 ba['peso'] += b.pesobala escribir(txtvw, "Balas clase A: %d; %s kg\n" % (ba['bultos'], utils.float2str(ba['peso']))) escribir(txtvw, "Balas clase B: %d; %s kg\n" % (bb['bultos'], utils.float2str(bb['peso']))) escribir(txtvw, "TOTAL: %d balas; %s kg\n" % (ba['bultos'] + bb['bultos'], utils.float2str( ba['peso'] + bb['peso']))) escribir(txtvw, "\nLote de fibra fabricado en los partes:\n") partes.sort(lambda p1, p2: int(p1.id - p2.id)) for parte in partes: escribir(txtvw, "%s (%s-%s)\n" % (utils.str_fecha(parte.fecha), utils.str_hora_corta(parte.horainicio), utils.str_hora_corta(parte.horafin))) def mostrar_produccion_partida(self, objeto, txtvw): """ Muestra la producción de los rollos de la partida. """ rs = {'bultos': 0, 'peso': 0.0, 'peso_sin': 0.0, 'metros2': 0.0, 'bultos_d': 0, 'peso_d': 0.0, 'peso_sin_d': 0.0, 'peso_teorico': objeto.get_kilos_teorico( contar_defectuosos = False), 'peso_teorico_d': objeto.get_kilos_teorico( contar_defectuosos = True), 'metros2_d': 0.0} partes = [] for r in objeto.rollos: if (r.articulo.parteDeProduccion != None and r.articulo.parteDeProduccion not in partes): partes.append(r.articulo.parteDeProduccion) rs['bultos'] += 1 rs['peso'] += r.peso rs['peso_sin'] += r.peso_sin rs['metros2'] += r.articulo.superficie for r in objeto.rollosDefectuosos: if (r.articulo.parteDeProduccion != None and r.articulo.parteDeProduccion not in partes): partes.append(r.articulo.parteDeProduccion) rs['bultos_d'] += 1 rs['peso_d'] += r.peso rs['peso_sin_d'] += r.peso_sin rs['metros2_d'] += r.articulo.superficie escribir(txtvw, "TOTAL:\n\t%d rollos;\n" "\t%d rollos defectuosos;\n" "\t\t%d rollos en total.\n" "\t%s kg reales (%s kg + %s kg en rollos defectuosos).\n" "\t%s kg sin embalaje (%s kg + %s kg en rollos defectuosos)." "\n""\t%s kg teóricos (%s kg teóricos incluyendo rollos " "defectuosos).\n" "\t%s m² (%s m² + %s m² en rollos defectuosos).\n" % ( rs['bultos'], rs['bultos_d'], rs['bultos'] + rs['bultos_d'], utils.float2str(rs['peso'] + rs['peso_d']), utils.float2str(rs['peso']), utils.float2str(rs['peso_d']), utils.float2str(rs['peso_sin'] + rs['peso_sin_d']), utils.float2str(rs['peso_sin']), utils.float2str(rs['peso_sin_d']), utils.float2str(rs['peso_teorico']), utils.float2str(rs['peso_teorico_d']), utils.float2str(rs['metros2'] + rs['metros2_d']), utils.float2str(rs['metros2']), utils.float2str(rs['metros2_d']))) escribir(txtvw, "\nPartida de geotextiles fabricada en los partes:\n") partes.sort(lambda p1, p2: int(p1.id - p2.id)) for parte in partes: escribir(txtvw, "%s (%s-%s)\n" % (utils.str_fecha(parte.fecha), utils.str_hora_corta(parte.horainicio), utils.str_hora_corta(parte.horafin))) escribir(txtvw, "\n\nConsumos:\n", ("rojo, negrita")) import geninformes escribir(txtvw, geninformes.consumoPartida(objeto), ("rojo")) def mostrar_produccion_lote_cemento(self, objeto, txtvw): """ Muestra el total de bigbags del lote y su peso total, también muestra los de clase A y B y las fechas y turnos de los partes en los que se fabricaron. """ bba = {'bultos': 0, 'peso': 0.0} bbb = {'bultos': 0, 'peso': 0.0} partes = [] for bb in objeto.bigbags: if (bb.articulo.parteDeProduccion != None and bb.articulo.parteDeProduccion not in partes): partes.append(bb.articulo.parteDeProduccion) if bb.claseb: bbb['bultos'] += 1 bbb['peso'] += bb.pesobigbag else: bba['bultos'] += 1 bba['peso'] += bb.pesobigbag escribir(txtvw, "Bigbags clase A: %d; %s kg\n" % ( bba['bultos'], utils.float2str(bba['peso']))) escribir(txtvw, "Bigbags clase B: %d; %s kg\n" % ( bbb['bultos'], utils.float2str(bbb['peso']))) escribir(txtvw, "TOTAL: %d bigbags; %s kg\n" % ( bba['bultos'] + bbb['bultos'], utils.float2str(bba['peso'] + bbb['peso']))) escribir(txtvw, "\nLote de fibra de cemento fabricado en los partes:\n") partes.sort(lambda p1, p2: int(p1.id - p2.id)) for parte in partes: escribir(txtvw, "%s (%s-%s)\n" % ( utils.str_fecha(parte.fecha), utils.str_hora_corta(parte.horainicio), utils.str_hora_corta(parte.horafin))) def mostrar_produccion_partidaCem(self, objeto, txtvw): """ Muestra el total de palés de la partida de cemento y su peso total, también muestra los de clase A y B y las fechas y turnos de los partes en los que se fabricaron. """ palesa = {'cajas': 0, 'bultos': 0, 'peso': 0.0} palesb = {'cajas': 0, 'bultos': 0, 'peso': 0.0} partes = [] for pale in objeto.pales: if (pale.parteDeProduccion != None and pale.parteDeProduccion not in partes): partes.append(pale.parteDeProduccion) if pale.claseb: palesb['bultos'] += 1 palesb['peso'] += pale.calcular_peso() palesb['cajas'] += len(pale.cajas) # Más realista en caso de # incoherencias en la base de datos que pale.numcajas. else: palesa['bultos'] += 1 palesa['peso'] += pale.calcular_peso() palesa['cajas'] += len(pale.cajas) escribir(txtvw, "Palés clase A: %d; %s kg (%d cajas)\n" % ( palesa['bultos'], utils.float2str(palesa['peso']), palesa['cajas'])) escribir(txtvw, "Palés clase B: %d; %s kg (%d cajas)\n" % ( palesb['bultos'], utils.float2str(palesb['peso']), palesb['cajas'])) escribir(txtvw, "TOTAL: %d palés; %s kg (%d cajas)\n" % ( palesa['bultos'] + palesb['bultos'], utils.float2str(palesa['peso'] + palesb['peso']), palesa['cajas'] + palesb['cajas'])) escribir(txtvw, "\nPartida de fibra de cemento embolsada " "fabricada en los partes:\n") partes.sort(lambda p1, p2: int(p1.id - p2.id)) for parte in partes: escribir(txtvw, "%s (%s-%s)\n" % ( utils.str_fecha(parte.fecha), utils.str_hora_corta(parte.horainicio), utils.str_hora_corta(parte.horafin))) def rellenar_info_lote(self, lote, txtvw): """ Recibe un lote y escribe en txtvw toda la información del mismo. """ escribir(txtvw, "Lote número: %d\n" % (lote.numlote)) escribir(txtvw, "Código de lote: %s\n" % (lote.codigo), ("negrita", )) escribir(txtvw, "Tenacidad: %s" % (lote.tenacidad)) escribir(txtvw, " (%s)\n" % ( utils.float2str(lote.calcular_tenacidad_media())), ("azul")) escribir(txtvw, "Elongación: %s" % (lote.elongacion)) escribir(txtvw, " (%s)\n" % ( utils.float2str(lote.calcular_elongacion_media())), ("azul")) escribir(txtvw, "Rizo: %s" % (lote.rizo)) escribir(txtvw, " (%s)\n" % ( utils.float2str(lote.calcular_rizo_medio())), ("azul")) escribir(txtvw, "Encogimiento: %s" % (lote.encogimiento)) escribir(txtvw, " (%s)\n" % ( utils.float2str(lote.calcular_encogimiento_medio())), ("azul")) escribir(txtvw, "Grasa: %s" % (utils.float2str(lote.grasa))) escribir(txtvw, " (%s)\n" % ( utils.float2str(lote.calcular_grasa_media())), ("azul")) escribir(txtvw, "Media de título: %s" % ( utils.float2str(lote.mediatitulo))) escribir(txtvw, " (%s)\n" % ( utils.float2str(lote.calcular_titulo_medio())), ("azul")) escribir(txtvw, "Tolerancia: %s\n" % ( utils.float2str(lote.tolerancia))) escribir(txtvw, "Muestras extraídas en el lote: %d\n" % len(lote.muestras)) escribir(txtvw, "Pruebas de estiramiento realizadas: %d\n" % len(lote.pruebasElongacion)) escribir(txtvw, "Pruebas de medida de rizo realizadas: %d\n" % len(lote.pruebasRizo)) escribir(txtvw, "Pruebas de encogimiento realizadas: %d\n" % len(lote.pruebasEncogimiento)) escribir(txtvw, "Pruebas de tenacidad realizadas: %d\n" % len(lote.pruebasTenacidad)) escribir(txtvw, "Pruebas de grasa realizadas: %d\n" % len(lote.pruebasGrasa)) escribir(txtvw, "Pruebas de título realizadas: %d\n" % len(lote.pruebasTitulo)) def rellenar_info_partida_cemento(self, partida, txtvw): """ Rellena la información de la partida de fibra de cemento. """ escribir(txtvw, "Partida de cemento número: %s\n" % ( partida and str(partida.numpartida) or "Sin partida relacionada.")) escribir(txtvw, "Código de partida: %s\n" % ( partida and partida.codigo or "Sin partida relacionada."), ("negrita", )) def rellenar_info_lote_cemento(self, lote, txtvw): """ Rellena la información del lote de cemento. """ escribir(txtvw, "Lote número: %d\n" % (lote.numlote)) escribir(txtvw, "Código de lote: %s\n" % (lote.codigo), ("negrita", )) escribir(txtvw, "Tenacidad: %s" % (lote.tenacidad)) escribir(txtvw, " (%s)\n" % (lote.calcular_tenacidad_media()), ("azul")) escribir(txtvw, "Elongación: %s" % (lote.elongacion)) escribir(txtvw, " (%s)\n" % (lote.calcular_elongacion_media()), ("azul")) escribir(txtvw, "Encogimiento: %s" % (lote.encogimiento)) escribir(txtvw, " (%s)\n" % (lote.calcular_encogimiento_medio()), ("azul")) escribir(txtvw, "Grasa: %s" % ( lote.grasa and utils.float2str(lote.grasa) or "-")) escribir(txtvw, " (%s)\n" % (lote.calcular_grasa_media()), ("azul")) escribir(txtvw, "Humedad: %s" % (lote.humedad)) escribir(txtvw, " (%s)\n" % (lote.calcular_humedad_media()), ("azul")) escribir(txtvw, "Media de título: %s" % ( lote.mediatitulo and utils.float2str(lote.mediatitulo) or "-")) escribir(txtvw, " (%s)\n" % (lote.calcular_titulo_medio()), ("azul")) escribir(txtvw, "Tolerancia: %s\n" % ( lote.tolerancia and utils.float2str(lote.tolerancia) or "-")) escribir(txtvw, "Muestras extraídas en el lote: %d\n" % ( len(lote.muestras))) escribir(txtvw, "Pruebas de estiramiento realizadas: %d\n" % ( len(lote.pruebasElongacion))) escribir(txtvw, "Pruebas de encogimiento realizadas: %d\n" % ( len(lote.pruebasEncogimiento))) escribir(txtvw, "Pruebas de grasa realizadas: %d\n" % ( len(lote.pruebasGrasa))) escribir(txtvw, "Pruebas de medida de humedad realizadas: %d\n" % (len(lote.pruebasHumedad))) escribir(txtvw, "Pruebas de tenacidad realizadas: %d\n" % ( len(lote.pruebasTenacidad))) escribir(txtvw, "Pruebas de título realizadas: %d\n" % ( len(lote.pruebasTitulo))) def rellenar_info_partida(self, partida, txtvw): """ Muestra la información de la partida en el txtvw. """ escribir(txtvw, "Número de partida: %d\n" % (partida.numpartida)) escribir(txtvw, "Código de partida: %s\n" % (partida.codigo), ("negrita")) escribir(txtvw, "Gramaje: %s" % (utils.float2str(partida.gramaje))) escribir(txtvw, " (%s)\n" % utils.float2str(partida.calcular_gramaje_medio()), ("azul")) escribir(txtvw, "Resistencia longitudinal: %s" % ( utils.float2str(partida.longitudinal))) escribir(txtvw, " (%s)\n" % (utils.float2str( partida.calcular_resistencia_longitudinal_media())), ("azul")) escribir(txtvw, "Alargamiento longitudinal: %s" % ( utils.float2str(partida.alongitudinal))) escribir(txtvw, " (%s)\n" % (utils.float2str( partida.calcular_alargamiento_longitudinal_medio())), ("azul")) escribir(txtvw, "Resistencia transversal: %s" % ( utils.float2str(partida.transversal))) escribir(txtvw, " (%s)\n" % (utils.float2str( partida.calcular_resistencia_transversal_media())), ("azul")) escribir(txtvw, "Alargamiento transversal: %s" % ( utils.float2str(partida.atransversal))) escribir(txtvw, " (%s)\n" % (utils.float2str( partida.calcular_alargamiento_transversal_medio())), ("azul")) escribir(txtvw, "CBR: %s" % (utils.float2str(partida.compresion))) escribir(txtvw, " (%s)\n" % ( utils.float2str(partida.calcular_compresion_media())), ("azul")) escribir(txtvw, "Perforación: %s" % (utils.float2str(partida.perforacion))) escribir(txtvw, " (%s)\n" % ( utils.float2str(partida.calcular_perforacion_media())), ("azul")) escribir(txtvw, "Espesor: %s" % (utils.float2str(partida.espesor))) escribir(txtvw, " (%s)\n" % ( utils.float2str(partida.calcular_espesor_medio())), ("azul")) escribir(txtvw, "Permeabilidad: %s" % ( utils.float2str(partida.permeabilidad))) escribir(txtvw, " (%s)\n" % ( utils.float2str(partida.calcular_permeabilidad_media())), ("azul")) escribir(txtvw, "Apertura de poros: %s" % (utils.float2str(partida.poros))) escribir(txtvw, " (%s)\n" % ( utils.float2str(partida.calcular_poros_medio())), ("azul")) escribir(txtvw, "Resistencia al punzonado piramidal: %s" % ( utils.float2str(partida.piramidal))) escribir(txtvw, " (%s)\n" % ( utils.float2str(partida.calcular_piramidal_media())), ("azul")) escribir(txtvw, "Muestras extraídas en la partida: %d\n" % len( partida.muestras)) escribir(txtvw, "Pruebas de alargamiento longitudinal realizadas: %d\n" % len( partida.pruebasAlargamientoLongitudinal)) escribir(txtvw, "Pruebas de alargamiento transversal realizadas: %d\n" % len( partida.pruebasAlargamientoTransversal)) escribir(txtvw, "Pruebas de compresión realizadas: %d\n" % len( partida.pruebasCompresion)) escribir(txtvw, "Pruebas de espesor realizadas: %d\n" % len( partida.pruebasEspesor)) escribir(txtvw, "Pruebas de gramaje realizadas: %d\n" % len( partida.pruebasGramaje)) escribir(txtvw, "Pruebas de perforación realizadas: %d\n" % len( partida.pruebasPerforacion)) escribir(txtvw, "Pruebas de permeabilidad realizadas: %d\n" % len( partida.pruebasPermeabilidad)) escribir(txtvw, "Pruebas de poros realizadas: %d\n"%len(partida.pruebasPoros)) escribir(txtvw, "Pruebas de resistencia longitudinal realizadas: %d\n" % len( partida.pruebasResistenciaLongitudinal)) escribir(txtvw, "Pruebas de resistencia transversal realizadas: %d\n" % len( partida.pruebasResistenciaTransversal)) escribir(txtvw, "Pruebas de punzonado piramidal realizadas: %d\n" % len( partida.pruebasPiramidal)) def rellenar_info_partidaCem(self, partida, txtvw): """ Muestra la información de la partida de cemento en el txtvw. """ escribir(txtvw, "Número de partida: %d\n" % (partida.numpartida)) escribir(txtvw, "Código de partida: %s\n" % (partida.codigo), ("negrita")) def rellenar_lotepartida(self, articulo): txtvw = self.wids['txt_lp'] borrar_texto(txtvw) if isinstance(articulo, pclases.Bala): self.rellenar_info_lote(articulo.lote, txtvw) elif isinstance(articulo, (pclases.Rollo, pclases.RolloDefectuoso)): self.rellenar_info_partida(articulo.partida, txtvw) elif isinstance(articulo, pclases.Bigbag): lote = articulo.loteCem self.rellenar_info_lote_cemento(articulo.loteCem, txtvw) elif isinstance(articulo, (pclases.BalaCable, pclases.RolloC)): lote = None # Las balas de cable no se agrupan por lotes. elif isinstance(articulo, (pclases.Pale, pclases.Caja)): #, pclases.Bolsa)): lote = articulo.partidaCem self.rellenar_info_partida_cemento(lote, txtvw) else: escribir(txtvw, "¡NO SE ENCONTRÓ INFORMACIÓN!\n" "Posible inconsistencia de la base de datos. " "Contacte con el administrador.") self.logger.error("trazabilidad_articulos.py::" "rellenar_lote_partida -> " "No se encontró información acerca del " "artículo ID %d." % (articulo.id)) def rellenar_albaran(self, articulo): txtvw = self.wids['txt_albaran'] borrar_texto(txtvw) if isinstance(articulo, pclases.Pale): pale = articulo cajas_a_mostrar = [] albaranes_tratados = [] for caja in pale.cajas: articulo_caja = caja.articulo alb = articulo_caja.albaranSalida if alb not in albaranes_tratados: albaranes_tratados.append(alb) cajas_a_mostrar.append(caja) for caja in cajas_a_mostrar: self.rellenar_albaran(caja) else: try: a = articulo.articulos[0] except IndexError, msg: self.logger.error("ERROR trazabilidad_articulos.py " "(rellenar_albaran): %s" % (msg)) else: for fecha, objeto, almacen in a.get_historial_trazabilidad(): if isinstance(objeto, pclases.AlbaranSalida): escribir(txtvw, "Albarán número: %s (%s)\n" % ( objeto.numalbaran, objeto.get_str_tipo()), ("_rojoclaro", )) escribir(txtvw, "Fecha: %s\n" % utils.str_fecha(objeto.fecha)) escribir(txtvw, "Transportista: %s\n" % ( objeto.transportista and objeto.transportista.nombre or '')) escribir(txtvw, "Cliente: %s\n" % ( objeto.cliente and objeto.cliente.nombre or ''), ("negrita", )) destino = (objeto.almacenDestino and objeto.almacenDestino.nombre or objeto.nombre) escribir(txtvw, "Origen: %s\n" % ( objeto.almacenOrigen and objeto.almacenOrigen.nombre or "ERROR - ¡Albarán sin almacén de origen!")) escribir(txtvw, "Destino: %s\n" % (destino)) elif isinstance(objeto, pclases.Abono): escribir(txtvw, "El artículo fue devuelto el %s a %s en el abono" " %s.\n" % (utils.str_fecha(fecha), almacen.nombre, objeto.numabono), ("rojo", )) # Y si ya está efectivamente en almacén, lo digo: adeda = None for ldd in objeto.lineasDeDevolucion: if ldd.articulo == a: # ¡Te encontré, sarraceno! adeda = ldd.albaranDeEntradaDeAbono if not adeda: escribir(txtvw,"El artículo aún no ha entrado" " en almacén. El abono no ha generado albarán " "de entrada de mercancía.\n", ("negrita", )) else: escribir(txtvw, "El artículo se recibió en " "el albarán de entrada de abono %s el día " "%s.\n" % ( adeda.numalbaran, utils.str_fecha(adeda.fecha))) elif isinstance(objeto, pclases.PartidaCarga): escribir(txtvw, "Se consumió el %s en la partida de carga %s.\n"%( utils.str_fecha(fecha), objeto.codigo), ("_rojoclaro", "cursiva")) if articulo.articulo.en_almacen(): escribir(txtvw, "El artículo está en almacén: %s.\n" % ( articulo.articulo.almacen and articulo.articulo.almacen.nombre or "¡Error de coherencia en la BD!"), ("_verdeclaro", )) if (hasattr(articulo, "parteDeProduccionID") and articulo.parteDeProduccionID): # Ahora también se pueden consumir los Bigbags. pdp = articulo.parteDeProduccion if pdp: if isinstance(articulo, pclases.Bigbag): escribir(txtvw, "\nBigbag consumido el día %s para producir la" " partida de fibra de cemento embolsado %s."%( utils.str_fecha(pdp.fecha), pdp.partidaCem.codigo), ("_rojoclaro", "cursiva")) def func_orden_ldds_por_albaran_salida(self, ldd1, ldd2): """ Devuelve -1, 1 ó 0 dependiendo de la fecha de los albaranes de salida relacionados con las líneas de devolución. Si las fechas son iguales, ordena por ID de las LDD. """ if ldd1.albaranSalida and (ldd2.albaranSalida == None or ldd1.albaranSalida.fecha < ldd2.albaranSalida.fecha): return -1 if ldd2.albaranSalida and (ldd1.albaranSalida == None or ldd1.albaranSalida.fecha > ldd2.albaranSalida.fecha): return 1 if ldd1.id < ldd2.id: return -1 if ldd1.id > ldd2.id: return 1 return 0 def mostrar_info_abonos(self, articulo): """ Muestra la información de los abonos del artículo. """ if articulo.lineasDeDevolucion: txtvw = self.wids['txt_albaran'] ldds = articulo.lineasDeDevolucion[:] ldds.sort(self.func_orden_ldds_por_albaran_salida) for ldd in ldds: try: escribir(txtvw, "Salida del almacén el día %s en el albarán " "%s para %s.\n" % ( utils.str_fecha(ldd.albaranSalida.fecha), ldd.albaranSalida.numalbaran, ldd.albaranSalida.cliente and ldd.albaranSalida.cliente.nombre or "?"), ("_rojoclaro", "cursiva")) escribir(txtvw, "Devuelto el día %s en el albarán de entrada " "de abono %s.\n" % ( utils.str_fecha( ldd.albaranDeEntradaDeAbono.fecha), ldd.albaranDeEntradaDeAbono.numalbaran), ("_verdeclaro", "cursiva")) except AttributeError, msg: escribir(txtvw, "ERROR DE INCONSISTENCIA. Contacte con el " "administrador de la base de datos.\n", ("negrita", )) txterror="trazabilidad_articulos.py::mostrar_info_abonos"\ " -> Excepción capturada con artículo "\ "ID %d: %s." % (articulo.id, msg) print txterror self.logger.error(txterror) escribir(txtvw, "\n") def rellenar_produccion(self, articulo): txtvw = self.wids['txt_produccion'] borrar_texto(txtvw) mostrar_parte = True if isinstance(articulo, pclases.Bala): escribir(txtvw, "Bala número: %s\n" % articulo.numbala) escribir(txtvw, "Código de trazabilidad: %s\n" % articulo.codigo) escribir(txtvw, "Fecha y hora de fabricación: %s\n" % articulo.fechahora.strftime('%d/%m/%Y %H:%M')) escribir(txtvw, "Peso: %s\n" % ( utils.float2str(articulo.pesobala, 1)), ("negrita",)) escribir(txtvw, "Se extrajo muestra para laboratorio: %s\n" % ( articulo.muestra and "Sí" or "No")) escribir(txtvw, articulo.claseb and "CLASE B\n" or "") escribir(txtvw, "Observaciones: %s\n" % (articulo.motivo or "-")) elif isinstance(articulo, pclases.Bigbag): escribir(txtvw, "BigBag número: %s\n" % articulo.numbigbag) escribir(txtvw, "Código de trazabilidad: %s\n" % articulo.codigo) escribir(txtvw, "Fecha y hora de fabricación: %s\n" % articulo.fechahora.strftime('%d/%m/%Y %H:%M')) escribir(txtvw, "Peso: %s\n" % (utils.float2str(articulo.pesobigbag, 1)), ("negrita",)) escribir(txtvw, "Se extrajo muestra para laboratorio: %s\n" % ( articulo.muestra and "Sí" or "No")) escribir(txtvw, articulo.claseb and "CLASE B\n" or "") escribir(txtvw, "Observaciones: %s\n" % (articulo.motivo or "-")) elif isinstance(articulo, (pclases.Rollo, pclases.RolloDefectuoso)): escribir(txtvw, "Rollo número: %d\n" % articulo.numrollo) escribir(txtvw, "Código de trazabilidad: %s\n" % articulo.codigo) escribir(txtvw, "Fecha y hora de fabricación: %s\n" % articulo.fechahora.strftime('%d/%m/%Y %H:%M')) escribir(txtvw, "Marcado como defectuoso: %s\n" % ( (isinstance(articulo, pclases.RolloDefectuoso) and "Sí") or (articulo.rollob and "Sí" or "No") ) ) escribir(txtvw, "Observaciones: %s\n" % articulo.observaciones) escribir(txtvw, "Se extrajo muestra para laboratorio: %s\n" % ( hasattr(articulo, "muestra") and articulo.muestra and "Sí" or "No")) escribir(txtvw, "Peso: %s\n" % (utils.float2str(articulo.peso, 1)), ("negrita",)) escribir(txtvw, "Densidad: %s\n" % ( utils.float2str(articulo.densidad, 1))) elif isinstance(articulo, (pclases.BalaCable, pclases.RolloC)): escribir(txtvw, "Código de trazabilidad: %s\n" % articulo.codigo) escribir(txtvw, "Peso: %s\n" % (utils.float2str(articulo.peso, 1)), ("negrita",)) escribir(txtvw, "Observaciones: %s\n" % (articulo.observaciones or "-")) escribir(txtvw, "Fecha y hora de embalado: %s\n" % utils.str_fechahora(articulo.fechahora)) mostrar_parte = False # Más que nada porque específicamente # no tienen. pdps = buscar_partes_fibra_fecha_y_hora(articulo.fechahora) opers = operarios_de_partes(pdps) if opers: escribir(txtvw, "\nOperarios del turno en la línea de fibra:\n") for oper in opers: escribir(txtvw, " %s, %s\n" % (oper.apellidos, oper.nombre)) else: self.logger.error("trazabilidad_articulos.py::rellenar_produccion" " -> Objeto ID %d no es de la clase bala, rollo" " ni bigbag." % (articulo.id)) if mostrar_parte: escribir(txtvw, "\n-----------------------------------\n", ("cursiva")) escribir(txtvw, "Información del parte de producción\n", ("cursiva")) escribir(txtvw, "-----------------------------------\n", ("cursiva")) try: pdp = articulo.articulos[0].parteDeProduccion except IndexError, msg: self.logger.error("ERROR trazabilidad_articulos.py " "(rellenar_produccion): %s" % (msg)) pdp = None except AttributeError: pdp = articulo.parteDeProduccion if pdp == None: escribir(txtvw, "¡No se econtró el parte de producción para la " "fabricación del artículo!\n", ("rojo", )) else: escribir(txtvw, "Fecha del parte: %s\n" % utils.str_fecha(pdp.fecha)) escribir(txtvw, "Hora de inicio: %s\n" % pdp.horainicio.strftime('%H:%M')) escribir(txtvw, "Hora de fin: %s\n" % pdp.horafin.strftime('%H:%M')) escribir(txtvw, "Parte verificado y bloqueado: %s\n" % ( pdp.bloqueado and "Sí" or "No")) escribir(txtvw, "Empleados:\n") for ht in pdp.horasTrabajadas: escribir(txtvw, "\t%s, %s (%s)\n" % (ht.empleado.apellidos, ht.empleado.nombre, ht.horas.strftime('%H:%M'))) def rellenar_producto(self, articulo): """ articulo es un pclases.Rollo, un pclases.Bala, un pclases.Bigbag o un pclases.BalaCable o un pclases.Pale o un pclases.Caja. """ txtvw = self.wids['txt_producto'] borrar_texto(txtvw) if isinstance(articulo, (pclases.Caja, pclases.Pale)): producto = articulo.productoVenta else: try: producto = articulo.articulos[0].productoVenta except IndexError, msg: self.logger.error("ERROR trazabilidad_articulos.py" " (rellenar_albaran): %s" % (msg)) producto = None if producto == None: escribir(txtvw, "¡NO SE ENCONTRÓ INFORMACIÓN!\nPosible inconsistencia " "de la base de datos. Contacte con el administrador.") self.logger.error("trazabilidad_articulos.py::rellenar_producto" " -> Objeto %s no tiene producto asociado." % ( articulo)) else: escribir(txtvw, "\nCódigo de trazabilidad: %s\n" % articulo.codigo, ("negrita", )) try: codigobarras39 = code39.Extended39(articulo.codigo, xdim = .070 * cm).guardar_a_png() codigobarras39 = gtk.gdk.pixbuf_new_from_file(codigobarras39) except Exception, e: self.logger.error("trazabilidad_articulos::rellenar_producto" " -> No se pudo guardar o mostrar el código" " %s. Excepción: %s" % (articulo.codigo, e)) else: insertar_imagen(txtvw, codigobarras39) if isinstance(articulo, pclases.Pale): escribir(txtvw, "\nPalé de %d cajas (salidas en rojo):\n\t" % len(articulo.cajas)) cajas = articulo.cajas[:] cajas.sort(lambda c1, c2: int(c1.numcaja) - int(c2.numcaja)) i = 0 for caja in cajas: codcaja = caja.codigo if caja.en_almacen(): escribir(txtvw, codcaja, ("negrita", "cursiva",)) else: escribir(txtvw, codcaja, ("negrita","cursiva","rojo")) i += 1 if i < len(cajas): escribir(txtvw, ", ") else: escribir(txtvw, "\n\n") elif isinstance(articulo, pclases.Caja): dict_bolsas = articulo.get_bolsas() codsbolsas = ", ".join([dict_bolsas[b]['código'] for b in dict_bolsas]) escribir(txtvw, "\nCaja de %d bolsas: %s\n\n" % (articulo.numbolsas, codsbolsas), ("negrita", "cursiva")) self.rellenar_info_producto_venta(producto, txtvw) def rellenar_info_producto_venta(self, producto, txtvw): """ Agrega la información del producto al txtvw. """ escribir(txtvw, "\n\t") insertar_imagen(txtvw, gtk.gdk.pixbuf_new_from_file( EanBarCode().getImage(producto.codigo))) escribir(txtvw, "\nProducto: ", ("negrita", "azul")) escribir(txtvw, "%s\n" % (producto.nombre), ("negrita", "azul", "grande")) escribir(txtvw, "Descripción: %s\n" % (producto.descripcion), ("negrita")) escribir(txtvw, "Código: %s\n" % (producto.codigo)) escribir(txtvw, "Arancel: %s\n" % (producto.arancel)) if producto.camposEspecificosRollo != None: escribir(txtvw, "Código de Composán: %s\n" % producto.camposEspecificosRollo.codigoComposan) escribir(txtvw, "gr/m²: %d\n" % producto.camposEspecificosRollo.gramos) escribir(txtvw, "Ancho: %s\n" % (utils.float2str( producto.camposEspecificosRollo.ancho, 2))) escribir(txtvw, "Diámetro: %d\n" % producto.camposEspecificosRollo.diametro) escribir(txtvw, "Metros lineales: %d\n" % producto.camposEspecificosRollo.metrosLineales) escribir(txtvw, "Rollos por camión: %d\n" % producto.camposEspecificosRollo.rollosPorCamion) escribir(txtvw, "Peso del embalaje: %s\n" % ( utils.float2str(producto.camposEspecificosRollo.pesoEmbalaje))) if producto.camposEspecificosBala != None: escribir(txtvw, "Material: %s\n" % ( producto.camposEspecificosBala.tipoMaterialBala and producto.camposEspecificosBala.tipoMaterialBala.descripcion or "-")) escribir(txtvw, "DTEX: %s\n" % (utils.float2str( producto.camposEspecificosBala.dtex))) escribir(txtvw, "Corte: %d\n" % ( producto.camposEspecificosBala.corte)) escribir(txtvw, "Color: %s\n" % ( producto.camposEspecificosBala.color)) escribir(txtvw, "Antiuv: %s\n" % ( producto.camposEspecificosBala.antiuv and "SÍ" or "NO")) if producto.camposEspecificos != []: escribir(txtvw, "Campos definidos por el usuario:\n") for cee in producto.camposEspecificos: escribir(txtvw, "\t%s: %s\n" % (cee.nombre, cee.valor)) if producto.camposEspecificosEspecial != None: escribir(txtvw, "Stock: %s\n" % ( utils.float2str(producto.camposEspecificosEspecial.stock))) escribir(txtvw, "Existencias: %s\n" % (utils.float2str( producto.camposEspecificosEspecial.existencias, 0))) escribir(txtvw, "Unidad: %s\n" % ( producto.camposEspecificosEspecial.unidad)) escribir(txtvw, "Observaciones: %s\n" % ( producto.camposEspecificosEspecial.observaciones)) def borrar_texto(txt): txt.get_buffer().set_text('') def insertar_imagen(txt, imagen): """ Inserta una imagen en el TextView txt en la posición actual del texto. """ buffer = txt.get_buffer() mark = buffer.get_insert() iter = buffer.get_iter_at_mark(mark) buffer.insert_pixbuf(iter, imagen) buffer.insert_at_cursor("\n") def buscar_partes_fibra_fecha_y_hora(fechahora): """ Busca los partes de fibra que hubiera en la fecha y hora recibida. Devuelve una lista con todos ellos. """ pdps = pclases.ParteDeProduccion.select(pclases.AND( pclases.ParteDeProduccion.q.fechahorainicio <= fechahora, pclases.ParteDeProduccion.q.fechahorafin >= fechahora)) res = [] for pdp in pdps: if pdp.es_de_fibra(): res.append(pdp) return res def operarios_de_partes(partes): """ Recibe una lista de partes de producción y devuelve otra lista con los operarios de los mismos. """ opers = [] for pdp in partes: for ht in pdp.horasTrabajadas: if ht.empleado not in opers: opers.append(ht.empleado) return opers def escribir(txt, texto, estilos = ()): """ Escribe "texto" en el buffer del TextView "txt". """ buffer = txt.get_buffer() if estilos == (): buffer.insert_at_cursor(texto) else: import pango iter_insert = buffer.get_iter_at_mark(buffer.get_insert()) tag = buffer.create_tag() if "negrita" in estilos: tag.set_property("weight", pango.WEIGHT_BOLD) #tag.set_property("stretch", pango.STRETCH_ULTRA_EXPANDED) if "cursiva" in estilos: tag.set_property("style", pango.STYLE_ITALIC) if "rojo" in estilos: tag.set_property("foreground", "red") if "azul" in estilos: tag.set_property("foreground", "blue") if "_rojoclaro" in estilos: tag.set_property("background", "pale violet red") if "_verdeclaro" in estilos: tag.set_property("background", "pale green") if "grande" in estilos: tag.set_property("size_points", 14) buffer.insert_with_tags(iter_insert, texto, tag) if __name__ == '__main__': t = TrazabilidadArticulos(usuario = pclases.Usuario.get(1))<|fim▁end|>
productos = [] if isinstance(objeto, pclases.Lote):
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-21 12:06 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Group', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255, unique=True)), ('slug', models.SlugField(allow_unicode=True, unique=True)), ('description', models.TextField(blank=True, default='')), ('description_html', models.TextField(blank=True, default='', editable=False)), ], options={ 'ordering': ['name'],<|fim▁hole|> migrations.CreateModel( name='GroupMember', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='memberships', to='groups.Group')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_groups', to=settings.AUTH_USER_MODEL)), ], ), migrations.AddField( model_name='group', name='members', field=models.ManyToManyField(through='groups.GroupMember', to=settings.AUTH_USER_MODEL), ), migrations.AlterUniqueTogether( name='groupmember', unique_together=set([('group', 'user')]), ), ]<|fim▁end|>
}, ),
<|file_name|>h3.py<|end_file_name|><|fim▁begin|>#!python3 import requests import yaml<|fim▁hole|>import sys import re import logging import ssl from requests.auth import HTTPDigestAuth from requests.auth import HTTPBasicAuth from lxml import etree as ET from requests.packages.urllib3.exceptions import InsecureRequestWarning from requests.adapters import HTTPAdapter from requests.packages.urllib3.poolmanager import PoolManager logger = logging.getLogger(__name__) with open("config/config.yaml") as f: config = yaml.load(f) # Silence self signed certificate security warning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) # Specify better cipher. Default causes errors on some systems with outdated ssl libs requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS += 'HIGH:!DH:!aNULL' try: requests.packages.urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST += 'HIGH:!DH:!aNULL' except AttributeError: # no pyopenssl support used / needed / available pass class Ssl3HttpAdapter(HTTPAdapter): """"Transport adapter" that allows us to use SSLv3.""" def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager( num_pools=connections, maxsize=maxsize, block=block, ssl_version=ssl.PROTOCOL_SSLv3) session = requests.Session() session.mount('https://wbgrp-crawl',Ssl3HttpAdapter()) class Crawl_Status(): none = "None" unbuilt = "Unbuilt" ready = "Ready" paused = "Active: PAUSED" running = "Active: RUNNING" finished = "Finished: ABORTED" class Crawl_Actions(): build = "build" launch = "launch" unpause = "unpause" pause = "pause" checkpoint = "checkpoint" terminate = "terminate" teardown = "teardown" class Crawl_Reports(): summary = "CrawlSummaryReport" seeds = "SeedsReport" source = "SourceTagsReport" hosts = "HostsReport" mime = "MimetypesReport" response = "ResponseCodeReport" processors = "ProcessorsReport" frontier = "FrontierSummaryReport" thread = "ToeThreadsReport" def get_crawl_status(url): response = session.get(url,auth=HTTPDigestAuth(config["h3_settings"]["username"],config["h3_settings"]["password"]),verify=False, headers= {'accept':'application/xml'}) if (response.status_code & 200) == 200: root=ET.fromstring(response.text) if root.find('statusDescription') is not None: return root.find('statusDescription').text elif root.find('crawlControllerState') is not None: return root.find('crawlControllerState').text def get_available_actions(url): response = session.get(url,auth=HTTPDigestAuth(config["h3_settings"]["username"],config["h3_settings"]["password"]),verify=False, headers= {'accept':'application/xml'}) actions = [] if (response.status_code & 200) == 200: root=ET.fromstring(response.text) for action in root.find('availableActions'): actions.append(action.text) return actions def main(): url = 'https://localhost:6440/engine/job/monthly_test' test_full_cycle(url) def get_crawljob_page(url): response = session.get(url,auth=HTTPDigestAuth(config["h3_settings"]["username"],config["h3_settings"]["password"]),verify=False, headers= {'accept':'application/xml'}) if (response.status_code & 200) == 200: return response def get_crawljob_text_page(url): response = requests.get(url,auth=HTTPDigestAuth(config["h3_settings"]["username"],config["h3_settings"]["password"]),verify=False) if (response.status_code & 200) == 200: return response def get_config_path(url): response = get_crawljob_page(url) root=ET.fromstring(response.text) config_path = root.find('primaryConfig').text return config_path def increment_crawl_number(url, source_config_file, dest_config_file): parser = ET.XMLParser(remove_comments=False) config_tree = ET.parse(source_config_file,parser=parser) ns = {'beans': 'http://www.springframework.org/schema/beans'} properties = config_tree.getroot().findall("./beans:bean[@id='simpleOverrides']/beans:property/beans:value",ns)[0].text m = re.finditer('(?m)^[^\.]*[wW]arcWriter\.prefix=[^\d]*-(?P<warcid>\d{3})(-.*)?',properties) for i in m: warc_id=int(i.group('warcid')) warc_id=warc_id+1 properties_incremented = re.sub('(?m)^(?P<prefix>[^\.]*[wW]arcWriter\.prefix=[^\d]*-)(?P<warcid>\d{3})(?P<suffix>(-.*)?)','\g<prefix>'+str(warc_id).zfill(3)+'\g<suffix>',properties) config_tree.getroot().findall("./beans:bean[@id='simpleOverrides']/beans:property/beans:value",ns)[0].text = properties_incremented config_tree.write(dest_config_file,xml_declaration=True,encoding="utf-8") def find_replace_xpath(url, source_config_file, dest_config_file, xpath, regex, replacement): parser = ET.XMLParser(remove_comments=False) config_tree = ET.parse(source_config_file,parser=parser) ns = {'beans': 'http://www.springframework.org/schema/beans'} config_field = config_tree.getroot().findall(xpath,ns)[0].text #print(config_field) modified_field = re.sub(re.compile(regex,re.MULTILINE),replacement,config_field) #print(modified_field) config_tree.getroot().findall(xpath,ns)[0].text=modified_field config_tree.write(dest_config_file,xml_declaration=True,encoding="utf-8") def test_full_cycle(url): status = get_crawl_status(url) logger.info("Status: %s" %status) available_actions = get_available_actions(url) if status == Crawl_Status.unbuilt and "build" in available_actions: build(url) status = get_crawl_status(url) available_actions = get_available_actions(url) if status == Crawl_Status.ready and "launch" in available_actions: launch(url) status = get_crawl_status(url) available_actions = get_available_actions(url) if status == Crawl_Status.paused and "unpause" in available_actions: unpause(url) time.sleep(5) status = get_crawl_status(url) available_actions = get_available_actions(url) if status == Crawl_Status.running and "pause" in available_actions: pause(url) runScript(url,'rawOut.println("testing")') runScript(url,'htmlOut.println("testing")') status = get_crawl_status(url) available_actions = get_available_actions(url) if status == Crawl_Status.paused and "checkpoint" in available_actions: checkpoint(url) status = get_crawl_status(url) available_actions = get_available_actions(url) if status == Crawl_Status.paused and "terminate" in available_actions: terminate(url) status = get_crawl_status(url) available_actions = get_available_actions(url) if status == Crawl_Status.finished and "teardown" in available_actions: teardown(url) def do_crawl_action_until_status(url, action, expected_status): logger.info("-Doing action: %s" %action) response = send_command(url,{"action":action}) if (response.status_code & 200) == 200: retries=0 while get_crawl_status(url) != expected_status: if retries > config["max_retries"]: logger.info("Max retries exceeded while waiting for: %s" % expected_status) sys.exit() logger.info("...") time.sleep(config["retry_delay_seconds"]) retries+=1 logger.error("Status: %s" %expected_status) def build(url): do_crawl_action_until_status(url, Crawl_Actions.build, Crawl_Status.ready) def launch(url): do_crawl_action_until_status(url,Crawl_Actions.launch, Crawl_Status.paused) def unpause(url): do_crawl_action_until_status(url,Crawl_Actions.unpause,Crawl_Status.running) def pause(url): do_crawl_action_until_status(url, Crawl_Actions.pause, Crawl_Status.paused) def checkpoint(url): do_crawl_action_until_status(url, Crawl_Actions.checkpoint, Crawl_Status.paused) def terminate(url): do_crawl_action_until_status(url, Crawl_Actions.terminate, Crawl_Status.finished) def teardown(url): do_crawl_action_until_status(url, Crawl_Actions.teardown, Crawl_Status.unbuilt) def runScript(url, script): response = send_command(url + '/script',{'engine':'groovy','script':script}) if (response.status_code & 200) == 200: logger.debug(response.text) root = ET.fromstring(response.text) return_script = root.find('script') raw_out = root.find('rawOutput') html_out = root.find('htmlOutput') lines_executed = root.find('linesExecuted') if return_script is not None: logger.info("Script run: %s" % return_script.text) if lines_executed is not None: logger.info("%s lines executed" % lines_executed.text) if raw_out is not None: logger.info("Output:\n %s" % raw_out.text) if html_out is not None: logger.info("Output:\n %s" % html_out.text) def send_command(url, data): response = session.post(url,data=data,auth=HTTPDigestAuth(config["h3_settings"]["username"],config["h3_settings"]["password"]),verify=False, headers= {'accept':'application/xml'}) return response if __name__ == "__main__": main()<|fim▁end|>
import time import enum
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>use ini::Ini; use ini::Properties; use postgres::config::Config; fn build_from_section(section: &Properties) -> Config { let mut username: Option<String> = None; let mut password: Option<String> = None; let mut builder = Config::new(); let mut options = String::new(); for (k,v) in section.iter() { match k { "host" => { builder.host(v); }, "hostaddr" => { builder.host(v); }, "port" => { builder.port(v.parse().unwrap()); }, "dbname" => { builder.dbname(v); }, "user" => username = Some(v.to_owned()), "password" => password = Some(v.to_owned()), _ => options += &format!("{}={} ", k, v), } } if !options.is_empty() { builder.options(&options); } if let Some(username) = username { builder.user(&username); } if let Some(password) = password { builder.password(&password); } builder } pub fn load_connect_params( service_name : &str<|fim▁hole|> { if let Ok(ini) = Ini::load_from_file(home + "/" + ".pg_service.conf") { if let Some(section) = ini.section(Some(service_name.clone())) { return Some(build_from_section(section)); } } } let confdir = std::env::var("PGSYSCONFDIR").unwrap_or("/etc/postgresql-common".into()); if let Ok(ini) = Ini::load_from_file(confdir + "/" + "pg_service.conf") { if let Some(section) = ini.section(Some(service_name)) { return Some(build_from_section(section)); } } None }<|fim▁end|>
) -> Option<Config> { if let Ok(home) = std::env::var("HOME")
<|file_name|>buffer-builder.js<|end_file_name|><|fim▁begin|>// Copyright 2015-present runtime.js project authors<|fim▁hole|>// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; class BufferBuilder { constructor() { this._p = []; this._repeatFirst = 0; this._repeatLast = 0; this._ck = null; this._checksumFirst = 0; this._checksumLast = 0; this._checksumOffset = 0; } uint8(valueOpt) { const value = (valueOpt >>> 0) & 0xff; this._p.push(value); this._repeatFirst = this._p.length - 1; this._repeatLast = this._p.length; return this; } uint16(valueOpt) { const value = valueOpt >>> 0; this.uint8((value >>> 8) & 0xff); this.uint8(value & 0xff); this._repeatFirst = this._p.length - 2; this._repeatLast = this._p.length; return this; } beginChecksum() { this._checksumFirst = this._p.length; return this; } endChecksum() { this._checksumLast = this._p.length; return this; } checksum(fn) { this._checksumOffset = this._p.length; this._ck = fn; return this.uint16(0); } uint32(valueOpt) { const value = valueOpt >>> 0; this.uint8((value >>> 24) & 0xff); this.uint8((value >>> 16) & 0xff); this.uint8((value >>> 8) & 0xff); this.uint8(value & 0xff); this._repeatFirst = this._p.length - 4; this._repeatLast = this._p.length; return this; } align(alignment = 0, value = 0) { while ((this._p.length % alignment) !== 0) { this.uint8(value); } return this; } array(u8) { for (const item of u8) { this.uint8(item & 0xff); } this._repeatFirst = this._p.length - u8.length; this._repeatLast = this._p.length; return this; } repeat(times = 0) { for (let t = 0; t < times; ++t) { for (let i = this._repeatFirst; i < this._repeatLast; ++i) { this._p.push(this._p[i]); } } return this; } buffer() { const buf = new Uint8Array(this._p); if (this._ck) { if (this._checksumLast === 0) { this._checksumLast = this._p.length; } const sub = buf.subarray(this._checksumFirst, this._checksumLast); const cksum = this._ck(sub); buf[this._checksumOffset] = (cksum >>> 8) & 0xff; buf[this._checksumOffset + 1] = cksum & 0xff; } return buf; } } module.exports = BufferBuilder;<|fim▁end|>
// // 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
<|file_name|>create_default_super_user.py<|end_file_name|><|fim▁begin|>from django.contrib.auth.models import User from django.core.management.base import BaseCommand from djangoautoconf.local_key_manager import get_default_admin_username, \ get_default_admin_password from djangoautoconf.management.commands.web_manage_tools.user_creator import create_admin def create_default_admin(): super_username = get_default_admin_username() super_password = get_default_admin_password() if not User.objects.filter(username=super_username).exists(): create_admin(super_username, super_password, "[email protected]")<|fim▁hole|> print("default admin already created") class Command(BaseCommand): args = '' help = 'Create command cache for environment where os.listdir is not working' def handle(self, *args, **options): create_default_admin()<|fim▁end|>
print("default admin created") else:
<|file_name|>macros.rs<|end_file_name|><|fim▁begin|>#[macro_export] macro_rules! declare_ser_tests { ($($name:ident { $($value:expr => $tokens:expr,)+ })+) => { $( #[test] fn $name() { $( ::token::assert_ser_tokens(&$value, $tokens); )+ } )+ } } #[macro_export] macro_rules! btreemap { () => { BTreeMap::new() }; ($($key:expr => $value:expr),+) => { { let mut map = BTreeMap::new(); $(map.insert($key, $value);)+ map } } } macro_rules! btreeset { () => { BTreeSet::new() }; ($($value:expr),+) => { { let mut set = BTreeSet::new(); $(set.insert($value);)+ set } } }<|fim▁hole|> }; ($($key:expr => $value:expr),+) => { { let mut map = BTreeMap::new(); $(map.insert($key, $value);)+ map } } } macro_rules! hashset { () => { HashSet::new() }; ($($value:expr),+) => { { let mut set = HashSet::new(); $(set.insert($value);)+ set } } } macro_rules! hashmap { () => { HashMap::new() }; ($($key:expr => $value:expr),+) => { { let mut map = HashMap::new(); $(map.insert($key, $value);)+ map } } }<|fim▁end|>
macro_rules! btreemap { () => { BTreeMap::new()
<|file_name|>macros.rs<|end_file_name|><|fim▁begin|>#[macro_export] #[cfg(not(feature = "clipboard"))] macro_rules! editeur_new { ($graphic: expr, $output: expr) => ({ use std::io; Editeur { graphic: $graphic, output: $output, input: io::stdin().events(), menu: Menu::default(), }<|fim▁hole|> #[macro_export] #[cfg(feature = "clipboard")] macro_rules! editeur_new { ($graphic: expr, $output: expr) => ({ use clipboard::ClipboardContext; use std::io; Editeur { graphic: $graphic, output: $output, input: io::stdin().events(), kopimism: ClipboardContext::new().unwrap(), menu: Menu::default(), } }); }<|fim▁end|>
}); }
<|file_name|>remove.rs<|end_file_name|><|fim▁begin|>use libc::{c_ulong, c_ulonglong, c_void}; use super::super::error_type::ErrorType; use super::super::instance::Instance; use super::format_error; #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct RemoveInternal { pub cookie: *mut c_void, pub key: *const c_void, pub nkey: c_ulong, pub cas: c_ulonglong, pub rc: ErrorType, pub version: u16, pub rflags: u16 }<|fim▁hole|> unsafe { match self.rc { ErrorType::Success => { let bytes = ::std::slice::from_raw_parts(self.key as *mut u8, self.nkey as usize); let text = ::std::str::from_utf8(bytes).unwrap(); Some(text.to_string()) }, _ => { None } } } } pub fn error(&self, instance: Instance) -> &'static str { format_error(instance, &self.rc) } } #[derive(Debug)] pub struct Remove { pub key: Option<String>, pub cas: u64, pub rc: ErrorType, pub version: u16, pub rflags: u16, } impl Remove { pub fn new(internal: &RemoveInternal) -> Remove { Remove { key: internal.key(), cas: internal.cas, rc: internal.rc, version: internal.version, rflags: internal.rflags } } }<|fim▁end|>
impl RemoveInternal { pub fn key(&self) -> Option<String> {
<|file_name|>deprecation.py<|end_file_name|><|fim▁begin|># Human friendly input/output in Python. # # Author: Peter Odding <[email protected]> # Last Change: March 2, 2020 # URL: https://humanfriendly.readthedocs.io """ Support for deprecation warnings when importing names from old locations. When software evolves, things tend to move around. This is usually detrimental to backwards compatibility (in Python this primarily manifests itself as :exc:`~exceptions.ImportError` exceptions). While backwards compatibility is very important, it should not get in the way of progress. It would be great to have the agility to move things around without breaking backwards compatibility. This is where the :mod:`humanfriendly.deprecation` module comes in: It enables the definition of backwards compatible aliases that emit a deprecation warning when they are accessed. The way it works is that it wraps the original module in an :class:`DeprecationProxy` object that defines a :func:`~DeprecationProxy.__getattr__()` special method to override attribute access of the module. """ # Standard library modules.<|fim▁hole|>import collections import functools import importlib import inspect import sys import types import warnings # Modules included in our package. from humanfriendly.text import format # Registry of known aliases (used by humanfriendly.sphinx). REGISTRY = collections.defaultdict(dict) # Public identifiers that require documentation. __all__ = ("DeprecationProxy", "define_aliases", "deprecated_args", "get_aliases", "is_method") def define_aliases(module_name, **aliases): """ Update a module with backwards compatible aliases. :param module_name: The ``__name__`` of the module (a string). :param aliases: Each keyword argument defines an alias. The values are expected to be "dotted paths" (strings). The behavior of this function depends on whether the Sphinx documentation generator is active, because the use of :class:`DeprecationProxy` to shadow the real module in :data:`sys.modules` has the unintended side effect of breaking autodoc support for ``:data:`` members (module variables). To avoid breaking Sphinx the proxy object is omitted and instead the aliased names are injected into the original module namespace, to make sure that imports can be satisfied when the documentation is being rendered. If you run into cyclic dependencies caused by :func:`define_aliases()` when running Sphinx, you can try moving the call to :func:`define_aliases()` to the bottom of the Python module you're working on. """ module = sys.modules[module_name] proxy = DeprecationProxy(module, aliases) # Populate the registry of aliases. for name, target in aliases.items(): REGISTRY[module.__name__][name] = target # Avoid confusing Sphinx. if "sphinx" in sys.modules: for name, target in aliases.items(): setattr(module, name, proxy.resolve(target)) else: # Install a proxy object to raise DeprecationWarning. sys.modules[module_name] = proxy def get_aliases(module_name): """ Get the aliases defined by a module. :param module_name: The ``__name__`` of the module (a string). :returns: A dictionary with string keys and values: 1. Each key gives the name of an alias created for backwards compatibility. 2. Each value gives the dotted path of the proper location of the identifier. An empty dictionary is returned for modules that don't define any backwards compatible aliases. """ return REGISTRY.get(module_name, {}) def deprecated_args(*names): """ Deprecate positional arguments without dropping backwards compatibility. :param names: The positional arguments to :func:`deprecated_args()` give the names of the positional arguments that the to-be-decorated function should warn about being deprecated and translate to keyword arguments. :returns: A decorator function specialized to `names`. The :func:`deprecated_args()` decorator function was created to make it easy to switch from positional arguments to keyword arguments [#]_ while preserving backwards compatibility [#]_ and informing call sites about the change. .. [#] Increased flexibility is the main reason why I find myself switching from positional arguments to (optional) keyword arguments as my code evolves to support more use cases. .. [#] In my experience positional argument order implicitly becomes part of API compatibility whether intended or not. While this makes sense for functions that over time adopt more and more optional arguments, at a certain point it becomes an inconvenience to code maintenance. Here's an example of how to use the decorator:: @deprecated_args('text') def report_choice(**options): print(options['text']) When the decorated function is called with positional arguments a deprecation warning is given:: >>> report_choice('this will give a deprecation warning') DeprecationWarning: report_choice has deprecated positional arguments, please switch to keyword arguments this will give a deprecation warning But when the function is called with keyword arguments no deprecation warning is emitted:: >>> report_choice(text='this will not give a deprecation warning') this will not give a deprecation warning """ def decorator(function): def translate(args, kw): # Raise TypeError when too many positional arguments are passed to the decorated function. if len(args) > len(names): raise TypeError( format( "{name} expected at most {limit} arguments, got {count}", name=function.__name__, limit=len(names), count=len(args), ) ) # Emit a deprecation warning when positional arguments are used. if args: warnings.warn( format( "{name} has deprecated positional arguments, please switch to keyword arguments", name=function.__name__, ), category=DeprecationWarning, stacklevel=3, ) # Translate positional arguments to keyword arguments. for name, value in zip(names, args): kw[name] = value if is_method(function): @functools.wraps(function) def wrapper(*args, **kw): """Wrapper for instance methods.""" args = list(args) self = args.pop(0) translate(args, kw) return function(self, **kw) else: @functools.wraps(function) def wrapper(*args, **kw): """Wrapper for module level functions.""" translate(args, kw) return function(**kw) return wrapper return decorator def is_method(function): """Check if the expected usage of the given function is as an instance method.""" try: # Python 3.3 and newer. signature = inspect.signature(function) return "self" in signature.parameters except AttributeError: # Python 3.2 and older. metadata = inspect.getargspec(function) return "self" in metadata.args class DeprecationProxy(types.ModuleType): """Emit deprecation warnings for imports that should be updated.""" def __init__(self, module, aliases): """ Initialize an :class:`DeprecationProxy` object. :param module: The original module object. :param aliases: A dictionary of aliases. """ # Initialize our superclass. super(DeprecationProxy, self).__init__(name=module.__name__) # Store initializer arguments. self.module = module self.aliases = aliases def __getattr__(self, name): """ Override module attribute lookup. :param name: The name to look up (a string). :returns: The attribute value. """ # Check if the given name is an alias. target = self.aliases.get(name) if target is not None: # Emit the deprecation warning. warnings.warn( format("%s.%s was moved to %s, please update your imports", self.module.__name__, name, target), category=DeprecationWarning, stacklevel=2, ) # Resolve the dotted path. return self.resolve(target) # Look up the name in the original module namespace. value = getattr(self.module, name, None) if value is not None: return value # Fall back to the default behavior. raise AttributeError(format("module '%s' has no attribute '%s'", self.module.__name__, name)) def resolve(self, target): """ Look up the target of an alias. :param target: The fully qualified dotted path (a string). :returns: The value of the given target. """ module_name, _, member = target.rpartition(".") module = importlib.import_module(module_name) return getattr(module, member)<|fim▁end|>
<|file_name|>writer.rs<|end_file_name|><|fim▁begin|>//! Writes audio samples to files. (Reads too, this module needs a rename) //! //! ### Audacity PCM import settings //! //! * File > Import > Raw Data... //! * Signed 16-bit PCM //! * Little-endian //! * 1 Channel (Mono) //! * Sample rate: 44_100Hz (or whatever your samples generated have) use std::fs::OpenOptions; use std::io::{BufReader, Error, Read, Result, Write}; use std::path::Path; use byteorder::{BigEndian, LittleEndian, ReadBytesExt, WriteBytesExt}; /// Creates a file at `filename` and writes a bunch of `&[i16]` samples to it as a PCM file. /// See module documentation for PCM settings. /// /// ``` /// use synthrs::wave::sine_wave; /// use synthrs::writer::write_pcm_file; /// use synthrs::synthesizer::{quantize_samples, make_samples}; /// /// write_pcm_file( /// "out/sine.wav", /// &quantize_samples::<i16>(&make_samples(0.1, 44_100, sine_wave(440.0))), /// ).expect("failed to write wav"); /// ``` pub fn write_pcm_file(filename: &str, samples: &[i16]) -> Result<()> { let path = Path::new(filename); let mut f = OpenOptions::new() .write(true) .truncate(true) .create(true) .open(&path)?; write_pcm(&mut f, samples) } /// Writes a bunch of `&[i16]` samples to a `Write` as raw PCM. /// See module documentation for PCM settings. /// /// Also see `synthrs::writer::write_pcm_file`. /// /// ``` /// use std::io::Cursor; /// use synthrs::wave::sine_wave; /// use synthrs::writer::write_pcm; /// use synthrs::synthesizer::{quantize_samples, make_samples}; /// /// let mut output_buffer: Vec<u8> = Vec::new(); /// let mut output_writer = Cursor::new(output_buffer); /// /// // You can use whatever implements `Write`, such as a `File`. /// write_pcm( /// &mut output_writer, /// &quantize_samples::<i16>(&make_samples(0.1, 44_100, sine_wave(440.0))), /// ).expect("failed to write wav"); /// ``` pub fn write_pcm<W>(writer: &mut W, samples: &[i16]) -> Result<()> where W: Write, { for &sample in samples.iter() { writer.write_i16::<LittleEndian>(sample)?; } Ok(()) } /// Creates a file at `filename` and writes a bunch of `&[i16]` samples to it as a WAVE file /// ``` /// use synthrs::wave::sine_wave; /// use synthrs::writer::write_wav_file; /// use synthrs::synthesizer::{quantize_samples, make_samples}; /// /// write_wav_file( /// "out/sine.wav", /// 44_100, /// &quantize_samples::<i16>(&make_samples(0.1, 44_100, sine_wave(440.0))), /// ).expect("failed to write wav"); /// ``` pub fn write_wav_file(filename: &str, sample_rate: usize, samples: &[i16]) -> Result<()> { let path = Path::new(filename); let mut f = OpenOptions::new() .write(true) .truncate(true) .create(true) .open(&path)?; write_wav(&mut f, sample_rate, samples) } /// Writes a bunch of `&[i16]` samples to a `Write`. Also see `synthrs::writer::write_wav_file`. /// ``` /// use std::io::Cursor; /// use synthrs::wave::sine_wave; /// use synthrs::writer::write_wav; /// use synthrs::synthesizer::{quantize_samples, make_samples}; /// /// let mut output_buffer: Vec<u8> = Vec::new(); /// let mut output_writer = Cursor::new(output_buffer); /// /// // You can use whatever implements `Write`, such as a `File`. /// write_wav( /// &mut output_writer, /// 44_100, /// &quantize_samples::<i16>(&make_samples(0.1, 44_100, sine_wave(440.0))), /// ).expect("failed to write wav"); /// ``` pub fn write_wav<W>(writer: &mut W, sample_rate: usize, samples: &[i16]) -> Result<()> where W: Write, { // See: http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html // Some WAV header fields let channels = 1; let bit_depth = 16; let subchunk_2_size = samples.len() * channels * bit_depth / 8; let chunk_size = 36 + subchunk_2_size as i32; let byte_rate = (sample_rate * channels * bit_depth / 8) as i32; let block_align = (channels * bit_depth / 8) as i16; writer.write_i32::<BigEndian>(0x5249_4646)?; // ChunkID, RIFF writer.write_i32::<LittleEndian>(chunk_size)?; // ChunkSize writer.write_i32::<BigEndian>(0x5741_5645)?; // Format, WAVE writer.write_i32::<BigEndian>(0x666d_7420)?; // Subchunk1ID, fmt writer.write_i32::<LittleEndian>(16)?; // Subchunk1Size, 16 for PCM writer.write_i16::<LittleEndian>(1)?; // AudioFormat, PCM = 1 (linear quantization) writer.write_i16::<LittleEndian>(channels as i16)?; // NumChannels writer.write_i32::<LittleEndian>(sample_rate as i32)?; // SampleRate writer.write_i32::<LittleEndian>(byte_rate)?; // ByteRate writer.write_i16::<LittleEndian>(block_align)?; // BlockAlign writer.write_i16::<LittleEndian>(bit_depth as i16)?; // BitsPerSample writer.write_i32::<BigEndian>(0x6461_7461)?; // Subchunk2ID, data writer.write_i32::<LittleEndian>(subchunk_2_size as i32)?; // Subchunk2Size, number of bytes in the data for sample in samples { writer.write_i16::<LittleEndian>(*sample)? } Ok(()) } // Borrowing of packed &wave.pcm is unsafe // #[repr(C, packed)] /// Representation of a WAV file. Does not contain fields for extended WAV formats. #[repr(C)] #[derive(Debug, Clone)] pub struct Wave { pub chunk_id: i32, pub chunk_size: i32, pub format: i32, pub subchunk_1_id: i32, pub subchunk_1_size: i32, /// 1 = PCM pub audio_format: i16, pub num_channels: i16, pub sample_rate: i32, pub byte_rate: i32, pub block_align: i16, pub bits_per_sample: i16, pub subchunk_2_id: i32, pub subchunk_2_size: i32, pub pcm: Vec<i16>, } /// Reads a wave file given a file path. Convenience wrapper around `crate::writer::read_wav_file`. /// ``` /// use synthrs::writer; /// /// let wave = writer::read_wav_file("./tests/assets/sine.wav").unwrap(); /// assert_eq!(wave.num_channels, 1); /// ``` pub fn read_wav_file(filename: &str) -> Result<Wave> { let path = Path::new(filename); let file = OpenOptions::new().read(true).open(&path)?; let mut reader = BufReader::new(file); read_wav(&mut reader) } /// Reads a wave file. Only supports mono 16-bit, little-endian, signed PCM WAV files /// /// ### Useful commands: /// /// * Use `ffmpeg -i .\example.wav` to inspect a wav /// * Use `ffmpeg -i "dirty.wav" -f wav -flags +bitexact -acodec pcm_s16le -ar 44100 -ac 1 "clean.wav"` to clean a WAV /// /// ``` /// use std::path::Path; /// use std::fs::OpenOptions; /// use std::io::BufReader; /// use synthrs::writer; /// /// let path = Path::new("./tests/assets/sine.wav"); /// let file = OpenOptions::new().read(true).open(&path).unwrap(); /// let mut reader = BufReader::new(file); /// /// let wave = writer::read_wav(&mut reader).unwrap(); /// assert_eq!(wave.num_channels, 1); /// ``` // For -acodec values, see https://trac.ffmpeg.org/wiki/audio%20types pub fn read_wav<R>(reader: &mut R) -> Result<Wave> where R: Read, { let chunk_id = reader.read_i32::<BigEndian>()?; // ChunkID, RIFF let chunk_size = reader.read_i32::<LittleEndian>()?; // ChunkSize let format = reader.read_i32::<BigEndian>()?; // Format, WAVE if format != 0x5741_5645 { return Err(Error::new( std::io::ErrorKind::InvalidInput, "file is not a WAV".to_string(), )); } let subchunk_1_id = reader.read_i32::<BigEndian>()?; // Subchunk1ID, fmt let subchunk_1_size = reader.read_i32::<LittleEndian>()?; // Subchunk1Size, Chunk size: 16, 18 or 40 let audio_format = reader.read_i16::<LittleEndian>()?; // AudioFormat, PCM = 1 (linear quantization) if audio_format != 1 { return Err(Error::new( std::io::ErrorKind::InvalidInput, format!( "only 16-bit little-endian signed PCM WAV supported, audio_format: {}", audio_format ), )); } let num_channels = reader.read_i16::<LittleEndian>()?; // NumChannels<|fim▁hole|> let sample_rate = reader.read_i32::<LittleEndian>()?; // SampleRate let byte_rate = reader.read_i32::<LittleEndian>()?; // ByteRate let block_align = reader.read_i16::<LittleEndian>()?; // BlockAlign let bits_per_sample = reader.read_i16::<LittleEndian>()?; // BitsPerSample let extra_bytes = subchunk_1_size - 16; if extra_bytes > 0 { let extension_size = reader.read_i16::<LittleEndian>()?; // Size of the extension (0 or 22) if extension_size == 22 { // TODO: Add this to `Wave` as optionals let _valid_bits_per_sample = reader.read_i16::<LittleEndian>()?; let _speaker_mask = reader.read_i16::<LittleEndian>()?; let _subformat = reader.read_i16::<BigEndian>()?; } else if extension_size != 0 { return Err(Error::new( std::io::ErrorKind::InvalidInput, format!( "unexpected fmt chunk extension size: should be 0 or 22 but got: {}", extension_size ), )); } } let subchunk_2_id = reader.read_i32::<BigEndian>()?; // Subchunk2ID, data if subchunk_2_id != 0x6461_7461 { return Err(Error::new( std::io::ErrorKind::InvalidInput, format!( "unexpected subchunk name: expecting data, got: {}", subchunk_2_id ), )); } let subchunk_2_size = reader.read_i32::<LittleEndian>()?; // Subchunk2Size, number of bytes in the data let mut pcm: Vec<i16> = Vec::with_capacity(2 * subchunk_2_size as usize); // `reader.read_into_i16(&pcm)` doesn't seem to work here due to bad input? // It just does nothing and &pcm is left empty after that. for _i in 0..subchunk_2_size { let sample = reader.read_i16::<LittleEndian>().unwrap_or(0); pcm.push(sample); } let wave = Wave { chunk_id, chunk_size, format, subchunk_1_id, subchunk_1_size, audio_format, num_channels, sample_rate, byte_rate, block_align, bits_per_sample, subchunk_2_id, subchunk_2_size, pcm, }; Ok(wave) } #[cfg(test)] mod tests { use super::*; #[test] fn test_read_wav() { // 1 second at 44,100Hz, PCM 16 (2-byte) let wave = read_wav_file("./tests/assets/sine.wav").unwrap(); assert_eq!(wave.format, 0x5741_5645); // WAVE assert_eq!(wave.audio_format, 1); assert_eq!(wave.num_channels, 1); assert_eq!(wave.sample_rate, 44_100); assert_eq!(wave.byte_rate, 88_200); assert_eq!(wave.block_align, 2); assert_eq!(wave.bits_per_sample, 16); assert_eq!(wave.subchunk_2_size, 88_200); assert_eq!(wave.pcm.len(), 88_200); } #[test] fn test_write_read_wav() { use crate::synthesizer::{make_samples, quantize_samples}; use crate::wave::sine_wave; use crate::writer::write_wav; use std::io::{Cursor, Seek, SeekFrom}; let output_buffer: Vec<u8> = Vec::new(); let mut output_writer = Cursor::new(output_buffer); write_wav( &mut output_writer, 44_100, &quantize_samples::<i16>(&make_samples(0.1, 44_100, sine_wave(440.0))), ) .unwrap(); let _ = output_writer.seek(SeekFrom::Start(0)); let wave = read_wav(&mut output_writer).unwrap(); assert_eq!(wave.format, 0x5741_5645); // WAVE assert_eq!(wave.audio_format, 1); assert_eq!(wave.num_channels, 1); assert_eq!(wave.sample_rate, 44_100); assert_eq!(wave.byte_rate, 88_200); assert_eq!(wave.block_align, 2); assert_eq!(wave.bits_per_sample, 16); assert_eq!(wave.subchunk_2_size, 8820); assert_eq!(wave.pcm.len(), 8820); } }<|fim▁end|>
<|file_name|>bitcoin_cs.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="cs" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="14"/> <source>About Emercoin</source> <translation>O Emercoinu</translation> </message> <message> <location filename="../forms/aboutdialog.ui" line="53"/> <source>&lt;b&gt;Emercoin&lt;/b&gt; version</source> <translation>&lt;b&gt;Emercoin&lt;/b&gt; verze</translation> </message> <message> <location filename="../forms/aboutdialog.ui" line="85"/> <source>Copyright © 2009-2012 Bitcoin Developers This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file license.txt 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>Copyright © 2009-2012 Vývojáři Emercoinu Tohle je experimentální program. Šířen pod licencí MIT/X11, viz přiložený soubor license.txt nebo http://www.opensource.org/licenses/mit-license.php. Tento produkt zahrnuje programy vyvinuté OpenSSL Projektem pro použití v OpenSSL Toolkitu (http://www.openssl.org/) a kryptografický program od Erika Younga ([email protected]) a program UPnP od Thomase Bernarda.</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="14"/> <source>Address Book</source> <translation>Adresář</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="20"/> <source>These are your Emercoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Tohle jsou tvé Emercoinové adresy pro příjem plateb. Můžeš pokaždé dát každému odesílateli jinou adresu, abys věděl, kdo ti kdy kolik platil.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="33"/> <source>Double-click to edit address or label</source> <translation>Dvojklikem myši začneš upravovat označení adresy</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="57"/> <source>Create a new address</source> <translation>Vytvoř novou adresu</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="60"/> <source>&amp;New Address...</source> <translation>Nová &amp;adresa...</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="71"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Zkopíruj aktuálně vybranou adresu do systémové schránky</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="74"/> <source>&amp;Copy to Clipboard</source> <translation>&amp;Zkopíruj do schránky</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="85"/> <source>Show &amp;QR Code</source> <translation>Zobraz &amp;QR kód</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="96"/> <source>Sign a message to prove you own this address</source> <translation>Podepiš zprávu, čímž prokážeš, že jsi vlastníkem této adresy</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="99"/> <source>&amp;Sign Message</source> <translation>Po&amp;depiš zprávu</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="110"/> <source>Delete the currently selected address from the list. Only sending addresses can be deleted.</source><|fim▁hole|> <source>&amp;Delete</source> <translation>S&amp;maž</translation> </message> <message> <location filename="../addressbookpage.cpp" line="61"/> <source>Copy address</source> <translation>Kopíruj adresu</translation> </message> <message> <location filename="../addressbookpage.cpp" line="62"/> <source>Copy label</source> <translation>Kopíruj označení</translation> </message> <message> <location filename="../addressbookpage.cpp" line="63"/> <source>Edit</source> <translation>Uprav</translation> </message> <message> <location filename="../addressbookpage.cpp" line="64"/> <source>Delete</source> <translation>Smaž</translation> </message> <message> <location filename="../addressbookpage.cpp" line="281"/> <source>Export Address Book Data</source> <translation>Exportuj data adresáře</translation> </message> <message> <location filename="../addressbookpage.cpp" line="282"/> <source>Comma separated file (*.csv)</source> <translation>CSV formát (*.csv)</translation> </message> <message> <location filename="../addressbookpage.cpp" line="295"/> <source>Error exporting</source> <translation>Chyba při exportu</translation> </message> <message> <location filename="../addressbookpage.cpp" line="295"/> <source>Could not write to file %1.</source> <translation>Nemohu zapisovat do souboru %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="77"/> <source>Label</source> <translation>Označení</translation> </message> <message> <location filename="../addresstablemodel.cpp" line="77"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location filename="../addresstablemodel.cpp" line="113"/> <source>(no label)</source> <translation>(bez označení)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="26"/> <source>Dialog</source> <translation>Dialog</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="32"/> <location filename="../forms/askpassphrasedialog.ui" line="97"/> <source>TextLabel</source> <translation>Textový popisek</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="50"/> <source>Enter passphrase</source> <translation>Zadej platné heslo</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="64"/> <source>New passphrase</source> <translation>Zadej nové heslo</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="78"/> <source>Repeat new passphrase</source> <translation>Totéž heslo ještě jednou</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="34"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Zadej nové heslo k peněžence.&lt;br/&gt;Použij &lt;b&gt;alespoň 10 náhodných znaků&lt;/b&gt; nebo &lt;b&gt;alespoň osm slov&lt;/b&gt;.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="35"/> <source>Encrypt wallet</source> <translation>Zašifruj peněženku</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="38"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>K provedení této operace musíš zadat heslo k peněžence, aby se mohla odemknout.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="43"/> <source>Unlock wallet</source> <translation>Odemkni peněženku</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="46"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>K provedení této operace musíš zadat heslo k peněžence, aby se mohla dešifrovat.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="51"/> <source>Decrypt wallet</source> <translation>Dešifruj peněženku</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="54"/> <source>Change passphrase</source> <translation>Změň heslo</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="55"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Zadej staré a nové heslo k peněžence.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="101"/> <source>Confirm wallet encryption</source> <translation>Potvrď zašifrování peněženky</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="102"/> <source>WARNING: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR EMERCOINS&lt;/b&gt;! Are you sure you wish to encrypt your wallet?</source> <translation>VAROVÁNÍ: Pokud zašifruješ peněženku a ztratíš či zapomeneš heslo, &lt;b&gt;PŘIJDEŠ O VŠECHNY EMERCOINY&lt;/b&gt;! Jsi si jistý, že chceš peněženku zašifrovat?</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="111"/> <location filename="../askpassphrasedialog.cpp" line="160"/> <source>Wallet encrypted</source> <translation>Peněženka je zašifrována</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="112"/> <source>Emercoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your emercoins from being stolen by malware infecting your computer.</source> <translation>Emercoin se teď ukončí, aby dokončil zašifrování. Pamatuj však, že pouhé zašifrování peněženky úplně nezabraňuje krádeži tvých emercoinů malwarem, kterým se může počítač nakazit.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="208"/> <location filename="../askpassphrasedialog.cpp" line="232"/> <source>Warning: The Caps Lock key is on.</source> <translation>Upozornění: Caps Lock je zapnutý.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="117"/> <location filename="../askpassphrasedialog.cpp" line="124"/> <location filename="../askpassphrasedialog.cpp" line="166"/> <location filename="../askpassphrasedialog.cpp" line="172"/> <source>Wallet encryption failed</source> <translation>Zašifrování peněženky selhalo</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="118"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Zašifrování peněženky selhalo kvůli vnitřní chybě. Tvá peněženka tedy nebyla zašifrována.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="125"/> <location filename="../askpassphrasedialog.cpp" line="173"/> <source>The supplied passphrases do not match.</source> <translation>Zadaná hesla nejsou shodná.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="136"/> <source>Wallet unlock failed</source> <translation>Odemčení peněženky selhalo</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="137"/> <location filename="../askpassphrasedialog.cpp" line="148"/> <location filename="../askpassphrasedialog.cpp" line="167"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Nezadal jsi správné heslo pro dešifrování peněženky.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="147"/> <source>Wallet decryption failed</source> <translation>Dešifrování peněženky selhalo</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="161"/> <source>Wallet passphrase was succesfully changed.</source> <translation>Heslo k peněžence bylo v pořádku změněno.</translation> </message> </context> <context> <name>EmercoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="69"/> <source>Emercoin Wallet</source> <translation>Emercoinová peněženka</translation> </message> <message> <location filename="../bitcoingui.cpp" line="142"/> <location filename="../bitcoingui.cpp" line="464"/> <source>Synchronizing with network...</source> <translation>Synchronizuji se sítí...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="145"/> <source>Block chain synchronization in progress</source> <translation>Provádí se synchronizace řetězce bloků</translation> </message> <message> <location filename="../bitcoingui.cpp" line="176"/> <source>&amp;Overview</source> <translation>&amp;Přehled</translation> </message> <message> <location filename="../bitcoingui.cpp" line="177"/> <source>Show general overview of wallet</source> <translation>Zobraz celkový přehled peněženky</translation> </message> <message> <location filename="../bitcoingui.cpp" line="182"/> <source>&amp;Transactions</source> <translation>&amp;Transakce</translation> </message> <message> <location filename="../bitcoingui.cpp" line="183"/> <source>Browse transaction history</source> <translation>Procházet historii transakcí</translation> </message> <message> <location filename="../bitcoingui.cpp" line="188"/> <source>&amp;Address Book</source> <translation>&amp;Adresář</translation> </message> <message> <location filename="../bitcoingui.cpp" line="189"/> <source>Edit the list of stored addresses and labels</source> <translation>Uprav seznam uložených adres a jejich označení</translation> </message> <message> <location filename="../bitcoingui.cpp" line="194"/> <source>&amp;Receive coins</source> <translation>Pří&amp;jem mincí</translation> </message> <message> <location filename="../bitcoingui.cpp" line="195"/> <source>Show the list of addresses for receiving payments</source> <translation>Zobraz seznam adres pro příjem plateb</translation> </message> <message> <location filename="../bitcoingui.cpp" line="200"/> <source>&amp;Send coins</source> <translation>P&amp;oslání mincí</translation> </message> <message> <location filename="../bitcoingui.cpp" line="201"/> <source>Send coins to a emercoin address</source> <translation>Pošli mince na Emercoinovou adresu</translation> </message> <message> <location filename="../bitcoingui.cpp" line="206"/> <source>Sign &amp;message</source> <translation>Po&amp;depiš zprávu</translation> </message> <message> <location filename="../bitcoingui.cpp" line="207"/> <source>Prove you control an address</source> <translation>Prokaž vlastnictví adresy</translation> </message> <message> <location filename="../bitcoingui.cpp" line="226"/> <source>E&amp;xit</source> <translation>&amp;Konec</translation> </message> <message> <location filename="../bitcoingui.cpp" line="227"/> <source>Quit application</source> <translation>Ukončit aplikaci</translation> </message> <message> <location filename="../bitcoingui.cpp" line="230"/> <source>&amp;About %1</source> <translation>&amp;O %1</translation> </message> <message> <location filename="../bitcoingui.cpp" line="231"/> <source>Show information about Emercoin</source> <translation>Zobraz informace o Emercoinu</translation> </message> <message> <location filename="../bitcoingui.cpp" line="233"/> <source>About &amp;Qt</source> <translation>O &amp;Qt</translation> </message> <message> <location filename="../bitcoingui.cpp" line="234"/> <source>Show information about Qt</source> <translation>Zobraz informace o Qt</translation> </message> <message> <location filename="../bitcoingui.cpp" line="236"/> <source>&amp;Options...</source> <translation>&amp;Možnosti...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="237"/> <source>Modify configuration options for emercoin</source> <translation>Uprav nastavení Emercoinu</translation> </message> <message> <location filename="../bitcoingui.cpp" line="239"/> <source>Open &amp;Emercoin</source> <translation>Otevři &amp;Emercoin</translation> </message> <message> <location filename="../bitcoingui.cpp" line="240"/> <source>Show the Emercoin window</source> <translation>Zobraz okno Emercoinu</translation> </message> <message> <location filename="../bitcoingui.cpp" line="241"/> <source>&amp;Export...</source> <translation>&amp;Export...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="242"/> <source>Export the data in the current tab to a file</source> <translation>Exportovat data z tohoto panelu do souboru</translation> </message> <message> <location filename="../bitcoingui.cpp" line="243"/> <source>&amp;Encrypt Wallet</source> <translation>Zaši&amp;fruj peněženku</translation> </message> <message> <location filename="../bitcoingui.cpp" line="244"/> <source>Encrypt or decrypt wallet</source> <translation>Zašifruj nebo dešifruj peněženku</translation> </message> <message> <location filename="../bitcoingui.cpp" line="246"/> <source>&amp;Backup Wallet</source> <translation>&amp;Zazálohovat peněženku</translation> </message> <message> <location filename="../bitcoingui.cpp" line="247"/> <source>Backup wallet to another location</source> <translation>Zazálohuj peněženku na jiné místo</translation> </message> <message> <location filename="../bitcoingui.cpp" line="248"/> <source>&amp;Change Passphrase</source> <translation>Změň &amp;heslo</translation> </message> <message> <location filename="../bitcoingui.cpp" line="249"/> <source>Change the passphrase used for wallet encryption</source> <translation>Změň heslo k šifrování peněženky</translation> </message> <message> <location filename="../bitcoingui.cpp" line="272"/> <source>&amp;File</source> <translation>&amp;Soubor</translation> </message> <message> <location filename="../bitcoingui.cpp" line="281"/> <source>&amp;Settings</source> <translation>&amp;Nastavení</translation> </message> <message> <location filename="../bitcoingui.cpp" line="287"/> <source>&amp;Help</source> <translation>Ná&amp;pověda</translation> </message> <message> <location filename="../bitcoingui.cpp" line="294"/> <source>Tabs toolbar</source> <translation>Panel s listy</translation> </message> <message> <location filename="../bitcoingui.cpp" line="305"/> <source>Actions toolbar</source> <translation>Panel akcí</translation> </message> <message> <location filename="../bitcoingui.cpp" line="317"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location filename="../bitcoingui.cpp" line="407"/> <source>emercoin-qt</source> <translation>emercoin-qt</translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="449"/> <source>%n active connection(s) to Emercoin network</source> <translation><numerusform>%n aktivní spojení do Emercoinové sítě</numerusform><numerusform>%n aktivní spojení do Emercoinové sítě</numerusform><numerusform>%n aktivních spojení do Emercoinové sítě</numerusform></translation> </message> <message> <location filename="../bitcoingui.cpp" line="475"/> <source>Downloaded %1 of %2 blocks of transaction history.</source> <translation>Staženo %1 z %2 bloků transakční historie.</translation> </message> <message> <location filename="../bitcoingui.cpp" line="487"/> <source>Downloaded %1 blocks of transaction history.</source> <translation>Staženo %1 bloků transakční historie.</translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="502"/> <source>%n second(s) ago</source> <translation><numerusform>před vteřinou</numerusform><numerusform>před %n vteřinami</numerusform><numerusform>před %n vteřinami</numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="506"/> <source>%n minute(s) ago</source> <translation><numerusform>před minutou</numerusform><numerusform>před %n minutami</numerusform><numerusform>před %n minutami</numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="510"/> <source>%n hour(s) ago</source> <translation><numerusform>před hodinou</numerusform><numerusform>před %n hodinami</numerusform><numerusform>před %n hodinami</numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="514"/> <source>%n day(s) ago</source> <translation><numerusform>včera</numerusform><numerusform>před %n dny</numerusform><numerusform>před %n dny</numerusform></translation> </message> <message> <location filename="../bitcoingui.cpp" line="520"/> <source>Up to date</source> <translation>aktuální</translation> </message> <message> <location filename="../bitcoingui.cpp" line="525"/> <source>Catching up...</source> <translation>Stahuji...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="533"/> <source>Last received block was generated %1.</source> <translation>Poslední stažený blok byl vygenerován %1.</translation> </message> <message> <location filename="../bitcoingui.cpp" line="597"/> <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>Tahle transakce přesahuje velikostní limit. I tak ji ale můžeš poslat, pokud za ni zaplatíš poplatek %1, který půjde uzlům, které tvou transakci zpracují, a navíc tak podpoříš síť. Chceš zaplatit poplatek?</translation> </message> <message> <location filename="../bitcoingui.cpp" line="602"/> <source>Sending...</source> <translation>Posílám...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="629"/> <source>Sent transaction</source> <translation>Odeslané transakce</translation> </message> <message> <location filename="../bitcoingui.cpp" line="630"/> <source>Incoming transaction</source> <translation>Příchozí transakce</translation> </message> <message> <location filename="../bitcoingui.cpp" line="631"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Datum: %1 Částka: %2 Typ: %3 Adresa: %4 </translation> </message> <message> <location filename="../bitcoingui.cpp" line="751"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Peněženka je &lt;b&gt;zašifrovaná&lt;/b&gt; a momentálně &lt;b&gt;odemčená&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoingui.cpp" line="759"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Peněženka je &lt;b&gt;zašifrovaná&lt;/b&gt; a momentálně &lt;b&gt;zamčená&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoingui.cpp" line="782"/> <source>Backup Wallet</source> <translation>Záloha peněženky</translation> </message> <message> <location filename="../bitcoingui.cpp" line="782"/> <source>Wallet Data (*.dat)</source> <translation>Data peněženky (*.dat)</translation> </message> <message> <location filename="../bitcoingui.cpp" line="785"/> <source>Backup Failed</source> <translation>Zálohování selhalo</translation> </message> <message> <location filename="../bitcoingui.cpp" line="785"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Při ukládání peněženky na nové místo se přihodila nějaká chyba.</translation> </message> </context> <context> <name>DisplayOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="270"/> <source>&amp;Unit to show amounts in: </source> <translation>&amp;Jednotka pro částky: </translation> </message> <message> <location filename="../optionsdialog.cpp" line="274"/> <source>Choose the default subdivision unit to show in the interface, and when sending coins</source> <translation>Zvol výchozí podjednotku, která se bude zobrazovat v programu a při posílání mincí</translation> </message> <message> <location filename="../optionsdialog.cpp" line="281"/> <source>Display addresses in transaction list</source> <translation>Ukazovat adresy ve výpisu transakcí</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="14"/> <source>Edit Address</source> <translation>Uprav adresu</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="25"/> <source>&amp;Label</source> <translation>&amp;Označení</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="35"/> <source>The label associated with this address book entry</source> <translation>Označení spojené s tímto záznamem v adresáři</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="42"/> <source>&amp;Address</source> <translation>&amp;Adresa</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="52"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Adresa spojená s tímto záznamem v adresáři. Lze upravovat jen pro odesílací adresy.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="20"/> <source>New receiving address</source> <translation>Nová přijímací adresa</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="24"/> <source>New sending address</source> <translation>Nová odesílací adresa</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="27"/> <source>Edit receiving address</source> <translation>Uprav přijímací adresu</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="31"/> <source>Edit sending address</source> <translation>Uprav odesílací adresu</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="91"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Zadaná adresa &quot;%1&quot; už v adresáři je.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="96"/> <source>The entered address &quot;%1&quot; is not a valid emercoin address.</source> <translation>Zadaná adresa &quot;%1&quot; není platná Emercoinová adresa.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="101"/> <source>Could not unlock wallet.</source> <translation>Nemohu odemknout peněženku.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="106"/> <source>New key generation failed.</source> <translation>Nepodařilo se mi vygenerovat nový klíč.</translation> </message> </context> <context> <name>MainOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="170"/> <source>&amp;Start Emercoin on window system startup</source> <translation>&amp;Spustit Emercoin při startu systému</translation> </message> <message> <location filename="../optionsdialog.cpp" line="171"/> <source>Automatically start Emercoin after the computer is turned on</source> <translation>Automaticky spustí Emercoin po zapnutí počítače</translation> </message> <message> <location filename="../optionsdialog.cpp" line="175"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimalizovávat do ikony v panelu</translation> </message> <message> <location filename="../optionsdialog.cpp" line="176"/> <source>Show only a tray icon after minimizing the window</source> <translation>Po minimalizaci okna zobrazí pouze ikonu v panelu</translation> </message> <message> <location filename="../optionsdialog.cpp" line="180"/> <source>Map port using &amp;UPnP</source> <translation>Namapovat port přes &amp;UPnP</translation> </message> <message> <location filename="../optionsdialog.cpp" line="181"/> <source>Automatically open the Emercoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Automaticky otevře potřebný port na routeru. Tohle funguje jen za předpokladu, že tvůj router podporuje UPnP a že je UPnP povolené.</translation> </message> <message> <location filename="../optionsdialog.cpp" line="185"/> <source>M&amp;inimize on close</source> <translation>&amp;Zavřením minimalizovat</translation> </message> <message> <location filename="../optionsdialog.cpp" line="186"/> <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>Zavřením se aplikace minimalizuje. Pokud je tato volba zaškrtnuta, tak se aplikace ukončí pouze zvolením Konec v menu.</translation> </message> <message> <location filename="../optionsdialog.cpp" line="190"/> <source>&amp;Connect through SOCKS4 proxy:</source> <translation>&amp;Připojit přes SOCKS4 proxy:</translation> </message> <message> <location filename="../optionsdialog.cpp" line="191"/> <source>Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)</source> <translation>Připojí se do Emercoinové sítě přes SOCKS4 proxy (např. když se připojuje přes Tor)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="196"/> <source>Proxy &amp;IP: </source> <translation>&amp;IP adresa proxy:</translation> </message> <message> <location filename="../optionsdialog.cpp" line="202"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP adresa proxy (např. 127.0.0.1)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="205"/> <source>&amp;Port: </source> <translation>P&amp;ort: </translation> </message> <message> <location filename="../optionsdialog.cpp" line="211"/> <source>Port of the proxy (e.g. 1234)</source> <translation>Port proxy (např. 1234)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="217"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation>Dobrovolný transakční poplatek za každý započatý kB dopomáhá k rychlému zpracování tvých transakcí. Většina transakcí má do 1 kB. Doporučená výše poplatku je 0.01.</translation> </message> <message> <location filename="../optionsdialog.cpp" line="223"/> <source>Pay transaction &amp;fee</source> <translation>Platit &amp;transakční poplatek</translation> </message> <message> <location filename="../optionsdialog.cpp" line="226"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation>Dobrovolný transakční poplatek za každý započatý kB dopomáhá k rychlému zpracování tvých transakcí. Většina transakcí má do 1 kB. Doporučená výše poplatku je 0.01.</translation> </message> </context> <context> <name>MessagePage</name> <message> <location filename="../forms/messagepage.ui" line="14"/> <source>Message</source> <translation>Zpráva</translation> </message> <message> <location filename="../forms/messagepage.ui" line="20"/> <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>Podepsáním zprávy svými adresami můžeš prokázat, že je skutečně vlastníš. Buď opatrný a nepodepisuj nic vágního; například při phishingových útocích můžeš být lákán, abys něco takového podepsal. Podepisuj pouze zcela úplná a detailní prohlášení, se kterými souhlasíš.</translation> </message> <message> <location filename="../forms/messagepage.ui" line="38"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Tvá adresa (např. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location filename="../forms/messagepage.ui" line="48"/> <source>Choose adress from address book</source> <translation>Vyber adresu z adresáře</translation> </message> <message> <location filename="../forms/messagepage.ui" line="58"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location filename="../forms/messagepage.ui" line="71"/> <source>Paste address from clipboard</source> <translation>Vlož adresu ze schránky</translation> </message> <message> <location filename="../forms/messagepage.ui" line="81"/> <source>Alt+P</source> <translation>Alt+V</translation> </message> <message> <location filename="../forms/messagepage.ui" line="93"/> <source>Enter the message you want to sign here</source> <translation>Sem vepiš zprávu, kterou chceš podepsat</translation> </message> <message> <location filename="../forms/messagepage.ui" line="105"/> <source>Click &quot;Sign Message&quot; to get signature</source> <translation>Kliknutím na &quot;Podepiš zprávu&quot; získáš podpis</translation> </message> <message> <location filename="../forms/messagepage.ui" line="117"/> <source>Sign a message to prove you own this address</source> <translation>Podepiš zprávu, čímž prokážeš, že jsi vlastníkem této adresy</translation> </message> <message> <location filename="../forms/messagepage.ui" line="120"/> <source>&amp;Sign Message</source> <translation>&amp;Podepiš zprávu</translation> </message> <message> <location filename="../forms/messagepage.ui" line="131"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Zkopíruj podpis do systémové schránky</translation> </message> <message> <location filename="../forms/messagepage.ui" line="134"/> <source>&amp;Copy to Clipboard</source> <translation>&amp;Zkopíruj do schránky</translation> </message> <message> <location filename="../messagepage.cpp" line="74"/> <location filename="../messagepage.cpp" line="89"/> <location filename="../messagepage.cpp" line="101"/> <source>Error signing</source> <translation>Chyba při podepisování</translation> </message> <message> <location filename="../messagepage.cpp" line="74"/> <source>%1 is not a valid address.</source> <translation>%1 není platná adresa.</translation> </message> <message> <location filename="../messagepage.cpp" line="89"/> <source>Private key for %1 is not available.</source> <translation>Soukromý klíč pro %1 není dostupný.</translation> </message> <message> <location filename="../messagepage.cpp" line="101"/> <source>Sign failed</source> <translation>Podepisování selhalo</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../optionsdialog.cpp" line="79"/> <source>Main</source> <translation>Hlavní</translation> </message> <message> <location filename="../optionsdialog.cpp" line="84"/> <source>Display</source> <translation>Zobrazení</translation> </message> <message> <location filename="../optionsdialog.cpp" line="104"/> <source>Options</source> <translation>Možnosti</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="14"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="40"/> <source>Balance:</source> <translation>Stav účtu:</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="47"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="54"/> <source>Number of transactions:</source> <translation>Počet transakcí:</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="61"/> <source>0</source> <translation>0</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="68"/> <source>Unconfirmed:</source> <translation>Nepotvrzeno:</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="75"/> <source>0 BTC</source> <translation>0 BTC</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="82"/> <source>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt; p, li { white-space: pre-wrap; } &lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Ubuntu'; font-size:11pt; font-weight:400; font-style:normal;&quot;&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Wallet&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt; p, li { white-space: pre-wrap; } &lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;Ubuntu&apos;; font-size:11pt; font-weight:400; font-style:normal;&quot;&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Peněženka&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="122"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Poslední transakce&lt;/b&gt;</translation> </message> <message> <location filename="../overviewpage.cpp" line="103"/> <source>Your current balance</source> <translation>Aktuální stav tvého účtu</translation> </message> <message> <location filename="../overviewpage.cpp" line="108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Celkem z transakcí, které ještě nejsou potvrzené a které se ještě nezapočítávají do celkového stavu účtu</translation> </message> <message> <location filename="../overviewpage.cpp" line="111"/> <source>Total number of transactions in wallet</source> <translation>Celkový počet transakcí v peněžence</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="14"/> <source>Dialog</source> <translation>Dialog</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="32"/> <source>QR Code</source> <translation>QR kód</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="52"/> <source>Request Payment</source> <translation>Požadovat platbu</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="67"/> <source>Amount:</source> <translation>Částka:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="102"/> <source>BTC</source> <translation>BTC</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="118"/> <source>Label:</source> <translation>Označení:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="141"/> <source>Message:</source> <translation>Zpráva:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="183"/> <source>&amp;Save As...</source> <translation>&amp;Ulož jako...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="101"/> <source>Save Image...</source> <translation>Ulož obrázek...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="101"/> <source>PNG Images (*.png)</source> <translation>PNG obrázky (*.png)</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="14"/> <location filename="../sendcoinsdialog.cpp" line="122"/> <location filename="../sendcoinsdialog.cpp" line="127"/> <location filename="../sendcoinsdialog.cpp" line="132"/> <location filename="../sendcoinsdialog.cpp" line="137"/> <location filename="../sendcoinsdialog.cpp" line="143"/> <location filename="../sendcoinsdialog.cpp" line="148"/> <location filename="../sendcoinsdialog.cpp" line="153"/> <source>Send Coins</source> <translation>Pošli mince</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="64"/> <source>Send to multiple recipients at once</source> <translation>Pošli více příjemcům naráz</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="67"/> <source>&amp;Add recipient...</source> <translation>Při&amp;dej příjemce...</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="84"/> <source>Remove all transaction fields</source> <translation>Smaž všechny transakční formuláře</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="87"/> <source>Clear all</source> <translation>Všechno smaž</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="106"/> <source>Balance:</source> <translation>Stav účtu:</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="113"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="144"/> <source>Confirm the send action</source> <translation>Potvrď odeslání</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="147"/> <source>&amp;Send</source> <translation>&amp;Pošli</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="94"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; pro %2 (%3)</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="99"/> <source>Confirm send coins</source> <translation>Potvrď odeslání mincí</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="100"/> <source>Are you sure you want to send %1?</source> <translation>Jsi si jistý, že chceš poslat %1?</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="100"/> <source> and </source> <translation> a </translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="123"/> <source>The recepient address is not valid, please recheck.</source> <translation>Adresa příjemce je neplatná, překontroluj ji prosím.</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="128"/> <source>The amount to pay must be larger than 0.</source> <translation>Odesílaná částka musí být větší než 0.</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="133"/> <source>Amount exceeds your balance</source> <translation>Částka překračuje stav účtu</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="138"/> <source>Total exceeds your balance when the %1 transaction fee is included</source> <translation>Celková částka při připočítání poplatku %1 překročí stav účtu</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="144"/> <source>Duplicate address found, can only send to each address once in one send operation</source> <translation>Zaznamenána duplikovaná adresa; každá adresa může být v odesílané platbě pouze jednou</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="149"/> <source>Error: Transaction creation failed </source> <translation>Chyba: Vytvoření transakce selhalo </translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="154"/> <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>Chyba Transakce byla odmítnuta. Tohle může nastat, pokud nějaké mince z tvé peněženky už jednou byly utraceny, například pokud používáš kopii souboru wallet.dat a mince byly utraceny v druhé kopii, ale nebyly označeny jako utracené v této.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="14"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="29"/> <source>A&amp;mount:</source> <translation>Čá&amp;stka:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="42"/> <source>Pay &amp;To:</source> <translation>&amp;Komu:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="66"/> <location filename="../sendcoinsentry.cpp" line="26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Zadej označení této adresy; obojí se ti pak uloží do adresáře</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="75"/> <source>&amp;Label:</source> <translation>&amp;Označení:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="93"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Adresa příjemce (např. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="103"/> <source>Choose address from address book</source> <translation>Vyber adresu z adresáře</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="113"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="120"/> <source>Paste address from clipboard</source> <translation>Vlož adresu ze schránky</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="130"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="137"/> <source>Remove this recipient</source> <translation>Smaž tohoto příjemce</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="25"/> <source>Enter a Emercoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Zadej Emercoinovou adresu (např. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="18"/> <source>Open for %1 blocks</source> <translation>Otevřeno pro %1 bloků</translation> </message> <message> <location filename="../transactiondesc.cpp" line="20"/> <source>Open until %1</source> <translation>Otřevřeno dokud %1</translation> </message> <message> <location filename="../transactiondesc.cpp" line="26"/> <source>%1/offline?</source> <translation>%1/offline?</translation> </message> <message> <location filename="../transactiondesc.cpp" line="28"/> <source>%1/unconfirmed</source> <translation>%1/nepotvrzeno</translation> </message> <message> <location filename="../transactiondesc.cpp" line="30"/> <source>%1 confirmations</source> <translation>%1 potvrzení</translation> </message> <message> <location filename="../transactiondesc.cpp" line="47"/> <source>&lt;b&gt;Status:&lt;/b&gt; </source> <translation>&lt;b&gt;Stav:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="52"/> <source>, has not been successfully broadcast yet</source> <translation>, ještě nebylo rozesláno</translation> </message> <message> <location filename="../transactiondesc.cpp" line="54"/> <source>, broadcast through %1 node</source> <translation>, rozesláno přes %1 uzel</translation> </message> <message> <location filename="../transactiondesc.cpp" line="56"/> <source>, broadcast through %1 nodes</source> <translation>, rozesláno přes %1 uzlů</translation> </message> <message> <location filename="../transactiondesc.cpp" line="60"/> <source>&lt;b&gt;Date:&lt;/b&gt; </source> <translation>&lt;b&gt;Datum:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="67"/> <source>&lt;b&gt;Source:&lt;/b&gt; Generated&lt;br&gt;</source> <translation>&lt;b&gt;Zdroj:&lt;/b&gt; Vygenerováno&lt;br&gt;</translation> </message> <message> <location filename="../transactiondesc.cpp" line="73"/> <location filename="../transactiondesc.cpp" line="90"/> <source>&lt;b&gt;From:&lt;/b&gt; </source> <translation>&lt;b&gt;Od:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="90"/> <source>unknown</source> <translation>neznámo</translation> </message> <message> <location filename="../transactiondesc.cpp" line="91"/> <location filename="../transactiondesc.cpp" line="114"/> <location filename="../transactiondesc.cpp" line="173"/> <source>&lt;b&gt;To:&lt;/b&gt; </source> <translation>&lt;b&gt;Pro:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="94"/> <source> (yours, label: </source> <translation> (tvoje, označení: </translation> </message> <message> <location filename="../transactiondesc.cpp" line="96"/> <source> (yours)</source> <translation> (tvoje)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="131"/> <location filename="../transactiondesc.cpp" line="145"/> <location filename="../transactiondesc.cpp" line="190"/> <location filename="../transactiondesc.cpp" line="207"/> <source>&lt;b&gt;Credit:&lt;/b&gt; </source> <translation>&lt;b&gt;Příjem:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="133"/> <source>(%1 matures in %2 more blocks)</source> <translation>(%1 dozraje po %2 blocích)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="137"/> <source>(not accepted)</source> <translation>(neakceptováno)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="181"/> <location filename="../transactiondesc.cpp" line="189"/> <location filename="../transactiondesc.cpp" line="204"/> <source>&lt;b&gt;Debit:&lt;/b&gt; </source> <translation>&lt;b&gt;Výdaj:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="195"/> <source>&lt;b&gt;Transaction fee:&lt;/b&gt; </source> <translation>&lt;b&gt;Transakční poplatek:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="211"/> <source>&lt;b&gt;Net amount:&lt;/b&gt; </source> <translation>&lt;b&gt;Čistá částka:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="217"/> <source>Message:</source> <translation>Zpráva:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="219"/> <source>Comment:</source> <translation>Komentář:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="221"/> <source>Transaction ID:</source> <translation>ID transakce:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="224"/> <source>Generated coins must wait 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, it will change to &quot;not accepted&quot; and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Vygenerované mince musí čekat 120 bloků, než mohou být utraceny. Když jsi vygeneroval tenhle blok, tak byl rozposlán do sítě, aby byl přidán do řetězce bloků. Pokud se mu nepodaří dostat se do řetězce, změní se na &quot;neakceptovaný&quot; a nepůjde utratit. Občas se to může stát, když jiný uzel vygeneruje blok zhruba ve stejném okamžiku jako ty.</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="14"/> <source>Transaction details</source> <translation>Detaily transakce</translation> </message> <message> <location filename="../forms/transactiondescdialog.ui" line="20"/> <source>This pane shows a detailed description of the transaction</source> <translation>Toto okno zobrazuje detailní popis transakce</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="213"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="213"/> <source>Type</source> <translation>Typ</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="213"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="213"/> <source>Amount</source> <translation>Částka</translation> </message> <message numerus="yes"> <location filename="../transactiontablemodel.cpp" line="274"/> <source>Open for %n block(s)</source> <translation><numerusform>Otevřeno pro 1 blok</numerusform><numerusform>Otevřeno pro %n bloky</numerusform><numerusform>Otevřeno pro %n bloků</numerusform></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="277"/> <source>Open until %1</source> <translation>Otřevřeno dokud %1</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="280"/> <source>Offline (%1 confirmations)</source> <translation>Offline (%1 potvrzení)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="283"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Nepotvrzeno (%1 z %2 potvrzení)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="286"/> <source>Confirmed (%1 confirmations)</source> <translation>Potvrzeno (%1 potvrzení)</translation> </message> <message numerus="yes"> <location filename="../transactiontablemodel.cpp" line="295"/> <source>Mined balance will be available in %n more blocks</source> <translation><numerusform>Vytěžené mince budou použitelné po jednom bloku</numerusform><numerusform>Vytěžené mince budou použitelné po %n blocích</numerusform><numerusform>Vytěžené mince budou použitelné po %n blocích</numerusform></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="301"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Tento blok nedostal žádný jiný uzel a pravděpodobně nebude akceptován!</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="304"/> <source>Generated but not accepted</source> <translation>Vygenerováno, ale neakceptováno</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="347"/> <source>Received with</source> <translation>Přijato do</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="349"/> <source>Received from</source> <translation>Přijato od</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="352"/> <source>Sent to</source> <translation>Posláno na</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="354"/> <source>Payment to yourself</source> <translation>Platba sama sobě</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="356"/> <source>Mined</source> <translation>Vytěženo</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="394"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="593"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Stav transakce. Najetím myši na toto políčko si zobrazíš počet potvrzení.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="595"/> <source>Date and time that the transaction was received.</source> <translation>Datum a čas přijetí transakce.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="597"/> <source>Type of transaction.</source> <translation>Druh transakce.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="599"/> <source>Destination address of transaction.</source> <translation>Cílová adresa transakce.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="601"/> <source>Amount removed from or added to balance.</source> <translation>Částka odečtená z nebo přičtená k účtu.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="55"/> <location filename="../transactionview.cpp" line="71"/> <source>All</source> <translation>Vše</translation> </message> <message> <location filename="../transactionview.cpp" line="56"/> <source>Today</source> <translation>Dnes</translation> </message> <message> <location filename="../transactionview.cpp" line="57"/> <source>This week</source> <translation>Tento týden</translation> </message> <message> <location filename="../transactionview.cpp" line="58"/> <source>This month</source> <translation>Tento měsíc</translation> </message> <message> <location filename="../transactionview.cpp" line="59"/> <source>Last month</source> <translation>Minulý měsíc</translation> </message> <message> <location filename="../transactionview.cpp" line="60"/> <source>This year</source> <translation>Letos</translation> </message> <message> <location filename="../transactionview.cpp" line="61"/> <source>Range...</source> <translation>Rozsah...</translation> </message> <message> <location filename="../transactionview.cpp" line="72"/> <source>Received with</source> <translation>Přijato</translation> </message> <message> <location filename="../transactionview.cpp" line="74"/> <source>Sent to</source> <translation>Posláno</translation> </message> <message> <location filename="../transactionview.cpp" line="76"/> <source>To yourself</source> <translation>Sám sobě</translation> </message> <message> <location filename="../transactionview.cpp" line="77"/> <source>Mined</source> <translation>Vytěženo</translation> </message> <message> <location filename="../transactionview.cpp" line="78"/> <source>Other</source> <translation>Ostatní</translation> </message> <message> <location filename="../transactionview.cpp" line="84"/> <source>Enter address or label to search</source> <translation>Zadej adresu nebo označení pro její vyhledání</translation> </message> <message> <location filename="../transactionview.cpp" line="90"/> <source>Min amount</source> <translation>Minimální částka</translation> </message> <message> <location filename="../transactionview.cpp" line="124"/> <source>Copy address</source> <translation>Kopíruj adresu</translation> </message> <message> <location filename="../transactionview.cpp" line="125"/> <source>Copy label</source> <translation>Kopíruj její označení</translation> </message> <message> <location filename="../transactionview.cpp" line="126"/> <source>Copy amount</source> <translation>Kopíruj částku</translation> </message> <message> <location filename="../transactionview.cpp" line="127"/> <source>Edit label</source> <translation>Uprav označení</translation> </message> <message> <location filename="../transactionview.cpp" line="128"/> <source>Show details...</source> <translation>Zobraz detaily....</translation> </message> <message> <location filename="../transactionview.cpp" line="268"/> <source>Export Transaction Data</source> <translation>Exportuj transakční data</translation> </message> <message> <location filename="../transactionview.cpp" line="269"/> <source>Comma separated file (*.csv)</source> <translation>CSV formát (*.csv)</translation> </message> <message> <location filename="../transactionview.cpp" line="277"/> <source>Confirmed</source> <translation>Potvrzeno</translation> </message> <message> <location filename="../transactionview.cpp" line="278"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location filename="../transactionview.cpp" line="279"/> <source>Type</source> <translation>Typ</translation> </message> <message> <location filename="../transactionview.cpp" line="280"/> <source>Label</source> <translation>Označení</translation> </message> <message> <location filename="../transactionview.cpp" line="281"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location filename="../transactionview.cpp" line="282"/> <source>Amount</source> <translation>Částka</translation> </message> <message> <location filename="../transactionview.cpp" line="283"/> <source>ID</source> <translation>ID</translation> </message> <message> <location filename="../transactionview.cpp" line="287"/> <source>Error exporting</source> <translation>Chyba při exportu</translation> </message> <message> <location filename="../transactionview.cpp" line="287"/> <source>Could not write to file %1.</source> <translation>Nemohu zapisovat do souboru %1.</translation> </message> <message> <location filename="../transactionview.cpp" line="382"/> <source>Range:</source> <translation>Rozsah:</translation> </message> <message> <location filename="../transactionview.cpp" line="390"/> <source>to</source> <translation>až</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="145"/> <source>Sending...</source> <translation>Posílám...</translation> </message> </context> <context> <name>emercoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="3"/> <source>Emercoin version</source> <translation>Verze Emercoinu</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="4"/> <source>Usage:</source> <translation>Užití:</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="5"/> <source>Send command to -server or emercoind</source> <translation>Poslat příkaz pro -server nebo emercoind</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="6"/> <source>List commands</source> <translation>Výpis příkazů</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="7"/> <source>Get help for a command</source> <translation>Získat nápovědu pro příkaz</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="8"/> <source>Options:</source> <translation>Možnosti:</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="9"/> <source>Specify configuration file (default: emercoin.conf)</source> <translation>Konfigurační soubor (výchozí: emercoin.conf)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="10"/> <source>Specify pid file (default: emercoind.pid)</source> <translation>PID soubor (výchozí: emercoind.pid)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="11"/> <source>Generate coins</source> <translation>Generovat mince</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="12"/> <source>Don&apos;t generate coins</source> <translation>Negenerovat mince</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="13"/> <source>Start minimized</source> <translation>Startovat minimalizovaně</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="14"/> <source>Specify data directory</source> <translation>Adresář pro data</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="15"/> <source>Specify connection timeout (in milliseconds)</source> <translation>Zadej časový limit spojení (v milisekundách)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="16"/> <source>Connect through socks4 proxy</source> <translation>Připojovat se přes socks4 proxy</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="17"/> <source>Allow DNS lookups for addnode and connect</source> <translation>Povolit DNS dotazy pro addnode (přidání uzlu) a connect (připojení)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="18"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation>Čekat na spojení na &lt;portu&gt; (výchozí: 8333 nebo testnet: 18333)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="19"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Povol nejvýše &lt;n&gt; připojení k uzlům (výchozí: 125)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="20"/> <source>Add a node to connect to</source> <translation>Přidat uzel, ke kterému se připojit</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="21"/> <source>Connect only to the specified node</source> <translation>Připojovat se pouze k udanému uzlu</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="22"/> <source>Don&apos;t accept connections from outside</source> <translation>Nepřijímat připojení zvenčí</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="23"/> <source>Don&apos;t bootstrap list of peers using DNS</source> <translation>Nenačítat seznam uzlů z DNS</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="24"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Práh pro odpojování nesprávně se chovajících uzlů (výchozí: 100)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="25"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Doba ve vteřinách, po kterou se nebudou moci nesprávně se chovající uzly znovu připojit (výchozí: 86400)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="28"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation>Maximální velikost přijímacího bufferu pro každé spojení, &lt;n&gt;*1000 bytů (výchozí: 10000)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="29"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation>Maximální velikost odesílacího bufferu pro každé spojení, &lt;n&gt;*1000 bytů (výchozí: 10000)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="30"/> <source>Don&apos;t attempt to use UPnP to map the listening port</source> <translation>Nesnažit se použít UPnP k namapování naslouchacího portu</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="31"/> <source>Attempt to use UPnP to map the listening port</source> <translation>Snažit se použít UPnP k namapování naslouchacího portu</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="32"/> <source>Fee per kB to add to transactions you send</source> <translation>Poplatek za kB, který se přidá ke každé odeslané transakci</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="33"/> <source>Accept command line and JSON-RPC commands</source> <translation>Akceptovat příkazy z příkazové řádky a přes JSON-RPC</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="34"/> <source>Run in the background as a daemon and accept commands</source> <translation>Běžet na pozadí jako démon a akceptovat příkazy</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="35"/> <source>Use the test network</source> <translation>Použít testovací síť (testnet)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="36"/> <source>Output extra debugging information</source> <translation>Tisknout speciální ladící informace</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="37"/> <source>Prepend debug output with timestamp</source> <translation>Připojit před ladící výstup časové razítko</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="38"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Posílat stopovací/ladící informace do konzole místo do souboru debug.log</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="39"/> <source>Send trace/debug info to debugger</source> <translation>Posílat stopovací/ladící informace do debuggeru</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="40"/> <source>Username for JSON-RPC connections</source> <translation>Uživatelské jméno pro JSON-RPC spojení</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="41"/> <source>Password for JSON-RPC connections</source> <translation>Heslo pro JSON-RPC spojení</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="42"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332)</source> <translation>Čekat na JSON-RPC spojení na &lt;portu&gt; (výchozí: 8332)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="43"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Povolit JSON-RPC spojení ze specifikované IP adresy</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="44"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Posílat příkazy uzlu běžícím na &lt;ip&gt; (výchozí: 127.0.0.1)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="45"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Nastavit zásobník klíčů na velikost &lt;n&gt; (výchozí: 100)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="46"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Přeskenovat řetězec bloků na chybějící transakce tvé pěněženky</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="47"/> <source> SSL options: (see the Emercoin Wiki for SSL setup instructions)</source> <translation> Možnosti SSL: (viz instrukce nastavení SSL v Emercoin Wiki)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="50"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Použít OpenSSL (https) pro JSON-RPC spojení</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="51"/> <source>Server certificate file (default: server.cert)</source> <translation>Soubor se serverovým certifikátem (výchozí: server.cert)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="52"/> <source>Server private key (default: server.pem)</source> <translation>Soubor se serverovým soukromým klíčem (výchozí: server.pem)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="53"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Akceptovatelné šifry (výchozí: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="56"/> <source>This help message</source> <translation>Tato nápověda</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="57"/> <source>Cannot obtain a lock on data directory %s. Emercoin is probably already running.</source> <translation>Nedaří se mi získat zámek na datový adresář %s. Emercoin pravděpodobně už jednou běží.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="60"/> <source>Loading addresses...</source> <translation>Načítám adresy...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="61"/> <source>Error loading addr.dat</source> <translation>Chyba při načítání addr.dat</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="63"/> <source>Error loading blkindex.dat</source> <translation>Chyba při načítání blkindex.dat</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="65"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Chyba při načítání wallet.dat: peněženka je poškozená</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="66"/> <source>Error loading wallet.dat: Wallet requires newer version of Emercoin</source> <translation>Chyba při načítání wallet.dat: peněženka vyžaduje novější verzi Emercoinu</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="67"/> <source>Wallet needed to be rewritten: restart Emercoin to complete</source> <translation>Soubor s peněženkou potřeboval přepsat: restartuj Emercoin, aby se operace dokončila</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="68"/> <source>Error loading wallet.dat</source> <translation>Chyba při načítání wallet.dat</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="62"/> <source>Loading block index...</source> <translation>Načítám index bloků...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="64"/> <source>Loading wallet...</source> <translation>Načítám peněženku...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="69"/> <source>Rescanning...</source> <translation>Přeskenovávám...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="70"/> <source>Done loading</source> <translation>Načítání dokončeno</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="71"/> <source>Invalid -proxy address</source> <translation>Neplatná -proxy adresa</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="72"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;</source> <translation>Neplatná částka pro -paytxfee=&lt;částka&gt;</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="73"/> <source>Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction.</source> <translation>Upozornění: -paytxfee je nastaveno velmi vysoko. Toto je transakční poplatek, který zaplatíš za každou poslanou transakci.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="76"/> <source>Error: CreateThread(StartNode) failed</source> <translation>Chyba: Selhalo CreateThread(StartNode)</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="77"/> <source>Warning: Disk space is low </source> <translation>Upozornění: Na disku je málo místa </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="78"/> <source>Unable to bind to port %d on this computer. Emercoin is probably already running.</source> <translation>Nedaří se mi připojit na port %d na tomhle počítači. Emercoin už pravděpodobně jednou běží.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="81"/> <source>Warning: Please check that your computer&apos;s date and time are correct. If your clock is wrong Emercoin will not work properly.</source> <translation>Upozornění: Zkontroluj, že máš v počítači správně nastavený datum a čas. Pokud jsou nastaveny špatně, Emercoin nebude fungovat správně.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="84"/> <source>beta</source> <translation>beta</translation> </message> </context> </TS><|fim▁end|>
<translation>Smaž aktuálně vybranou adresu ze seznamu. Smazány mohou být pouze adresy příjemců.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="113"/>
<|file_name|>api.py<|end_file_name|><|fim▁begin|>import copy from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ from django_countries import countries import accounts import third_party_auth from edxmako.shortcuts import marketing_link from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from openedx.core.djangoapps.user_api.helpers import FormDescription from openedx.features.enterprise_support.api import enterprise_customer_for_request from student.forms import get_registration_extension_form from student.models import UserProfile def get_password_reset_form(): """Return a description of the password reset form. This decouples clients from the API definition: if the API decides to modify the form, clients won't need to be updated. See `user_api.helpers.FormDescription` for examples of the JSON-encoded form description. Returns: HttpResponse """ form_desc = FormDescription("post", reverse("password_change_request")) # Translators: This label appears above a field on the password reset # form meant to hold the user's email address. email_label = _(u"Email") # Translators: This example email address is used as a placeholder in # a field on the password reset form meant to hold the user's email address. email_placeholder = _(u"[email protected]") # Translators: These instructions appear on the password reset form, # immediately below a field meant to hold the user's email address. email_instructions = _(u"The email address you used to register with {platform_name}").format( platform_name=configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME) ) form_desc.add_field( "email", field_type="email", label=email_label, placeholder=email_placeholder, instructions=email_instructions, restrictions={ "min_length": accounts.EMAIL_MIN_LENGTH, "max_length": accounts.EMAIL_MAX_LENGTH, } ) return form_desc def get_login_session_form(): """Return a description of the login form. This decouples clients from the API definition: if the API decides to modify the form, clients won't need to be updated. See `user_api.helpers.FormDescription` for examples of the JSON-encoded form description. Returns: HttpResponse """ form_desc = FormDescription("post", reverse("user_api_login_session")) # Translators: This label appears above a field on the login form # meant to hold the user's email address. email_label = _(u"Email") # Translators: This example email address is used as a placeholder in # a field on the login form meant to hold the user's email address. email_placeholder = _(u"[email protected]") # Translators: These instructions appear on the login form, immediately # below a field meant to hold the user's email address. email_instructions = _("The email address you used to register with {platform_name}").format( platform_name=configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME) ) form_desc.add_field( "email", field_type="email", label=email_label, placeholder=email_placeholder, instructions=email_instructions, restrictions={ "min_length": accounts.EMAIL_MIN_LENGTH, "max_length": accounts.EMAIL_MAX_LENGTH, } ) # Translators: This label appears above a field on the login form # meant to hold the user's password. password_label = _(u"Password") form_desc.add_field( "password", label=password_label, field_type="password", restrictions={ "max_length": accounts.PASSWORD_MAX_LENGTH, } ) form_desc.add_field( "remember", field_type="checkbox", label=_("Remember me"), default=False, required=False, ) return form_desc class RegistrationFormFactory(object): """HTTP end-points for creating a new user. """ DEFAULT_FIELDS = ["email", "name", "username", "password"] EXTRA_FIELDS = [ "confirm_email", "first_name", "last_name", "city", "state", "country", "gender", "year_of_birth", "level_of_education", "company", "title", "mailing_address", "goals", "honor_code", "terms_of_service", "profession", "specialty", ] def _is_field_visible(self, field_name): """Check whether a field is visible based on Django settings. """ return self._extra_fields_setting.get(field_name) in ["required", "optional"] def _is_field_required(self, field_name): """Check whether a field is required based on Django settings. """ return self._extra_fields_setting.get(field_name) == "required" def __init__(self): # Backwards compatibility: Honor code is required by default, unless # explicitly set to "optional" in Django settings. self._extra_fields_setting = copy.deepcopy(configuration_helpers.get_value('REGISTRATION_EXTRA_FIELDS')) if not self._extra_fields_setting: self._extra_fields_setting = copy.deepcopy(settings.REGISTRATION_EXTRA_FIELDS) self._extra_fields_setting["honor_code"] = self._extra_fields_setting.get("honor_code", "required") # Check that the setting is configured correctly for field_name in self.EXTRA_FIELDS: if self._extra_fields_setting.get(field_name, "hidden") not in ["required", "optional", "hidden"]: msg = u"Setting REGISTRATION_EXTRA_FIELDS values must be either required, optional, or hidden." raise ImproperlyConfigured(msg) # Map field names to the instance method used to add the field to the form self.field_handlers = {} valid_fields = self.DEFAULT_FIELDS + self.EXTRA_FIELDS for field_name in valid_fields: handler = getattr(self, "_add_{field_name}_field".format(field_name=field_name)) self.field_handlers[field_name] = handler field_order = configuration_helpers.get_value('REGISTRATION_FIELD_ORDER') if not field_order: field_order = settings.REGISTRATION_FIELD_ORDER or valid_fields # Check that all of the valid_fields are in the field order and vice versa, if not set to the default order if set(valid_fields) != set(field_order): field_order = valid_fields self.field_order = field_order def get_registration_form(self, request): """Return a description of the registration form. This decouples clients from the API definition: if the API decides to modify the form, clients won't need to be updated. This is especially important for the registration form, since different edx-platform installations might collect different demographic information. See `user_api.helpers.FormDescription` for examples of the JSON-encoded form description. Arguments: request (HttpRequest) Returns: HttpResponse """ form_desc = FormDescription("post", reverse("user_api_registration")) self._apply_third_party_auth_overrides(request, form_desc) # Custom form fields can be added via the form set in settings.REGISTRATION_EXTENSION_FORM custom_form = get_registration_extension_form() if custom_form: # Default fields are always required for field_name in self.DEFAULT_FIELDS: self.field_handlers[field_name](form_desc, required=True) for field_name, field in custom_form.fields.items(): restrictions = {} if getattr(field, 'max_length', None): restrictions['max_length'] = field.max_length if getattr(field, 'min_length', None): restrictions['min_length'] = field.min_length field_options = getattr( getattr(custom_form, 'Meta', None), 'serialization_options', {} ).get(field_name, {}) field_type = field_options.get('field_type', FormDescription.FIELD_TYPE_MAP.get(field.__class__)) if not field_type: raise ImproperlyConfigured( "Field type '{}' not recognized for registration extension field '{}'.".format( field_type, field_name ) ) form_desc.add_field( field_name, label=field.label, default=field_options.get('default'), field_type=field_options.get('field_type', FormDescription.FIELD_TYPE_MAP.get(field.__class__)), placeholder=field.initial, instructions=field.help_text, required=field.required, restrictions=restrictions, options=getattr(field, 'choices', None), error_messages=field.error_messages, include_default_option=field_options.get('include_default_option'), ) # Extra fields configured in Django settings # may be required, optional, or hidden for field_name in self.EXTRA_FIELDS: if self._is_field_visible(field_name): self.field_handlers[field_name]( form_desc, required=self._is_field_required(field_name) ) else: # Go through the fields in the fields order and add them if they are required or visible for field_name in self.field_order: if field_name in self.DEFAULT_FIELDS: self.field_handlers[field_name](form_desc, required=True) elif self._is_field_visible(field_name): self.field_handlers[field_name]( form_desc, required=self._is_field_required(field_name) ) return form_desc def _add_email_field(self, form_desc, required=True): """Add an email field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a field on the registration form # meant to hold the user's email address. email_label = _(u"Email") # Translators: This example email address is used as a placeholder in # a field on the registration form meant to hold the user's email address. email_placeholder = _(u"[email protected]") # Translators: These instructions appear on the registration form, immediately # below a field meant to hold the user's email address. email_instructions = _(u"This is what you will use to login.") form_desc.add_field( "email", field_type="email", label=email_label, placeholder=email_placeholder, instructions=email_instructions, restrictions={ "min_length": accounts.EMAIL_MIN_LENGTH, "max_length": accounts.EMAIL_MAX_LENGTH, }, required=required ) def _add_confirm_email_field(self, form_desc, required=True): """Add an email confirmation field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a field on the registration form<|fim▁hole|> form_desc.add_field( "confirm_email", label=email_label, required=required, error_messages={ "required": error_msg } ) def _add_name_field(self, form_desc, required=True): """Add a name field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a field on the registration form # meant to hold the user's full name. name_label = _(u"Full Name") # Translators: This example name is used as a placeholder in # a field on the registration form meant to hold the user's name. name_placeholder = _(u"Jane Q. Learner") # Translators: These instructions appear on the registration form, immediately # below a field meant to hold the user's full name. name_instructions = _(u"This name will be used on any certificates that you earn.") form_desc.add_field( "name", label=name_label, placeholder=name_placeholder, instructions=name_instructions, restrictions={ "max_length": accounts.NAME_MAX_LENGTH, }, required=required ) def _add_username_field(self, form_desc, required=True): """Add a username field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a field on the registration form # meant to hold the user's public username. username_label = _(u"Public Username") username_instructions = _( # Translators: These instructions appear on the registration form, immediately # below a field meant to hold the user's public username. u"The name that will identify you in your courses. " u"It cannot be changed later." ) # Translators: This example username is used as a placeholder in # a field on the registration form meant to hold the user's username. username_placeholder = _(u"Jane_Q_Learner") form_desc.add_field( "username", label=username_label, instructions=username_instructions, placeholder=username_placeholder, restrictions={ "min_length": accounts.USERNAME_MIN_LENGTH, "max_length": accounts.USERNAME_MAX_LENGTH, }, required=required ) def _add_password_field(self, form_desc, required=True): """Add a password field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a field on the registration form # meant to hold the user's password. password_label = _(u"Password") form_desc.add_field( "password", label=password_label, field_type="password", restrictions={ "min_length": accounts.PASSWORD_MIN_LENGTH, "max_length": accounts.PASSWORD_MAX_LENGTH, }, required=required ) def _add_level_of_education_field(self, form_desc, required=True): """Add a level of education field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a dropdown menu on the registration # form used to select the user's highest completed level of education. education_level_label = _(u"Highest level of education completed") error_msg = accounts.REQUIRED_FIELD_LEVEL_OF_EDUCATION_MSG # The labels are marked for translation in UserProfile model definition. options = [(name, _(label)) for name, label in UserProfile.LEVEL_OF_EDUCATION_CHOICES] # pylint: disable=translation-of-non-string form_desc.add_field( "level_of_education", label=education_level_label, field_type="select", options=options, include_default_option=True, required=required, error_messages={ "required": error_msg } ) def _add_gender_field(self, form_desc, required=True): """Add a gender field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a dropdown menu on the registration # form used to select the user's gender. gender_label = _(u"Gender") # The labels are marked for translation in UserProfile model definition. options = [(name, _(label)) for name, label in UserProfile.GENDER_CHOICES] # pylint: disable=translation-of-non-string form_desc.add_field( "gender", label=gender_label, field_type="select", options=options, include_default_option=True, required=required ) def _add_year_of_birth_field(self, form_desc, required=True): """Add a year of birth field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a dropdown menu on the registration # form used to select the user's year of birth. yob_label = _(u"Year of birth") options = [(unicode(year), unicode(year)) for year in UserProfile.VALID_YEARS] form_desc.add_field( "year_of_birth", label=yob_label, field_type="select", options=options, include_default_option=True, required=required ) def _add_field_with_configurable_select_options(self, field_name, field_label, form_desc, required=False): """Add a field to a form description. If select options are given for this field, it will be a select type otherwise it will be a text type. Arguments: field_name: name of field field_label: label for the field form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to False """ extra_field_options = configuration_helpers.get_value('EXTRA_FIELD_OPTIONS') if extra_field_options is None or extra_field_options.get(field_name) is None: field_type = "text" include_default_option = False options = None error_msg = '' exec("error_msg = accounts.REQUIRED_FIELD_%s_TEXT_MSG" % (field_name.upper())) else: field_type = "select" include_default_option = True field_options = extra_field_options.get(field_name) options = [(unicode(option.lower()), option) for option in field_options] error_msg = '' exec("error_msg = accounts.REQUIRED_FIELD_%s_SELECT_MSG" % (field_name.upper())) form_desc.add_field( field_name, label=field_label, field_type=field_type, options=options, include_default_option=include_default_option, required=required, error_messages={ "required": error_msg } ) def _add_profession_field(self, form_desc, required=False): """Add a profession field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to False """ # Translators: This label appears above a dropdown menu on the registration # form used to select the user's profession profession_label = _("Profession") self._add_field_with_configurable_select_options('profession', profession_label, form_desc, required=required) def _add_specialty_field(self, form_desc, required=False): """Add a specialty field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to False """ # Translators: This label appears above a dropdown menu on the registration # form used to select the user's specialty specialty_label = _("Specialty") self._add_field_with_configurable_select_options('specialty', specialty_label, form_desc, required=required) def _add_mailing_address_field(self, form_desc, required=True): """Add a mailing address field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a field on the registration form # meant to hold the user's mailing address. mailing_address_label = _(u"Mailing address") error_msg = accounts.REQUIRED_FIELD_MAILING_ADDRESS_MSG form_desc.add_field( "mailing_address", label=mailing_address_label, field_type="textarea", required=required, error_messages={ "required": error_msg } ) def _add_goals_field(self, form_desc, required=True): """Add a goals field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This phrase appears above a field on the registration form # meant to hold the user's reasons for registering with edX. goals_label = _(u"Tell us why you're interested in {platform_name}").format( platform_name=configuration_helpers.get_value("PLATFORM_NAME", settings.PLATFORM_NAME) ) error_msg = accounts.REQUIRED_FIELD_GOALS_MSG form_desc.add_field( "goals", label=goals_label, field_type="textarea", required=required, error_messages={ "required": error_msg } ) def _add_city_field(self, form_desc, required=True): """Add a city field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a field on the registration form # which allows the user to input the city in which they live. city_label = _(u"City") error_msg = accounts.REQUIRED_FIELD_CITY_MSG form_desc.add_field( "city", label=city_label, required=required, error_messages={ "required": error_msg } ) def _add_state_field(self, form_desc, required=False): """Add a State/Province/Region field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to False """ # Translators: This label appears above a field on the registration form # which allows the user to input the State/Province/Region in which they live. state_label = _(u"State/Province/Region") form_desc.add_field( "state", label=state_label, required=required ) def _add_company_field(self, form_desc, required=False): """Add a Company field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to False """ # Translators: This label appears above a field on the registration form # which allows the user to input the Company company_label = _(u"Company") form_desc.add_field( "company", label=company_label, required=required ) def _add_title_field(self, form_desc, required=False): """Add a Title field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to False """ # Translators: This label appears above a field on the registration form # which allows the user to input the Title title_label = _(u"Title") form_desc.add_field( "title", label=title_label, required=required ) def _add_first_name_field(self, form_desc, required=False): """Add a First Name field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to False """ # Translators: This label appears above a field on the registration form # which allows the user to input the First Name first_name_label = _(u"First Name") form_desc.add_field( "first_name", label=first_name_label, required=required ) def _add_last_name_field(self, form_desc, required=False): """Add a Last Name field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to False """ # Translators: This label appears above a field on the registration form # which allows the user to input the First Name last_name_label = _(u"Last Name") form_desc.add_field( "last_name", label=last_name_label, required=required ) def _add_country_field(self, form_desc, required=True): """Add a country field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a dropdown menu on the registration # form used to select the country in which the user lives. country_label = _(u"Country or Region of Residence") country_instructions = _( # Translators: These instructions appear on the registration form, immediately # below a field meant to hold the user's country. u"The country or region where you live." ) error_msg = accounts.REQUIRED_FIELD_COUNTRY_MSG # If we set a country code, make sure it's uppercase for the sake of the form. default_country = form_desc._field_overrides.get('country', {}).get('defaultValue') if default_country: form_desc.override_field_properties( 'country', default=default_country.upper() ) form_desc.add_field( "country", label=country_label, instructions=country_instructions, field_type="select", options=list(countries), include_default_option=True, required=required, error_messages={ "required": error_msg } ) def _add_honor_code_field(self, form_desc, required=True): """Add an honor code field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Separate terms of service and honor code checkboxes if self._is_field_visible("terms_of_service"): terms_label = _(u"Honor Code") terms_link = marketing_link("HONOR") terms_text = _(u"Review the Honor Code") # Combine terms of service and honor code checkboxes else: # Translators: This is a legal document users must agree to # in order to register a new account. terms_label = _(u"Terms of Service and Honor Code") terms_link = marketing_link("HONOR") terms_text = _(u"Review the Terms of Service and Honor Code") # Translators: "Terms of Service" is a legal document users must agree to # in order to register a new account. label = _(u"I agree to the {platform_name} {terms_of_service}").format( platform_name=configuration_helpers.get_value("PLATFORM_NAME", settings.PLATFORM_NAME), terms_of_service=terms_label ) # Translators: "Terms of Service" is a legal document users must agree to # in order to register a new account. error_msg = _(u"You must agree to the {platform_name} {terms_of_service}").format( platform_name=configuration_helpers.get_value("PLATFORM_NAME", settings.PLATFORM_NAME), terms_of_service=terms_label ) form_desc.add_field( "honor_code", label=label, field_type="checkbox", default=False, required=required, error_messages={ "required": error_msg }, supplementalLink=terms_link, supplementalText=terms_text ) def _add_terms_of_service_field(self, form_desc, required=True): """Add a terms of service field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This is a legal document users must agree to # in order to register a new account. terms_label = _(u"Terms of Service") terms_link = marketing_link("TOS") terms_text = _(u"Review the Terms of Service") # Translators: "Terms of service" is a legal document users must agree to # in order to register a new account. label = _(u"I agree to the {platform_name} {terms_of_service}").format( platform_name=configuration_helpers.get_value("PLATFORM_NAME", settings.PLATFORM_NAME), terms_of_service=terms_label ) # Translators: "Terms of service" is a legal document users must agree to # in order to register a new account. error_msg = _(u"You must agree to the {platform_name} {terms_of_service}").format( platform_name=configuration_helpers.get_value("PLATFORM_NAME", settings.PLATFORM_NAME), terms_of_service=terms_label ) form_desc.add_field( "terms_of_service", label=label, field_type="checkbox", default=False, required=required, error_messages={ "required": error_msg }, supplementalLink=terms_link, supplementalText=terms_text ) def _apply_third_party_auth_overrides(self, request, form_desc): """Modify the registration form if the user has authenticated with a third-party provider. If a user has successfully authenticated with a third-party provider, but does not yet have an account with EdX, we want to fill in the registration form with any info that we get from the provider. This will also hide the password field, since we assign users a default (random) password on the assumption that they will be using third-party auth to log in. Arguments: request (HttpRequest): The request for the registration form, used to determine if the user has successfully authenticated with a third-party provider. form_desc (FormDescription): The registration form description """ if third_party_auth.is_enabled(): running_pipeline = third_party_auth.pipeline.get(request) if running_pipeline: current_provider = third_party_auth.provider.Registry.get_from_pipeline(running_pipeline) if current_provider: # Override username / email / full name field_overrides = current_provider.get_register_form_data( running_pipeline.get('kwargs') ) # When the TPA Provider is configured to skip the registration form and we are in an # enterprise context, we need to hide all fields except for terms of service and # ensure that the user explicitly checks that field. hide_registration_fields_except_tos = (current_provider.skip_registration_form and enterprise_customer_for_request(request)) for field_name in self.DEFAULT_FIELDS + self.EXTRA_FIELDS: if field_name in field_overrides: form_desc.override_field_properties( field_name, default=field_overrides[field_name] ) if (field_name not in ['terms_of_service', 'honor_code'] and field_overrides[field_name] and hide_registration_fields_except_tos): form_desc.override_field_properties( field_name, field_type="hidden", label="", instructions="", ) # Hide the password field form_desc.override_field_properties( "password", default="", field_type="hidden", required=False, label="", instructions="", restrictions={} ) # used to identify that request is running third party social auth form_desc.add_field( "social_auth_provider", field_type="hidden", label="", default=current_provider.name if current_provider.name else "Third Party", required=False, )<|fim▁end|>
# meant to confirm the user's email address. email_label = _(u"Confirm Email") error_msg = accounts.REQUIRED_FIELD_CONFIRM_EMAIL_MSG
<|file_name|>webid.js<|end_file_name|><|fim▁begin|>var passport = require('passport'); var WebIDStrategy = require('passport-webid').Strategy; var tokens = require('../../util/tokens'); var ids = require('../../util/id'); var console = require('../../log'); var createError = require('http-errors'); var dateUtils = require('../../util/date'); var url = require('url'); function loadStrategy(conf, entityStorageConf) { var auth_type = "webid"; var db = require('../../db')(conf, entityStorageConf);<|fim▁hole|> if (enabled.length === 0) { console.log('ignoring ' + auth_type + ' strategy for user authentication. Not enabled in the configuration'); return false; } else { try { passport.use(auth_type, new WebIDStrategy( function (webid, certificate, req, done) { console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); var id = { user_name: webid, auth_type: auth_type }; var oauth2ReturnToParsed = url.parse(req.session.returnTo, true).query; console.log(" sesion in strategy " + auth_type + JSON.stringify(oauth2ReturnToParsed)); console.log(" client id from session in " + auth_type + JSON.stringify(oauth2ReturnToParsed.client_id)); console.log(" response_type for oauth2 in " + auth_type + JSON.stringify(oauth2ReturnToParsed.response_type)); var accessToken = tokens.uid(30); var d = Date.parse(certificate.valid_to); var default_exp = dateUtils.dateToEpochMilis(d); db.users.findByUsernameAndAuthType(webid, auth_type, function (err, user) { if (err) { return done(err); } if (!user) { return done(null, false); } db.accessTokens.saveOauth2Token(accessToken, user.id, oauth2ReturnToParsed.client_id, "bearer", [conf.gateway_id], default_exp, null, oauth2ReturnToParsed.response_type, function (err) { if (err) { return done(err); } return done(null, user); }); }); } )); console.log('finished registering passport ' + auth_type + ' strategy'); return true; } catch (e) { console.log('FAIL TO register a strategy'); console.log('ERROR: error loading ' + auth_type + ' passport strategy: ' + e); return false; } } } module.exports = loadStrategy;<|fim▁end|>
var enabled = conf.enabledStrategies.filter(function (v) { return (v === auth_type); });
<|file_name|>set-tp-dst.js<|end_file_name|><|fim▁begin|>/* * Author: Zoltán Lajos Kis <[email protected]> */ "use strict"; (function() { var util = require('util'); var ofp = require('../ofp.js'); var offsets = ofp.offsets.ofp_action_tp_port; module.exports = {<|fim▁hole|> "body" : {} }; var len = buffer.readUInt16BE(offset + offsets.len, true); if (len != ofp.sizes.ofp_action_tp_port) { return { "error" : { "desc" : util.format('%s action at offset %d has invalid length (%d).', action.header.type, offset, len), "type" : 'OFPET_BAD_ACTION', "code" : 'OFPBAC_BAD_LEN' } } } action.body.tp_port = buffer.readUInt16BE(offset + offsets.tp_port, true); return { "action" : action, "offset" : offset + len } } } })();<|fim▁end|>
"unpack" : function(buffer, offset) { var action = { "header" : {"type" : 'OFPAT_SET_TP_DST'},
<|file_name|>QTextStream.py<|end_file_name|><|fim▁begin|># encoding: utf-8 # module PyQt4.QtCore # from /usr/lib/python3/dist-packages/PyQt4/QtCore.cpython-34m-x86_64-linux-gnu.so # by generator 1.135 # no doc # imports import sip as __sip class QTextStream(): # skipped bases: <class 'sip.simplewrapper'> """ QTextStream() QTextStream(QIODevice) QTextStream(QByteArray, QIODevice.OpenMode mode=QIODevice.ReadWrite) """ def atEnd(self): # real signature unknown; restored from __doc__ """ QTextStream.atEnd() -> bool """ return False def autoDetectUnicode(self): # real signature unknown; restored from __doc__ """ QTextStream.autoDetectUnicode() -> bool """ return False def codec(self): # real signature unknown; restored from __doc__ """ QTextStream.codec() -> QTextCodec """ return QTextCodec def device(self): # real signature unknown; restored from __doc__ """ QTextStream.device() -> QIODevice """ return QIODevice def fieldAlignment(self): # real signature unknown; restored from __doc__ """ QTextStream.fieldAlignment() -> QTextStream.FieldAlignment """ pass def fieldWidth(self): # real signature unknown; restored from __doc__ """ QTextStream.fieldWidth() -> int """ return 0 def flush(self): # real signature unknown; restored from __doc__ """ QTextStream.flush() """ pass def generateByteOrderMark(self): # real signature unknown; restored from __doc__ """ QTextStream.generateByteOrderMark() -> bool """ return False def integerBase(self): # real signature unknown; restored from __doc__ """ QTextStream.integerBase() -> int """ return 0 def locale(self): # real signature unknown; restored from __doc__ """ QTextStream.locale() -> QLocale """ return QLocale def numberFlags(self): # real signature unknown; restored from __doc__ """ QTextStream.numberFlags() -> QTextStream.NumberFlags """ pass def padChar(self): # real signature unknown; restored from __doc__ """ QTextStream.padChar() -> str """ return "" <|fim▁hole|> def pos(self): # real signature unknown; restored from __doc__ """ QTextStream.pos() -> int """ return 0 def read(self, p_int): # real signature unknown; restored from __doc__ """ QTextStream.read(int) -> str """ return "" def readAll(self): # real signature unknown; restored from __doc__ """ QTextStream.readAll() -> str """ return "" def readLine(self, int_maxLength=0): # real signature unknown; restored from __doc__ """ QTextStream.readLine(int maxLength=0) -> str """ return "" def realNumberNotation(self): # real signature unknown; restored from __doc__ """ QTextStream.realNumberNotation() -> QTextStream.RealNumberNotation """ pass def realNumberPrecision(self): # real signature unknown; restored from __doc__ """ QTextStream.realNumberPrecision() -> int """ return 0 def reset(self): # real signature unknown; restored from __doc__ """ QTextStream.reset() """ pass def resetStatus(self): # real signature unknown; restored from __doc__ """ QTextStream.resetStatus() """ pass def seek(self, p_int): # real signature unknown; restored from __doc__ """ QTextStream.seek(int) -> bool """ return False def setAutoDetectUnicode(self, bool): # real signature unknown; restored from __doc__ """ QTextStream.setAutoDetectUnicode(bool) """ pass def setCodec(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads """ QTextStream.setCodec(QTextCodec) QTextStream.setCodec(str) """ pass def setDevice(self, QIODevice): # real signature unknown; restored from __doc__ """ QTextStream.setDevice(QIODevice) """ pass def setFieldAlignment(self, QTextStream_FieldAlignment): # real signature unknown; restored from __doc__ """ QTextStream.setFieldAlignment(QTextStream.FieldAlignment) """ pass def setFieldWidth(self, p_int): # real signature unknown; restored from __doc__ """ QTextStream.setFieldWidth(int) """ pass def setGenerateByteOrderMark(self, bool): # real signature unknown; restored from __doc__ """ QTextStream.setGenerateByteOrderMark(bool) """ pass def setIntegerBase(self, p_int): # real signature unknown; restored from __doc__ """ QTextStream.setIntegerBase(int) """ pass def setLocale(self, QLocale): # real signature unknown; restored from __doc__ """ QTextStream.setLocale(QLocale) """ pass def setNumberFlags(self, QTextStream_NumberFlags): # real signature unknown; restored from __doc__ """ QTextStream.setNumberFlags(QTextStream.NumberFlags) """ pass def setPadChar(self, p_str): # real signature unknown; restored from __doc__ """ QTextStream.setPadChar(str) """ pass def setRealNumberNotation(self, QTextStream_RealNumberNotation): # real signature unknown; restored from __doc__ """ QTextStream.setRealNumberNotation(QTextStream.RealNumberNotation) """ pass def setRealNumberPrecision(self, p_int): # real signature unknown; restored from __doc__ """ QTextStream.setRealNumberPrecision(int) """ pass def setStatus(self, QTextStream_Status): # real signature unknown; restored from __doc__ """ QTextStream.setStatus(QTextStream.Status) """ pass def setString(self, *args, **kwargs): # real signature unknown pass def skipWhiteSpace(self): # real signature unknown; restored from __doc__ """ QTextStream.skipWhiteSpace() """ pass def status(self): # real signature unknown; restored from __doc__ """ QTextStream.status() -> QTextStream.Status """ pass def string(self, *args, **kwargs): # real signature unknown pass def __init__(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads pass def __lshift__(self, *args, **kwargs): # real signature unknown """ Return self<<value. """ pass def __rlshift__(self, *args, **kwargs): # real signature unknown """ Return value<<self. """ pass def __rrshift__(self, *args, **kwargs): # real signature unknown """ Return value>>self. """ pass def __rshift__(self, *args, **kwargs): # real signature unknown """ Return self>>value. """ pass __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """list of weak references to the object (if defined)""" AlignAccountingStyle = 3 AlignCenter = 2 AlignLeft = 0 AlignRight = 1 FieldAlignment = None # (!) real value is '' FixedNotation = 1 ForcePoint = 2 ForceSign = 4 NumberFlag = None # (!) real value is '' NumberFlags = None # (!) real value is '' Ok = 0 ReadCorruptData = 2 ReadPastEnd = 1 RealNumberNotation = None # (!) real value is '' ScientificNotation = 2 ShowBase = 1 SmartNotation = 0 Status = None # (!) real value is '' UppercaseBase = 8 UppercaseDigits = 16 WriteFailed = 3<|fim▁end|>
<|file_name|>objectinspector.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, division, print_function import os from idaskins import UI_DIR from PyQt5 import uic from PyQt5.Qt import qApp from PyQt5.QtCore import Qt from PyQt5.QtGui import QCursor, QFont, QKeySequence from PyQt5.QtWidgets import QShortcut, QWidget Ui_ObjectInspector, ObjectInspectorBase = uic.loadUiType( os.path.join(UI_DIR, 'ObjectInspector.ui') ) class ObjectInspector(ObjectInspectorBase): """ Rudimentary Qt object inspector. Allows for easier finding of object names and classes for usage in QSS stylesheets. """ def __init__(self, *args, **kwargs): super(ObjectInspector, self).__init__(*args, **kwargs) self._selected_widget = None self._ui = Ui_ObjectInspector() self._ui.setupUi(self) # Make everything monospace. font = QFont('Monospace') font.setStyleHint(QFont.TypeWriter) self._ui.teInspectionResults.setFont(font) # Register signals. self._update_key = QShortcut(QKeySequence(Qt.Key_F7), self) self._ui.btnSelectParent.released.connect(self.select_parent)<|fim▁hole|> self._update_key.activated.connect(self.update_inspection) def update_inspection(self): widget = qApp.widgetAt(QCursor.pos()) self.update_selected_widget(widget) def select_parent(self): if self._selected_widget: parent = self._selected_widget.parent() if parent and parent.inherits('QWidget'): self.update_selected_widget(parent) def update_selected_widget(self, widget): if self._selected_widget: self._selected_widget.destroyed.disconnect( self.on_selected_widget_destroyed ) self._selected_widget = widget if widget: self._ui.btnSelectParent.setEnabled(widget.parent() is not None) self._ui.teInspectionResults.setText(( "Type: {}\n" "Name: {}\n" "Number of children: {}\n" "QSS: {}" ).format( widget.metaObject().className(), widget.objectName() or '<none>', len(widget.children()), widget.styleSheet() or '<none>', )) self._selected_widget.destroyed.connect( self.on_selected_widget_destroyed ) else: self._ui.teInspectionResults.setText('<no object under cursor>') def on_selected_widget_destroyed(self, obj): self._selected_widget = None<|fim▁end|>
<|file_name|>imagecropper.controller.js<|end_file_name|><|fim▁begin|>//this controller simply tells the dialogs service to open a mediaPicker window //with a specified callback, this callback will receive an object with a selection on it angular.module('umbraco') .controller("Umbraco.PropertyEditors.ImageCropperController", function ($rootScope, $routeParams, $scope, $log, mediaHelper, cropperHelper, $timeout, editorState, umbRequestHelper, fileManager) { var config = angular.copy($scope.model.config); //move previously saved value to the editor if ($scope.model.value) { //backwards compat with the old file upload (incase some-one swaps them..) if (angular.isString($scope.model.value)) { config.src = $scope.model.value; $scope.model.value = config; } else if ($scope.model.value.crops) { //sync any config changes with the editor and drop outdated crops _.each($scope.model.value.crops, function (saved) { var configured = _.find(config.crops, function (item) { return item.alias === saved.alias }); if (configured && configured.height === saved.height && configured.width === saved.width) { configured.coordinates = saved.coordinates; } }); $scope.model.value.crops = config.crops; //restore focalpoint if missing if (!$scope.model.value.focalPoint) { $scope.model.value.focalPoint = { left: 0.5, top: 0.5 }; } } $scope.imageSrc = $scope.model.value.src; } //crop a specific crop $scope.crop = function (crop) { $scope.currentCrop = crop; $scope.currentPoint = undefined; }; //done cropping $scope.done = function () { $scope.currentCrop = undefined; $scope.currentPoint = undefined; };<|fim▁hole|> //crop a specific crop $scope.clear = function (crop) { //clear current uploaded files fileManager.setFiles($scope.model.alias, []); //clear the ui $scope.imageSrc = undefined; if ($scope.model.value) { delete $scope.model.value; } }; //show previews $scope.togglePreviews = function () { if ($scope.showPreviews) { $scope.showPreviews = false; $scope.tempShowPreviews = false; } else { $scope.showPreviews = true; } }; //on image selected, update the cropper $scope.$on("filesSelected", function (ev, args) { $scope.model.value = config; if (args.files && args.files[0]) { fileManager.setFiles($scope.model.alias, args.files); var reader = new FileReader(); reader.onload = function (e) { $scope.$apply(function () { $scope.imageSrc = e.target.result; }); }; reader.readAsDataURL(args.files[0]); } }); }) .run(function (mediaHelper, umbRequestHelper) { if (mediaHelper && mediaHelper.registerFileResolver) { mediaHelper.registerFileResolver("Umbraco.ImageCropper", function (property, entity, thumbnail) { if (property.value.src) { if (thumbnail === true) { return property.value.src + "?width=600&mode=max"; } else { return property.value.src; } //this is a fallback in case the cropper has been asssigned a upload field } else if (angular.isString(property.value)) { if (thumbnail) { if (mediaHelper.detectIfImageByExtension(property.value)) { var thumbnailUrl = umbRequestHelper.getApiUrl( "imagesApiBaseUrl", "GetBigThumbnail", [{ originalImagePath: property.value }]); return thumbnailUrl; } else { return null; } } else { return property.value; } } return null; }); } });<|fim▁end|>
<|file_name|>SalesforceStepTest.java<|end_file_name|><|fim▁begin|>/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.trans.steps.salesforce; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.mockito.Mockito; import org.pentaho.di.core.KettleEnvironment; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleValueException; import org.pentaho.di.core.logging.LoggingObjectInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.junit.rules.RestorePDIEngineEnvironment; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.steps.mock.StepMockHelper; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class SalesforceStepTest { @ClassRule public static RestorePDIEngineEnvironment env = new RestorePDIEngineEnvironment(); private StepMockHelper<SalesforceStepMeta, SalesforceStepData> smh; @BeforeClass public static void setUpBeforeClass() throws KettleException { KettleEnvironment.init( false ); } @Before public void setUp() throws KettleException { smh = new StepMockHelper<SalesforceStepMeta, SalesforceStepData>( "Salesforce", SalesforceStepMeta.class, SalesforceStepData.class ); when( smh.logChannelInterfaceFactory.create( any(), any( LoggingObjectInterface.class ) ) ).thenReturn( smh.logChannelInterface ); when( smh.trans.isRunning() ).thenReturn( true ); } @After public void cleanUp() { smh.cleanUp(); } @Test public void testErrorHandling() { SalesforceStepMeta meta = mock( SalesforceStepMeta.class, Mockito.CALLS_REAL_METHODS ); assertFalse( meta.supportsErrorHandling() ); } @Test public void testInitDispose() { SalesforceStepMeta meta = mock( SalesforceStepMeta.class, Mockito.CALLS_REAL_METHODS ); SalesforceStep step = spy( new MockSalesforceStep( smh.stepMeta, smh.stepDataInterface, 0, smh.transMeta, smh.trans ) ); /* * Salesforce Step should fail if username and password are not set * We should not set a default account for all users */ meta.setDefault(); assertFalse( step.init( meta, smh.stepDataInterface ) ); meta.setDefault(); meta.setTargetURL( null ); assertFalse( step.init( meta, smh.stepDataInterface ) ); meta.setDefault(); meta.setUsername( "anonymous" ); assertFalse( step.init( meta, smh.stepDataInterface ) ); meta.setDefault(); meta.setUsername( "anonymous" ); meta.setPassword( "myPwd" ); meta.setModule( null ); assertFalse( step.init( meta, smh.stepDataInterface ) ); /* * After setting username and password, we should have enough defaults to properly init */ meta.setDefault(); meta.setUsername( "anonymous" ); meta.setPassword( "myPwd" ); assertTrue( step.init( meta, smh.stepDataInterface ) ); // Dispose check assertNotNull( smh.stepDataInterface.connection ); step.dispose( meta, smh.stepDataInterface ); assertNull( smh.stepDataInterface.connection ); } class MockSalesforceStep extends SalesforceStep { public MockSalesforceStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans ) { super( stepMeta, stepDataInterface, copyNr, transMeta, trans ); } } @Test public void createIntObjectTest() throws KettleValueException { SalesforceStep step = spy( new MockSalesforceStep( smh.stepMeta, smh.stepDataInterface, 0, smh.transMeta, smh.trans ) ); ValueMetaInterface valueMeta = Mockito.mock( ValueMetaInterface.class ); Mockito.when( valueMeta.getType() ).thenReturn( ValueMetaInterface.TYPE_INTEGER ); Object value = step.normalizeValue( valueMeta, 100L ); Assert.assertTrue( value instanceof Integer ); } @Test public void createDateObjectTest() throws KettleValueException, ParseException { SalesforceStep step = spy( new MockSalesforceStep( smh.stepMeta, smh.stepDataInterface, 0, smh.transMeta, smh.trans ) ); ValueMetaInterface valueMeta = Mockito.mock( ValueMetaInterface.class ); DateFormat dateFormat = new SimpleDateFormat( "dd-MM-yyyy hh:mm:ss" ); Date date = dateFormat.parse( "12-10-2017 15:10:25" ); Mockito.when( valueMeta.isDate() ).thenReturn( true );<|fim▁hole|> Mockito.when( valueMeta.getDate( Mockito.eq( date ) ) ).thenReturn( date ); Object value = step.normalizeValue( valueMeta, date ); Assert.assertTrue( value instanceof Calendar ); DateFormat minutesDateFormat = new SimpleDateFormat( "mm:ss" ); //check not missing minutes and seconds Assert.assertEquals( minutesDateFormat.format( date ), minutesDateFormat.format( ( (Calendar) value ).getTime() ) ); } }<|fim▁end|>
Mockito.when( valueMeta.getDateFormatTimeZone() ).thenReturn( TimeZone.getTimeZone( "UTC" ) );
<|file_name|>topic.py<|end_file_name|><|fim▁begin|>""" Author: Keith Bourgoin, Emmett Butler """ __license__ = """ Copyright 2015 Parse.ly, 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. """ __all__ = ["Topic"] import logging from collections import defaultdict from .balancedconsumer import BalancedConsumer from .common import OffsetType from .exceptions import LeaderNotAvailable from .handlers import GEventHandler from .partition import Partition from .producer import Producer from .protocol import PartitionOffsetRequest from .simpleconsumer import SimpleConsumer from .utils.compat import iteritems, itervalues log = logging.getLogger(__name__) try: from . import rdkafka log.info("Successfully loaded pykafka.rdkafka extension.") except ImportError: rdkafka = False log.info("Could not load pykafka.rdkafka extension.", exc_info=True) class Topic(object): """ A Topic is an abstraction over the kafka concept of a topic. It contains a dictionary of partitions that comprise it. """ def __init__(self, cluster, topic_metadata): """Create the Topic from metadata. :param cluster: The Cluster to use :type cluster: :class:`pykafka.cluster.Cluster` :param topic_metadata: Metadata for all topics. :type topic_metadata: :class:`pykafka.protocol.TopicMetadata` """ self._name = topic_metadata.name self._cluster = cluster self._partitions = {} self.update(topic_metadata) def __repr__(self): return "<{module}.{classname} at {id_} (name={name})>".format( module=self.__class__.__module__, classname=self.__class__.__name__, id_=hex(id(self)), name=self._name ) @property def name(self): """The name of this topic""" return self._name @property def partitions(self): """A dictionary containing all known partitions for this topic""" return self._partitions def get_producer(self, use_rdkafka=False, **kwargs): """Create a :class:`pykafka.producer.Producer` for this topic. For a description of all available `kwargs`, see the Producer docstring. """ if not rdkafka and use_rdkafka: raise ImportError("use_rdkafka requires rdkafka to be installed") if isinstance(self._cluster.handler, GEventHandler) and use_rdkafka: raise ImportError("use_rdkafka cannot be used with gevent") Cls = rdkafka.RdKafkaProducer if rdkafka and use_rdkafka else Producer return Cls(self._cluster, self, **kwargs) def get_sync_producer(self, **kwargs): """Create a :class:`pykafka.producer.Producer` for this topic. For a description of all available `kwargs`, see the Producer docstring. """ return Producer(self._cluster, self, sync=True, **kwargs) def fetch_offset_limits(self, offsets_before, max_offsets=1): """Get earliest or latest offset. Use the Offset API to find a limit of valid offsets for each partition in this topic. :param offsets_before: Return an offset from before this timestamp (in milliseconds) :type offsets_before: int :param max_offsets: The maximum number of offsets to return :type max_offsets: int """ requests = defaultdict(list) # one request for each broker for part in itervalues(self.partitions): requests[part.leader].append(PartitionOffsetRequest( self.name, part.id, offsets_before, max_offsets )) output = {}<|fim▁hole|> for broker, reqs in iteritems(requests): res = broker.request_offset_limits(reqs) output.update(res.topics[self.name]) return output def earliest_available_offsets(self): """Get the earliest offset for each partition of this topic.""" return self.fetch_offset_limits(OffsetType.EARLIEST) def latest_available_offsets(self): """Get the latest offset for each partition of this topic.""" return self.fetch_offset_limits(OffsetType.LATEST) def update(self, metadata): """Update the Partitions with metadata about the cluster. :param metadata: Metadata for all topics :type metadata: :class:`pykafka.protocol.TopicMetadata` """ p_metas = metadata.partitions # Remove old partitions removed = set(self._partitions.keys()) - set(p_metas.keys()) if len(removed) > 0: log.info('Removing %d partitions', len(removed)) for id_ in removed: log.debug('Removing partition %s', self._partitions[id_]) self._partitions.pop(id_) # Add/update current partitions brokers = self._cluster.brokers if len(p_metas) > 0: log.info("Adding %d partitions", len(p_metas)) for id_, meta in iteritems(p_metas): if meta.leader not in brokers: raise LeaderNotAvailable() if meta.id not in self._partitions: log.debug('Adding partition %s/%s', self.name, meta.id) self._partitions[meta.id] = Partition( self, meta.id, brokers[meta.leader], [brokers[b] for b in meta.replicas], [brokers[b] for b in meta.isr], ) else: self._partitions[id_].update(brokers, meta) def get_simple_consumer(self, consumer_group=None, use_rdkafka=False, **kwargs): """Return a SimpleConsumer of this topic :param consumer_group: The name of the consumer group to join :type consumer_group: str :param use_rdkafka: Use librdkafka-backed consumer if available :type use_rdkafka: bool """ if not rdkafka and use_rdkafka: raise ImportError("use_rdkafka requires rdkafka to be installed") if isinstance(self._cluster.handler, GEventHandler) and use_rdkafka: raise ImportError("use_rdkafka cannot be used with gevent") Cls = (rdkafka.RdKafkaSimpleConsumer if rdkafka and use_rdkafka else SimpleConsumer) return Cls(self, self._cluster, consumer_group=consumer_group, **kwargs) def get_balanced_consumer(self, consumer_group, **kwargs): """Return a BalancedConsumer of this topic :param consumer_group: The name of the consumer group to join :type consumer_group: str """ if "zookeeper_connect" not in kwargs and \ self._cluster._zookeeper_connect is not None: kwargs['zookeeper_connect'] = self._cluster._zookeeper_connect return BalancedConsumer(self, self._cluster, consumer_group, **kwargs)<|fim▁end|>
<|file_name|>init.go<|end_file_name|><|fim▁begin|>package cmd import ( "fmt" "io/ioutil" "os" "github.com/mpppk/gitany" "github.com/mpppk/hlb/hlblib" "github.com/spf13/cobra" "gopkg.in/yaml.v2" ) // initCmd represents the init command var initCmd = &cobra.Command{ Use: "init", Short: "Generate setting file to ~/.config/hlb", Long: ``, Run: func(cmd *cobra.Command, args []string) { configFilePath, err := hlblib.GetConfigFilePath() hlblib.PanicIfErrorExist(err) if _, err := os.Stat(configFilePath); err != nil { hosts := []*gitany.ServiceConfig{ { Host: "github.com", Type: "github", Token: "", Protocol: "https", }, { Host: "gitlab.com", Type: "gitlab", Token: "", Protocol: "https", }, } <|fim▁hole|> err = os.MkdirAll(configFileDirPath, 0777) hlblib.PanicIfErrorExist(err) err = ioutil.WriteFile(configFilePath, f, 0666) hlblib.PanicIfErrorExist(err) } else { fmt.Println("config file already exist:", configFilePath) } }, } func init() { RootCmd.AddCommand(initCmd) }<|fim▁end|>
config := hlblib.Config{Services: hosts} f, err := yaml.Marshal(config) hlblib.PanicIfErrorExist(err) configFileDirPath, err := hlblib.GetConfigDirPath()
<|file_name|>RequestApplication.go<|end_file_name|><|fim▁begin|>// Code generated by msgraph.go/gen DO NOT EDIT. package msgraph import "context" // ApplicationRequestBuilder is request builder for Application type ApplicationRequestBuilder struct{ BaseRequestBuilder } // Request returns ApplicationRequest func (b *ApplicationRequestBuilder) Request() *ApplicationRequest { return &ApplicationRequest{ BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client}, } } // ApplicationRequest is request for Application type ApplicationRequest struct{ BaseRequest } // Get performs GET request for Application func (r *ApplicationRequest) Get(ctx context.Context) (resObj *Application, err error) { var query string if r.query != nil { query = "?" + r.query.Encode() } err = r.JSONRequest(ctx, "GET", query, nil, &resObj) return } // Update performs PATCH request for Application func (r *ApplicationRequest) Update(ctx context.Context, reqObj *Application) error { return r.JSONRequest(ctx, "PATCH", "", reqObj, nil) } // Delete performs DELETE request for Application func (r *ApplicationRequest) Delete(ctx context.Context) error { return r.JSONRequest(ctx, "DELETE", "", nil, nil) } // ApplicationSignInDetailedSummaryRequestBuilder is request builder for ApplicationSignInDetailedSummary type ApplicationSignInDetailedSummaryRequestBuilder struct{ BaseRequestBuilder } // Request returns ApplicationSignInDetailedSummaryRequest func (b *ApplicationSignInDetailedSummaryRequestBuilder) Request() *ApplicationSignInDetailedSummaryRequest { return &ApplicationSignInDetailedSummaryRequest{ BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client}, } } // ApplicationSignInDetailedSummaryRequest is request for ApplicationSignInDetailedSummary type ApplicationSignInDetailedSummaryRequest struct{ BaseRequest } // Get performs GET request for ApplicationSignInDetailedSummary func (r *ApplicationSignInDetailedSummaryRequest) Get(ctx context.Context) (resObj *ApplicationSignInDetailedSummary, err error) { var query string if r.query != nil { query = "?" + r.query.Encode() } err = r.JSONRequest(ctx, "GET", query, nil, &resObj) return } // Update performs PATCH request for ApplicationSignInDetailedSummary func (r *ApplicationSignInDetailedSummaryRequest) Update(ctx context.Context, reqObj *ApplicationSignInDetailedSummary) error { return r.JSONRequest(ctx, "PATCH", "", reqObj, nil) } // Delete performs DELETE request for ApplicationSignInDetailedSummary func (r *ApplicationSignInDetailedSummaryRequest) Delete(ctx context.Context) error { return r.JSONRequest(ctx, "DELETE", "", nil, nil) } // ApplicationTemplateRequestBuilder is request builder for ApplicationTemplate type ApplicationTemplateRequestBuilder struct{ BaseRequestBuilder } // Request returns ApplicationTemplateRequest func (b *ApplicationTemplateRequestBuilder) Request() *ApplicationTemplateRequest { return &ApplicationTemplateRequest{ BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client}, } } // ApplicationTemplateRequest is request for ApplicationTemplate type ApplicationTemplateRequest struct{ BaseRequest } // Get performs GET request for ApplicationTemplate func (r *ApplicationTemplateRequest) Get(ctx context.Context) (resObj *ApplicationTemplate, err error) { var query string if r.query != nil { query = "?" + r.query.Encode() } err = r.JSONRequest(ctx, "GET", query, nil, &resObj) return } // Update performs PATCH request for ApplicationTemplate func (r *ApplicationTemplateRequest) Update(ctx context.Context, reqObj *ApplicationTemplate) error { return r.JSONRequest(ctx, "PATCH", "", reqObj, nil) } // Delete performs DELETE request for ApplicationTemplate func (r *ApplicationTemplateRequest) Delete(ctx context.Context) error { return r.JSONRequest(ctx, "DELETE", "", nil, nil) } // type ApplicationAddKeyRequestBuilder struct{ BaseRequestBuilder } // AddKey action undocumented func (b *ApplicationRequestBuilder) AddKey(reqObj *ApplicationAddKeyRequestParameter) *ApplicationAddKeyRequestBuilder { bb := &ApplicationAddKeyRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder} bb.BaseRequestBuilder.baseURL += "/addKey" bb.BaseRequestBuilder.requestObject = reqObj return bb } // type ApplicationAddKeyRequest struct{ BaseRequest } // func (b *ApplicationAddKeyRequestBuilder) Request() *ApplicationAddKeyRequest { return &ApplicationAddKeyRequest{ BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject}, } } // func (r *ApplicationAddKeyRequest) Post(ctx context.Context) (resObj *KeyCredential, err error) { err = r.JSONRequest(ctx, "POST", "", r.requestObject, &resObj) return } // type ApplicationAddPasswordRequestBuilder struct{ BaseRequestBuilder } // AddPassword action undocumented func (b *ApplicationRequestBuilder) AddPassword(reqObj *ApplicationAddPasswordRequestParameter) *ApplicationAddPasswordRequestBuilder { bb := &ApplicationAddPasswordRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder} bb.BaseRequestBuilder.baseURL += "/addPassword" bb.BaseRequestBuilder.requestObject = reqObj return bb } // type ApplicationAddPasswordRequest struct{ BaseRequest } // func (b *ApplicationAddPasswordRequestBuilder) Request() *ApplicationAddPasswordRequest { return &ApplicationAddPasswordRequest{ BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject}, } } // func (r *ApplicationAddPasswordRequest) Post(ctx context.Context) (resObj *PasswordCredential, err error) { err = r.JSONRequest(ctx, "POST", "", r.requestObject, &resObj) return }<|fim▁hole|> // RemoveKey action undocumented func (b *ApplicationRequestBuilder) RemoveKey(reqObj *ApplicationRemoveKeyRequestParameter) *ApplicationRemoveKeyRequestBuilder { bb := &ApplicationRemoveKeyRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder} bb.BaseRequestBuilder.baseURL += "/removeKey" bb.BaseRequestBuilder.requestObject = reqObj return bb } // type ApplicationRemoveKeyRequest struct{ BaseRequest } // func (b *ApplicationRemoveKeyRequestBuilder) Request() *ApplicationRemoveKeyRequest { return &ApplicationRemoveKeyRequest{ BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject}, } } // func (r *ApplicationRemoveKeyRequest) Post(ctx context.Context) error { return r.JSONRequest(ctx, "POST", "", r.requestObject, nil) } // type ApplicationRemovePasswordRequestBuilder struct{ BaseRequestBuilder } // RemovePassword action undocumented func (b *ApplicationRequestBuilder) RemovePassword(reqObj *ApplicationRemovePasswordRequestParameter) *ApplicationRemovePasswordRequestBuilder { bb := &ApplicationRemovePasswordRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder} bb.BaseRequestBuilder.baseURL += "/removePassword" bb.BaseRequestBuilder.requestObject = reqObj return bb } // type ApplicationRemovePasswordRequest struct{ BaseRequest } // func (b *ApplicationRemovePasswordRequestBuilder) Request() *ApplicationRemovePasswordRequest { return &ApplicationRemovePasswordRequest{ BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject}, } } // func (r *ApplicationRemovePasswordRequest) Post(ctx context.Context) error { return r.JSONRequest(ctx, "POST", "", r.requestObject, nil) } // type ApplicationTemplateInstantiateRequestBuilder struct{ BaseRequestBuilder } // Instantiate action undocumented func (b *ApplicationTemplateRequestBuilder) Instantiate(reqObj *ApplicationTemplateInstantiateRequestParameter) *ApplicationTemplateInstantiateRequestBuilder { bb := &ApplicationTemplateInstantiateRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder} bb.BaseRequestBuilder.baseURL += "/instantiate" bb.BaseRequestBuilder.requestObject = reqObj return bb } // type ApplicationTemplateInstantiateRequest struct{ BaseRequest } // func (b *ApplicationTemplateInstantiateRequestBuilder) Request() *ApplicationTemplateInstantiateRequest { return &ApplicationTemplateInstantiateRequest{ BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject}, } } // func (r *ApplicationTemplateInstantiateRequest) Post(ctx context.Context) (resObj *ApplicationServicePrincipal, err error) { err = r.JSONRequest(ctx, "POST", "", r.requestObject, &resObj) return }<|fim▁end|>
// type ApplicationRemoveKeyRequestBuilder struct{ BaseRequestBuilder }
<|file_name|>parser.go<|end_file_name|><|fim▁begin|>package schego import ( "bytes" "encoding/binary" "errors" "fmt" "math" "strconv" "strings" ) type AstNodeType int const ( ProgramNode AstNodeType = iota AddNode SubNode MulNode DivNode GtNode LtNode GteNode LteNode EqNode IfNode DefNode LambdaNode IdentNode IntNode FloatNode StringNode BoolNode ) // base interface for functions needing to accept any kind of AST node type AstNode interface { GetSubNodes() []AstNode AddSubNode(AstNode) GetType() AstNodeType DebugString() string } // base struct that all AST node implementations build off of type SExp struct { subNodes []AstNode } func (s *SExp) GetSubNodes() []AstNode { return s.subNodes } func (s *SExp) AddSubNode(node AstNode) { s.subNodes = append(s.subNodes, node) } type Program struct { SExp } func NewProgram(nodes ...AstNode) *Program { program := new(Program) for _, node := range nodes { program.AddSubNode(node) } return program } func (p Program) GetType() AstNodeType { return ProgramNode } type AddExp struct { SExp } func NewAddExp(lhs AstNode, rhs AstNode) *AddExp { node := new(AddExp) node.AddSubNode(lhs) node.AddSubNode(rhs) return node } func (a AddExp) GetType() AstNodeType { return AddNode } func (a AddExp) DebugString() string { return "AddExp(" + a.subNodes[0].DebugString() + ", " + a.subNodes[1].DebugString() + ")" } type SubExp struct { SExp } func NewSubExp(lhs AstNode, rhs AstNode) *SubExp { node := new(SubExp) node.AddSubNode(lhs) node.AddSubNode(rhs) return node } func (s SubExp) GetType() AstNodeType { return SubNode } func (s SubExp) DebugString() string { return "SubExp(" + s.subNodes[0].DebugString() + ", " + s.subNodes[1].DebugString() + ")" } type MulExp struct { SExp } func NewMulExp(lhs AstNode, rhs AstNode) *MulExp { node := new(MulExp) node.AddSubNode(lhs) node.AddSubNode(rhs) return node } func (m MulExp) GetType() AstNodeType { return MulNode } func (m MulExp) DebugString() string { return "MulExp(" + m.subNodes[0].DebugString() + ", " + m.subNodes[1].DebugString() + ")" } type DivExp struct { SExp } func NewDivExp(lhs AstNode, rhs AstNode) *DivExp { node := new(DivExp) node.AddSubNode(lhs) node.AddSubNode(rhs) return node } func (d DivExp) GetType() AstNodeType { return DivNode } func (d DivExp) DebugString() string { return "DivExp(" + d.subNodes[0].DebugString() + ", " + d.subNodes[1].DebugString() + ")" } type LtExp struct { SExp } func NewLtExp(lhs AstNode, rhs AstNode) *LtExp { node := new(LtExp) node.AddSubNode(lhs) node.AddSubNode(rhs) return node } func (l LtExp) GetType() AstNodeType { return LtNode } func (l LtExp) DebugString() string { return "LtExp(" + l.subNodes[0].DebugString() + ", " + l.subNodes[1].DebugString() + ")" } type LteExp struct { SExp } func NewLteExp(lhs AstNode, rhs AstNode) *LteExp { node := new(LteExp) node.AddSubNode(lhs) node.AddSubNode(rhs) return node } func (l LteExp) GetType() AstNodeType { return LteNode } func (l LteExp) DebugString() string { return "LteExp(" + l.subNodes[0].DebugString() + ", " + l.subNodes[1].DebugString() + ")" } type GtExp struct { SExp } func NewGtExp(lhs AstNode, rhs AstNode) *GtExp { node := new(GtExp) node.AddSubNode(lhs) node.AddSubNode(rhs) return node } func (g GtExp) GetType() AstNodeType { return GtNode } func (g GtExp) DebugString() string { return "GtExp(" + g.subNodes[0].DebugString() + ", " + g.subNodes[1].DebugString() + ")" } type GteExp struct { SExp } func NewGteExp(lhs AstNode, rhs AstNode) *GteExp { node := new(GteExp) node.AddSubNode(lhs) node.AddSubNode(rhs) return node } func (g GteExp) GetType() AstNodeType { return LteNode } func (g GteExp) DebugString() string { return "GteExp(" + g.subNodes[0].DebugString() + ", " + g.subNodes[1].DebugString() + ")" } type EqExp struct { SExp } func NewEqExp(lhs AstNode, rhs AstNode) *EqExp { node := new(EqExp) node.AddSubNode(lhs) node.AddSubNode(rhs) return node } func (e EqExp) GetType() AstNodeType { return EqNode } func (e EqExp) DebugString() string { return "EqExp(" + e.subNodes[0].DebugString() + ", " + e.subNodes[1].DebugString() + ")" } type IfExp struct { SExp } func NewIfExp(cond AstNode, onTrue AstNode, onFalse AstNode) *IfExp { node := new(IfExp) node.AddSubNode(cond) node.AddSubNode(onTrue) node.AddSubNode(onFalse) return node } func (i IfExp) GetType() AstNodeType { return IfNode } func (i IfExp) DebugString() string { return "IfExp(" + i.subNodes[0].DebugString() + ", " + i.subNodes[1].DebugString() + ", " + i.subNodes[2].DebugString() + ")" } type DefExp struct { SExp Name string } func NewDefExp(name string, exp AstNode) *DefExp { node := new(DefExp) node.Name = name node.AddSubNode(exp) return node } func (d DefExp) GetType() AstNodeType { return DefNode } func (d DefExp) DebugString() string { return "DefExp(" + d.Name + ", " + d.subNodes[0].DebugString() + ")" } type LambdaExp struct { SExp Args []string } func NewLambdaExp(args []string, exp AstNode) *LambdaExp { node := new(LambdaExp) // copy to avoid the fact that the slice refers to data that could and will // get overwritten node.Args = append([]string(nil), args...) node.AddSubNode(exp) return node } func (l LambdaExp) GetType() AstNodeType { return LambdaNode } func (l LambdaExp) DebugString() string { return "LambdaExp(" + strings.Trim(fmt.Sprintf("%v", l.Args), "[]") + ", " + l.subNodes[0].DebugString() + ")" } type IdentExp struct { SExp Name string } func NewIdentExp(name string) *IdentExp { node := new(IdentExp) node.Name = name return node } func (i IdentExp) GetType() AstNodeType { return IdentNode } func (i IdentExp) DebugString() string { return i.Name } type IntLiteral struct { SExp Value int64 } func NewIntLiteral(value int64) *IntLiteral { node := new(IntLiteral) node.Value = value return node } func (i IntLiteral) GetType() AstNodeType { return IntNode } func (i IntLiteral) DebugString() string { return strconv.FormatInt(i.Value, 10) } type FloatLiteral struct { SExp Value float64 } func NewFloatLiteral(value float64) *FloatLiteral { node := new(FloatLiteral) node.Value = value return node } func (f FloatLiteral) GetType() AstNodeType { return FloatNode } func (f FloatLiteral) DebugString() string { return strconv.FormatFloat(f.Value, 'g', -1, 64) } type StringLiteral struct { SExp Value string } func NewStringLiteral(value string) *StringLiteral { node := new(StringLiteral) node.Value = value return node } func (s StringLiteral) GetType() AstNodeType { return StringNode } func (s StringLiteral) DebugString() string { return "\"" + s.Value + "\"" } type BoolLiteral struct { SExp Value bool } func NewBoolLiteral(value bool) *BoolLiteral { node := new(BoolLiteral) node.Value = value return node } func (b BoolLiteral) GetType() AstNodeType { return BoolNode } func (b BoolLiteral) DebugString() string { return strconv.FormatBool(b.Value) } // ParseTokens takes tokens and returns an AST (Abstract Syntax Tree) representation func ParseTokens(tokens []*Token) *Program { program := NewProgram() currentIndex := 0 for len(tokens)-1 >= currentIndex { node, _ := parseExpression(tokens, &currentIndex) program.AddSubNode(node) } return program } // accept checks to see if the current token matches a given token type, and advances if so func accept(tokens []*Token, expectedType TokenType, currentIndex *int) bool { if tokens[*currentIndex].Type == expectedType { *currentIndex++ return true } return false } // grabAccepted returns the token just before current, useful for grabbing the value of an accepted token func grabAccepted(tokens []*Token, currentIndex *int) *Token { return tokens[*currentIndex-1] } // expect returns an error if the current token doesn't match the given type func expect(tokens []*Token, expectedType TokenType, currentIndex *int) error { if len(tokens)-1 < *currentIndex { return errors.New("Unexpected EOF") } else if tokens[*currentIndex].Type != expectedType { return errors.New("Unexpected token " + tokens[*currentIndex].Value.String()) } return nil } func parseExpression(tokens []*Token, currentIndex *int) (AstNode, error) { // try literals/idents first if accept(tokens, TokenIntLiteral, currentIndex) { literal := grabAccepted(tokens, currentIndex) return NewIntLiteral(bufferToInt(literal.Value)), nil } else if accept(tokens, TokenFloatLiteral, currentIndex) { literal := grabAccepted(tokens, currentIndex) return NewFloatLiteral(bufferToFloat(literal.Value)), nil } else if accept(tokens, TokenStringLiteral, currentIndex) { literal := grabAccepted(tokens, currentIndex) return NewStringLiteral(literal.Value.String()), nil } else if accept(tokens, TokenBoolLiteral, currentIndex) { literal := grabAccepted(tokens, currentIndex) return NewBoolLiteral(literal.Value.Bytes()[0] == 1), nil } else if accept(tokens, TokenIdent, currentIndex) { identToken := grabAccepted(tokens, currentIndex) return NewIdentExp(identToken.Value.String()), nil } // not a literal, attempt to parse an expression lparenError := expect(tokens, TokenLParen, currentIndex) if lparenError != nil { return nil, lparenError } // jump past the lparen *currentIndex++ if accept(tokens, TokenOp, currentIndex) { // grab the operator token so we can find out which one it is opToken := grabAccepted(tokens, currentIndex) // parse the left-hand and right hand sides recursively // this also takes care of handling nested expressions lhs, lhsError := parseExpression(tokens, currentIndex) if lhsError != nil { return nil, lhsError } rhs, rhsError := parseExpression(tokens, currentIndex) if rhsError != nil { return nil, rhsError } // what sort of operator node do we want to build? var expNode AstNode switch opToken.Value.String() { case "+": expNode = NewAddExp(lhs, rhs) case "-": expNode = NewSubExp(lhs, rhs) case "*": expNode = NewMulExp(lhs, rhs) case "/": expNode = NewDivExp(lhs, rhs) case "<": expNode = NewLtExp(lhs, rhs) case "<=": expNode = NewLteExp(lhs, rhs) case ">": expNode = NewGtExp(lhs, rhs) case ">=": expNode = NewGteExp(lhs, rhs) case "=": expNode = NewEqExp(lhs, rhs) } // make sure the expression has a closing rparen expError := closeExp(tokens, currentIndex) if expError != nil { return nil, expError } return expNode, nil } if accept(tokens, TokenIdent, currentIndex) { identToken := grabAccepted(tokens, currentIndex) switch identToken.Value.String() { case "if": // TODO: error-handling here (and throughout the parser!) cond, _ := parseExpression(tokens, currentIndex) ifTrue, _ := parseExpression(tokens, currentIndex) ifFalse, _ := parseExpression(tokens, currentIndex) ifNode := NewIfExp(cond, ifTrue, ifFalse) expError := closeExp(tokens, currentIndex) if expError != nil { return nil, expError }<|fim▁hole|> return ifNode, nil case "define": // are we attempting to define a function? if accept(tokens, TokenLParen, currentIndex) { nameError := expect(tokens, TokenIdent, currentIndex) if nameError != nil { return nil, nameError } accept(tokens, TokenIdent, currentIndex) funcName := grabAccepted(tokens, currentIndex).Value.String() funcArgs, _ := parseArgs(tokens, currentIndex) lambdaExp, _ := parseExpression(tokens, currentIndex) expError := closeExp(tokens, currentIndex) if expError != nil { return nil, expError } lambdaNode := NewLambdaExp(funcArgs, lambdaExp) defNode := NewDefExp(funcName, lambdaNode) return defNode, nil } else { // defining something besides a function nameError := expect(tokens, TokenIdent, currentIndex) if nameError != nil { return nil, nameError } accept(tokens, TokenIdent, currentIndex) name := grabAccepted(tokens, currentIndex) // this handles longhand lambda definitions too newExp, _ := parseExpression(tokens, currentIndex) expError := closeExp(tokens, currentIndex) if expError != nil { return nil, expError } defNode := NewDefExp(name.Value.String(), newExp) return defNode, nil } case "lambda": lparenError := expect(tokens, TokenLParen, currentIndex) if lparenError != nil { return nil, lparenError } *currentIndex++ lambdaArgs, _ := parseArgs(tokens, currentIndex) lambdaExp, _ := parseExpression(tokens, currentIndex) expError := closeExp(tokens, currentIndex) if expError != nil { return nil, expError } lambdaNode := NewLambdaExp(lambdaArgs, lambdaExp) return lambdaNode, nil } } // no matches? return nil, errors.New("Unexpected token") } // convenience function to ensure an expression is properly closed func closeExp(tokens []*Token, currentIndex *int) error { rparenError := expect(tokens, TokenRParen, currentIndex) if rparenError != nil { return rparenError } *currentIndex += 1 return nil } // convenience function to parse the argument list for a function/lambda func parseArgs(tokens []*Token, currentIndex *int) ([]string, error) { funcArgs := make([]string, 0) for { if accept(tokens, TokenIdent, currentIndex) { arg := grabAccepted(tokens, currentIndex).Value.String() funcArgs = append(funcArgs, arg) } else { expError := closeExp(tokens, currentIndex) if expError != nil { return nil, expError } break } } return funcArgs, nil } func bufferToInt(buffer bytes.Buffer) int64 { num, _ := binary.Varint(buffer.Bytes()) return num } func bufferToFloat(buffer bytes.Buffer) float64 { bits := binary.LittleEndian.Uint64(buffer.Bytes()) return math.Float64frombits(bits) }<|fim▁end|>
<|file_name|>kendo.culture.pa-IN.js<|end_file_name|><|fim▁begin|>/* * Kendo UI v2014.3.1119 (http://www.telerik.com/kendo-ui) * Copyright 2014 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["pa-IN"] = { name: "pa-IN", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3,2], percent: { pattern: ["-n %","n %"], decimals: 2, ",": ",", ".": ".", groupSize: [3,2], symbol: "%" }, currency: { pattern: ["$ -n","$ n"], decimals: 2, ",": ",", ".": ".", groupSize: [3,2], symbol: "ਰੁ" } }, calendars: { standard: { days: { names: ["ਐਤਵਾਰ","ਸੋਮਵਾਰ","ਮੰਗਲਵਾਰ","ਬੁੱਧਵਾਰ","ਵੀਰਵਾਰ","ਸ਼ੁੱਕਰਵਾਰ","ਸ਼ਨਿੱਚਰਵਾਰ"], namesAbbr: ["ਐਤ.","ਸੋਮ.","ਮੰਗਲ.","ਬੁੱਧ.","ਵੀਰ.","ਸ਼ੁਕਰ.","ਸ਼ਨਿੱਚਰ."], namesShort: ["ਐ","ਸ","ਮ","ਬ","ਵ","ਸ਼","ਸ਼"] }, months: { names: ["ਜਨਵਰੀ","ਫ਼ਰਵਰੀ","ਮਾਰਚ","ਅਪ੍ਰੈਲ","ਮਈ","ਜੂਨ","ਜੁਲਾਈ","ਅਗਸਤ","ਸਤੰਬਰ","ਅਕਤੂਬਰ","ਨਵੰਬਰ","ਦਸੰਬਰ",""], namesAbbr: ["ਜਨਵਰੀ","ਫ਼ਰਵਰੀ","ਮਾਰਚ","ਅਪ੍ਰੈਲ","ਮਈ","ਜੂਨ","ਜੁਲਾਈ","ਅਗਸਤ","ਸਤੰਬਰ","ਅਕਤੂਬਰ","ਨਵੰਬਰ","ਦਸੰਬਰ",""] }, AM: ["ਸਵੇਰ","ਸਵੇਰ","ਸਵੇਰ"], PM: ["ਸ਼ਾਮ","ਸ਼ਾਮ","ਸ਼ਾਮ"], patterns: { d: "dd-MM-yy", D: "dd MMMM yyyy dddd", F: "dd MMMM yyyy dddd tt hh:mm:ss", g: "dd-MM-yy tt hh:mm", G: "dd-MM-yy tt hh:mm:ss", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "tt hh:mm", T: "tt hh:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM, yyyy", Y: "MMMM, yyyy" }, "/": "-", ":": ":", firstDay: 1<|fim▁hole|> } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });<|fim▁end|>
} }
<|file_name|>escape.js<|end_file_name|><|fim▁begin|>YUI.add('escape', function(Y) { /** Provides utility methods for escaping strings. @module escape @class Escape @static @since 3.3.0 **/ var HTML_CHARS = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '/': '&#x2F;', '`': '&#x60;' }, Escape = { // -- Public Static Methods ------------------------------------------------ /** Returns a copy of the specified string with special HTML characters escaped. The following characters will be converted to their corresponding character entities: & < > " ' / ` This implementation is based on the [OWASP HTML escaping recommendations][1]. In addition to the characters in the OWASP recommendations, we also escape the <code>&#x60;</code> character, since IE interprets it as an attribute delimiter. If _string_ is not already a string, it will be coerced to a string. [1]: http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet @method html @param {String} string String to escape. @return {String} Escaped string. @static **/ html: function (string) { return (string + '').replace(/[&<>"'\/`]/g, Escape._htmlReplacer); }, /** Returns a copy of the specified string with special regular expression characters escaped, allowing the string to be used safely inside a regex. The following characters, and all whitespace characters, are escaped: - # $ ^ * ( ) + [ ] { } | \ , . ? If _string_ is not already a string, it will be coerced to a string. @method regex @param {String} string String to escape. @return {String} Escaped string. @static **/ regex: function (string) { return (string + '').replace(/[\-#$\^*()+\[\]{}|\\,.?\s]/g, '\\$&'); }, // -- Protected Static Methods --------------------------------------------- /** * Regex replacer for HTML escaping. * * @method _htmlReplacer * @param {String} match Matched character (must exist in HTML_CHARS). * @returns {String} HTML entity. * @static * @protected */ _htmlReplacer: function (match) {<|fim▁hole|> return HTML_CHARS[match]; } }; Escape.regexp = Escape.regex; Y.Escape = Escape; }, '@VERSION@' ,{requires:['yui-base']});<|fim▁end|>
<|file_name|>suggestion.py<|end_file_name|><|fim▁begin|>import json from google.appengine.ext import ndb from models.account import Account class Suggestion(ndb.Model): """ Suggestions are generic containers for user-submitted data corrections to the site. The generally store a model, a key, and then a json blob of fields to append or ammend in the model. """ MODELS = set(["event", "match", "media"]) REVIEW_ACCEPTED = 1 REVIEW_PENDING = 0 REVIEW_REJECTED = -1 review_state = ndb.IntegerProperty(default=0) reviewed_at = ndb.DateTimeProperty() reviewer = ndb.KeyProperty(kind=Account) author = ndb.KeyProperty(kind=Account, required=True) contents_json = ndb.StringProperty(indexed=False) # a json blob target_key = ndb.StringProperty() # "2012cmp" target_model = ndb.StringProperty(choices=MODELS, required=True) # "event" created = ndb.DateTimeProperty(auto_now_add=True, indexed=False) updated = ndb.DateTimeProperty(auto_now=True, indexed=False) def __init__(self, *args, **kw): self._contents = None super(Suggestion, self).__init__(*args, **kw) @property def contents(self): """ Lazy load contents_json """ if self._contents is None: self._contents = json.loads(self.contents_json) return self._contents @contents.setter def contents(self, contents): self._contents = contents self.contents_json = json.dumps(self._contents) @property def youtube_video(self): if "youtube_videos" in self.contents: return self.contents["youtube_videos"][0] @classmethod def render_media_key_name(cls, year, target_model, target_key, foreign_type, foreign_key):<|fim▁hole|> return 'media_{}_{}_{}_{}_{}'.format(year, target_model, target_key, foreign_type, foreign_key) @classmethod def render_webcast_key_name(cls, event_key, webcast_dict): """ Keys aren't required for this model. This is only necessary if checking for duplicate suggestions is desired. """ return 'webcast_{}_{}_{}_{}'.format( event_key, webcast_dict.get('type', None), webcast_dict.get('channel', None), webcast_dict.get('file', None))<|fim▁end|>
""" Keys aren't required for this model. This is only necessary if checking for duplicate suggestions is desired. """
<|file_name|>google-docs.js<|end_file_name|><|fim▁begin|><|fim▁hole|> const GoogleDocs = Component.extend({ layout, tagName: 'a', attributeBindings: ['href', 'rel', 'target'], type: 'reference', referenceUrl: 'https://developers.google.com/maps/documentation/javascript/reference#', guideUrl: 'https://developers.google.com/maps/documentation/javascript/', rel: 'noopener', target: '_blank', baseUrl: computed('type', function() { return (this.type === 'reference') ? this.referenceUrl : this.guideUrl; }), displayType: computed('type', function() { return capitalize(this.type); }), href: computed(function() { return get(this, 'baseUrl') + get(this, 'section'); }) }); GoogleDocs.reopenClass({ positionalParams: ['section'] }); export default GoogleDocs;<|fim▁end|>
import Component from '@ember/component'; import layout from '../templates/components/google-docs'; import { computed, get } from '@ember/object'; import { capitalize } from '@ember/string';
<|file_name|>Yasara.py<|end_file_name|><|fim▁begin|>#!/bin/env python # # This file is part Protein Engineering Analysis Tool (PEAT) # (C) Copyright Jens Erik Nielsen, University College Dublin 2003- # All rights reserved # # Damien Farrell April 2010 from Tkinter import * import Pmw class YasaraControl(Frame): """A yasara controller for comparison use""" def __init__(self, parent, yasara): Frame.__init__(self, parent, height=200,width=160) self.yasara = yasara c=Button(self,text='Align', command=self.align) c.grid(row=1,column=0,sticky='news',padx=2,pady=2) '''c = Pmw.Counter(parent, <|fim▁hole|> label_text = 'residue:', entryfield_value = 0, entryfield_command = self.selectRes, entryfield_validate = {'validator' : 'integer', 'min' : 0, 'max' : 1000}) c.grid(row=2,column=0,columnspan=2,padx=2,pady=2)''' return def align(self): """try to align objects""" Y = self.yasara Y.AlignMultiAll() return def selectRes(self): """Allow highlight residue from list""" return<|fim▁end|>
labelpos = 'w',
<|file_name|>outline-intro-step.ts<|end_file_name|><|fim▁begin|>/* Copyright 2018 The Outline 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. */ import '@polymer/polymer/polymer-legacy'; import '@polymer/paper-button/paper-button'; import './cloud-install-styles'; import './outline-step-view'; import './style.css'; import {Polymer} from '@polymer/polymer/lib/legacy/polymer-fn'; import {html} from '@polymer/polymer/lib/utils/html-tag'; const DO_CARD_HTML = html` <style> :host { --do-blue: #1565c0; } #digital-ocean img { height: 22px; width: 22px; } .card#digital-ocean .tag, .card#digital-ocean .email { color: var(--medium-gray); } #digital-ocean .description ul { /* NOTE: this URL must be relative to the ui_components sub dir, unlike our <img src="..."> attributes */ list-style-image: url("../images/check_white.svg"); } /* Reverse check icon for RTL languages */ :host(:dir(rtl)) #digital-ocean .description ul { list-style-image: url("../images/check_white_rtl.svg"); } /* DigitalOcean card background colours (gets brighter, inactive -> active). */ .card#digital-ocean { background: var(--do-blue); } .card#digital-ocean:hover { background: rgba(28, 103, 189, 0.92); } </style> <div id="digital-ocean" class="card" on-tap="connectToDigitalOceanTapped"> <div class="card-header"> <div class="tag" hidden\$="[[_computeIsAccountConnected(digitalOceanAccountName)]]">[[localize('setup-recommended')]]</div> <div class="email" hidden\$="[[!_computeIsAccountConnected(digitalOceanAccountName)]]">[[digitalOceanAccountName]]</div> <img src="images/do_white_logo.svg"> </div> <div class="card-title">DigitalOcean</div> <div class="card-body"> <div class="description"> <ul hidden\$="[[_computeIsAccountConnected(digitalOceanAccountName)]]"> <li>[[localize('setup-do-easiest')]]</li> <li>[[localize('setup-do-cost')]]</li> <li>[[localize('setup-do-data')]]</li> <li>[[localize('setup-cancel')]]</li> </ul> <p hidden\$="[[!_computeIsAccountConnected(digitalOceanAccountName)]]"> [[localize('setup-do-create')]] </p> </div> </div> <div class="card-footer"> <paper-button class="primary" hidden\$="[[_computeIsAccountConnected(digitalOceanAccountName)]]">[[localize('setup-action')]]</paper-button> <paper-button class="primary" hidden\$="[[!_computeIsAccountConnected(digitalOceanAccountName)]]">[[localize('setup-create')]]</paper-button> </div> </div> `; const GCP_STYLES = html` <style> :host { --gcp-blue: #4285f4; } .card#gcp .tag { color: var(--gcp-blue); } #gcp .description ul { list-style-image: url("../images/check_blue.svg"); } :host(:dir(rtl)) #gcp .description ul { list-style-image: url("../images/check_blue_rtl.svg"); } iron-icon { width: 16px; height: 16px; margin-left: 4px; vertical-align: middle; } </style> `; const GCP_EXPERIMENTAL_CARD_HTML = html` ${GCP_STYLES} <style> /* This card contains hyperlinks so the whole thing can't be clickable. */ .card#gcp { cursor: auto; } .card-footer { cursor: pointer; } </style> <div id="gcp" class="card" hidden\$="[[!_showNewGcpFlow(gcpAccountName)]]"> <div class="card-header"> <div class="tag">[[localize('experimental')]]</div> <div class="email" hidden\$="[[!_computeIsAccountConnected(gcpAccountName)]]">[[gcpAccountName]]</div> <img src="images/gcp-logo.svg"> </div> <div class="card-title">Google Cloud Platform</div> <div class="card-body"> <div class="description"> <ul hidden\$="[[_computeIsAccountConnected(gcpAccountName)]]"> <li>[[localize('setup-gcp-easy')]]</li> <li inner-h-t-m-l="[[localize('setup-gcp-free-tier', 'openLinkFreeTier', _openLinkFreeTier, 'openLinkIpPrice', _openLinkIpPrice, 'closeLink', _closeLink)]]"></li> <li inner-h-t-m-l="[[localize('setup-gcp-free-trial', 'openLinkFreeTrial', _openLinkFreeTrial, 'closeLink', _closeLink)]]"></li> <li>[[localize('setup-cancel')]]</li> </ul> <p hidden\$="[[!_computeIsAccountConnected(gcpAccountName)]]"> [[localize('setup-gcp-create')]] </p> </div> </div> <div class="card-footer" on-tap="setUpGcpTapped"> <paper-button class="primary" hidden\$="[[_computeIsAccountConnected(gcpAccountName)]]">[[localize('setup-action')]]</paper-button> <paper-button class="primary" hidden\$="[[!_computeIsAccountConnected(gcpAccountName)]]">[[localize('setup-create')]]</paper-button> </div> </div> `; const GCP_ADVANCED_CARD_HTML = html` ${GCP_STYLES} <div id="gcp" class="card" on-tap="setUpGcpAdvancedTapped" hidden\$="[[_showNewGcpFlow(gcpAccountName)]]"> <div class="card-header"> <div class="tag">[[localize('setup-advanced')]]</div> <img src="images/gcp-logo.svg"> </div> <div class="card-title">Google Cloud Platform</div> <div class="card-body"> <div class="description"> <ul> <li>[[localize('setup-step-by-step')]]</li> <li>[[localize('setup-firewall-instructions')]]</li> <li>[[localize('setup-simple-commands')]]</li> </ul> </div> </div> <div class="card-footer"> <paper-button class="primary">[[localize('setup-action')]]</paper-button> </div> </div> `; const AWS_CARD_HTML = html` <style> :host { --aws-orange: #ff9900; } .card#aws .tag { color: var(--aws-orange); } #aws .description ul { list-style-image: url("../images/check_orange.svg"); } :host(:dir(rtl)) #aws .description ul { list-style-image: url("../images/check_orange_rtl.svg"); } </style> <div id="aws" class="card" on-tap="setUpAwsTapped"> <div class="card-header"> <div class="tag">[[localize('setup-advanced')]]</div> <img src="images/aws-logo.svg"> </div> <div class="card-title">Amazon Lightsail</div> <div class="card-body"> <div class="description"> <ul> <li>[[localize('setup-step-by-step')]]</li> <li>[[localize('setup-firewall-instructions')]]</li> <li>[[localize('setup-simple-commands')]]</li> </ul> </div> </div> <div class="card-footer"> <paper-button on-tap="setUpAwsTapped" class="primary">[[localize('setup-action')]]</paper-button> </div> </div> `; const MANUAL_CARD_HTML = html` <style> :host { --manual-server-green: #00bfa5; } .card#manual-server .tag { color: var(--manual-server-green); } #manual-server .description ul { list-style-image: url("../images/check_green.svg"); } :host(:dir(rtl)) #manual-server .description ul { list-style-image: url("../images/check_green_rtl.svg"); } </style> <div id="manual-server" class="card" on-tap="setUpGenericCloudProviderTapped"> <div class="card-header"> <div class="tag">[[localize('setup-advanced')]]</div> <img src="images/cloud.svg"> </div> <div class="card-title">[[localize('setup-anywhere')]]</div> <div class="card-body"> <div class="description"> <ul> <li>[[localize('setup-tested')]]</li> <li>[[localize('setup-simple-commands')]]</li> </ul> </div> </div> <div class="card-footer"> <paper-button on-tap="setUpGenericCloudProviderTapped">[[localize('setup-action')]]</paper-button> </div> </div> `; Polymer({ _template: html` <style include="cloud-install-styles"></style> <style> :host { text-align: center; } .container { display: flex; flex-flow: row wrap; padding: 12px 0; } .card { background-color: var(--background-contrast-color); display: flex; flex-direction: column; flex: 1 0 40%; justify-content: space-between; padding: 16px 24px 12px 24px; margin: 12px 12px 0 0; height: 320px; text-align: left; color: var(--medium-gray); font-weight: normal; border-radius: 2px; /* For shadows and hover/click colours. */ transition: 135ms; /* Whole card is clickable. */ cursor: pointer; box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.02), 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12); } /* Card shadows (common to all cards). */ .card:hover { box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.2), 0 4px 5px 0 rgba(0, 0, 0, 0.1), 0 1px 10px 0 rgba(0, 0, 0, 0.2); } .card:active { box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2), 0 8px 10px 1px rgba(0, 0, 0, 0.14), 0 3px 14px 2px rgba(0, 0, 0, 0.12); } /* Non-DigitalOcean card background colours (get darker, inactive -> active). */ .card:hover { background: rgba(38, 50, 56, 0.16); } .card .card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; color: var(--light-gray); } .card .card-body { flex: 6; /* for spacing */ } .card p { margin: 0; } .card .tag { font-weight: 500; letter-spacing: 0.05em; font-size: 10px; text-transform: uppercase; } .card p { color: var(--medium-gray); } .card-title { font-size: 20px; line-height: 32px; flex: 2; /* for spacing */ color: var(--light-gray); } .card img { margin-top: 11px; } .card .description { letter-spacing: 0; line-height: 24px; } .card .description ul { margin-top: 0px; padding-left: 16px; } .card .description ul li { margin-bottom: 8px; } .card-footer { padding-top: 12px; border-top: 1px solid var(--border-color); } .card-footer paper-button { width: 100%; height: 100%; margin: 0; letter-spacing: 0.75px; background-color: inherit; color: var(--light-gray); } </style> <outline-step-view> <span slot="step-title">[[localize('setup-title')]]</span> <span slot="step-description">[[localize('setup-description')]]</span> <div class="container"> ${DO_CARD_HTML} ${GCP_EXPERIMENTAL_CARD_HTML} ${GCP_ADVANCED_CARD_HTML} ${AWS_CARD_HTML} ${MANUAL_CARD_HTML} </div> </outline-step-view> `, is: 'outline-intro-step', properties: { digitalOceanAccountName: { type: String, value: null, }, gcpAccountName: { type: String,<|fim▁hole|> type: Function, }, }, _openLinkFreeTier: '<a href="https://cloud.google.com/free/docs/gcp-free-tier#compute">', _openLinkIpPrice: '<a href="https://cloud.google.com/vpc/network-pricing#ipaddress">', _openLinkFreeTrial: '<a href="https://cloud.google.com/free/docs/gcp-free-tier/#free-trial">', _closeLink: '<iron-icon icon=open-in-new></iron-icon></a>', _computeIsAccountConnected(accountName: string) { return Boolean(accountName); }, _showNewGcpFlow(gcpAccountName: string) { return outline.gcpAuthEnabled || this._computeIsAccountConnected(gcpAccountName); }, connectToDigitalOceanTapped() { if (this.digitalOceanAccountName) { this.fire('CreateDigitalOceanServerRequested'); } else { this.fire('ConnectDigitalOceanAccountRequested'); } }, setUpGenericCloudProviderTapped() { this.fire('SetUpGenericCloudProviderRequested'); }, setUpAwsTapped() { this.fire('SetUpAwsRequested'); }, setUpGcpTapped() { if (this.gcpAccountName) { this.fire('CreateGcpServerRequested'); } else { this.fire('ConnectGcpAccountRequested'); } }, setUpGcpAdvancedTapped() { this.fire('SetUpGcpRequested'); } });<|fim▁end|>
value: null, }, localize: {
<|file_name|>property.js<|end_file_name|><|fim▁begin|>/** * Checks if a given DOM property of an element has the expected value. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element). * * @example * this.demoTest = function (browser) { * browser.expect.element('body').to.have.property('className').equals('test-class'); * browser.expect.element('body').to.have.property('className').matches(/^something\ else/); * browser.expect.element('body').to.not.have.property('classList').equals('test-class'); * browser.expect.element('body').to.have.property('classList').deep.equal(['class-one', 'class-two']); * browser.expect.element('body').to.have.property('classList').contain('class-two'); * };<|fim▁hole|> * @param {string} [message] Optional log message to display in the output. If missing, one is displayed by default. * @display .property(name) * @api expect.element */ const BaseAssertion = require('./_element-assertion.js'); class PropertyAssertion extends BaseAssertion { static get assertionType() { return BaseAssertion.AssertionType.METHOD; } init(property, msg) { super.init(); this.flag('attributeFlag', true); this.property = property; this.hasCustomMessage = typeof msg != 'undefined'; this.message = msg || 'Expected element <%s> to ' + (this.negate ? 'not have' : 'have') + ' dom property "' + property + '"'; this.start(); } executeCommand() { return this.executeProtocolAction('getElementProperty', [this.property]).then(result => { if (!this.transport.isResultSuccess(result) || result.value === null) { throw result; } return result; }).catch(result => { this.propertyNotFound(); return false; }); } onResultSuccess() { if (this.retries > 0 && this.negate) { return; } if (!this.hasCondition()) { this.passed = !this.negate; this.expected = this.negate ? 'not found' : 'found'; this.actual = 'found'; } this.addExpectedInMessagePart(); } propertyNotFound() { this.processFlags(); this.passed = this.hasCondition() ? false : this.negate; if (!this.passed && this.shouldRetry()) { this.scheduleRetry(); } else { this.addExpectedInMessagePart(); if (!this.hasCondition()) { //this.expected = this.negate ? 'not found' : 'found'; this.actual = 'not found'; } if (!this.negate) { this.messageParts.push(' - property was not found'); } this.done(); } } onResultFailed() { this.passed = false; } } module.exports = PropertyAssertion;<|fim▁end|>
* * @method property * @param {string} property The property name
<|file_name|>PersistenceManager.java<|end_file_name|><|fim▁begin|>package org.drools.persistence; import javax.transaction.xa.XAResource; public interface PersistenceManager { XAResource getXAResource(); Transaction getTransaction(); <|fim▁hole|>}<|fim▁end|>
void save(); void load();
<|file_name|>xcb.rs<|end_file_name|><|fim▁begin|>use libc::{c_int, c_char, c_uchar, c_ushort, c_uint}; use std::ptr; use std::mem; use std::default::Default; // CONSTANTS const XCB_WINDOW_CLASS_INPUT_OUTPUT: c_ushort = 1; const XCB_GC_FOREGROUND: c_uint = 4; const XCB_GC_GRAPHICS_EXPOSURES: c_uint = 65536; const XCB_CW_BACK_PIXEL: c_uint = 2; const XCB_CW_EVENT_MASK: c_uint = 2048; const XCB_EVENT_MASK_KEY_PRESS: c_uint = 1; const XCB_EVENT_MASK_EXPOSURE: c_uint = 32768; // TYPES & STRUCTURES type XCBKeycodeFFI = c_uchar; type XCBWindowFFI = c_uint; type XCBColormapFFI = c_uint; type XCBVisualidFFI = c_uint; type XCBGcontextFFI = c_uint; type XCBDrawableFFI = c_uint; #[repr(C)] struct XCBConnectionFFI; #[repr(C)] #[derive(Copy)] struct XCBSetupFFI { status: c_uchar, pad0: c_uchar, protocol_major_version: c_ushort, protocol_minor_version: c_ushort, length: c_ushort, release_number: c_uint, resource_id_base: c_uint, resource_id_mask: c_uint, motion_buffer_size: c_uint, vendor_len: c_ushort, maximum_request_length: c_ushort, roots_len: c_uchar, pixmap_formats_len: c_uchar, image_byte_order: c_uchar, bitmap_format_bit_order: c_uchar, bitmap_format_scanline_unit: c_uchar, bitmap_format_scanline_pad: c_uchar, min_keycode: XCBKeycodeFFI, max_keycode: XCBKeycodeFFI, pad1: [c_uchar; 4usize], } #[repr(C)] #[derive(Copy)] struct XCBScreenFFI { root: XCBWindowFFI, default_colormap: XCBColormapFFI, white_pixel: c_uint, black_pixel: c_uint, current_input_masks: c_uint, width_in_pixels: c_ushort, height_in_pixels: c_ushort, width_in_millimeters: c_ushort, height_in_millimeters: c_ushort, min_installed_maps: c_ushort, max_installed_maps: c_ushort, root_visual: XCBVisualidFFI, backing_stores: c_uchar, save_unders: c_uchar, root_depth: c_uchar, allowed_depths_len: c_uchar, } #[repr(C)] #[derive(Copy)] struct XCBScreenIteratorFFI { data: *mut XCBScreenFFI, rem: c_int, index: c_int, } #[repr(C)] #[derive(Copy)] struct XCBVoidCookieFFI { sequence: c_uint, } impl Default for XCBVoidCookieFFI { fn default() -> XCBVoidCookieFFI { unsafe { mem::zeroed() } } } #[repr(C)] #[derive(Copy)] struct XCBGenericEventFFI { response_type: c_uchar, pad0: c_uchar, sequence: c_ushort, pad: [c_uint; 7usize], full_sequence: c_uint, } impl Default for XCBGenericEventFFI { fn default() -> XCBGenericEventFFI { unsafe { mem::zeroed() } } } #[repr(C)] #[derive(Copy)] pub struct XCBRectangleFFI { pub x: c_ushort, pub y: c_ushort, pub width: c_ushort, pub height: c_ushort, } impl Default for XCBRectangleFFI { fn default() -> XCBRectangleFFI { unsafe { mem::zeroed() } } } // FUNCTIONS #[link(name = "xcb")] extern { fn xcb_connect(displayname: *const c_char, screenp:*mut c_int) -> *mut XCBConnectionFFI; fn xcb_connection_has_error(c: *mut XCBConnectionFFI) -> c_int; fn xcb_disconnect(c: *mut XCBConnectionFFI); fn xcb_get_setup(c: *mut XCBConnectionFFI) -> *const XCBSetupFFI; fn xcb_setup_roots_iterator(R: *const XCBSetupFFI) -> XCBScreenIteratorFFI; fn xcb_generate_id(c: *mut XCBConnectionFFI) -> c_uint; fn xcb_create_gc( c: *mut XCBConnectionFFI, cid: XCBGcontextFFI, drawable: XCBDrawableFFI, value_mask: c_uint, value_list: *const c_uint ) -> XCBVoidCookieFFI; fn xcb_create_window( c: *mut XCBConnectionFFI, depth: c_uchar, wid: XCBWindowFFI, parent: XCBWindowFFI, x: c_ushort, y: c_ushort, width: c_ushort, height: c_ushort, border_width: c_ushort, _class: c_ushort, visual: XCBVisualidFFI, value_mask: c_uint, value_list: *const c_uint ) -> XCBVoidCookieFFI; fn xcb_map_window(c: *mut XCBConnectionFFI, window: XCBWindowFFI) -> XCBVoidCookieFFI; fn xcb_flush(c: *mut XCBConnectionFFI) -> c_int; fn xcb_wait_for_event(c: *mut XCBConnectionFFI) -> *mut XCBGenericEventFFI; fn xcb_poly_rectangle( c: *mut XCBConnectionFFI, drawable: XCBDrawableFFI, gc: XCBGcontextFFI, rectangles_len: c_uint, rectangles: *const XCBRectangleFFI ) -> XCBVoidCookieFFI; } // PUB API pub struct XCB { connection: *mut XCBConnectionFFI, screen: Option<*mut XCBScreenFFI>, window: Option<XCBWindowFFI>, } impl XCB { #[inline] pub fn new() -> Self { unsafe { let mut screen: c_int = 0; let connection = xcb_connect(ptr::null(), &mut screen); if xcb_connection_has_error(connection) > 0 {<|fim▁hole|> panic!("Fatal error during establishing a XCB connection.") } XCB { connection: connection, screen: None, window: None, } } } #[inline] pub fn disconnect(&self) { unsafe { xcb_disconnect(self.connection); } } pub fn create_window(&mut self) { self.init_screen(); unsafe { let window = xcb_generate_id(self.connection); self.window = Some(window); let screen = *self.screen.unwrap(); let mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK; let value_list: [u32; 2] = [ screen.white_pixel, XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_KEY_PRESS ]; xcb_create_window( self.connection, 0, // Depth - copy from parent window, screen.root, 0, 0, screen.width_in_pixels, screen.height_in_pixels, 0, XCB_WINDOW_CLASS_INPUT_OUTPUT, screen.root_visual, mask, value_list.as_ptr(), ); xcb_map_window(self.connection, window); xcb_flush(self.connection); } } pub fn exec(&self) { unsafe { let screen = *self.screen.unwrap(); let windowp = self.window.unwrap(); let foreground = xcb_generate_id(self.connection); let mask = XCB_GC_FOREGROUND | XCB_GC_GRAPHICS_EXPOSURES; let value_list: [u32; 2] = [screen.black_pixel, 0]; xcb_create_gc(self.connection, foreground, windowp, mask, value_list.as_ptr()); let rectangles: [XCBRectangleFFI; 2] = [ XCBRectangleFFI { x: 100, y: 100, width: 150, height: 100, }, XCBRectangleFFI { x: 300, y: 100, width: 250, height: 100, } ]; loop { let event = xcb_wait_for_event(self.connection); let event_type = (*event).response_type & !0x80; if event_type == 12 { // XCB_EXPOSE xcb_poly_rectangle(self.connection, windowp, foreground, 2, rectangles.as_ptr()); xcb_flush(self.connection); } else if event_type == 2 { // XCB_KEY_PRESS break; } } } } fn init_screen(&mut self) { match self.screen { None => unsafe { let iterator = xcb_setup_roots_iterator( xcb_get_setup(self.connection) ); self.screen = Some(iterator.data); }, Some(_) => () } } }<|fim▁end|>
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>""" Performs management commands for the scheduler app """ import hashlib from flask.ext.script import Manager from sqlalchemy import exc # Importing routes causes our URL routes to be registered from src import routes from src import models from src import scheduler scheduler.app.config.from_object(scheduler.ConfigDevelopment) manager = Manager(scheduler.app) def add_coaches(): """ Adds two coaches (for testing) """ user_1 = models.User( id='ecf1bcae-9c8f-11e5-b5b4-d895b95699bb', fullname='Pat Blargstone', username='pat', password=hashlib.md5('secret').hexdigest()) coach_1 = models.Coach( id='ee8d1d30-9c8f-11e5-89d4-d895b95699bb', user_id=user_1.id) user_2 = models.User( id='ef2a95b0-9c8f-11e5-bd27-d895b95699bb', fullname='Sandy Blargwright', username='sandy', password=hashlib.md5('secret').hexdigest()) coach_2 = models.Coach( id='efad3330-9c8f-11e5-9654-d895b95699bb', user_id=user_2.id)<|fim▁hole|> scheduler.db.session.add(user_2) scheduler.db.session.add(coach_1) scheduler.db.session.add(coach_2) scheduler.db.session.commit() except exc.SQLAlchemyError: pass if __name__ == '__main__': scheduler.db.create_all() add_coaches() manager.run()<|fim▁end|>
try: scheduler.db.session.add(user_1)
<|file_name|>log_utils.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import logging import datetime def get_logger(directory, name): """ """ logger = logging.getLogger(name) logger.setLevel(logging.INFO) date_handler = DateFileHandler(directory, name) fmt_str = '%(asctime)s %(process)d %(module)s.%(funcName)s.%(lineno)d %(levelname)s : %(message)s' fmt = logging.Formatter(fmt_str, datefmt='%Y-%m-%d %H:%M:%S') date_handler.setFormatter(fmt) logger.addHandler(date_handler) return logger class DateFileHandler(logging.StreamHandler): """ log by date file """ def __init__(self, directory, log_name='', mode='a'): self.directory = directory self.log_name = log_name self.mode = mode self.last_date = None logging.StreamHandler.__init__(self, self._open()) def close(self): """ Closes the stream. """<|fim▁hole|> if hasattr(self.stream, "close"): self.stream.close() logging.StreamHandler.close(self) self.stream = None finally: self.release() def gen_file_name(self): self.last_date = datetime.datetime.now().date() log_directory = '%s/%04d-%02d' % (self.directory, self.last_date.year, self.last_date.month) os.system("mkdir -p %s" % log_directory) log_file = '%s/%s.%s.log' % (log_directory, self.last_date.day, self.log_name) return log_file def _open(self): log_file = self.gen_file_name() stream = open(log_file, self.mode) return stream def should_roll(self): date = datetime.datetime.now().date() if date == self.last_date: return False else: return True def emit(self, record): """ Emit a record. """ if self.should_roll(): self.close() if self.stream is None: self.stream = self._open() logging.StreamHandler.emit(self, record)<|fim▁end|>
self.acquire() try: if self.stream: self.flush()
<|file_name|>AttackProcess.py<|end_file_name|><|fim▁begin|>from threading import Thread import time<|fim▁hole|> class AttackProcess(Thread): def __init__(self, main): Thread.__init__(self) self.main = main self.selected_hosts = [] self.is_attacking = False def run(self): while True: while self.is_attacking: packets = [] for host in self.main.HostMgr.hosts: if host.is_selected: packets.append(host.packet) time.sleep(1) send(packets) time.sleep(5)<|fim▁end|>
from scapy.all import *
<|file_name|>fire.py<|end_file_name|><|fim▁begin|># Source:https://github.com/FastLED/FastLED/blob/master/examples/Fire2012WithPalette/Fire2012WithPalette.ino from __future__ import division import math import random <|fim▁hole|> from components import App def hex_to_rgb(value): value = value.lstrip('#') lv = len(value) return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3)) class Pattern_Fire(App): """ Create a fire animation """ def __init__(self, device): self.device = device self.width = device.width self.height = device.height self.heat = [[0 for x in range(device.width)] for y in range(device.height)] # COOLING: How much does the air cool as it rises? # Less cooling = taller flames. More cooling = shorter flames. # Default 55, suggested range 20-100 self.cooling = 100 # SPARKING: What chance (out of 255) is there that a new spark will be lit? # Higher chance = more roaring fire. Lower chance = more flickery fire. # Default 120, suggested range 50-200. self.sparking = 80 black = Color("black") red = Color("red") yellow = Color("yellow") blue = Color("#6b99ff") white = Color("white") self.colors = [] self.colors += list(black.range_to(red, 116)) self.colors += list(red.range_to(yellow, 140)) self.colors += list(yellow.range_to(white, 10)) self.image = None def handle_input(self, command): if command == "UP": self.cooling -= 1 elif command == "DOWN": self.cooling += 1 elif command == "LEFT": self.sparking += 1 elif command == "RIGHT": self.sparking -= 1 self.cooling = min(max(self.cooling, 0), 255) self.sparking = min(max(self.sparking, 0), 255) def draw_frame(self): pix = self.device.image.load() for x in range(self.width): # Step 1: cool down every cell a little for y in range(self.height): cooling_factor = random.randint( 0, int(((self.cooling * 10) / self.height) + 2)) self.heat[x][y] = max(self.heat[x][y] - cooling_factor, 0) # Step 2: Heat from each cell drifts up and diffuses a little for y in range(self.height): y1 = min(y + 1, self.height - 1) y2 = min(y + 2, self.height - 1) self.heat[x][y] = (self.heat[x][y1] + self.heat[x] [y2] + self.heat[x][y2]) / 3 # Step 3: Randomly ignite sparks of heat if random.randrange(0, 255) < self.sparking: y0 = self.height - 1 self.heat[x][y0] = min( (self.heat[x][y0] + random.randrange(160, 255)), 255) # Step 4: Map to the colors for y in range(self.height): color_index = int(self.heat[x][y]) # int(math.ceil(self.heat[x][y])) c = self.colors[color_index] pix[x, y] = (int(c.red * 255), int(c.green * 255), int(c.blue * 255)) self.device.display() return 10<|fim▁end|>
from colour import Color #import randomcolor from PIL import Image, ImageChops, ImageDraw, ImageFont
<|file_name|>fdmgrid.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """interpret a comapct grid specification using regex""" import re # use a compact regular expression with nested OR expressions, # and hence many groups, but name the outer (main) groups: real_short1 = \<|fim▁hole|> r'\s*(?P<upper>-?(\d+(\.\d*)?|\d*\.\d+)([eE][+\-]?\d+)?)\s*' # regex for real interval [a,b] : domain = r'\[' + real_short1 + ',' + real_short2 + r'\]' # regex for integer interval [a:b] : indices = r'\[\s*(-?\d+)\s*:\s*(-?\d+)\s*\]' # test: examples = ('domain=[0,10] indices=[0:11]', 'domain=[0.1,1.1]x[0,2E+00] indices=[1:21]x[1:101]', '[0,1]x[0,2]x[-1,1.5] [1:21]x[1:11]x[-10:15]') for ex in examples: print re.findall(indices, ex) # a nested list is returned; requires nested group counting print re.findall(domain, ex) print # work with compiled expressions and the groupindex dictionary to # extract the named groups easily from the nested list that is # returned from re.findall: print 'work with groupindex:' for ex in examples: print re.findall(indices, ex) c = re.compile(domain) groups = c.findall(ex) intervals = [] for i in range(len(groups)): intervals.append( (groups[i][c.groupindex['lower']-1], groups[i][c.groupindex['upper']-1])) print intervals print # work with non-capturing parenthesis of the form (?:pattern) real_short1 = \ r'\s*(?P<lower>-?(?:\d+(?:\.\d*)?|\d*\.\d+)(?:[eE][+\-]?\d+)?)\s*' real_short2 = \ r'\s*(?P<upper>-?(?:\d+(?:\.\d*)?|\d*\.\d+)(?:[eE][+\-]?\d+)?)\s*' # regex for real interval [a,b] : domain = r'\[' + real_short1 + ',' + real_short2 + r'\]' print 'non-capturing groups:' for ex in examples: print re.findall(domain, ex) print # avoid parenthesis, i.e., nested OR expressions: real_sn = r'-?\d\.?\d*[Ee][+\-][0-9]+' real_dn = r'-?\d*\.\d*' real_in = r'-?\d+' real1 = \ r'\s*(?P<lower>' + real_sn + '|' + real_dn + '|' + real_in + ')\s*' real2 = \ r'\s*(?P<upper>' + real_sn + '|' + real_dn + '|' + real_in + ')\s*' # regex for real interval [a,b] : domain = r'\[' + real1 + ',' + real2 + r'\]' # regex for integer interval [a:b] : indices = r'\[\s*(-?\d+)\s*:\s*(-?\d+)\s*\]' print '\navoid so many parenthesis (just two groups now for each interval):' for ex in examples: print re.findall(indices, ex) print re.findall(domain, ex) print # much simpler _working_ versions: domain = r'\[([^,]*),([^\]]*)\]' indices = r'\[([^:,]*):([^\]]*)\]' print '\nsimpler regular expressions:\n', domain, indices for ex in examples: print re.findall(indices, ex) print re.findall(domain, ex) print # these give wrong results domain = r'\[(.*?),(.*?)\]' indices = r'\[(.*?):(.*?)\]' print '\nalternative; simpler regular expressions:\n', domain, indices for ex in examples: print re.findall(indices, ex) print re.findall(domain, ex) print<|fim▁end|>
r'\s*(?P<lower>-?(\d+(\.\d*)?|\d*\.\d+)([eE][+\-]?\d+)?)\s*' real_short2 = \
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|># License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from . import event_mass_edit<|fim▁end|>
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*- # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol
<|file_name|>ee-TG.ts<|end_file_name|><|fim▁begin|><|fim▁hole|> * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js function plural(n: number): number { if (n === 1) return 1; return 5; } export default [ 'ee-TG', [ ['ŋ', 'ɣ'], ['ŋdi', 'ɣetrɔ'], ], , [ ['k', 'd', 'b', 'k', 'y', 'f', 'm'], ['kɔs', 'dzo', 'bla', 'kuɖ', 'yaw', 'fiɖ', 'mem'], ['kɔsiɖa', 'dzoɖa', 'blaɖa', 'kuɖa', 'yawoɖa', 'fiɖa', 'memleɖa'], ['kɔs', 'dzo', 'bla', 'kuɖ', 'yaw', 'fiɖ', 'mem'] ], , [ ['d', 'd', 't', 'a', 'd', 'm', 's', 'd', 'a', 'k', 'a', 'd'], ['dzv', 'dzd', 'ted', 'afɔ', 'dam', 'mas', 'sia', 'dea', 'any', 'kel', 'ade', 'dzm'], [ 'dzove', 'dzodze', 'tedoxe', 'afɔfĩe', 'dama', 'masa', 'siamlɔm', 'deasiamime', 'anyɔnyɔ', 'kele', 'adeɛmekpɔxe', 'dzome' ] ], , [['HYV', 'Yŋ'], , ['Hafi Yesu Va', 'Yesu ŋɔli']], 1, [6, 0], ['M/d/yy', 'MMM d \'lia\', y', 'MMMM d \'lia\' y', 'EEEE, MMMM d \'lia\' y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], [ '{0} {1}', , , ], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'mnn', ':'], ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'CFA', 'ɣetoɖofe afrikaga CFA franc BCEAO', plural ];<|fim▁end|>
/**
<|file_name|>api.ts<|end_file_name|><|fim▁begin|>/// <reference path="indexer.ts" /> module api { declare var window; declare var uuid; export var version = 0; type Id = string; type Fact = any[]; interface Constraint { view?: Id, leftSource?: Id, leftField?: Id, rightSource?: Id, rightField?: Id, operation?: Id, } export function now() { if (window.performance) { return window.performance.now(); } return (new Date()).getTime(); } export var arraysIdentical:(a:any[], b:any[])=>boolean = Indexing.arraysIdentical; export var zip:(keys:string[], rows:any[][])=>any[] = Indexing.zip; export var clone:<T>(item:T)=>T = Indexing.clone; if(!window.DEBUG) { window.DEBUG = {RECEIVE: 0, SEND: 0, INDEXER: 0, TABLE_CELL_LOOKUP: true}; } export var KEYS = { BACKSPACE: 8, UP: 38, DOWN: 40, ENTER: 13, Z: 90, F: 70, ESC: 27, SPACE: 32, }; export function extend(dest, src) { for(var key in src) { if(!src.hasOwnProperty(key)) { continue; } dest[key] = src[key]; } return dest; } export function displaySort(idA:string, idB:string): number { var orderA = ixer.index("display order")[idA]; var orderB = ixer.index("display order")[idB]; if(orderB - orderA) { return orderB - orderA; } else { return idA.localeCompare(idB); } } export function invert(obj:Object): Object { var res = {}; for(var key in obj) { if(!obj.hasOwnProperty(key)) { continue; } res[obj[key]] = key; } return res; } export var alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; export var alphabetLower = alphabet.map(function(char) { return char.toLowerCase(); }); var alphabetLowerToIx = invert(alphabetLower); export function reverseDiff(diff) { var neue = []; for(var diffIx = 0, diffLen = diff.length; diffIx < diffLen; diffIx++) { var copy = diff[diffIx].slice(); neue[diffIx] = copy; if(copy[1] === "inserted") { copy[1] = "removed"; } else { copy[1] = "inserted"; } } return neue; } export function checkVersion(callback:(error:Error, newVersionExists?:boolean) => void) { let request = new XMLHttpRequest(); request.onreadystatechange = function() { if(request.readyState === 4) { if(request.status !== 200) { return callback(new Error(`HTTP Response: ${request.status}`)); } callback(undefined, +request.responseText > +api.version); } } //request.open("GET", "https://gist.githubusercontent.com/joshuafcole/117ec93af90c054bac23/raw/1350f2aae121e19129e561678b107ec042a6cbd2/version"); request.open("GET", "https://raw.githubusercontent.com/witheve/Eve/master/version"); request.send(); } export function writeToGist(name:string, content:string, callback:(error:Error, url?:string) => void) { let request = new XMLHttpRequest(); request.onreadystatechange = function() { if(request.readyState === 4) { if(request.status !== 201) { return callback(new Error(`HTTP Response: ${request.status}`)); } let response:any = JSON.parse(request.responseText); let file = response.files[name]; let url = file.raw_url.split("/raw/")[0]; let err = (file.truncated) ? new Error("File to large: Maximum gist size is 10mb") : undefined; callback(err, url); } }; let payload = { public: true, description: "", files: {} } payload.files[name] = {content: content}; console.log("P", payload); request.open("POST", "https://api.github.com/gists"); request.send(JSON.stringify(payload)); } export function readFromGist(url:string, callback:(error:Error, content?:string) => void) { let request = new XMLHttpRequest(); request.onreadystatechange = function() { if(request.readyState === 4) { if(request.status !== 200) { return callback(new Error(`HTTP Response: ${request.status}`)); } callback(undefined, request.responseText); } } request.open("GET", url); request.send(); } //--------------------------------------------------------- // Data //--------------------------------------------------------- export var ixer = new Indexing.Indexer(); export var newPrimitiveDefaults = { "<": {"<: A": 0, "<: B": 0}, "<=": {"<=: A": 0, "<=: B": 0}, "!=": {"!=: A": 0, "!=: B": 0}, "+": {"+: A": 0, "+: B": 0}, "*": {"*: A": 0, "*: B": 0}, "-": {"-: A": 0, "-: B": 0}, "/": {"/: A": 0, "/: B": 0}, remainder: {"remainder: A": 0, "remainder: B": 0}, round: {"round: A": 0, "round: B": 0}, contains: {"contains: inner": " ", "contains: outer": ""}, count: {"count: A": []}, mean: {"mean: A": []}, split: {"split: split": " ", "split: string": ""}, concat: {"concat: A": "", "concat: B": ""}, "as number": {"as number: A": "0"}, "as text": {"as text: A": ""}, "standard deviation": {"standard deviation: A": []}, sum: {"sum: A": []} } // This index needs to be hardcoded for code.ix to work. ixer.addIndex("id to tags", "tag", Indexing.create.collector(["tag: view"])); ixer.addIndex("view to fields", "field", Indexing.create.collector(["field: view"])); ixer.addIndex("display name", "display name", Indexing.create.lookup(["display name: id", "display name: name"])); ixer.addIndex("display order", "display order", Indexing.create.lookup(["display order: id", "display order: priority"])); // editor ixer.addIndex("eveusers id to username", "eveusers", Indexing.create.lookup(["eveusers: id", "eveusers: username"])); // ui ixer.addIndex("uiComponentElement", "uiComponentElement", Indexing.create.lookup(["uiComponentElement: id", false])); ixer.addIndex("uiComponentToElements", "uiComponentElement", Indexing.create.collector(["uiComponentElement: component"])); ixer.addIndex("uiComponentLayer", "uiComponentLayer", Indexing.create.lookup(["uiComponentLayer: id", false])); ixer.addIndex("parentLayerToLayers", "uiComponentLayer", Indexing.create.collector(["uiComponentLayer: parentLayer"])); ixer.addIndex("uiComponentToLayers", "uiComponentLayer", Indexing.create.collector(["uiComponentLayer: component"])); ixer.addIndex("uiLayerToElements", "uiComponentElement", Indexing.create.collector(["uiComponentElement: layer"])); ixer.addIndex("uiStyles", "uiStyle", Indexing.create.collector(["uiStyle: id"])); ixer.addIndex("uiStyle", "uiStyle", Indexing.create.lookup(["uiStyle: id", false])); ixer.addIndex("uiElementToStyle", "uiStyle", Indexing.create.lookup(["uiStyle: element", "uiStyle: type", false])); ixer.addIndex("uiElementToStyles", "uiStyle", Indexing.create.collector(["uiStyle: element"])); ixer.addIndex("stylesBySharedAndType", "uiStyle", Indexing.create.collector(["uiStyle: shared", "uiStyle: type", "uiStyle: id"])); ixer.addIndex("uiStyleToAttr", "uiComponentAttribute", Indexing.create.lookup(["uiComponentAttribute: id", "uiComponentAttribute: property", false])); ixer.addIndex("uiStyleToAttrs", "uiComponentAttribute", Indexing.create.collector(["uiComponentAttribute: id"])); ixer.addIndex("groupToBinding", "uiGroupBinding", Indexing.create.lookup(["uiGroupBinding: group", "uiGroupBinding: view"])); ixer.addIndex("elementAttrToBinding", "uiAttrBinding", Indexing.create.lookup(["uiAttrBinding: elementId", "uiAttrBinding: attr", "uiAttrBinding: field"])); ixer.addIndex("elementAttrBindings", "uiAttrBinding", Indexing.create.collector(["uiAttrBinding: elementId"])); ixer.addIndex("uiElementToMap", "uiMap", Indexing.create.lookup(["uiMap: element", false])); ixer.addIndex("uiMapAttr", "uiMapAttr", Indexing.create.lookup(["uiMapAttr: map","uiMapAttr: property", "uiMapAttr: value"])); //--------------------------------------------------------- // Data interaction code //--------------------------------------------------------- export var code = { name: function(id:Id): string { return ixer.index("display name", true)[id] || ""; }, hasTag: function(id:Id, tag:string): boolean { var tags = ixer.index("id to tags", true)[id] || []; return tags.some(function(cur) { return cur["tag: tag"] === tag; }); }, activeItemId: function(): Id|void { return localState.activeItem; }, sortedViewFields: function(viewId:Id): Id[] { var fields = (ixer.index("view to fields")[viewId] || []).slice(); var fieldsLength = fields.length; for(var ix = 0; ix < fieldsLength; ix++) { var fieldId = fields[ix][1]; fields[ix] = [ixer.index("display order")[fieldId], fieldId]; } fields.sort(function(a, b) { var delta = b[0] - a[0]; if(delta) { return delta; } else { return a[1].localeCompare(b[1]); } }); var fieldIds = []; for(var ix = 0; ix < fieldsLength; ix++) { fieldIds.push(fields[ix][1]); } return fieldIds; }, layerToChildLayers: function layerToChildLayers(layer:Fact) { var result = []; var lookup = ixer.index("parentLayerToLayers"); var childLayers = lookup[layer[1]]; if(!childLayers) { return result; } else { childLayers = childLayers.slice(); } while(childLayers.length !== 0) { var curLayer = childLayers.pop(); result.push(curLayer); var children = lookup[curLayer[1]]; if(children && children.length) { childLayers.push.apply(childLayers, children); } } return result; }, minPriority: function(ids:Id[]): number { var order = ixer.index("display order"); return ids.reduce(function(memo, id) { var neue = order[id]; if(neue <= memo) { return neue - 1; } return memo; }, 0); } }; export var localState: any = { txId: 0, uiActiveLayer: null, openLayers: {}, initialAttrs: [], initialElements: [], activeItem: null, showMenu: true, uiGridSize: 10, initialValue: undefined, queryEditorActive: undefined, queryEditorInfo: undefined, sort: {} }; export type Diff = any[]; interface Context {[key:string]: Id} interface Write<T> {type: string, content: T|T[], context?: Context|Context[], mode?: string, originalKeys?: string[], useIds?: boolean} interface Schema { key?: string|string[] dependents?: Id[] foreign?: {[field:string]: string} singular?: boolean } var pkDependents = ["display order", "tag"]; var schemas:{[id:string]: Schema} = { "display name": {foreign: {$last: "id"}, singular: true}, "display order": {foreign: {$last: "id"}, singular: true}, tag: {foreign: {$last: "view"}}, view: {key: "view", dependents: pkDependents.concat( ["field"])}, source: {key: "source", foreign: {view: "view"}, dependents: []}, field: {key: "field", foreign: {view: "view"}, dependents: pkDependents, }, "chunked source": {}, "ordinal binding": {}, "grouped field": {}, "negated source": {}, "sorted field": {}, "select": {}, "variable" : {}, "binding": {}, "constant binding": {}, "view description": {}, "text input": {}, "mouse position": {}, "click": {}, "client event": {}, "location": {}, "session url": {}, "captured key": {}, "editor node position": {key: "node"}, }; /***************************************************************************\ * Read/Write primitives. \***************************************************************************/ function fillForeignKeys(type, query, context, silentThrow?) { var schema = schemas[type]; if(!schema) { throw new Error("Attempted to process unknown type " + type + " with query " + JSON.stringify(query)); } var foreignKeys = schema.foreign; if(!foreignKeys) { return query; } for(var contextKey in foreignKeys) { var foreignKey = foreignKeys[contextKey]; if(!foreignKeys.hasOwnProperty(contextKey)) { continue; } if(query[foreignKey] !== undefined) { continue; } if(context[contextKey] === undefined && !silentThrow) { throw new Error("Unspecified field " + foreignKey + " for type " + type + " with no compatible parent to link to in context " + JSON.stringify(context)); } query[foreignKey] = context[contextKey]; } return query; } export function process(type:string, params, context?:Context, useIds = false): Write<any> { if(!params) { return; } if(params instanceof Array) { var write = {type: type, content: [], context: []}; for(var item of params) { var result = process(type, item, clone(context), useIds); write.content.push(result.content); write.context.push(result.context); } return write; } var schema = schemas[type] || {}; if(!params) { throw new Error("Invalid params specified for type " + type + " with params " + JSON.stringify(params)); } if(!context) { context = {}; } // @NOTE: Should we clone this? If so, should we clone params as well? // Link foreign keys from context if missing. if(schema.foreign) { var params = fillForeignKeys(type, params, context); } // Fill primary keys if missing. var keys:string[] = (schema.key instanceof Array) ? <string[]>schema.key : (schema.key) ? [<string>schema.key] : []; for(var key of keys) { if(params[key] === undefined) { params[key] = uuid(); } context[key] = params[key]; } if(keys.length === 1) { context["$last"] = params[keys[0]]; } // Ensure remaining fields exist and contain something. var fieldIds = ixer.getFields(type); for(var fieldId of fieldIds) { var fieldName = useIds ? fieldId : code.name(fieldId); if(params[fieldName] === undefined || params[fieldName] === null) { throw new Error("Missing value for field " + fieldName + " on type " + type); } } // Process dependents recursively. if(params.dependents) { var dependents = params.dependents; for(var dep in dependents) { if(!dependents.hasOwnProperty(dep)) { continue; } if(dependents[dep] instanceof Array) { for(var depItem of dependents[dep]) { process(dep, depItem, context); } } else { var result = process(dep, dependents[dep], context); if(!result) { delete dependents[dep]; } } } } return {type: type, content: params, context: context}; } export function retrieve(type:string, query:{[key:string]:string}, context?, useIds = false) { context = context || {}; var schema = schemas[type] || {}; var keys:string[] = (schema.key instanceof Array) ? <string[]>schema.key : (schema.key) ? [<string>schema.key] : []; var facts = useIds ? ixer.select(type, query, useIds) : ixer.selectPretty(type, query); if(!facts.length) { return; } for(var fact of facts) { if(!fact) { continue; } var factContext = clone(context); for(var key of keys) { factContext[key] = fact[key]; } if(keys.length === 1) { factContext["$last"] = fact[keys[0]]; } var dependents = {}; var hasDependents = false; if(schema.dependents) { for(var dependent of schema.dependents) { var depSchema = schemas[dependent]; //debugger; var q = <{[key:string]:string}>fillForeignKeys(dependent, {}, factContext, true); var results = retrieve(dependent, q, clone(factContext)); if(results && results.length) { if(depSchema.singular) { dependents[dependent] = results[0]; } else { dependents[dependent] = results; } hasDependents = true; } } } if(hasDependents) { fact.dependents = dependents; } } return facts; } /***************************************************************************\ * Read/Write API \***************************************************************************/ export function mapToFact(viewId:Id, props, useIds = false) { if(arguments.length < 2) { throw new Error("Must specify viewId and map to convert to fact."); } var fieldIds = code.sortedViewFields(viewId); // @FIXME: We need to cache these horribly badly. var length = fieldIds.length; var fact = new Array(length); for(var ix = 0; ix < length; ix++) { var name = useIds ? fieldIds[ix] : code.name(fieldIds[ix]); var val = props[name]; if(val === undefined || val === null) { throw new Error("Malformed value in " + viewId + " for field " + name + " of fact " + JSON.stringify(props)); } fact[ix] = val; } return fact; } export function factToMap(viewId:Id, fact:Fact) { if(arguments.length < 2) { throw new Error("Must specify viewId and fact to convert to map."); } var fieldIds = code.sortedViewFields(viewId); // @FIXME: We need to cache these horribly badly. var length = fieldIds.length; var map = {}; for(var ix = 0; ix < length; ix++) { var name = code.name(fieldIds[ix]); map[name] = fact[ix]; } return map; } export function insert(type:string, params, context?:Context, useIds = false):Write<any> { if(arguments.length < 2) { throw new Error("Must specify type and parameters for insert."); } var write = process(type, params, context, useIds); write.mode = "inserted"; write.useIds = useIds; return write; } function writeInto(dest, src) { if(dest.constructor === Array) { return dest.map(function(item) { return writeInto(item, src); }) } for(var key in src) { if(src[key] === undefined) { continue; } // If the source attribute is an array, append its contents to the dest key. if(src[key].constructor === Array) { if(dest[key].constructor !== Array) { dest[key] = [dest[key]]; } dest[key] = dest[key].concat(src[key]); } // If it's an object, recurse. // @NOTE: This will fail if the destination is dissimilarly shaped (e.g. contains a primitive here). else if(typeof src[key] === "object") { dest[key] = writeInto(dest[key] || {}, src[key]); } // If it's a primitive value, overwrite the current value. else { dest[key] = src[key]; } } return dest; } export function change(type:string, params, changes, upsert:boolean = false, context?:Context, useIds = false):Write<any> { if(arguments.length < 3) { throw new Error("Must specify type and query and changes for change."); } // When useIds is set, retrieve will return undefined for an empty result var read = retrieve(type, params, context, useIds) || []; var write = read.map(function(item) { return writeInto(item, changes); }); if(!write.length && upsert) { var insertParams = writeInto(writeInto({}, params), changes); return insert(type, insertParams, {}, useIds); } return {type: type, content: write, context: context, mode: "changed", originalKeys: clone(params), useIds}; } export function remove(type:string, params, context?:Context, useIds = false):Write<any> { if(arguments.length < 2) { throw new Error("Must specify type and query for remove."); } var read = retrieve(type, params, context, useIds); return {type: type, content: read, context: context, mode: "removed", useIds}; } export function toDiffs(writes:Write<any>|Write<any>[]):Diff[] { var diffs = []; if(writes instanceof Array) { for(var write of writes) { if(!write) { continue; } var result = toDiffs(write); if(result !== undefined) { diffs = diffs.concat(result); } } return diffs; } else { var write:Write<any> = <Write<any>>writes; if(write.content === undefined) { return diffs; } } var type = write.type; var params = write.content; var mode = write.mode;<|fim▁hole|> return; } if(mode === "changed") { // Remove the existing root and all of its dependents, then swap mode to inserted to replace them. if(!write.originalKeys) { throw new Error("Change specified for " + type + ", but no write.originalKeys specified."); } diffs = diffs.concat(toDiffs(remove(type, write.originalKeys))); mode = "inserted"; } if(params instanceof Array) { for(var item of params) { diffs = diffs.concat(toDiffs({type: type, content: item, context: write.context, mode: mode, useIds: write.useIds})); } return diffs; } // Process root fact. diffs.push([type, mode, mapToFact(type, params, write.useIds)]); // Process dependents. var dependents = params.dependents || {}; for(var key in dependents) { if(!dependents.hasOwnProperty(key)) { continue; } diffs = diffs.concat(toDiffs({type: key, content: dependents[key], context: write.context, mode: mode})); } return diffs; } }<|fim▁end|>
if(!params) { //if we have no content, then there's nothing for us to do.
<|file_name|>basic.py<|end_file_name|><|fim▁begin|>"""Base class for all the objects in SymPy""" from __future__ import print_function, division from .assumptions import BasicMeta, ManagedProperties from .cache import cacheit from .sympify import _sympify, sympify, SympifyError from .compatibility import (iterable, Iterator, ordered, string_types, with_metaclass, zip_longest, range) from .singleton import S from inspect import getmro class Basic(with_metaclass(ManagedProperties)): """ Base class for all objects in SymPy. Conventions: 1) Always use ``.args``, when accessing parameters of some instance: >>> from sympy import cot >>> from sympy.abc import x, y >>> cot(x).args (x,) >>> cot(x).args[0] x >>> (x*y).args (x, y) >>> (x*y).args[1] y 2) Never use internal methods or variables (the ones prefixed with ``_``): >>> cot(x)._args # do not use this, use cot(x).args instead (x,) """ __slots__ = ['_mhash', # hash value '_args', # arguments '_assumptions' ] # To be overridden with True in the appropriate subclasses is_number = False is_Atom = False is_Symbol = False is_Dummy = False is_Wild = False is_Function = False is_Add = False is_Mul = False is_Pow = False is_Number = False is_Float = False is_Rational = False is_Integer = False is_NumberSymbol = False is_Order = False is_Derivative = False is_Piecewise = False is_Poly = False is_AlgebraicNumber = False is_Relational = False is_Equality = False is_Boolean = False is_Not = False is_Matrix = False is_Vector = False is_Point = False def __new__(cls, *args): obj = object.__new__(cls) obj._assumptions = cls.default_assumptions obj._mhash = None # will be set by __hash__ method. obj._args = args # all items in args must be Basic objects return obj def copy(self): return self.func(*self.args) def __reduce_ex__(self, proto): """ Pickling support.""" return type(self), self.__getnewargs__(), self.__getstate__() def __getnewargs__(self): return self.args def __getstate__(self): return {} def __setstate__(self, state): for k, v in state.items(): setattr(self, k, v) def __hash__(self): # hash cannot be cached using cache_it because infinite recurrence # occurs as hash is needed for setting cache dictionary keys h = self._mhash if h is None: h = hash((type(self).__name__,) + self._hashable_content()) self._mhash = h return h def _hashable_content(self): """Return a tuple of information about self that can be used to compute the hash. If a class defines additional attributes, like ``name`` in Symbol, then this method should be updated accordingly to return such relevant attributes. Defining more than _hashable_content is necessary if __eq__ has been defined by a class. See note about this in Basic.__eq__.""" return self._args @property def assumptions0(self): """ Return object `type` assumptions. For example: Symbol('x', real=True) Symbol('x', integer=True) are different objects. In other words, besides Python type (Symbol in this case), the initial assumptions are also forming their typeinfo. Examples ======== >>> from sympy import Symbol >>> from sympy.abc import x >>> x.assumptions0 {'commutative': True} >>> x = Symbol("x", positive=True) >>> x.assumptions0 {'commutative': True, 'complex': True, 'hermitian': True, 'imaginary': False, 'negative': False, 'nonnegative': True, 'nonpositive': False, 'nonzero': True, 'positive': True, 'real': True, 'zero': False} """ return {} def compare(self, other): """ Return -1, 0, 1 if the object is smaller, equal, or greater than other. Not in the mathematical sense. If the object is of a different type from the "other" then their classes are ordered according to the sorted_classes list. Examples ======== >>> from sympy.abc import x, y >>> x.compare(y) -1 >>> x.compare(x) 0 >>> y.compare(x) 1 """ # all redefinitions of __cmp__ method should start with the # following lines: if self is other: return 0 n1 = self.__class__ n2 = other.__class__ c = (n1 > n2) - (n1 < n2) if c: return c # st = self._hashable_content() ot = other._hashable_content() c = (len(st) > len(ot)) - (len(st) < len(ot)) if c: return c for l, r in zip(st, ot): l = Basic(*l) if isinstance(l, frozenset) else l r = Basic(*r) if isinstance(r, frozenset) else r if isinstance(l, Basic): c = l.compare(r) else: c = (l > r) - (l < r) if c: return c return 0 @staticmethod def _compare_pretty(a, b): from sympy.series.order import Order if isinstance(a, Order) and not isinstance(b, Order): return 1 if not isinstance(a, Order) and isinstance(b, Order): return -1 if a.is_Rational and b.is_Rational: l = a.p * b.q r = b.p * a.q return (l > r) - (l < r) else: from sympy.core.symbol import Wild p1, p2, p3 = Wild("p1"), Wild("p2"), Wild("p3") r_a = a.match(p1 * p2**p3) if r_a and p3 in r_a: a3 = r_a[p3] r_b = b.match(p1 * p2**p3) if r_b and p3 in r_b: b3 = r_b[p3] c = Basic.compare(a3, b3) if c != 0: return c return Basic.compare(a, b) @classmethod def fromiter(cls, args, **assumptions): """ Create a new object from an iterable. This is a convenience function that allows one to create objects from any iterable, without having to convert to a list or tuple first. Examples ======== >>> from sympy import Tuple >>> Tuple.fromiter(i for i in range(5)) (0, 1, 2, 3, 4) """ return cls(*tuple(args), **assumptions) @classmethod def class_key(cls): """Nice order of classes. """ return 5, 0, cls.__name__ @cacheit def sort_key(self, order=None): """ Return a sort key. Examples ======== >>> from sympy.core import S, I >>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key()) [1/2, -I, I] >>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]") [x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)] >>> sorted(_, key=lambda x: x.sort_key()) [x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2] """ # XXX: remove this when issue 5169 is fixed def inner_key(arg): if isinstance(arg, Basic): return arg.sort_key(order) else: return arg args = self._sorted_args args = len(args), tuple([inner_key(arg) for arg in args]) return self.class_key(), args, S.One.sort_key(), S.One def __eq__(self, other): """Return a boolean indicating whether a == b on the basis of their symbolic trees. This is the same as a.compare(b) == 0 but faster. Notes ===== If a class that overrides __eq__() needs to retain the implementation of __hash__() from a parent class, the interpreter must be told this explicitly by setting __hash__ = <ParentClass>.__hash__. Otherwise the inheritance of __hash__() will be blocked, just as if __hash__ had been explicitly set to None. References ========== from http://docs.python.org/dev/reference/datamodel.html#object.__hash__ """ from sympy import Pow if self is other: return True from .function import AppliedUndef, UndefinedFunction as UndefFunc if isinstance(self, UndefFunc) and isinstance(other, UndefFunc): if self.class_key() == other.class_key(): return True else: return False if type(self) is not type(other): # issue 6100 a**1.0 == a like a**2.0 == a**2 if isinstance(self, Pow) and self.exp == 1: return self.base == other if isinstance(other, Pow) and other.exp == 1: return self == other.base try: other = _sympify(other) except SympifyError: return False # sympy != other if isinstance(self, AppliedUndef) and isinstance(other, AppliedUndef): if self.class_key() != other.class_key(): return False elif type(self) is not type(other): return False return self._hashable_content() == other._hashable_content() def __ne__(self, other): """a != b -> Compare two symbolic trees and see whether they are different this is the same as: a.compare(b) != 0 but faster """ return not self.__eq__(other) def dummy_eq(self, other, symbol=None): """ Compare two expressions and handle dummy symbols. Examples ======== >>> from sympy import Dummy >>> from sympy.abc import x, y >>> u = Dummy('u') >>> (u**2 + 1).dummy_eq(x**2 + 1) True >>> (u**2 + 1) == (x**2 + 1) False >>> (u**2 + y).dummy_eq(x**2 + y, x) True >>> (u**2 + y).dummy_eq(x**2 + y, y) False """ dummy_symbols = [s for s in self.free_symbols if s.is_Dummy] if not dummy_symbols: return self == other elif len(dummy_symbols) == 1: dummy = dummy_symbols.pop() else: raise ValueError( "only one dummy symbol allowed on the left-hand side") if symbol is None: symbols = other.free_symbols if not symbols: return self == other elif len(symbols) == 1: symbol = symbols.pop() else: raise ValueError("specify a symbol in which expressions should be compared") tmp = dummy.__class__() return self.subs(dummy, tmp) == other.subs(symbol, tmp) # Note, we always use the default ordering (lex) in __str__ and __repr__, # regardless of the global setting. See issue 5487. def __repr__(self): from sympy.printing import sstr return sstr(self, order=None) def __str__(self): from sympy.printing import sstr return sstr(self, order=None) def atoms(self, *types): """Returns the atoms that form the current object. By default, only objects that are truly atomic and can't be divided into smaller pieces are returned: symbols, numbers, and number symbols like I and pi. It is possible to request atoms of any type, however, as demonstrated below. Examples ======== >>> from sympy import I, pi, sin >>> from sympy.abc import x, y >>> (1 + x + 2*sin(y + I*pi)).atoms() set([1, 2, I, pi, x, y]) If one or more types are given, the results will contain only those types of atoms. Examples ======== >>> from sympy import Number, NumberSymbol, Symbol >>> (1 + x + 2*sin(y + I*pi)).atoms(Symbol) set([x, y]) >>> (1 + x + 2*sin(y + I*pi)).atoms(Number) set([1, 2]) >>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol) set([1, 2, pi]) >>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol, I) set([1, 2, I, pi]) Note that I (imaginary unit) and zoo (complex infinity) are special types of number symbols and are not part of the NumberSymbol class. The type can be given implicitly, too: >>> (1 + x + 2*sin(y + I*pi)).atoms(x) # x is a Symbol set([x, y]) Be careful to check your assumptions when using the implicit option since ``S(1).is_Integer = True`` but ``type(S(1))`` is ``One``, a special type of sympy atom, while ``type(S(2))`` is type ``Integer`` and will find all integers in an expression: >>> from sympy import S >>> (1 + x + 2*sin(y + I*pi)).atoms(S(1)) set([1]) >>> (1 + x + 2*sin(y + I*pi)).atoms(S(2)) set([1, 2]) Finally, arguments to atoms() can select more than atomic atoms: any sympy type (loaded in core/__init__.py) can be listed as an argument and those types of "atoms" as found in scanning the arguments of the expression recursively: >>> from sympy import Function, Mul >>> from sympy.core.function import AppliedUndef >>> f = Function('f') >>> (1 + f(x) + 2*sin(y + I*pi)).atoms(Function) set([f(x), sin(y + I*pi)]) >>> (1 + f(x) + 2*sin(y + I*pi)).atoms(AppliedUndef) set([f(x)]) >>> (1 + x + 2*sin(y + I*pi)).atoms(Mul) set([I*pi, 2*sin(y + I*pi)]) """ if types: types = tuple( [t if isinstance(t, type) else type(t) for t in types]) else: types = (Atom,) result = set() for expr in preorder_traversal(self): if isinstance(expr, types): result.add(expr) return result @property def free_symbols(self): """Return from the atoms of self those which are free symbols. For most expressions, all symbols are free symbols. For some classes this is not true. e.g. Integrals use Symbols for the dummy variables which are bound variables, so Integral has a method to return all symbols except those. Derivative keeps track of symbols with respect to which it will perform a derivative; those are bound variables, too, so it has its own free_symbols method. Any other method that uses bound variables should implement a free_symbols method.""" return set().union(*[a.free_symbols for a in self.args]) @property def canonical_variables(self): """Return a dictionary mapping any variable defined in ``self.variables`` as underscore-suffixed numbers corresponding to their position in ``self.variables``. Enough underscores are added to ensure that there will be no clash with existing free symbols. Examples ======== >>> from sympy import Lambda >>> from sympy.abc import x >>> Lambda(x, 2*x).canonical_variables {x: 0_} """ from sympy import Symbol if not hasattr(self, 'variables'): return {} u = "_" while any(s.name.endswith(u) for s in self.free_symbols): u += "_" name = '%%i%s' % u V = self.variables return dict(list(zip(V, [Symbol(name % i, **v.assumptions0) for i, v in enumerate(V)]))) def rcall(self, *args): """Apply on the argument recursively through the expression tree. This method is used to simulate a common abuse of notation for operators. For instance in SymPy the the following will not work: ``(x+Lambda(y, 2*y))(z) == x+2*z``, however you can use >>> from sympy import Lambda >>> from sympy.abc import x, y, z >>> (x + Lambda(y, 2*y)).rcall(z) x + 2*z """ return Basic._recursive_call(self, args) @staticmethod def _recursive_call(expr_to_call, on_args): from sympy import Symbol def the_call_method_is_overridden(expr): for cls in getmro(type(expr)): if '__call__' in cls.__dict__: return cls != Basic if callable(expr_to_call) and the_call_method_is_overridden(expr_to_call): if isinstance(expr_to_call, Symbol): # XXX When you call a Symbol it is return expr_to_call # transformed into an UndefFunction else: return expr_to_call(*on_args) elif expr_to_call.args: args = [Basic._recursive_call( sub, on_args) for sub in expr_to_call.args] return type(expr_to_call)(*args) else: return expr_to_call def is_hypergeometric(self, k): from sympy.simplify import hypersimp return hypersimp(self, k) is not None @property def is_comparable(self): """Return True if self can be computed to a real number (or already is a real number) with precision, else False. Examples ======== >>> from sympy import exp_polar, pi, I >>> (I*exp_polar(I*pi/2)).is_comparable True >>> (I*exp_polar(I*pi*2)).is_comparable False A False result does not mean that `self` cannot be rewritten into a form that would be comparable. For example, the difference computed below is zero but without simplification it does not evaluate to a zero with precision: >>> e = 2**pi*(1 + 2**pi) >>> dif = e - e.expand() >>> dif.is_comparable False >>> dif.n(2)._prec 1 """ is_real = self.is_real if is_real is False: return False is_number = self.is_number if is_number is False: return False n, i = [p.evalf(2) if not p.is_Number else p for p in self.as_real_imag()] if not i.is_Number or not n.is_Number: return False if i: # if _prec = 1 we can't decide and if not, # the answer is False because numbers with # imaginary parts can't be compared # so return False return False else: return n._prec != 1 @property def func(self): """ The top-level function in an expression. The following should hold for all objects:: >> x == x.func(*x.args) Examples ======== >>> from sympy.abc import x >>> a = 2*x >>> a.func <class 'sympy.core.mul.Mul'> >>> a.args (2, x) >>> a.func(*a.args) 2*x >>> a == a.func(*a.args) True """ return self.__class__ @property def args(self): """Returns a tuple of arguments of 'self'. Examples ======== >>> from sympy import cot >>> from sympy.abc import x, y >>> cot(x).args (x,) >>> cot(x).args[0] x >>> (x*y).args (x, y) >>> (x*y).args[1] y Notes ===== Never use self._args, always use self.args. Only use _args in __new__ when creating a new function. Don't override .args() from Basic (so that it's easy to change the interface in the future if needed). """ return self._args @property def _sorted_args(self): """ The same as ``args``. Derived classes which don't fix an order on their arguments should override this method to produce the sorted representation. """ return self.args def as_poly(self, *gens, **args): """Converts ``self`` to a polynomial or returns ``None``. >>> from sympy import sin >>> from sympy.abc import x, y >>> print((x**2 + x*y).as_poly()) Poly(x**2 + x*y, x, y, domain='ZZ') >>> print((x**2 + x*y).as_poly(x, y)) Poly(x**2 + x*y, x, y, domain='ZZ') >>> print((x**2 + sin(y)).as_poly(x, y)) None """ from sympy.polys import Poly, PolynomialError try: poly = Poly(self, *gens, **args) if not poly.is_Poly: return None else: return poly except PolynomialError: return None def as_content_primitive(self, radical=False, clear=True): """A stub to allow Basic args (like Tuple) to be skipped when computing the content and primitive components of an expression. See docstring of Expr.as_content_primitive """ return S.One, self def subs(self, *args, **kwargs): """ Substitutes old for new in an expression after sympifying args. `args` is either: - two arguments, e.g. foo.subs(old, new) - one iterable argument, e.g. foo.subs(iterable). The iterable may be o an iterable container with (old, new) pairs. In this case the replacements are processed in the order given with successive patterns possibly affecting replacements already made. o a dict or set whose key/value items correspond to old/new pairs. In this case the old/new pairs will be sorted by op count and in case of a tie, by number of args and the default_sort_key. The resulting sorted list is then processed as an iterable container (see previous). If the keyword ``simultaneous`` is True, the subexpressions will not be evaluated until all the substitutions have been made. Examples ======== >>> from sympy import pi, exp, limit, oo >>> from sympy.abc import x, y >>> (1 + x*y).subs(x, pi) pi*y + 1 >>> (1 + x*y).subs({x:pi, y:2}) 1 + 2*pi >>> (1 + x*y).subs([(x, pi), (y, 2)]) 1 + 2*pi >>> reps = [(y, x**2), (x, 2)] >>> (x + y).subs(reps) 6 >>> (x + y).subs(reversed(reps)) x**2 + 2 >>> (x**2 + x**4).subs(x**2, y) y**2 + y To replace only the x**2 but not the x**4, use xreplace: >>> (x**2 + x**4).xreplace({x**2: y}) x**4 + y To delay evaluation until all substitutions have been made, set the keyword ``simultaneous`` to True: >>> (x/y).subs([(x, 0), (y, 0)]) 0 >>> (x/y).subs([(x, 0), (y, 0)], simultaneous=True) nan This has the added feature of not allowing subsequent substitutions to affect those already made: >>> ((x + y)/y).subs({x + y: y, y: x + y}) 1 >>> ((x + y)/y).subs({x + y: y, y: x + y}, simultaneous=True) y/(x + y) In order to obtain a canonical result, unordered iterables are sorted by count_op length, number of arguments and by the default_sort_key to break any ties. All other iterables are left unsorted. >>> from sympy import sqrt, sin, cos >>> from sympy.abc import a, b, c, d, e >>> A = (sqrt(sin(2*x)), a) >>> B = (sin(2*x), b) >>> C = (cos(2*x), c) >>> D = (x, d) >>> E = (exp(x), e) >>> expr = sqrt(sin(2*x))*sin(exp(x)*x)*cos(2*x) + sin(2*x) >>> expr.subs(dict([A, B, C, D, E])) a*c*sin(d*e) + b The resulting expression represents a literal replacement of the old arguments with the new arguments. This may not reflect the limiting behavior of the expression: >>> (x**3 - 3*x).subs({x: oo}) nan >>> limit(x**3 - 3*x, x, oo) oo If the substitution will be followed by numerical evaluation, it is better to pass the substitution to evalf as >>> (1/x).evalf(subs={x: 3.0}, n=21) 0.333333333333333333333 rather than >>> (1/x).subs({x: 3.0}).evalf(21) 0.333333333333333314830 as the former will ensure that the desired level of precision is obtained. See Also ======== replace: replacement capable of doing wildcard-like matching, parsing of match, and conditional replacements xreplace: exact node replacement in expr tree; also capable of using matching rules evalf: calculates the given formula to a desired level of precision """ from sympy.core.containers import Dict from sympy.utilities import default_sort_key from sympy import Dummy, Symbol unordered = False if len(args) == 1: sequence = args[0] if isinstance(sequence, set): unordered = True elif isinstance(sequence, (Dict, dict)): unordered = True sequence = sequence.items() elif not iterable(sequence): from sympy.utilities.misc import filldedent raise ValueError(filldedent(""" When a single argument is passed to subs it should be a dictionary of old: new pairs or an iterable of (old, new) tuples.""")) elif len(args) == 2: sequence = [args] else: raise ValueError("subs accepts either 1 or 2 arguments") sequence = list(sequence) for i in range(len(sequence)): s = list(sequence[i]) for j, si in enumerate(s): try: si = sympify(si, strict=True) except SympifyError: if type(si) is str: si = Symbol(si) else: # if it can't be sympified, skip it sequence[i] = None break s[j] = si else: sequence[i] = None if _aresame(*s) else tuple(s) sequence = list(filter(None, sequence)) if unordered: sequence = dict(sequence) if not all(k.is_Atom for k in sequence): d = {} for o, n in sequence.items(): try: ops = o.count_ops(), len(o.args) except TypeError: ops = (0, 0) d.setdefault(ops, []).append((o, n)) newseq = [] for k in sorted(d.keys(), reverse=True): newseq.extend( sorted([v[0] for v in d[k]], key=default_sort_key)) sequence = [(k, sequence[k]) for k in newseq] del newseq, d else: sequence = sorted([(k, v) for (k, v) in sequence.items()], key=default_sort_key) if kwargs.pop('simultaneous', False): # XXX should this be the default for dict subs? reps = {} rv = self kwargs['hack2'] = True m = Dummy() for old, new in sequence: d = Dummy(commutative=new.is_commutative) # using d*m so Subs will be used on dummy variables # in things like Derivative(f(x, y), x) in which x # is both free and bound rv = rv._subs(old, d*m, **kwargs) if not isinstance(rv, Basic): break reps[d] = new reps[m] = S.One # get rid of m return rv.xreplace(reps) else: rv = self for old, new in sequence: rv = rv._subs(old, new, **kwargs) if not isinstance(rv, Basic): break return rv @cacheit def _subs(self, old, new, **hints): """Substitutes an expression old -> new. If self is not equal to old then _eval_subs is called. If _eval_subs doesn't want to make any special replacement then a None is received which indicates that the fallback should be applied wherein a search for replacements is made amongst the arguments of self. >>> from sympy import Add >>> from sympy.abc import x, y, z Examples ======== Add's _eval_subs knows how to target x + y in the following so it makes the change: >>> (x + y + z).subs(x + y, 1) z + 1 Add's _eval_subs doesn't need to know how to find x + y in the following: >>> Add._eval_subs(z*(x + y) + 3, x + y, 1) is None True The returned None will cause the fallback routine to traverse the args and pass the z*(x + y) arg to Mul where the change will take place and the substitution will succeed: >>> (z*(x + y) + 3).subs(x + y, 1) z + 3 ** Developers Notes ** An _eval_subs routine for a class should be written if: 1) any arguments are not instances of Basic (e.g. bool, tuple); 2) some arguments should not be targeted (as in integration variables); 3) if there is something other than a literal replacement that should be attempted (as in Piecewise where the condition may be updated without doing a replacement). If it is overridden, here are some special cases that might arise: 1) If it turns out that no special change was made and all the original sub-arguments should be checked for replacements then None should be returned. 2) If it is necessary to do substitutions on a portion of the expression then _subs should be called. _subs will handle the case of any sub-expression being equal to old (which usually would not be the case) while its fallback will handle the recursion into the sub-arguments. For example, after Add's _eval_subs removes some matching terms it must process the remaining terms so it calls _subs on each of the un-matched terms and then adds them onto the terms previously obtained. 3) If the initial expression should remain unchanged then the original expression should be returned. (Whenever an expression is returned, modified or not, no further substitution of old -> new is attempted.) Sum's _eval_subs routine uses this strategy when a substitution is attempted on any of its summation variables. """ def fallback(self, old, new): """ Try to replace old with new in any of self's arguments. """ hit = False args = list(self.args) for i, arg in enumerate(args): if not hasattr(arg, '_eval_subs'): continue arg = arg._subs(old, new, **hints) if not _aresame(arg, args[i]): hit = True args[i] = arg if hit: rv = self.func(*args) hack2 = hints.get('hack2', False) if hack2 and self.is_Mul and not rv.is_Mul: # 2-arg hack coeff = S.One nonnumber = [] for i in args: if i.is_Number: coeff *= i else: nonnumber.append(i) nonnumber = self.func(*nonnumber) if coeff is S.One: return nonnumber else: return self.func(coeff, nonnumber, evaluate=False) return rv return self if _aresame(self, old): return new rv = self._eval_subs(old, new) if rv is None: rv = fallback(self, old, new) return rv def _eval_subs(self, old, new): """Override this stub if you want to do anything more than attempt a replacement of old with new in the arguments of self. See also: _subs """ return None def xreplace(self, rule): """ Replace occurrences of objects within the expression. Parameters ========== rule : dict-like Expresses a replacement rule Returns ======= xreplace : the result of the replacement Examples ======== >>> from sympy import symbols, pi, exp >>> x, y, z = symbols('x y z') >>> (1 + x*y).xreplace({x: pi}) pi*y + 1 >>> (1 + x*y).xreplace({x: pi, y: 2}) 1 + 2*pi Replacements occur only if an entire node in the expression tree is matched: >>> (x*y + z).xreplace({x*y: pi}) z + pi >>> (x*y*z).xreplace({x*y: pi}) x*y*z >>> (2*x).xreplace({2*x: y, x: z}) y >>> (2*2*x).xreplace({2*x: y, x: z}) 4*z >>> (x + y + 2).xreplace({x + y: 2}) x + y + 2 >>> (x + 2 + exp(x + 2)).xreplace({x + 2: y}) x + exp(y) + 2 xreplace doesn't differentiate between free and bound symbols. In the following, subs(x, y) would not change x since it is a bound symbol, but xreplace does: >>> from sympy import Integral >>> Integral(x, (x, 1, 2*x)).xreplace({x: y}) Integral(y, (y, 1, 2*y)) Trying to replace x with an expression raises an error: >>> Integral(x, (x, 1, 2*x)).xreplace({x: 2*y}) # doctest: +SKIP ValueError: Invalid limits given: ((2*y, 1, 4*y),) See Also ======== replace: replacement capable of doing wildcard-like matching, parsing of match, and conditional replacements subs: substitution of subexpressions as defined by the objects themselves. """ value, _ = self._xreplace(rule) return value def _xreplace(self, rule): """ Helper for xreplace. Tracks whether a replacement actually occurred. """ if self in rule: return rule[self], True elif rule: args = [] changed = False for a in self.args: try: a_xr = a._xreplace(rule) args.append(a_xr[0]) changed |= a_xr[1] except AttributeError: args.append(a) args = tuple(args) if changed: return self.func(*args), True return self, False @cacheit def has(self, *patterns): """ Test whether any subexpression matches any of the patterns. Examples ======== >>> from sympy import sin >>> from sympy.abc import x, y, z >>> (x**2 + sin(x*y)).has(z) False >>> (x**2 + sin(x*y)).has(x, y, z) True >>> x.has(x) True Note that ``expr.has(*patterns)`` is exactly equivalent to ``any(expr.has(p) for p in patterns)``. In particular, ``False`` is returned when the list of patterns is empty. >>> x.has() False """ return any(self._has(pattern) for pattern in patterns) def _has(self, pattern): """Helper for .has()""" from sympy.core.function import UndefinedFunction, Function if isinstance(pattern, UndefinedFunction): return any(f.func == pattern or f == pattern for f in self.atoms(Function, UndefinedFunction)) pattern = sympify(pattern) if isinstance(pattern, BasicMeta): return any(isinstance(arg, pattern) for arg in preorder_traversal(self)) try: match = pattern._has_matcher() return any(match(arg) for arg in preorder_traversal(self)) except AttributeError: return any(arg == pattern for arg in preorder_traversal(self)) def _has_matcher(self): """Helper for .has()""" return self.__eq__ def replace(self, query, value, map=False, simultaneous=True, exact=False): """ Replace matching subexpressions of ``self`` with ``value``. If ``map = True`` then also return the mapping {old: new} where ``old`` was a sub-expression found with query and ``new`` is the replacement value for it. If the expression itself doesn't match the query, then the returned value will be ``self.xreplace(map)`` otherwise it should be ``self.subs(ordered(map.items()))``. Traverses an expression tree and performs replacement of matching subexpressions from the bottom to the top of the tree. The default approach is to do the replacement in a simultaneous fashion so changes made are targeted only once. If this is not desired or causes problems, ``simultaneous`` can be set to False. In addition, if an expression containing more than one Wild symbol is being used to match subexpressions and the ``exact`` flag is True, then the match will only succeed if non-zero values are received for each Wild that appears in the match pattern. The list of possible combinations of queries and replacement values is listed below: Examples ======== Initial setup >>> from sympy import log, sin, cos, tan, Wild, Mul, Add >>> from sympy.abc import x, y >>> f = log(sin(x)) + tan(sin(x**2)) 1.1. type -> type obj.replace(type, newtype) When object of type ``type`` is found, replace it with the result of passing its argument(s) to ``newtype``. >>> f.replace(sin, cos) log(cos(x)) + tan(cos(x**2)) >>> sin(x).replace(sin, cos, map=True) (cos(x), {sin(x): cos(x)}) >>> (x*y).replace(Mul, Add) x + y 1.2. type -> func obj.replace(type, func) When object of type ``type`` is found, apply ``func`` to its argument(s). ``func`` must be written to handle the number of arguments of ``type``. >>> f.replace(sin, lambda arg: sin(2*arg)) log(sin(2*x)) + tan(sin(2*x**2)) >>> (x*y).replace(Mul, lambda *args: sin(2*Mul(*args))) sin(2*x*y) 2.1. pattern -> expr obj.replace(pattern(wild), expr(wild)) Replace subexpressions matching ``pattern`` with the expression written in terms of the Wild symbols in ``pattern``. >>> a = Wild('a') >>> f.replace(sin(a), tan(a)) log(tan(x)) + tan(tan(x**2)) >>> f.replace(sin(a), tan(a/2)) log(tan(x/2)) + tan(tan(x**2/2)) >>> f.replace(sin(a), a) log(x) + tan(x**2) >>> (x*y).replace(a*x, a) y When the default value of False is used with patterns that have more than one Wild symbol, non-intuitive results may be obtained: >>> b = Wild('b') >>> (2*x).replace(a*x + b, b - a) 2/x For this reason, the ``exact`` option can be used to make the replacement only when the match gives non-zero values for all Wild symbols: >>> (2*x + y).replace(a*x + b, b - a, exact=True) y - 2 >>> (2*x).replace(a*x + b, b - a, exact=True) 2*x 2.2. pattern -> func obj.replace(pattern(wild), lambda wild: expr(wild)) All behavior is the same as in 2.1 but now a function in terms of pattern variables is used rather than an expression: >>> f.replace(sin(a), lambda a: sin(2*a)) log(sin(2*x)) + tan(sin(2*x**2)) 3.1. func -> func obj.replace(filter, func) Replace subexpression ``e`` with ``func(e)`` if ``filter(e)`` is True. >>> g = 2*sin(x**3) >>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2) 4*sin(x**9) The expression itself is also targeted by the query but is done in such a fashion that changes are not made twice. >>> e = x*(x*y + 1) >>> e.replace(lambda x: x.is_Mul, lambda x: 2*x) 2*x*(2*x*y + 1) See Also ======== subs: substitution of subexpressions as defined by the objects themselves. xreplace: exact node replacement in expr tree; also capable of using matching rules """ from sympy.core.symbol import Dummy from sympy.simplify.simplify import bottom_up try: query = sympify(query) except SympifyError: pass try: value = sympify(value) except SympifyError: pass if isinstance(query, type): _query = lambda expr: isinstance(expr, query) if isinstance(value, type): _value = lambda expr, result: value(*expr.args) elif callable(value): _value = lambda expr, result: value(*expr.args) else: raise TypeError( "given a type, replace() expects another " "type or a callable") elif isinstance(query, Basic): _query = lambda expr: expr.match(query) # XXX remove the exact flag and make multi-symbol # patterns use exact=True semantics; to do this the query must # be tested to find out how many Wild symbols are present. # See https://groups.google.com/forum/ # ?fromgroups=#!topic/sympy/zPzo5FtRiqI # for a method of inspecting a function to know how many # parameters it has. if isinstance(value, Basic): if exact: _value = lambda expr, result: (value.subs(result) if all(val for val in result.values()) else expr) else: _value = lambda expr, result: value.subs(result) elif callable(value): # match dictionary keys get the trailing underscore stripped # from them and are then passed as keywords to the callable; # if ``exact`` is True, only accept match if there are no null # values amongst those matched. if exact: _value = lambda expr, result: (value(**dict([( str(key)[:-1], val) for key, val in result.items()])) if all(val for val in result.values()) else expr) else: _value = lambda expr, result: value(**dict([( str(key)[:-1], val) for key, val in result.items()])) else: raise TypeError( "given an expression, replace() expects " "another expression or a callable") elif callable(query): _query = query if callable(value): _value = lambda expr, result: value(expr) else: raise TypeError( "given a callable, replace() expects " "another callable") else: raise TypeError( "first argument to replace() must be a " "type, an expression or a callable") mapping = {} # changes that took place mask = [] # the dummies that were used as change placeholders def rec_replace(expr): result = _query(expr) if result or result == {}: new = _value(expr, result) if new is not None and new != expr: mapping[expr] = new if simultaneous: # don't let this expression be changed during rebuilding com = getattr(new, 'is_commutative', True) if com is None: com = True d = Dummy(commutative=com) mask.append((d, new)) expr = d else: expr = new return expr rv = bottom_up(self, rec_replace, atoms=True) # restore original expressions for Dummy symbols if simultaneous: mask = list(reversed(mask)) for o, n in mask: r = {o: n} rv = rv.xreplace(r) if not map: return rv else: if simultaneous: # restore subexpressions in mapping for o, n in mask: r = {o: n} mapping = dict([(k.xreplace(r), v.xreplace(r)) for k, v in mapping.items()]) return rv, mapping def find(self, query, group=False): """Find all subexpressions matching a query. """ query = _make_find_query(query) results = list(filter(query, preorder_traversal(self))) if not group: return set(results) else: groups = {} for result in results: if result in groups: groups[result] += 1 else: groups[result] = 1 return groups def count(self, query): """Count the number of matching subexpressions. """ query = _make_find_query(query) return sum(bool(query(sub)) for sub in preorder_traversal(self)) def matches(self, expr, repl_dict={}, old=False): """ Helper method for match() that looks for a match between Wild symbols in self and expressions in expr. Examples ======== >>> from sympy import symbols, Wild, Basic >>> a, b, c = symbols('a b c') >>> x = Wild('x') >>> Basic(a + x, x).matches(Basic(a + b, c)) is None True >>> Basic(a + x, x).matches(Basic(a + b + c, b + c)) {x_: b + c} """ expr = sympify(expr) if not isinstance(expr, self.__class__): return None if self == expr: return repl_dict if len(self.args) != len(expr.args): return None d = repl_dict.copy() for arg, other_arg in zip(self.args, expr.args): if arg == other_arg: continue d = arg.xreplace(d).matches(other_arg, d, old=old) if d is None: return None return d def match(self, pattern, old=False): """ Pattern matching. Wild symbols match all. Return ``None`` when expression (self) does not match with pattern. Otherwise return a dictionary such that:: pattern.xreplace(self.match(pattern)) == self Examples ======== >>> from sympy import Wild >>> from sympy.abc import x, y >>> p = Wild("p") >>> q = Wild("q") >>> r = Wild("r") >>> e = (x+y)**(x+y) >>> e.match(p**p) {p_: x + y} >>> e.match(p**q) {p_: x + y, q_: x + y} >>> e = (2*x)**2 >>> e.match(p*q**r) {p_: 4, q_: x, r_: 2} >>> (p*q**r).xreplace(e.match(p*q**r)) 4*x**2 The ``old`` flag will give the old-style pattern matching where expressions and patterns are essentially solved to give the match. Both of the following give None unless ``old=True``: >>> (x - 2).match(p - x, old=True) {p_: 2*x - 2} >>> (2/x).match(p*x, old=True) {p_: 2/x**2} """ pattern = sympify(pattern) return pattern.matches(self, old=old) def count_ops(self, visual=None): """wrapper for count_ops that returns the operation count.""" from sympy import count_ops return count_ops(self, visual) def doit(self, **hints): """Evaluate objects that are not evaluated by default like limits, integrals, sums and products. All objects of this kind will be evaluated recursively, unless some species were excluded via 'hints' or unless the 'deep' hint was set to 'False'. >>> from sympy import Integral >>> from sympy.abc import x >>> 2*Integral(x, x) 2*Integral(x, x) >>> (2*Integral(x, x)).doit() x**2 >>> (2*Integral(x, x)).doit(deep=False) 2*Integral(x, x) """ if hints.get('deep', True): terms = [term.doit(**hints) if isinstance(term, Basic) else term for term in self.args] return self.func(*terms) else: return self def _eval_rewrite(self, pattern, rule, **hints): if self.is_Atom: if hasattr(self, rule): return getattr(self, rule)() return self if hints.get('deep', True): args = [a._eval_rewrite(pattern, rule, **hints) if isinstance(a, Basic) else a for a in self.args] else: args = self.args if pattern is None or isinstance(self.func, pattern): if hasattr(self, rule): rewritten = getattr(self, rule)(*args) if rewritten is not None: return rewritten return self.func(*args) def rewrite(self, *args, **hints): """ Rewrite functions in terms of other functions. Rewrites expression containing applications of functions of one kind in terms of functions of different kind. For example you can rewrite trigonometric functions as complex exponentials or combinatorial functions as gamma function. As a pattern this function accepts a list of functions to to rewrite (instances of DefinedFunction class). As rule you can use string or a destination function instance (in this case rewrite() will use the str() function). There is also the possibility to pass hints on how to rewrite the given expressions. For now there is only one such hint defined called 'deep'. When 'deep' is set to False it will forbid functions to rewrite their contents. Examples ======== >>> from sympy import sin, exp >>> from sympy.abc import x Unspecified pattern: >>> sin(x).rewrite(exp) -I*(exp(I*x) - exp(-I*x))/2 Pattern as a single function: >>> sin(x).rewrite(sin, exp) -I*(exp(I*x) - exp(-I*x))/2 Pattern as a list of functions: >>> sin(x).rewrite([sin, ], exp) -I*(exp(I*x) - exp(-I*x))/2 """ if not args: return self else: pattern = args[:-1] if isinstance(args[-1], string_types): rule = '_eval_rewrite_as_' + args[-1] else: rule = '_eval_rewrite_as_' + args[-1].__name__ if not pattern: return self._eval_rewrite(None, rule, **hints) else: if iterable(pattern[0]): pattern = pattern[0] pattern = [p.__class__ for p in pattern if self.has(p)] if pattern: return self._eval_rewrite(tuple(pattern), rule, **hints) else: return self class Atom(Basic): """ A parent class for atomic things. An atom is an expression with no subexpressions. Examples ======== Symbol, Number, Rational, Integer, ... But not: Add, Mul, Pow, ... """ is_Atom = True __slots__ = [] def matches(self, expr, repl_dict={}, old=False): if self == expr: return repl_dict def xreplace(self, rule, hack2=False): return rule.get(self, self) def doit(self, **hints): return self @classmethod def class_key(cls): return 2, 0, cls.__name__ @cacheit def sort_key(self, order=None): return self.class_key(), (1, (str(self),)), S.One.sort_key(), S.One def _eval_simplify(self, ratio, measure): return self @property def _sorted_args(self): # this is here as a safeguard against accidentally using _sorted_args # on Atoms -- they cannot be rebuilt as atom.func(*atom._sorted_args) # since there are no args. So the calling routine should be checking # to see that this property is not called for Atoms. raise AttributeError('Atoms have no args. It might be necessary' ' to make a check for Atoms in the calling code.') def _aresame(a, b): """Return True if a and b are structurally the same, else False. Examples ======== To SymPy, 2.0 == 2: >>> from sympy import S >>> 2.0 == S(2) True Since a simple 'same or not' result is sometimes useful, this routine was written to provide that query: >>> from sympy.core.basic import _aresame >>> _aresame(S(2.0), S(2)) False """ from .function import AppliedUndef, UndefinedFunction as UndefFunc for i, j in zip_longest(preorder_traversal(a), preorder_traversal(b)): if i != j or type(i) != type(j): if ((isinstance(i, UndefFunc) and isinstance(j, UndefFunc)) or (isinstance(i, AppliedUndef) and isinstance(j, AppliedUndef))): if i.class_key() != j.class_key(): return False else: return False else: return True def _atomic(e): """Return atom-like quantities as far as substitution is<|fim▁hole|> Examples ======== >>> from sympy import Derivative, Function, cos >>> from sympy.abc import x, y >>> from sympy.core.basic import _atomic >>> f = Function('f') >>> _atomic(x + y) set([x, y]) >>> _atomic(x + f(y)) set([x, f(y)]) >>> _atomic(Derivative(f(x), x) + cos(x) + y) set([y, cos(x), Derivative(f(x), x)]) """ from sympy import Derivative, Function, Symbol pot = preorder_traversal(e) seen = set() try: free = e.free_symbols except AttributeError: return set([e]) atoms = set() for p in pot: if p in seen: pot.skip() continue seen.add(p) if isinstance(p, Symbol) and p in free: atoms.add(p) elif isinstance(p, (Derivative, Function)): pot.skip() atoms.add(p) return atoms class preorder_traversal(Iterator): """ Do a pre-order traversal of a tree. This iterator recursively yields nodes that it has visited in a pre-order fashion. That is, it yields the current node then descends through the tree breadth-first to yield all of a node's children's pre-order traversal. For an expression, the order of the traversal depends on the order of .args, which in many cases can be arbitrary. Parameters ========== node : sympy expression The expression to traverse. keys : (default None) sort key(s) The key(s) used to sort args of Basic objects. When None, args of Basic objects are processed in arbitrary order. If key is defined, it will be passed along to ordered() as the only key(s) to use to sort the arguments; if ``key`` is simply True then the default keys of ordered will be used. Yields ====== subtree : sympy expression All of the subtrees in the tree. Examples ======== >>> from sympy import symbols >>> from sympy.core.basic import preorder_traversal >>> x, y, z = symbols('x y z') The nodes are returned in the order that they are encountered unless key is given; simply passing key=True will guarantee that the traversal is unique. >>> list(preorder_traversal((x + y)*z, keys=None)) # doctest: +SKIP [z*(x + y), z, x + y, y, x] >>> list(preorder_traversal((x + y)*z, keys=True)) [z*(x + y), z, x + y, x, y] """ def __init__(self, node, keys=None): self._skip_flag = False self._pt = self._preorder_traversal(node, keys) def _preorder_traversal(self, node, keys): yield node if self._skip_flag: self._skip_flag = False return if isinstance(node, Basic): if not keys and hasattr(node, '_argset'): # LatticeOp keeps args as a set. We should use this if we # don't care about the order, to prevent unnecessary sorting. args = node._argset else: args = node.args if keys: if keys != True: args = ordered(args, keys, default=False) else: args = ordered(args) for arg in args: for subtree in self._preorder_traversal(arg, keys): yield subtree elif iterable(node): for item in node: for subtree in self._preorder_traversal(item, keys): yield subtree def skip(self): """ Skip yielding current node's (last yielded node's) subtrees. Examples ======== >>> from sympy.core import symbols >>> from sympy.core.basic import preorder_traversal >>> x, y, z = symbols('x y z') >>> pt = preorder_traversal((x+y*z)*z) >>> for i in pt: ... print(i) ... if i == x+y*z: ... pt.skip() z*(x + y*z) z x + y*z """ self._skip_flag = True def __next__(self): return next(self._pt) def __iter__(self): return self def _make_find_query(query): """Convert the argument of Basic.find() into a callable""" try: query = sympify(query) except SympifyError: pass if isinstance(query, type): return lambda expr: isinstance(expr, query) elif isinstance(query, Basic): return lambda expr: expr.match(query) is not None return query<|fim▁end|>
concerned: Derivatives, Functions and Symbols. Don't return any 'atoms' that are inside such quantities unless they also appear outside, too.
<|file_name|>ivy_jinja.py<|end_file_name|><|fim▁begin|># ------------------------------------------------------------------------------ # This extension adds support for Jinja templates. # ------------------------------------------------------------------------------ import sys from ivy import hooks, site, templates try: import jinja2 except ImportError: jinja2 = None # Stores an initialized Jinja environment instance. env = None # The jinja2 package is an optional dependency. if jinja2: # Initialize our Jinja environment on the 'init' event hook. @hooks.register('init') def init(): # Initialize a template loader. settings = { 'loader': jinja2.FileSystemLoader(site.theme('templates')) } # Check the site's config file for any custom settings. settings.update(site.config.get('jinja', {})) # Initialize an Environment instance. global env env = jinja2.Environment(**settings) # Register our template engine callback for files with a .jinja extension. @templates.register('jinja') def callback(page, filename): try: template = env.get_template(filename) return template.render(page) except jinja2.TemplateError as err:<|fim▁hole|> msg += " Jinja Template Error \n" msg += "------------------------\n\n" msg += " Template: %s\n" % filename msg += " Page: %s\n\n" % page['filepath'] msg += " %s: %s" % (err.__class__.__name__, err) if err.__context__: cause = err.__context__ msg += "\n\n The following cause was reported:\n\n" msg += " %s: %s" % (cause.__class__.__name__, cause) sys.exit(msg)<|fim▁end|>
msg = "------------------------\n"
<|file_name|>complex1.py<|end_file_name|><|fim▁begin|># test basic complex number functionality # constructor print(complex(1)) print(complex(1.2)) print(complex(1.2j)) print(complex("1")) print(complex("1.2")) print(complex("1.2j")) print(complex(1, 2)) print(complex(1j, 2j)) # unary ops print(bool(1j)) print(+(1j)) print(-(1 + 2j)) # binary ops print(1j + False) print(1j + True) print(1j + 2) print(1j + 2j) print(1j - 2) print(1j - 2j) print(1j * 2) print(1j * 2j) print(1j / 2) print((1j / 2j).real) print(1j / (1 + 2j)) ans = 0j ** 0; print("%.5g %.5g" % (ans.real, ans.imag)) ans = 0j ** 1; print("%.5g %.5g" % (ans.real, ans.imag)) ans = 0j ** 0j; print("%.5g %.5g" % (ans.real, ans.imag)) ans = 1j ** 2.5; print("%.5g %.5g" % (ans.real, ans.imag)) ans = 1j ** 2.5j; print("%.5g %.5g" % (ans.real, ans.imag)) # comparison print(1j == 1) print(1j == 1j) # comparison of nan is special nan = float('nan') * 1j print(nan == 1j) print(nan == nan) # builtin abs print(abs(1j)) print("%.5g" % abs(1j + 2)) # builtin hash print(hash(1 + 0j)) print(type(hash(1j))) # float on lhs should delegate to complex print(1.2 + 3j) # negative base and fractional power should create a complex ans = (-1) ** 2.3; print("%.5g %.5g" % (ans.real, ans.imag)) ans = (-1.2) ** -3.4; print("%.5g %.5g" % (ans.real, ans.imag)) # check printing of inf/nan print(float('nan') * 1j) print(float('-nan') * 1j) print(float('inf') * (1 + 1j)) print(float('-inf') * (1 + 1j)) # can't assign to attributes try: (1j).imag = 0 except AttributeError: print('AttributeError') # can't convert rhs to complex try: 1j + []<|fim▁hole|>try: ~(1j) except TypeError: print("TypeError") # unsupported binary op try: 1j // 2 except TypeError: print("TypeError") # unsupported binary op try: 1j < 2j except TypeError: print("TypeError") #small int on LHS, complex on RHS, unsupported op try: print(1 | 1j) except TypeError: print('TypeError') # zero division try: 1j / 0 except ZeroDivisionError: print("ZeroDivisionError") # zero division via power try: 0j ** -1 except ZeroDivisionError: print("ZeroDivisionError") try: 0j ** 1j except ZeroDivisionError: print("ZeroDivisionError")<|fim▁end|>
except TypeError: print("TypeError") # unsupported unary op
<|file_name|>queue.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding:UTF-8 __author__ = 'shenshijun' import copy class Queue(object): """ 使用Python的list快速实现一个队列 """ def __init__(self, *arg): super(Queue, self).__init__() self.__queue = list(copy.copy(arg)) self.__size = len(self.__queue) def enter(self, value): self.__size += 1 self.__queue.append(value)<|fim▁hole|> else: value = self.__queue[0] self.__size -= 1 del self.__queue[0] return value def __len__(self): return self.__size def empty(self): return self.__size <= 0 def __str__(self): return "".join(["Queue(list=", str(self.__queue), ",size=", str(self.__size)])<|fim▁end|>
def exit(self): if self.__size <= 0: return None
<|file_name|>inFuture.js<|end_file_name|><|fim▁begin|>export default function (value, opts) {<|fim▁hole|>}<|fim▁end|>
return value > Date.now() ? opts.fn(this) : '';
<|file_name|>test_notifications.py<|end_file_name|><|fim▁begin|># Copyright (c) 2012 OpenStack Foundation # 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. """Tests for common notifications.""" import copy from oslo.config import cfg from nova.compute import flavors from nova.compute import task_states from nova.compute import vm_states from nova import context from nova import db from nova.network import api as network_api from nova import notifications from nova import test from nova.tests import fake_network from nova.tests import fake_notifier CONF = cfg.CONF CONF.import_opt('compute_driver', 'nova.virt.driver') class NotificationsTestCase(test.TestCase): def setUp(self): super(NotificationsTestCase, self).setUp() self.net_info = fake_network.fake_get_instance_nw_info(self.stubs, 1, 1) def fake_get_nw_info(cls, ctxt, instance): self.assertTrue(ctxt.is_admin) return self.net_info self.stubs.Set(network_api.API, 'get_instance_nw_info', fake_get_nw_info) fake_network.set_stub_network_methods(self.stubs) fake_notifier.stub_notifier(self.stubs) self.addCleanup(fake_notifier.reset) self.flags(compute_driver='nova.virt.fake.FakeDriver', network_manager='nova.network.manager.FlatManager', notify_on_state_change="vm_and_task_state", host='testhost') self.user_id = 'fake' self.project_id = 'fake' self.context = context.RequestContext(self.user_id, self.project_id) self.instance = self._wrapped_create() def _wrapped_create(self, params=None): instance_type = flavors.get_flavor_by_name('m1.tiny') sys_meta = flavors.save_flavor_info({}, instance_type) inst = {} inst['image_ref'] = 1 inst['user_id'] = self.user_id inst['project_id'] = self.project_id inst['instance_type_id'] = instance_type['id'] inst['root_gb'] = 0 inst['ephemeral_gb'] = 0 inst['access_ip_v4'] = '1.2.3.4' inst['access_ip_v6'] = 'feed:5eed' inst['display_name'] = 'test_instance' inst['hostname'] = 'test_instance_hostname' inst['node'] = 'test_instance_node' inst['system_metadata'] = sys_meta<|fim▁hole|> if params: inst.update(params) return db.instance_create(self.context, inst) def test_send_api_fault_disabled(self): self.flags(notify_api_faults=False) notifications.send_api_fault("http://example.com/foo", 500, None) self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) def test_send_api_fault(self): self.flags(notify_api_faults=True) exception = None try: # Get a real exception with a call stack. raise test.TestingException("junk") except test.TestingException as e: exception = e notifications.send_api_fault("http://example.com/foo", 500, exception) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) n = fake_notifier.NOTIFICATIONS[0] self.assertEqual(n.priority, 'ERROR') self.assertEqual(n.event_type, 'api.fault') self.assertEqual(n.payload['url'], 'http://example.com/foo') self.assertEqual(n.payload['status'], 500) self.assertIsNotNone(n.payload['exception']) def test_notif_disabled(self): # test config disable of the notifications self.flags(notify_on_state_change=None) old = copy.copy(self.instance) self.instance["vm_state"] = vm_states.ACTIVE old_vm_state = old['vm_state'] new_vm_state = self.instance["vm_state"] old_task_state = old['task_state'] new_task_state = self.instance["task_state"] notifications.send_update_with_states(self.context, self.instance, old_vm_state, new_vm_state, old_task_state, new_task_state, verify_states=True) notifications.send_update(self.context, old, self.instance) self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) def test_task_notif(self): # test config disable of just the task state notifications self.flags(notify_on_state_change="vm_state") # we should not get a notification on task stgate chagne now old = copy.copy(self.instance) self.instance["task_state"] = task_states.SPAWNING old_vm_state = old['vm_state'] new_vm_state = self.instance["vm_state"] old_task_state = old['task_state'] new_task_state = self.instance["task_state"] notifications.send_update_with_states(self.context, self.instance, old_vm_state, new_vm_state, old_task_state, new_task_state, verify_states=True) self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) # ok now enable task state notifications and re-try self.flags(notify_on_state_change="vm_and_task_state") notifications.send_update(self.context, old, self.instance) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) def test_send_no_notif(self): # test notification on send no initial vm state: old_vm_state = self.instance['vm_state'] new_vm_state = self.instance['vm_state'] old_task_state = self.instance['task_state'] new_task_state = self.instance['task_state'] notifications.send_update_with_states(self.context, self.instance, old_vm_state, new_vm_state, old_task_state, new_task_state, service="compute", host=None, verify_states=True) self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) def test_send_on_vm_change(self): # pretend we just transitioned to ACTIVE: params = {"vm_state": vm_states.ACTIVE} (old_ref, new_ref) = db.instance_update_and_get_original(self.context, self.instance['uuid'], params) notifications.send_update(self.context, old_ref, new_ref) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) def test_send_on_task_change(self): # pretend we just transitioned to task SPAWNING: params = {"task_state": task_states.SPAWNING} (old_ref, new_ref) = db.instance_update_and_get_original(self.context, self.instance['uuid'], params) notifications.send_update(self.context, old_ref, new_ref) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) def test_no_update_with_states(self): notifications.send_update_with_states(self.context, self.instance, vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING, task_states.SPAWNING, verify_states=True) self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) def test_vm_update_with_states(self): notifications.send_update_with_states(self.context, self.instance, vm_states.BUILDING, vm_states.ACTIVE, task_states.SPAWNING, task_states.SPAWNING, verify_states=True) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) notif = fake_notifier.NOTIFICATIONS[0] payload = notif.payload access_ip_v4 = self.instance["access_ip_v4"] access_ip_v6 = self.instance["access_ip_v6"] display_name = self.instance["display_name"] hostname = self.instance["hostname"] node = self.instance["node"] self.assertEqual(vm_states.BUILDING, payload["old_state"]) self.assertEqual(vm_states.ACTIVE, payload["state"]) self.assertEqual(task_states.SPAWNING, payload["old_task_state"]) self.assertEqual(task_states.SPAWNING, payload["new_task_state"]) self.assertEqual(payload["access_ip_v4"], access_ip_v4) self.assertEqual(payload["access_ip_v6"], access_ip_v6) self.assertEqual(payload["display_name"], display_name) self.assertEqual(payload["hostname"], hostname) self.assertEqual(payload["node"], node) def test_task_update_with_states(self): self.flags(notify_on_state_change="vm_and_task_state") notifications.send_update_with_states(self.context, self.instance, vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING, None, verify_states=True) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) notif = fake_notifier.NOTIFICATIONS[0] payload = notif.payload access_ip_v4 = self.instance["access_ip_v4"] access_ip_v6 = self.instance["access_ip_v6"] display_name = self.instance["display_name"] hostname = self.instance["hostname"] self.assertEqual(vm_states.BUILDING, payload["old_state"]) self.assertEqual(vm_states.BUILDING, payload["state"]) self.assertEqual(task_states.SPAWNING, payload["old_task_state"]) self.assertIsNone(payload["new_task_state"]) self.assertEqual(payload["access_ip_v4"], access_ip_v4) self.assertEqual(payload["access_ip_v6"], access_ip_v6) self.assertEqual(payload["display_name"], display_name) self.assertEqual(payload["hostname"], hostname) def test_update_no_service_name(self): notifications.send_update_with_states(self.context, self.instance, vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING, None) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) # service name should default to 'compute' notif = fake_notifier.NOTIFICATIONS[0] self.assertEqual('compute.testhost', notif.publisher_id) def test_update_with_service_name(self): notifications.send_update_with_states(self.context, self.instance, vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING, None, service="testservice") self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) # service name should default to 'compute' notif = fake_notifier.NOTIFICATIONS[0] self.assertEqual('testservice.testhost', notif.publisher_id) def test_update_with_host_name(self): notifications.send_update_with_states(self.context, self.instance, vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING, None, host="someotherhost") self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) # service name should default to 'compute' notif = fake_notifier.NOTIFICATIONS[0] self.assertEqual('compute.someotherhost', notif.publisher_id) def test_payload_has_fixed_ip_labels(self): info = notifications.info_from_instance(self.context, self.instance, self.net_info, None) self.assertIn("fixed_ips", info) self.assertEqual(info["fixed_ips"][0]["label"], "test1") def test_send_access_ip_update(self): notifications.send_update(self.context, self.instance, self.instance) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) notif = fake_notifier.NOTIFICATIONS[0] payload = notif.payload access_ip_v4 = self.instance["access_ip_v4"] access_ip_v6 = self.instance["access_ip_v6"] self.assertEqual(payload["access_ip_v4"], access_ip_v4) self.assertEqual(payload["access_ip_v6"], access_ip_v6) def test_send_name_update(self): param = {"display_name": "new_display_name"} new_name_inst = self._wrapped_create(params=param) notifications.send_update(self.context, self.instance, new_name_inst) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) notif = fake_notifier.NOTIFICATIONS[0] payload = notif.payload old_display_name = self.instance["display_name"] new_display_name = new_name_inst["display_name"] self.assertEqual(payload["old_display_name"], old_display_name) self.assertEqual(payload["display_name"], new_display_name) def test_send_no_state_change(self): called = [False] def sending_no_state_change(context, instance, **kwargs): called[0] = True self.stubs.Set(notifications, '_send_instance_update_notification', sending_no_state_change) notifications.send_update(self.context, self.instance, self.instance) self.assertTrue(called[0]) def test_fail_sending_update(self): def fail_sending(context, instance, **kwargs): raise Exception('failed to notify') self.stubs.Set(notifications, '_send_instance_update_notification', fail_sending) notifications.send_update(self.context, self.instance, self.instance) self.assertEqual(0, len(fake_notifier.NOTIFICATIONS))<|fim▁end|>
<|file_name|>test_python_driver.py<|end_file_name|><|fim▁begin|>import io import json import os import subprocess import sys import unittest from os.path import join, abspath, dirname sys.path.append('..') from python_driver import __version__, get_processor_instance from python_driver.requestprocessor import ( Request, Response, RequestProcessorJSON, InBuffer, EmptyCodeException) from typing import Dict, Any, List, AnyStr, Optional, Iterator, cast CURDIR = abspath(dirname(__file__)) # Disabled until I update the new module with typing # class TestTypeCheck(unittest.TestCase): # def test_10_check(self) -> None: # prevdir = os.getcwd() # try: # os.chdir(dirname(CURDIR)) # srcdir = abspath(join(dirname(CURDIR), 'python_driver', '*')) # self.assertEqual(subprocess.call(['test/typecheck.sh', srcdir], shell=True), 0) # finally: # os.chdir(prevdir) class TestPythonDriverBase(unittest.TestCase): def _restart_data(self, format_: str='json') -> None: assert format_ == 'json' with open(join(CURDIR, 'data', 'helloworld.py')) as f: testcode = f.read() self.data = Request({ 'filepath': 'test.py', 'action': 'ParseAST', 'content': testcode, 'language': 'python', }) bufferclass = io.StringIO if format_ == 'json' else io.BytesIO # This will mock the python_driver stdin self.sendbuffer = bufferclass() # This will mock the python_driver stdout self.recvbuffer = bufferclass() @staticmethod def _extract_docs(inbuffer: InBuffer) -> Iterator[Response]: """ This generator will read the inbuffer yielding the JSON docs when it finds the ending mark """ line: str for line in inbuffer.readlines(): yield json.loads(line) def _loadResults(self, format_: str) -> List[Response]: """Read all msgs from the recvbuffer""" self.recvbuffer.seek(0) res: List[Response] = [] res = [doc for doc in self._extract_docs(self.recvbuffer)] return res class Test10ProcessRequestFunc(TestPythonDriverBase): def _add_to_buffer(self, count: int, format_: str) -> None: """Add count test msgs to the sendbuffer""" for i in range(count): msg = '' msg = json.dumps(self.data, ensure_ascii=False) + '\n' self.sendbuffer.write(msg) self.sendbuffer.flush() def _send_receive(self, nummsgs: int, outformat: str='json', dataupdate: Optional[Dict[AnyStr, Any]]=None, restart_data: bool=True) -> List[Response]: if restart_data: self._restart_data(outformat) if dataupdate: self.data.update(dataupdate) self._add_to_buffer(nummsgs, outformat) self.sendbuffer.seek(0) processor, _ = get_processor_instance( outformat, custom_outbuffer=self.recvbuffer, custom_inbuffer=self.sendbuffer ) processor.process_requests(self.sendbuffer) return self._loadResults(outformat) def _check_reply_dict(self, response: Response, has_errors: bool=False) -> None: self.assertIsInstance(response, dict) status = response.get('status') if has_errors: assert status in ('error', 'fatal') errors = response.get('errors', list) self.assertIsInstance(errors, list) self.assertGreater(len(errors), 0) else: self.assertEqual(status, 'ok') self._check_AST_dict(response) language_version = response['metadata'].get('language_version', -1) assert str(language_version) in ('2', '3') def _check_AST_dict(self, response: Response) -> None: self.assertIsNotNone(response) assert 'ast' in response self.assertIsInstance(response['ast'], dict) root_key = list(response['ast'].keys())[0] assert root_key for key in ('ast_type', 'body'): assert key in response['ast'][root_key]<|fim▁hole|> for item in response['ast'][root_key]['body']: for key in ('ast_type', 'lineno', 'col_offset'): assert key in item def test_010_normal_json(self) -> None: replies = self._send_receive(1, 'json') self.assertEqual(len(replies), 1) self._check_reply_dict(replies[0]) def test_020_normal_json_many(self) -> None: replies = self._send_receive(100, 'json') self.assertEqual(len(replies), 100) for reply in replies: self._check_reply_dict(reply) def test_030_error_print(self) -> None: wrongcode = 'wtf lol' replies = self._send_receive(1, 'json', {'content': wrongcode}) self.assertEqual(len(replies), 1) ast = replies[0].get('ast') self.assertIsNone(ast) self._check_reply_dict(replies[0], has_errors=True) # Check that it still alive self._restart_data() replies = self._send_receive(1, 'json') self.assertEqual(len(replies), 1) def test_040_broken_json(self) -> None: self._restart_data('json') brokendata = json.dumps(self.data, ensure_ascii=False)[:-30] self.sendbuffer.write(brokendata) self.sendbuffer.flush() reply = self._send_receive(1, 'json', restart_data=False)[0] self.assertEqual(reply['status'], 'fatal') self.assertEqual(len(reply['errors']), 1) class Test20ReqProcMethods(TestPythonDriverBase): def test_10_send_response_json(self) -> None: self._restart_data('json') processor = RequestProcessorJSON(self.recvbuffer) processor._send_response(cast(Response, self.data)) res = self._loadResults('json') self.assertEqual(len(res), 1) self.assertDictEqual(self.data, res[0]) # process request already tested with TestPythonDriverBase def test_20_return_error(self) -> None: self._restart_data('json') processor = RequestProcessorJSON(self.recvbuffer) processor.errors = ['test error'] processor._return_error('test.py', 'fatal') res = self._loadResults('json') self.assertEqual(len(res), 1) self.assertDictEqual(res[0] , {'driver': 'python23:%s' % __version__, 'errors': ['test error'], 'filepath': 'test.py', 'ast': None, 'status': 'fatal'}) if __name__ == '__main__': unittest.main()<|fim▁end|>
self.assertIsInstance(response['ast'][root_key]['body'], list)
<|file_name|>test_model_versioned_delete.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*- import pytest from django.utils import timezone from base.model_utils import BaseError from example_base.models import FruitCake from login.tests.factories import UserFactory from .factories import FruitCakeFactory @pytest.mark.django_db def test_factory(): FruitCakeFactory() @pytest.mark.django_db def test_str(): str(FruitCakeFactory()) @pytest.mark.django_db def test_set_deleted(): obj = FruitCakeFactory() assert 0 == obj.deleted_version user = UserFactory() FruitCake.objects.set_deleted(obj, user) obj.refresh_from_db() assert obj.deleted is True assert obj.user_deleted == user assert obj.date_deleted is not None assert 1 == obj.deleted_version @pytest.mark.django_db def test_set_deleted_multi(): user = UserFactory() c1 = FruitCakeFactory(number=19, description='c1') FruitCake.objects.set_deleted(c1, user) c2 = FruitCakeFactory(number=19, description='c2') FruitCake.objects.set_deleted(c2, user) FruitCakeFactory(number=19, description='c3') result = FruitCake.objects.filter(number=19).order_by('description') assert 3 == result.count() assert [ (19, True, 1), (19, True, 2), (19, False, 0), ] == [(o.number, o.deleted, o.deleted_version) for o in result] @pytest.mark.django_db def test_set_deleted_model(): """Standard way to delete rows from non-versioned delete models""" obj = FruitCakeFactory() with pytest.raises(BaseError) as e: obj.set_deleted(UserFactory()) assert 'model with deleted version tracking' in str(e.value) @pytest.mark.django_db def test_undelete(): obj = FruitCakeFactory() user = UserFactory() FruitCake.objects.set_deleted(obj, user) assert obj.deleted_version > 0 obj.refresh_from_db() obj.undelete() obj.refresh_from_db()<|fim▁hole|> assert obj.user_deleted is None assert obj.date_deleted is None assert 0 == obj.deleted_version<|fim▁end|>
assert obj.deleted is False
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from __future__ import print_function __author__ = 'breddels' # import astropy.vo.samp as sampy import platform import vaex.utils import sys import threading import vaex.export import vaex.utils import vaex.promise import vaex.settings import vaex.remote import psutil from vaex.parallelize import parallelize from vaex.ui.plot_windows import PlotDialog import vaex.ui.columns import vaex.ui.variables import vaex.ui.qt as dialogs import astropy.units # py2/p3 compatibility try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse import vaex as vx # from PySide import QtGui, QtCore from vaex.ui.qt import * from vaex.ui.table import * from vaex.samp import Samp # help py2app, it was missing this import try: # in Pyinstaller this doesn't work, and we can get away with not setting this, total mystery import sip sip.setapi('QVariant', 2) sip.setapi('QString', 2) except: pass darwin = "darwin" in platform.system().lower() frozen = getattr(sys, 'frozen', False) # print "DEFAULT ENCODING is: %s"%(sys.getdefaultencoding()) # print "FILE SYSTEM ENCODING is: %s"%(sys.getfilesystemencoding()) # if darwin: if sys.getfilesystemencoding() == None: # TODO: why does this happen in pyinstaller? def getfilesystemencoding_wrapper(): return "UTF-8" sys.getfilesystemencoding = getfilesystemencoding_wrapper # on osx 10.8 we sometimes get pipe errors while printing, ignore these # signal.signal(signal.SIGPIPE, signal.SIG_DFL) try: import pdb import astropy.io.fits # pdb.set_trace() except Exception as e: print(e) pdb.set_trace() import vaex.ui.plot_windows as vp from vaex.ui.ranking import * import vaex.ui.undo import vaex.kld import vaex.utils import vaex.dataset # import subspacefind # import ctypes import imp import logging logger = logging.getLogger("vaex") # import locale # locale.setlocale(locale.LC_ALL, ) # samp stuff # import astropy.io.votable custom = None custompath = path = os.path.expanduser('~/.vaex/custom.py') # print path if os.path.exists(path): customModule = imp.load_source('vaex.custom', path) # custom = customModule.Custom() else: custom = None logger.debug("%s does not exist" % path) # print "root path is", vaex.utils.get_root_path() if getattr(sys, 'frozen', False): application_path = os.path.dirname(sys.executable) elif __file__: application_path = os.path.dirname(__file__) if not frozen: # astropy not working :s pass # import pdb # pdb.set_trace() # fix from Chris Beaumont # import astropy.logger # astropy.logger.log.disable_warnings_logging() __import__("astropy.io.votable") # for osx if "darwin" in platform.system().lower(): application_path = os.path.abspath(".") def error(title, msg): print("Error", title, msg) from vaex.dataset import * possibleFractions = [10**base * f for base in [-3, -2, -1, 0] for f in [0.25, 0.5, 0.75, 1.]] possibleFractions.insert(0, 10**-4) # print possibleFractions class DatasetSelector(QtGui.QListWidget): def __init__(self, parent): super(DatasetSelector, self).__init__(parent) # self.icon = QtGui.QIcon('icons/png/24x24/devices/memory.png') # self.icon_server = QtGui.QIcon('icons/png/24x24/devices/memory.png') self.icon = QtGui.QIcon(vp.iconfile('drive')) self.icon_server = QtGui.QIcon(vp.iconfile('server-network')) self.icon_memory = QtGui.QIcon(vp.iconfile('memory')) self.datasets = [] self.signal_pick = vaex.events.Signal("pick") self.signal_add_dataset = vaex.events.Signal("add dataset") self.signal_add_dataset.connect(self.on_add_dataset) self.signal_dataset_select = vaex.events.Signal("dataset-select") self.currentItemChanged.connect(self.onDatasetSelected) # self.items def onDatasetSelected(self, data_item, previous): if data_item is not None: data = data_item.data(QtCore.Qt.UserRole) if hasattr(data, "toPyObject"): dataset = data.toPyObject() self.signal_dataset_select.emit(dataset) else: self.signal_dataset_select.emit(data) def on_add_dataset(self, dataset): # print "added dataset", dataset self.datasets.append(dataset) dataset.signal_pick.connect(self.on_pick) def on_pick(self, dataset, row): # broadcast logger.debug("broadcast pick") self.signal_pick.emit(dataset, row) def setBestFraction(self, dataset): return Nmax = 1000 * 1000 * 10 for fraction in possibleFractions[::-1]: N = len(dataset) if N > Nmax: dataset.set_active_fraction(fraction) logger.debug("set best fraction for dataset %r to %r" % (dataset, fraction)) else: break def is_empty(self): return len(self.datasets) == 0 def open(self, path, **kwargs): ds = vaex.open(path, **kwargs) return self.add(ds) def add(self, dataset): self.setBestFraction(dataset) item = QtGui.QListWidgetItem(self) item.setText(dataset.name) icon = self.icon if hasattr(dataset, "filename"): item.setToolTip("file: " + dataset.filename) if isinstance(dataset, vaex.remote.DataFrameRemote): icon = self.icon_server item.setToolTip("source: " + dataset.path) if isinstance(dataset, vaex.dataset.DatasetArrays): icon = self.icon_memory item.setIcon(icon) # TODO: this hangs on pyside 1.2.1, linux item.setData(QtCore.Qt.UserRole, dataset) self.setCurrentItem(item) self.signal_add_dataset.emit(dataset) return dataset class Worker(QtCore.QThread): def __init__(self, parent, name, func, *args, **kwargs): QtCore.QThread.__init__(self, parent=None) self.func = func self.args = args self.kwargs = kwargs self.name = name self.signal = QtCore.SIGNAL("signal") def run(self): time.sleep(0.1) print("in thread", self.currentThreadId()) self.result = self.func(*self.args, **self.kwargs) print("result:", self.result) # self.emit(self.signal, self.result) # self.exec_() def MyStats(object): def __init__(self, data): self.data = data def __call___(self, args): print(args) # stat_name, column_name = args # print "do", stat_name, "on", column_name return 1 # f = stats[stat_name] # return column_name, stat_name, f(self.data.columns[column_name]) # stats = {"minimum": lambda x: str(np.nanmin(x)), "maximum": lambda x: str(np.nanmax(x)), "mean": lambda x: str(np.mean(x)), "std": lambda x: str(np.std(x)), "median": lambda x: str(np.median(x))} stats = {"minimum": lambda x: str(np.nanmin(x)), "maximum": lambda x: str(np.nanmax(x)), "mean": lambda x: str(np.mean(x)), "std": lambda x: str(np.std(x))} def statsrun(args): columns, stat_name, column_name = args f = stats[stat_name] # print args return 1 class StatWorker(QtCore.QThread): def __init__(self, parent, data): QtCore.QThread.__init__(self, parent=parent) self.data = data def run(self): time.sleep(0.1) print("in thread", self.currentThreadId()) jobs = [(stat_name, column_name) for stat_name in list(stats.keys()) for column_name in list(self.data.columns.keys())] @parallelize(cores=QtCore.QThread.idealThreadCount()) def dostats(args, data=self.data): stat_name, column_name = args columns = data.columns f = stats[stat_name] result = f(columns[column_name][slice(*data.current_slice)]) print(result) return result values = dostats(jobs) self.results = {} for job, value in zip(jobs, values): stat_name, column_name = job if stat_name not in self.results: self.results[stat_name] = {} self.results[stat_name][column_name] = value print("results", self.results) class StatisticsDialog(QtGui.QDialog): def __init__(self, parent, data): super(StatisticsDialog, self).__init__(parent) self.data = data # self.form_layout = QtGui.QFormLayout() # self.min = QtGui.QLabel('...computing...', self) # self.form_layout.addRow('Minimum:', self.min) # self.setLayout(self.form_layout) self.boxlist = QtGui.QHBoxLayout(self) self.headers = ['minimum', 'maximum', 'mean', 'std'] # WorkerMinimum = lambda parent, data, column_name: Worker(parent, 'minimum', lambda data, column_name: str(min(data.columns[column_name])), data=data, column_name=column_name) # WorkerMaximum = lambda parent, data, column_name: Worker(parent, 'maximum', lambda data, column_name: str(max(data.columns[column_name])), data=data, column_name=column_name) # self.workers = {'minimum':WorkerMinimum, 'maximum': WorkerMaximum} self.table = QtGui.QTableWidget(data.nColumns, len(self.headers), self) self.table.setHorizontalHeaderLabels(self.headers) self.table.setVerticalHeaderLabels(list(self.data.columns.keys())) # pool = multiprocessing.Pool() #processes=QtCore.QThread.idealThreadCount()) # print "jobs:", jobs worker = StatWorker(self, self.data) def onFinish(worker=worker): for column, stat in enumerate(self.headers): for row, column_name in enumerate(self.data.columns.keys()): value = worker.results[stat][column_name] item = QtGui.QTableWidgetItem(value) self.table.setItem(row, column, item) worker.finished.connect(onFinish) worker.start() # for name in self.header: # for column_name in self.data.colums.keys(): # self.table.set # worker.finished.connect(onFinish) if 0: self.worker_list = [] # keep references def onFinish(): for column, stat in enumerate(self.headers): for row, column_name in enumerate(self.data.columns.keys()): value = worker.results[stat][column_name] item = QtGui.QTableWidgetItem(worker.result) self.table.setItem(row, column, item) for column, stat in enumerate(self.headers): for row, column_name in enumerate(self.data.columns.keys()): worker = self.workers[stat](parent, data, column_name) def onFinish(worker=worker, row=row, column=column): print("finished running", worker.result) item = QtGui.QTableWidgetItem(worker.result) self.table.setItem(row, column, item) worker.finished.connect(onFinish) print("starting", row, column) worker.start(QtCore.QThread.IdlePriority) self.worker_list.append(worker) # keeps reference to avoid GC self.boxlist.addWidget(self.table) self.setLayout(self.boxlist) if 0: # w1 = Worker(self, lambda data: str(min(data.columns.items()[0])), self.data) self.w1 = Worker(self, self.test, self.data) # self.connect(self.w1, self.w1.signal, self.setmin) def setmin(): print(self.min.setText(self.w1.result)) self.w1.finished.connect(setmin) self.w1.start() def test(self, data): print("test") data = list(data.columns.values())[0] return str(min(data)) # return "test" def onFinish(self, worker): print("worker", worker) # print "setting", result # self.min = str class TextEdit(QtGui.QTextEdit): doubleClicked = QtCore.pyqtSignal(object) def mouseDoubleClickEvent(self, event): self.doubleClicked.emit(event) class DatasetPanel(QtGui.QFrame): def __init__(self, parent, dataset_list): super(DatasetPanel, self).__init__(parent) self.dataset = None self.column_changed_handler = None self.active_fraction_changed_handler = None self.dataset_list = dataset_list self.app = parent self.undoManager = vaex.ui.undo.UndoManager() self.form_layout = QtGui.QFormLayout() self.name = QtGui.QLabel('', self) self.form_layout.addRow('Name:', self.name) self.label_columns = QtGui.QLabel('', self) self.form_layout.addRow('Columns:', self.label_columns) self.label_length = QtGui.QLabel('', self) self.form_layout.addRow('Length:', self.label_length) if 0: self.button_variables = QtGui.QPushButton('Variables', self) self.form_layout.addRow('', self.button_variables) self.fractionLabel = QtGui.QLabel("Use:...") self.fractionWidget = QtGui.QWidget(self) self.fractionLayout = QtGui.QHBoxLayout(self.fractionWidget) self.fractionSlider = QtGui.QSlider(QtCore.Qt.Horizontal, self) self.fractionSlider.setMinimum(0) self.fractionSlider.setMaximum(len(possibleFractions) - 1) # self.numberLabel = QtGui.QLabel('') self.fractionLayout.addWidget(self.fractionSlider) # self.fractionLayout.addWidget(self.numberLabel) self.fractionWidget.setLayout(self.fractionLayout) # self.fractionSlider.setTickInterval(len(possibleFractions)) self.form_layout.addRow(self.fractionLabel, self.fractionWidget) self.auto_fraction_label = QtGui.QLabel("Display", parent) self.auto_fraction_checkbox = QtGui.QCheckBox("Let server determine how much to display", parent) self.form_layout.addRow(self.auto_fraction_label, self.auto_fraction_checkbox) def on_change(state): checked = state == QtCore.Qt.Checked self.dataset.set_auto_fraction(checked) self.fractionSlider.setEnabled(not self.dataset.get_auto_fraction()) self.auto_fraction_checkbox.stateChanged.connect(on_change) self.fractionSlider.sliderReleased.connect(self.onFractionSet) self.fractionSlider.valueChanged.connect(self.onValueChanged) self.onValueChanged(0) self.button_suggesions = QtGui.QToolButton(self) self.button_suggesions.setText('Suggestions') self.button_suggesions.setIcon(QtGui.QIcon(vp.iconfile('light-bulb'))) self.button_suggesions.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon) self.button_suggesions.setPopupMode(QtGui.QToolButton.InstantPopup) self.menu_common = QtGui.QMenu() self.button_suggesions.setMenu(self.menu_common) self.form_layout.addRow('Suggestions:', self.button_suggesions) # self.histogramButton = QtGui.QPushButton('histogram (1d)', self) self.button_histogram = QtGui.QToolButton(self) self.button_histogram.setText('histogram (1d)') self.button_histogram.setIcon(QtGui.QIcon(vp.iconfile('layout'))) self.button_histogram.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon) self.form_layout.addRow('Plotting:', self.button_histogram) self.menu_1d = QtGui.QMenu(self) self.button_histogram.setMenu(self.menu_1d) self.button_2d = QtGui.QToolButton(self) self.button_2d.setIcon(QtGui.QIcon(vp.iconfile('layout-2-equal'))) self.button_2d.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon) self.button_2d.setText('x/y density') self.form_layout.addRow('', self.button_2d) self.menu_2d = QtGui.QMenu(self) self.button_2d.setMenu(self.menu_2d) self.button_3d = QtGui.QToolButton(self) self.button_3d.setIcon(QtGui.QIcon(vp.iconfile('layout-3'))) self.button_3d.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon) self.button_3d.setText('x/y/z density') self.form_layout.addRow('', self.button_3d) self.menu_3d = QtGui.QMenu(self) self.button_3d.setMenu(self.menu_3d) if 0: self.scatter1dSeries = QtGui.QPushButton('series', self) self.form_layout.addRow('', self.scatter1dSeries) self.scatter2dSeries = QtGui.QPushButton('x/y series', self) self.form_layout.addRow('', self.scatter2dSeries) if 0: self.serieSlice = QtGui.QToolButton(self) self.serieSlice.setText('serie slice') self.form_layout.addRow('', self.serieSlice) if 0: self.statistics = QtGui.QPushButton('Statistics', self) self.statistics.setDisabled(True) self.statistics.setIcon(QtGui.QIcon(vp.iconfile('table-sum'))) # self.statistics.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon) self.form_layout.addRow('Data:', self.statistics) self.rank = QtGui.QPushButton('Rank subspaces', self) self.rank.setIcon(QtGui.QIcon(vp.iconfile('sort-quantity'))) # self.table.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon) self.form_layout.addRow('', self.rank) self.table = QtGui.QPushButton('Open table', self) self.table.setIcon(QtGui.QIcon(vp.iconfile('table'))) # self.table.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon) self.form_layout.addRow('', self.table) self.button_histogram.clicked.connect(self.onOpenHistogram) # self.statistics.clicked.connect(self.onOpenStatistics) self.button_2d.clicked.connect(self.onOpenScatter) self.button_3d.clicked.connect(self.onOpenScatter3d) # self.scatter1dSeries.clicked.connect(self.onOpenScatter1dSeries) # self.scatter2dSeries.clicked.connect(self.onOpenScatter2dSeries) # self.serieSlice.clicked.connect(self.onOpenSerieSlice) self.rank.clicked.connect(self.onOpenRank) self.table.clicked.connect(self.onOpenTable) self.description = TextEdit('', self) self.description.setReadOnly(True) self.form_layout.addRow('Description:', self.description) self.description.doubleClicked.connect(self.onEditDescription) self.setLayout(self.form_layout) self.signal_open_plot = vaex.events.Signal("open plot") def onEditDescription(self): text = dialogs.gettext(self, "Edit description", "Edit description", self.description.toPlainText()) if text is not None: self.dataset.description = text self.description.setText(text) self.dataset.write_meta() def onOpenStatistics(self): if self.dataset is not None: dialog = StatisticsDialog(self, self.dataset) dialog.show() def onOpenScatter(self): if self.dataset is not None: xname, yname = self.default_columns_2d self.plotxy(xname, yname) def onOpenScatter3d(self): if self.dataset is not None: xname, yname, zname = self.dataset.column_names[:3] self.plotxyz(xname, yname, zname) def onOpenSerieSlice(self): if self.dataset is not None: xname, yname = self.dataset.rank1names[:2] self.plotseriexy(xname, yname) def onOpenScatter1dSeries(self): if self.dataset is not None: dialog = vp.SequencePlot(self, self.dataset) dialog.show() self.dataset.executor.execute() def onOpenScatter2dSeries(self): if self.dataset is not None: dialog = vp.ScatterSeries2dPlotDialog(self, self.dataset) dialog.show() def onOpenHistogram(self): if self.dataset is not None: xname = self.dataset.column_names[0] self.histogram(xname) def plotxy(self, xname, yname, **kwargs): dialog = vp.ScatterPlotDialog(self, self.dataset, app=self.app, **kwargs) dialog.add_layer([xname, yname], self.dataset, **kwargs) if not vaex.ui.hidden: dialog.show() else: # we get a different output size when we don't show the dialog, which makes testing impossible dialog.show() dialog.hide() # dialog.updateGeometry() # dialog.adjustSize() # self.dataset.executor.execute() # self.dataset.executor.execute() self.signal_open_plot.emit(dialog) return dialog def plotxyz(self, xname, yname, zname, **kwargs): dialog = vp.VolumeRenderingPlotDialog(self, self.dataset, app=self.app, **kwargs) dialog.add_layer([xname, yname, zname], **kwargs) dialog.show() # self.dataset.executor.execute() self.dataset.executor.execute() self.signal_open_plot.emit(dialog) return dialog def plotmatrix(self, *expressions): dialog = vp.ScatterPlotMatrixDialog(self, self.dataset, expressions) dialog.show() self.dataset.executor.execute() return dialog def plotxyz_old(self, xname, yname, zname): dialog = vp.PlotDialog3d(self, self.dataset, xname, yname, zname) dialog.show() def histogram(self, xname, **kwargs): dialog = vp.HistogramPlotDialog(self, self.dataset, app=self.app, **kwargs) dialog.add_layer([xname], **kwargs) dialog.show() # self.dataset.executor.execute() # self.dataset.executor.execute() self.signal_open_plot.emit(dialog) return dialog def onOpenRank(self): if self.dataset is not None: self.ranking() def onOpenTable(self): if self.dataset is not None: self.tableview() def onFractionSet(self): index = self.fractionSlider.value() fraction = possibleFractions[index] if self.dataset: self.dataset.set_active_fraction(fraction) self.update_length() # self.numberLabel.setText("{:,}".format(len(self.dataset))) # self.dataset.executor.execute() # self.dataset.executor.execute() def onValueChanged(self, index): fraction = possibleFractions[index] text = "Dispay: %9.4f%%" % (fraction * 100) self.fractionLabel.setText(text) def on_active_fraction_changed(self, dataset, fraction): self.update_active_fraction() def update_active_fraction(self): fraction = self.dataset.get_active_fraction() distances = np.abs(np.array(possibleFractions) - fraction) index = np.argsort(distances)[0] self.fractionSlider.setValue(index) # this will fire an event and execute the above event code def update_length(self): if self.dataset.get_active_fraction() == 1: self.label_length.setText("{:,}".format(self.dataset.length_original())) else: self.label_length.setText("{:,} of {:,}".format(len(self.dataset), self.dataset.length_original())) def on_column_change(self, *args): logger.debug("updating columns") self.show_dataset(self.dataset) def show_dataset(self, dataset): if self.active_fraction_changed_handler: self.dataset.signal_active_fraction_changed.disconnect(self.active_fraction_changed_handler) if self.column_changed_handler: self.dataset.signal_column_changed.disconnect(self.column_changed_handler) self.refs = [] self.dataset = dataset self.active_fraction_changed_handler = self.dataset.signal_active_fraction_changed.connect(self.on_active_fraction_changed) self.column_changed_handler = self.dataset.signal_column_changed.connect(self.on_column_change) self.name.setText(dataset.name) self.description.setText(dataset.description if dataset.description else "") self.label_columns.setText(str(dataset.column_count())) self.update_length() self.label_length.setText("{:,}".format(self.dataset.length_original())) self.update_active_fraction() self.button_2d.setEnabled(self.dataset.column_count() > 0) self.auto_fraction_checkbox.setEnabled(not dataset.is_local()) self.fractionSlider.setEnabled(not dataset.get_auto_fraction()) self.menu_common.clear() if dataset.ucd_find(["^pos.eq.ra", "^pos.eq.dec"]) and dataset.ucd_find(["^pos.galactic.lon", "^pos.galactic.lat"]) is None: def add(*args): vaex.ui.columns.add_celestial(self, self.dataset) action = QtGui.QAction("Add galactic coordinates", self) action.triggered.connect(add) self.refs.append((action, add)) self.menu_common.addAction(action) if dataset.ucd_find(["^pos.eq.ra", "^pos.eq.dec"]) and dataset.ucd_find(["^pos.ecliptic.lon", "^pos.ecliptic.lat"]) is None: def add(*args): vaex.ui.columns.add_celestial_eq2ecl(self, self.dataset) action = QtGui.QAction("Add ecliptic coordinates", self) action.triggered.connect(add) self.refs.append((action, add)) self.menu_common.addAction(action) if dataset.ucd_find(["pos.parallax"]) and not dataset.ucd_find(["pos.distance"]): def add(*args): vaex.ui.columns.add_distance(self, self.dataset) action = QtGui.QAction("Add distance from parallax", self) action.triggered.connect(add) self.refs.append((action, add)) self.menu_common.addAction(action) spherical_galactic = dataset.ucd_find(["^pos.distance", "^pos.galactic.lon", "^pos.galactic.lat"]) if spherical_galactic and not dataset.ucd_find(["^pos.cartesian.x;pos.galactocentric", "^pos.cartesian.y;pos.galactocentric", "^pos.cartesian.z;pos.galactocentric"]): def add(*args): vaex.ui.columns.add_cartesian(self, self.dataset, True) action = QtGui.QAction("Add galactic cartesian positions", self) action.triggered.connect(add) self.refs.append((action, add)) self.menu_common.addAction(action) if dataset.ucd_find(["pos.cartesian.x;pos.galactocentric", "pos.cartesian.y;pos.galactocentric", "pos.cartesian.z;pos.galactocentric"]) and \ not dataset.ucd_find(["pos.distance;pos.galactocentric", "pos.galactic.lon", "pos.galactic.lat"]): def add(*args): vaex.ui.columns.add_sky(self, self.dataset, True) action = QtGui.QAction("Add galactic sky coordinates", self) action.triggered.connect(add) self.refs.append((action, add)) self.menu_common.addAction(action) if dataset.ucd_find(["^pos.eq.ra", "^pos.eq.dec", "pos.pm;pos.eq.ra", "pos.pm;pos.eq.dec"]) and \ not dataset.ucd_find(["pos.pm;pos.galactic.lon", "pos.pm;pos.galactic.lat"]): def add(*args): vaex.ui.columns.add_proper_motion_eq2gal(self, self.dataset) action = QtGui.QAction("Equatorial proper motions to galactic", self) action.triggered.connect(add) self.refs.append((action, add)) self.menu_common.addAction(action) # dataset.add_virtual_columns_proper_motion_eq2gal("RA_ICRS_", "DE_ICRS_", "pmRA", "pmDE", "pm_l", "pm_b") # dataset.add_virtual_columns_eq2gal("RA_ICRS_", "DE_ICRS_", "l", "b") if dataset.ucd_find(["^pos.galactic.lon", "^pos.galactic.lat", "^pos.distance", "pos.pm;pos.galactic.lon", "pos.pm;pos.galactic.lat", "spect.dopplerVeloc"]): def add(*args): vaex.ui.columns.add_cartesian_velocities(self, self.dataset) action = QtGui.QAction("Galactic velocities", self) action.triggered.connect(add) self.refs.append((action, add)) self.menu_common.addAction(action) spherical_galactic = dataset.ucd_find(["^pos.galactic.lon", "^pos.galactic.lat"]) if spherical_galactic: def add(*args): vaex.ui.columns.add_aitoff(self, self.dataset, True) action = QtGui.QAction("Add galactic aitoff projection", self) action.triggered.connect(add) self.refs.append((action, add)) self.menu_common.addAction(action) self.button_suggesions.setEnabled(len(self.menu_common.actions()) > 0) self.menu_1d.clear() for column_name in self.dataset.get_column_names(virtual=True): # action = QtGui.QAction # QtGui.QAction(QtGui.QIcon(iconfile('glue_cross')), '&Pick', self) action = QtGui.QAction(column_name, self) action.triggered.connect(functools.partial(self.histogram, xname=column_name)) self.menu_1d.addAction(action) self.default_columns_2d = None self.menu_2d.clear() ucd_pairs = [("^pos.cartesian.x", "^pos.cartesian.y"), ("^pos.cartesian.x", "^pos.cartesian.z"), ("^pos.cartesian.y", "^pos.cartesian.z"), ("^pos.eq.ra", "^pos.eq.dec"), ("^pos.galactic.lon", "^pos.galactic.lat"), ("^pos.ecliptic.lon", "^pos.ecliptic.lat"), ("^pos.earth.lon", "^pos.earth.lat")] for ucd_pair in ucd_pairs: done = False exclude = [] while not done: pair = dataset.ucd_find(ucd_pair, exclude=exclude) if pair: action = QtGui.QAction(", ".join(pair), self) action.triggered.connect(functools.partial(self.plotxy, xname=pair[0], yname=pair[1])) self.menu_2d.addAction(action) if self.default_columns_2d is None: self.default_columns_2d = pair exclude.extend(pair) else: done = True column_names = self.dataset.get_column_names(virtual=True) for column_name1 in column_names: # action1 = QtGui.QAction(column_name, self) submenu = self.menu_2d.addMenu(column_name1) for column_name2 in self.dataset.get_column_names(virtual=True): action = QtGui.QAction(column_name2, self) action.triggered.connect(functools.partial(self.plotxy, xname=column_name1, yname=column_name2)) submenu.addAction(action) if self.default_columns_2d is None: if len(column_names) >= 2: self.default_columns_2d = column_names[:2] elif len(column_names) == 1: self.default_columns_2d = [column_names[0], ""] self.default_columns_2d = ["", ""] return if 0: # TODO 3d menu takes long to generate when many columns are present, can we do this lazy? for column_name1 in self.dataset.get_column_names(): # action1 = QtGui.QAction(column_name, self) submenu = self.scatterMenu3d.addMenu(column_name1) for column_name2 in self.dataset.get_column_names(): subsubmenu = submenu.addMenu(column_name2) for column_name3 in self.dataset.get_column_names(): action = QtGui.QAction(column_name3, self) action.triggered.connect(functools.partial(self.plotxyz, xname=column_name1, yname=column_name2, zname=column_name3)) subsubmenu.addAction(action) if 0: self.serieSliceMenu = QtGui.QMenu(self) for column_name1 in self.dataset.rank1names: # action1 = QtGui.QAction(column_name, self) submenu = self.serieSliceMenu.addMenu(column_name1) for column_name2 in self.dataset.rank1names: action = QtGui.QAction(column_name2, self) action.triggered.connect(functools.partial(self.plotseriexy, xname=column_name1, yname=column_name2)) submenu.addAction(action) self.serieSlice.setMenu(self.serieSliceMenu) def plotseriexy(self, xname, yname): if self.dataset is not None: dialog = vp.Rank1ScatterPlotDialog(self, self.dataset, xname + "[index]", yname + "[index]") self.dataset.executor.execute() self.signal_open_plot.emit(dialog) dialog.show() def tableview(self): dialog = TableDialog(self.dataset, self) dialog.show() return dialog def ranking(self, **options): dialog = RankDialog(self.dataset, self, self, **options) dialog.show() return dialog def pca(self, **options): # dialog = RankDialog(self.dataset, self, self, **options) # dialog.show() # return dialog import vaex.pca vaex.pca.pca(self.dataset, self.dataset.get_column_names()) class WidgetUsage(QtGui.QWidget): def __init__(self, parent): super(WidgetUsage, self).__init__(parent) self.setMinimumHeight(16) self.setMinimumWidth(100) self.timer = QtCore.QTimer(self) self.timer.timeout.connect(self.update) self.timer.start(500) self.t_prev = time.time() self.bytes_read_prev = psutil.disk_io_counters().read_bytes def paintEvent(self, event): painter = QtGui.QPainter() painter.begin(self) painter.fillRect(event.rect(), QtGui.QBrush(QtCore.Qt.white)) size = self.size() width, height = size.width(), size.height() self.tool_lines = [] # self.tool_text = "" try: def drawbar(index, count, fraction, color=QtCore.Qt.red): if fraction == fraction: # check nan # print "bar", index, count, height * (index)/ count, height * (index+1)/ count rect = QtCore.QRect(0, height * (index) / count, int(width * fraction + 0.5), height / count) # painter.setBrush(QtGui.QBrush(QtCore.Qt.blue)) painter.fillRect(rect, QtGui.QBrush(color)) cpu_fraction = psutil.cpu_percent() / 100. # print cpu_fraction drawbar(0, 4, cpu_fraction, QtCore.Qt.green) self.tool_lines.append("Cpu usage: %.1f%%" % (cpu_fraction * 100,)) vmem = psutil.virtual_memory() mem_fraction = (vmem.total - vmem.available) * 1. / vmem.total self.tool_lines.append("Virtual memory: %s used of %s (=%.1f%%)%%" % (vaex.utils.filesize_format(vmem.total - vmem.available), vaex.utils.filesize_format(vmem.total), mem_fraction * 100.)) drawbar(1, 4, mem_fraction, QtCore.Qt.red) swapmem = psutil.swap_memory() swap_fraction = swapmem.used * 1. / swapmem.total drawbar(2, 4, swap_fraction, QtCore.Qt.blue) self.tool_lines.append("Swap memory: %s used of %s (=%.1f%%)" % (vaex.utils.filesize_format(swapmem.used), vaex.utils.filesize_format(swapmem.total), swap_fraction * 100.)) self.t_now = time.time() self.bytes_read_new = psutil.disk_io_counters().read_bytes bytes_per_second = (self.bytes_read_new - self.bytes_read_prev) / (self.t_now - self.t_prev) Mbytes_per_second = bytes_per_second / 1024**2 # go from 1 mb to 10*1024 mb/s in log spacing disk_fraction = np.clip(np.log2(Mbytes_per_second) / np.log2(10 * 1024), 0, 1) drawbar(3, 4, disk_fraction, QtCore.Qt.magenta) self.tool_lines.append("Reading at %.2f MiB/s" % (Mbytes_per_second,)) self.t_prev = self.t_now self.bytes_read_prev = self.bytes_read_new self.tool_text = "\n".join(self.tool_lines) painter.end() self.setToolTip(self.tool_text) except: pass class VaexApp(QtGui.QMainWindow): """ :type windows: list[PlotDialog] """ signal_samp_notification = QtCore.pyqtSignal(str, str, str, dict, dict) signal_samp_call = QtCore.pyqtSignal(str, str, str, str, dict, dict) def __init__(self, argv=[], open_default=False, enable_samp=True): super(VaexApp, self).__init__() is_py2 = (sys.version_info[0] == 2) self.enable_samp = enable_samp # if (enable_samp is not None) else is_py2 self.windows = [] self.current_window = None self.current_dataset = None QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10)) # self.setToolTip('This is a <b>QWidget</b> widget') if 0: qbtn = QtGui.QPushButton('Quit', self) qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit) qbtn.resize(qbtn.sizeHint()) qbtn.move(150, 150) btn = QtGui.QPushButton('Button', self) btn.setToolTip('This is a <b>QPushButton</b> widget') btn.resize(btn.sizeHint()) btn.move(50, 50) # self.setGeometry(300, 300, 250, 150) self.resize(700, 500) # self.center() self.setWindowTitle(u'V\xe6X v' + vaex.__version__) # self.statusBar().showMessage('Ready') self.toolbar = self.addToolBar('Main toolbar') self.toolbar.setVisible(False) self.left = QtGui.QFrame(self) self.left.setFrameShape(QtGui.QFrame.StyledPanel) self.dataset_selector = DatasetSelector(self.left) self.dataset_selector.setMinimumWidth(300) self.tabs = QtGui.QTabWidget() self.dataset_panel = DatasetPanel(self, self.dataset_selector.datasets) # QtGui.QFrame(self) self.dataset_panel.setFrameShape(QtGui.QFrame.StyledPanel) self.tabs.addTab(self.dataset_panel, "Main") self.main_panel = self.dataset_panel self.splitter = QtGui.QSplitter(QtCore.Qt.Horizontal) self.splitter.addWidget(self.left) # self.splitter.addWidget(self.dataset_panel) self.splitter.addWidget(self.tabs) # self.hbox = QtGui.QHBoxLayout(self) # self.hbox.addWidget(self.splitter) self.setCentralWidget(self.splitter) # self.setLayout(self.hbox) # this widget uses a time which causes an fps drop for opengl # self.widget_usage = WidgetUsage(self.left) # self.list.resize(30 self.boxlist = QtGui.QVBoxLayout(self.left) self.boxlist.addWidget(self.dataset_selector) # self.boxlist.addWidget(self.widget_usage) self.left.setLayout(self.boxlist) def on_dataset_select(dataset): self.current_dataset = dataset current.dataset = dataset self.dataset_panel.show_dataset(dataset) self.columns_panel.set_dataset(dataset) self.variables_panel.set_dataset(dataset) self.dataset_selector.signal_dataset_select.connect(on_dataset_select) # self.list.currentItemChanged.connect(self.infoPanel.onDataSelected) # self.dataset_selector.currentItemChanged.connect(self.dataset_panel.onDataSelected) # self.dataset_selector.currentItemChanged.connect(self.dataset_panel.onDataSelected) # self.list.testfill() if not vaex.ui.hidden: self.show() self.raise_() # self.list.itemSelectionChanged.connect(self.right.onDataSelected) # self.action_open = QtGui.QAction(vp.iconfile('quickopen-file', '&Open', self) # self.action_open. self.action_open_hdf5_gadget = QtGui.QAction(QtGui.QIcon(vp.iconfile('table-import')), '&Open Gadget hdf5', self) self.action_open_hdf5_vaex = QtGui.QAction(QtGui.QIcon(vp.iconfile('table-import')), '&Open Vaex hdf5', self) self.action_open_hdf5_amuse = QtGui.QAction(QtGui.QIcon(vp.iconfile('table-import')), '&Open Amuse hdf5', self) self.action_open_fits = QtGui.QAction(QtGui.QIcon(vp.iconfile('table-import')), '&Open FITS (binary table)', self) self.action_save_hdf5 = QtGui.QAction(QtGui.QIcon(vp.iconfile('table-export')), '&Export to hdf5', self) self.action_save_fits = QtGui.QAction(QtGui.QIcon(vp.iconfile('table-export')), '&Export to fits', self) self.server_connect_action = QtGui.QAction(QtGui.QIcon(vp.iconfile('database-cloud')), '&Connect to server', self) def server_connect(*ignore): servers = vaex.settings.main.get("servers", ["ws://localhost:9000/"]) server = str(dialogs.choose(self, "Connect to server", "Connect to server", servers, editable=True)) if server is None: return try: vaex_server = vaex.server(server, thread_mover=self.call_in_main_thread) datasets = vaex_server.datasets() except Exception as e: dialogs.dialog_error(self, "Error connecting", "Error connecting: %r" % e) return dataset_descriptions = ["{} ({:,} rows)".format(dataset.name, len(dataset)) for dataset in datasets] dataset_index = dialogs.choose(self, "Choose datasets", "Choose dataset", dataset_descriptions) if dataset_index is None: return dataset = datasets[dataset_index] self.dataset_selector.add(dataset) self.add_recently_opened(dataset.path) if server in servers: servers.remove(server) servers.insert(0, server) vaex.settings.main.store("servers", servers) self.server_connect_action.triggered.connect(server_connect) exitAction = QtGui.QAction(QtGui.QIcon('icons/png/24x24/actions/application-exit-2.png'), '&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setShortcut('Alt+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(QtGui.qApp.quit) self.samp = None """ ipythonAction = QtGui.QAction(QtGui.QIcon(vp.iconfile('table-import')), '&IPython console', self) ipythonAction.setShortcut('Alt+I') ipythonAction.setStatusTip('Show IPython console') def show_ipython_console(*args): ipython_console.show() ipythonAction.triggered.connect(show_ipython_console) """ menubar = self.menuBar() fileMenu = menubar.addMenu('&File') self.menu_open = fileMenu.addMenu("&Open") self.menu_open.addAction(self.action_open_hdf5_vaex) self.menu_open.addAction(self.action_open_hdf5_gadget) self.menu_open.addAction(self.action_open_hdf5_amuse) self.menu_recent = fileMenu.addMenu("&Open Recent") self.recently_opened = vaex.settings.main.get("recent", []) self.update_recently_opened() if (not frozen) or darwin: self.menu_open.addAction(self.action_open_fits) fileMenu.addAction(self.action_save_hdf5) fileMenu.addAction(self.action_save_fits) # fileMenu.addAction(self.action_open) fileMenu.addAction(self.server_connect_action) # fileMenu.addAction(ipythonAction) fileMenu.addAction(exitAction) self.menu_data = menubar.addMenu('&Data') def check_memory(bytes): if bytes > psutil.virtual_memory().available: if bytes < (psutil.virtual_memory().available + psutil.swap_memory().free): text = "Action requires %s, you have enough swap memory available but it will make your computer slower, do you want to continue?" % (vaex.utils.filesize_format(bytes),) return confirm(self, "Memory usage issue", text) else: text = "Action requires %s, you do not have enough swap memory available, do you want try anyway?" % (vaex.utils.filesize_format(bytes),) return confirm(self, "Memory usage issue", text) return True for level in [20, 25, 27, 29, 30, 31, 32]: N = 2**level action = QtGui.QAction('Generate Soneira Peebles fractal: N={:,}'.format(N), self) def do(ignore=None, level=level): if level < 29: if check_memory(4 * 8 * 2**level): sp = vx.file.other.SoneiraPeebles(dimension=4, eta=2, max_level=level, L=[1.1, 1.3, 1.6, 2.]) self.dataset_selector.add(sp) else: if check_memory(2 * 8 * 2**level): sp = vx.file.other.SoneiraPeebles(dimension=2, eta=2, max_level=level, L=[1.6, 2.]) self.dataset_selector.add(sp) action.triggered.connect(do) self.menu_data.addAction(action) for dim in [2, 3]: if dim == 3: res = [128, 256, 512, 1024] if dim == 2: res = [512, 1024, 2048] for N in res: for power in [-1.5, -2.5]: count = N**dim name = 'Zeldovich d={dim} N={N:,}, count={count:,} powerspectrum={power:}'.format(**locals()) action = QtGui.QAction('Generate ' + name, self) def do(ignore=None, dim=dim, N=N, power=power, name=name): t = None z = vx.file.other.Zeldovich(dim, N, power, t, name=name) self.dataset_selector.add(z) action.triggered.connect(do) self.menu_data.addAction(action) self.menu_columns = menubar.addMenu('&Columns') self.columns_panel = vaex.ui.columns.ColumnsTable(self.tabs, menu=self.menu_columns) self.tabs.addTab(self.columns_panel, "Columns") self.variables_panel = vaex.ui.variables.VariablesTable(self.tabs, menu=self.menu_columns) self.tabs.addTab(self.variables_panel, "Variables") use_toolbar = "darwin" not in platform.system().lower() use_toolbar = True self.toolbar.setIconSize(QtCore.QSize(16, 16)) # self.toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) # self.toolbar.addAction(exitAction) if self.enable_samp: self.action_samp_connect = QtGui.QAction(QtGui.QIcon(vp.iconfile('plug-connect')), 'Connect to SAMP HUB', self) self.action_samp_connect.setShortcut('Alt+S') self.action_samp_connect.setCheckable(True) if use_toolbar: self.toolbar.addAction(self.action_samp_connect) self.action_samp_connect.triggered.connect(self.onSampConnect) self.action_samp_table_send = QtGui.QAction(QtGui.QIcon(vp.iconfile('table--arrow')), 'Send active dataset via SAMP', self) self.action_samp_table_send.setShortcut('Alt+T') if use_toolbar: self.toolbar.addAction(self.action_samp_table_send) self.action_samp_table_send.triggered.connect(self.onSampSend) self.action_samp_sand_table_select_row_list = QtGui.QAction(QtGui.QIcon(vp.iconfile('block--arrow')), 'Send selection via SAMP(table.select.rowlist)', self) self.action_samp_sand_table_select_row_list.setShortcut('Alt+R') if use_toolbar: self.toolbar.addAction(self.action_samp_sand_table_select_row_list) self.action_samp_sand_table_select_row_list.triggered.connect(self.on_samp_send_table_select_rowlist) self.toolbar.addSeparator() self.action_save_hdf5.triggered.connect(self.onExportHdf5) self.action_save_fits.triggered.connect(self.onExportFits) self.sampMenu = menubar.addMenu('&Samp') self.sampMenu.addAction(self.action_samp_connect) # self.sampMenu.addAction(self.action_samp_table_send) self.sampMenu.addAction(self.action_samp_sand_table_select_row_list) if use_toolbar: # self.toolbar.addAction(self.action_open_hdf5_gadget) # self.toolbar.addAction(self.action_open_hdf5_vaex) # if (not frozen) or darwin: # self.toolbar.addAction(self.action_open_fits) self.toolbar.addAction(self.action_save_hdf5) self.toolbar.addAction(self.action_save_fits) if len(argv) == 0 and open_default: if custom is not None: custom.loadDatasets(self.dataset_selector) custom.openPlots(self.dataset_panel) elif 1: # frozen: # for index, name in list(enumerate("gas halo disk stars sat".split()))[::-1]: # self.dataset_selector.open(os.path.join(application_path, 'data/disk-galaxy.hdf5'), particle_name=name) # f = vaex.utils.get_data_file("data/helmi-dezeeuw-2000-10p.hdf5") # if f and os.path.exists(f): # self.dataset_selector.open(f) # self.dataset_selector.open(os.path.join(application_path, "data/Aq-A-2-999-shuffled-fraction.hdf5")) dataset_example = vaex.example(download=False) if dataset_example is not None: self.dataset_selector.add(dataset_example) for pluginpath in [os.path.expanduser('~/.vaex/plugin')]: logger.debug("pluginpath: %s" % pluginpath) if os.path.exists(pluginpath): import glob paths = glob.glob(pluginpath + "/*.py") for path in paths: logger.debug("plugin file: %s" % path) filename = os.path.basename(path) name = os.path.splitext(filename)[0] imp.load_source('vaexuser.plugin.' + name, path) self.open_generators = [] # for reference counts self.action_open_hdf5_gadget.triggered.connect(self.openGenerator(self.gadgethdf5, "Gadget HDF5 file", "*.hdf5")) self.action_open_hdf5_vaex.triggered.connect(self.openGenerator(self.vaex_hdf5, "Gaia HDF5 file", "*.hdf5")) self.action_open_hdf5_amuse.triggered.connect(self.openGenerator(self.amuse_hdf5, "Amuse HDF5 file", "*.hdf5")) if (not frozen) or darwin: self.action_open_fits.triggered.connect(self.openGenerator(self.open_fits, "FITS file", "*.fits")) self.help_menu = menubar.addMenu('&Help') self.action_help = QtGui.QAction("Help", self) self.action_credits = QtGui.QAction("Credits", self) self.help_menu.addAction(self.action_help) self.help_menu.addAction(self.action_credits) self.action_help.triggered.connect(self.onActionHelp) self.action_credits.triggered.connect(self.onActionCredits) if self.enable_samp: self.signal_samp_notification.connect(self.on_samp_notification) self.signal_samp_call.connect(self.on_samp_call) QtCore.QCoreApplication.instance().aboutToQuit.connect(self.clean_up) self.action_samp_connect.setChecked(True) self.onSampConnect(ignore_error=True) self.dataset_selector.signal_pick.connect(self.on_pick) self.samp_ping_timer = QtCore.QTimer() self.samp_ping_timer.timeout.connect(self.on_samp_ping_timer) # self.samp_ping_timer.start(1000) self.highlighed_row_from_samp = False def on_open_plot(plot_dialog): self.dataset_selector.signal_add_dataset.connect(lambda dataset: plot_dialog.fill_menu_layer_new()) plot_dialog.signal_samp_send_selection.connect(lambda dataset: self.on_samp_send_table_select_rowlist(dataset=dataset)) current.window = plot_dialog # current.layer = plot_dialog.current_layer if kernel: kernel.shell.push({"window": plot_dialog}) kernel.shell.push({"layer": plot_dialog.current_layer}) self.windows.append(plot_dialog) # TODO remove from list def on_close(window): self.windows.remove(window) if self.current_window == window: self.current_window = None current.window = None plot_dialog.signal_closed.connect(on_close) self.current_window = plot_dialog self.dataset_panel.signal_open_plot.connect(on_open_plot) self.signal_call_in_main_thread.connect(self.on_signal_call_in_main_thread) import queue self.queue_call_in_main_thread = queue.Queue(1) self.parse_args(argv) # this queue is used to return values from the main thread to the callers thread signal_call_in_main_thread = QtCore.pyqtSignal(object, object, object) # fn, args, kwargs # signal_promise = QtCore.pyqtSignal(str) def call_in_main_thread(self, fn, *args, **kwargs): # print "send promise to main thread using signal", threading.currentThread() logger.debug("sending call to main thread, we are in thread: %r", threading.currentThread()) assert self.queue_call_in_main_thread.empty() self.signal_call_in_main_thread.emit(fn, args, kwargs) logger.debug("emitted...") return self.queue_call_in_main_thread.get() # self.signal_promise.emit("blaat") def on_signal_call_in_main_thread(self, fn, args, kwargs): logger.debug("got callback %r, and should call it with argument: %r %r (from thread %r)", fn, args, kwargs, threading.currentThread()) assert self.queue_call_in_main_thread.empty() return_value = None try: return_value = fn(*args, **kwargs) finally: self.queue_call_in_main_thread.put(return_value) # promise.fulfill(value) def select(self, *args): args = list(args) # copy since we will modify it if len(args) == 0: print("select requires at least one argument") return index = args.pop(0) if (index < 0) or index >= len(self.windows): print("window index %d out of range [%d, %d]" % (index, 0, len(self.windows) - 1)) else: current.window = self.windows[index] if len(args) > 0: layer_index = args.pop(0) current.window.select_layer(layer_index) current.layer = current.window.current_layer def plot(self, *args, **kwargs): if current.window is None: if len(args) == 1: self.dataset_panel.histogram(args[0], **kwargs) if len(args) == 2: self.dataset_panel.plotxy(args[0], args[1], **kwargs) else: layer = current.window.current_layer if layer: layer.apply_options(kwargs) if len(args) == 1: layer.x = args[0] if len(args) == 2: layer.x = args[0] layer.y = args[1] else: print("no current layer") # window_name = kwargs.get("window_name") # layer_name = kwargs.get("layer_name") # name = kwargs.get("name") # if name is not None: # window_name, layer_name = name.split(":") # kwargs["window_name"] = window_name # kwargs["layer_name"] = layer_name # layer = None # window = None # windows = [window for window in self.windows if window.name == window_name] # if windows: # window = windows[0] # layers = [layer for layer in window.layers if layer.name == layer_name] # if layer is None: # if len(args) == 1: # self.dataset_panel.histogram(args[0], **kwargs) # if len(args) == 2: # self.dataset_panel.plotxy(args[0], args[1], **kwargs) # if len(args) == 1: # self.dataset_panel.histogram(args[0], kwargs) # else: def parse_args(self, args): # args = sys.argv[1:] index = 0 def error(msg): print(msg, file=sys.stderr) sys.exit(1) hold_plot = False plot = None while index < len(args): filename = args[index] filename = args[index] print("filename", filename) dataset = None if filename.startswith("cluster://"): dataset = vaex.open(filename) # , thread_mover=self.call_in_main_thread) elif filename.startswith("http://") or filename.startswith("ws://"): # TODO: thinkg about https wss # o = urlparse(filename) # assert o.scheme == "http" # base_path, should_be_datasets, dataset_name = o.path.rsplit("/", 2) # if should_be_datasets != "datasets": # error("expected an url in the form http://host:port/optional/part/datasets/dataset_name") # server = vaex.server(hostname=o.hostname, port = o.port or 80, thread_mover=self.call_in_main_thread, base_path=base_path) if 0: server = vaex.server(filename, thread_mover=self.call_in_main_thread) datasets = server.datasets() names = [dataset.name for dataset in datasets] index += 1 if index >= len(args): error("expected dataset to follow url, e.g. vaex http://servername:9000 somedataset, possible dataset names: %s" % " ".join(names)) name = args[index] if name not in names: error("no such dataset '%s' at server, possible dataset names: %s" % (name, " ".join(names))) found = [dataset for dataset in datasets if dataset.name == name] if found: dataset = found[0] dataset = vaex.open(filename, thread_mover=self.call_in_main_thread) self.add_recently_opened(filename) # dataset = self.open(filename) elif filename[0] == ":": # not a filename, but a classname classname = filename.split(":")[1] if classname not in vaex.dataset.dataset_type_map: print(classname, "does not exist, options are", sorted(vaex.dataset.dataset_type_map.keys())) sys.exit(-1) class_ = vaex.dataset.dataset_type_map[classname] clsargs = [eval(value) for value in filename.split(":")[2:]] dataset = class_(*clsargs) else: options = filename.split(":") clsargs = [eval(value) for value in options[1:]] filename = options[0] dataset = vaex.open(filename, *clsargs) # vaex.dataset.load_file(filename, *clsargs) self.add_recently_opened(filename) if dataset is None: error("cannot open file {filename}".format(**locals())) index += 1 self.dataset_selector.add(dataset) # for this dataset, keep opening plots (seperated by -) or add layers (seperated by +) plot = plot if hold_plot else None options = {} # if we find --<task> we don't plot but do sth else if index < len(args) and args[index].startswith("--") and len(args[index]) > 2: task_name = args[index][2:] index += 1 if task_name in ["rank", "pca"]: options = {} while index < len(args): if args[index] == "-": index += 1 break elif args[index] == "--": index += 1 break elif "=" in args[index]: key, value = args[index].split("=", 1) options[key] = value else: error("unkown option for task %r: %r " % (task_name, args[index])) index += 1 if task_name == "rank": self.dataset_panel.ranking(**options) if task_name == "pca": self.dataset_panel.pca(**options) else: error("unkown task: %r" % task_name) # else: if 1: while index < len(args) and args[index] != "--": columns = [] while index < len(args) and args[index] not in ["+", "-", "--", "++"]: if "=" in args[index]: key, value = args[index].split("=", 1) if ":" in key: type, key = key.split(":", 1) if type == "vcol": dataset.virtual_columns[key] = value elif type == "var": dataset.variables[key] = value else: error("unknown expression, %s, type %s not recognized" % (type + ":" + key, type)) elif key.startswith("@"): method_name = key[1:] method = getattr(dataset, method_name) method(*eval(value)) # if method is Non # error("unknown expression, %s, type %s not recognized" % (type + ":" + key, type)) else: options[key] = value else: columns.append(args[index]) index += 1 if plot is None: if len(columns) == 1: plot = self.dataset_panel.histogram(columns[0], **options) elif len(columns) == 2: plot = self.dataset_panel.plotxy(columns[0], columns[1], **options) elif len(columns) == 3: plot = self.dataset_panel.plotxyz(columns[0], columns[1], columns[2], **options) else: error("cannot plot more than 3 columns yet: %r" % columns) else: layer = plot.add_layer(columns, dataset=dataset, **options) # layer.jobs_manager.execute() options = {} if index < len(args) and args[index] == "-": plot = None # set to None to create a new plot, + will do a new layer if index < len(args) and args[index] == "--": hold_plot = False break # break out for the next dataset if index < len(args) and args[index] == "++": hold_plot = True break # break out for the next dataset, but keep the same plot index += 1 if index < len(args): pass index += 1 def on_samp_ping_timer(self): if self.samp: connected = self.samp.client.is_connected # print "samp is", "connected" if connected else "disconnected!" if not connected: self.samp = None if self.samp: try: self.samp.client.ping() except: print("oops, ping went wrong, disconnect detected") try: self.samp.disconnect() except: pass self.samp = None self.action_samp_connect.setChecked(self.samp is not None) def on_pick(self, dataset, row): logger.debug("samp pick event") # avoid sending an event if this was caused by a samp event if self.samp and not self.highlighed_row_from_samp: # TODO: check if connected, kwargs = {"row": str(row)} if hasattr(dataset, "samp_id") and dataset.samp_id: kwargs["table-id"] = dataset.samp_id # kwargs["url"] = "file:" + dataset.filename kwargs["url"] = dataset.samp_id else: if dataset.path: kwargs["table-id"] = "file:" + dataset.path kwargs["url"] = "file:" + dataset.path else: kwargs["table-id"] = "file:" + dataset.name kwargs["url"] = "file:" + dataset.name self.samp.client.enotify_all("table.highlight.row", **kwargs) def on_samp_send_table_select_rowlist(self, ignore=None, dataset=None): if self.samp: # TODO: check if connected dataset = dataset or self.dataset_panel.dataset rows = [] print(dataset.has_selection(), dataset.evaluate_selection_mask()) if dataset.has_selection() is not None: rows = np.arange(len(dataset))[dataset.evaluate_selection_mask()] rowlist = list(map(str, rows)) kwargs = {"row-list": rowlist} if dataset.samp_id: kwargs["table-id"] = dataset.samp_id # kwargs["url"] = "file:" + dataset.filename kwargs["url"] = "file:" + dataset.samp_id else: kwargs["table-id"] = "file:" + dataset.path self.samp.client.enotify_all("table.select.rowList", **kwargs) def onActionHelp(self): filename = vaex.utils.get_data_file("doc/index.html") url = "file://" + filename vaex.utils.os_open(url) # self.webDialog("doc/index.html") def onActionCredits(self): filename = vaex.utils.get_data_file("doc/credits.html") url = "file://" + filename vaex.utils.os_open(url) # vaex.utils.os_open("doc/credits.html") # self.webDialog("html/credits.html") def _webDialog(self, url): view = QWebView() view.load(QtCore.QUrl(url)) dialog = QtGui.QDialog(self) layout = QtGui.QVBoxLayout() dialog.setLayout(layout) # text = file("html/credits.html").read() # print text # label = QtGui.QLabel(text, dialog) # layout.addWidget(label) layout.addWidget(view) dialog.resize(300, 300) dialog.show() def onExportHdf5(self): self.export("hdf5") def onExportFits(self): self.export("fits") def export(self, type="hdf5"): dataset = self.dataset_panel.dataset name = dataset.name + "-mysubset.hdf5" options = ["All: %r records, filesize: %r" % (len(dataset), vaex.utils.filesize_format(dataset.byte_size()))] options += ["Selection: %r records, filesize: %r" % (dataset.count(selection=True), vaex.utils.filesize_format(dataset.byte_size(selection=True)))] index = dialogs.choose(self, "What do you want to export?", "Choose what to export:", options) if index is None: return export_selection = index == 1 logger.debug("export selection: %r", export_selection) # select_many(None, "lala", ["aap", "noot"] + ["item-%d-%s" % (k, "-" * k) for k in range(30)]) ok, columns_mask = dialogs.select_many(self, "Select columns", dataset.get_column_names(virtual=True)) if not ok: # cancel return selected_column_names = [column_name for column_name, selected in zip(dataset.get_column_names(virtual=True), columns_mask) if selected] logger.debug("export column names: %r", selected_column_names) shuffle = dialogs.dialog_confirm(self, "Shuffle?", "Do you want the dataset to be shuffled (output the rows in random order)") logger.debug("export shuffled: %r", shuffle) if shuffle and dataset.length_original() != len(dataset): dialogs.dialog_info(self, "Shuffle", "You selected shuffling while not exporting the full dataset, will select random rows from the full dataset") partial_shuffle = True else: partial_shuffle = False if export_selection and shuffle: dialogs.dialog_info(self, "Shuffle", "Shuffling with selection not supported") return if type == "hdf5": endian_options = ["Native", "Little endian", "Big endian"] index = dialogs.choose(self, "Which endianness", "Which endianness / byte order:", endian_options) if index is None: return endian_option = ["=", "<", ">"][index] logger.debug("export endian: %r", endian_option) if type == "hdf5": filename = dialogs.get_path_save(self, "Save to HDF5", name, "HDF5 *.hdf5") else: filename = dialogs.get_path_save(self, "Save to col-fits", name, "FITS (*.fits)") logger.debug("export to file: %r", filename) # print args filename = str(filename) if not filename.endswith("." + type): filename += "." + type if filename: with dialogs.ProgressExecution(self, "Copying data...", "Abort export") as progress_dialog: if type == "hdf5": vaex.export.export_hdf5(dataset, filename, column_names=selected_column_names, shuffle=shuffle, selection=export_selection, byteorder=endian_option, progress=progress_dialog.progress) if type == "fits": vaex.export.export_fits(dataset, filename, column_names=selected_column_names, shuffle=shuffle, selection=export_selection, progress=progress_dialog.progress) logger.debug("export done") def gadgethdf5(self, filename): logger.debug("open gadget hdf5: %r", filename) for index, name in list(enumerate("gas halo disk bulge stars sat".split()))[::-1]: self.dataset_selector.addGadgetHdf5(str(filename), name, index) def vaex_hdf5(self, filename): logger.debug("open vaex hdf5: %r", filename) dataset = vaex.open(str(filename)) self.dataset_selector.add(dataset) def amuse_hdf5(self, filename): logger.debug("open amuse: %r", filename) dataset = vaex.open(str(filename)) self.dataset_selector.add(dataset) def open_fits(self, filename): logger.debug("open fits: %r", filename) dataset = vaex.open(str(filename)) self.dataset_selector.add(dataset) def open(self, path): """Add a dataset and add it to the UI""" logger.debug("open dataset: %r", path)<|fim▁hole|> self.add_recently_opened(path) self.dataset_selector.add(dataset) return dataset def add(self, dataset): """Add an dataset to the UI""" self.dataset_selector.add(dataset) def openGenerator(self, callback_, description, filemask): # print repr(callback_) def open(arg=None, callback_=callback_, filemask=filemask): # print repr(callback_), repr(filemask) filename = QtGui.QFileDialog.getOpenFileName(self, description, "", filemask) if isinstance(filename, tuple): filename = str(filename[0]) # ] # print repr(callback_) if filename: callback_(filename) self.add_recently_opened(filename) self.open_generators.append(open) return open def add_recently_opened(self, path): # vaex.recent[""] if path.startswith("http") or path.startswith("ws"): pass else: # non url's will be converted to an absolute path path = os.path.abspath(path) while path in self.recently_opened: self.recently_opened.remove(path) self.recently_opened.insert(0, path) self.recently_opened = self.recently_opened[:10] vaex.settings.main.store("recent", self.recently_opened) self.update_recently_opened() def update_recently_opened(self): self.menu_recent.clear() self.menu_recent_subactions = [] for path in self.recently_opened: def open(ignore=None, path=path): self.open(path) name = vaex.utils.filename_shorten(path) action = QtGui.QAction(name, self) action.triggered.connect(open) self.menu_recent_subactions.append(action) self.menu_recent.addAction(action) self.menu_recent.addSeparator() def clear(ignore=None): self.recently_opened = [] vaex.settings.main.store("recent", self.recently_opened) self.update_recently_opened() action = QtGui.QAction("Clear recent list", self) action.triggered.connect(clear) self.menu_recent_subactions.append(action) self.menu_recent.addAction(action) def onSampConnect(self, ignore_error=False): if self.action_samp_connect.isChecked(): if self.samp is None: self.samp = Samp(daemon=True, name="vaex") # self.samp.tableLoadCallbacks.append(self.onLoadTable) connected = self.samp.client.is_connected # print "samp is connected:", connected if connected: self.samp.client.bind_receive_notification("table.highlight.row", self._on_samp_notification) self.samp.client.bind_receive_call("table.select.rowList", self._on_samp_call) self.samp.client.bind_receive_notification("table.load.votable", self._on_samp_notification) self.samp.client.bind_receive_call("table.load.votable", self._on_samp_call) self.samp.client.bind_receive_notification("table.load.fits", self._on_samp_notification) self.samp.client.bind_receive_call("table.load.fits", self._on_samp_call) else: if not ignore_error: dialog_error(self, "Connecting to SAMP server", "Could not connect, make sure a SAMP HUB is running (for instance TOPCAT)") self.samp = None self.action_samp_connect.setChecked(False) else: print("disconnect") # try: self.samp.client.disconnect() self.samp = None # self.action_samp_connect.setText("disconnect from SAMP HUB" if self.samp else "conncet to SAMP HUB") # except: # dialog_exception(self, "Connecting to SAMP server", "Could not connect, make sure a SAMP HUB is running (for instance TOPCAT)") def _on_samp_notification(self, private_key, sender_id, mtype, params, extra): # this callback will be in a different thread, so we use pyqt's signal mechanism to # push an event in the main thread's event loop print(private_key, sender_id, mtype, params, extra) self.signal_samp_notification.emit(private_key, sender_id, mtype, params, extra) def _on_samp_call(self, private_key, sender_id, msg_id, mtype, params, extra): # same as _on_samp_notification # print private_key, sender_id, msg_id, mtype, params, extra self.signal_samp_call.emit(private_key, sender_id, msg_id, mtype, params, extra) self.samp.client.ereply(msg_id, sampy.SAMP_STATUS_OK, result={"txt": "printed"}) def on_samp_notification(self, private_key, sender_id, mtype, params, extra): # and this should execute in the main thread logger.debug("samp notification: %r" % ((private_key, sender_id, mtype),)) assert QtCore.QThread.currentThread() == main_thread def dash_to_underscore(hashmap): hashmap = dict(hashmap) # copy for key, value in list(hashmap.items()): del hashmap[key] hashmap[key.replace("-", "_")] = value return hashmap params = dash_to_underscore(params) if mtype == "table.highlight.row": self.samp_table_highlight_row(**params) if mtype == "table.select.rowList": self.samp_table_select_rowlist(**params) if mtype == "table.load.votable": self.samp_table_load_votable(**params) def on_samp_call(self, private_key, sender_id, msg_id, mtype, params, extra): # and this should execute in the main thread assert QtCore.QThread.currentThread() == main_thread # we simply see a call as a notification self.on_samp_notification(private_key, sender_id, mtype, params, extra) def samp_table_highlight_row(self, row, url=None, table_id=None): logger.debug("highlight row: {url}:{row}".format(**locals())) print(("highlight row: {url}:{row}".format(**locals()))) row = int(row) # only supports url for the moment for id in (url, table_id): if id is not None: for dataset in self._samp_find_datasets(id): # avoid triggering another samp event and an infinite loop self.highlighed_row_from_samp = True try: dataset.set_current_row(row) finally: self.highlighed_row_from_samp = False def samp_table_select_rowlist(self, row_list, url=None, table_id=None): print("----") logger.debug("select rowlist: {url}".format(**locals())) print(("select rowlist: {url}".format(**locals()))) row_list = np.array([int(k) for k in row_list]) # did_select = False datasets_updated = [] # keep a list to avoid multiple 'setMask' calls (which would do an update twice) # TODO: this method is not compatible with the selection history... how to deal with this? New SelectionObject? for id in (url, table_id): if id is not None: for dataset in self._samp_find_datasets(id): if dataset not in datasets_updated: mask = np.zeros(len(dataset), dtype=np.bool) mask[row_list] = True print("match dataset", dataset) dataset._set_mask(mask) # did_select = True datasets_updated.append(dataset) # if did_select: # self.main_panel.jobsManager.execute() def samp_table_load_votable(self, url=None, table_id=None, name=None): filenames = [] if table_id is not None: filename = table_id if filename.startswith("file:/"): filename = filename[5:] basename, ext = os.path.splitext(filename) if os.path.exists(filename): filenames.append(filename) for other_ext in [".hdf5", ".fits"]: filename = basename + other_ext print(filename) if os.path.exists(filename) and filename not in filenames: filenames.append(filename) filenames = list(filter(vaex.file.can_open, filenames)) options = [] for filename in filenames: options.append(filename + " | read directly from file (faster)") options.append(url + " | load as VOTable (slower)") # options.append("link to existing opened dataset") for dataset in self.dataset_selector.datasets: options.append("link to existing open dataset: " + dataset.name) index = choose(self, "SAMP: load table", "Choose how to load table", options) if index is not None: if index < len(filenames): print("open file", filenames[index]) self.load_file(filenames[index], table_id) elif index == len(filenames): self.load_votable(url, table_id) print("load votable", url) else: self.dataset_selector.datasets[index - len(filenames) - 1].samp_id = table_id def load_file(self, path, samp_id=None): dataset_class = None ds = vx.open(path) if ds: ds.samp_id = samp_id self.dataset_selector.add(ds) def load_votable(self, url, table_id): dialog = QtGui.QProgressDialog("Downloading VO table", "cancel", 0, 0, self) # self.dialog.show() dialog.setWindowModality(QtCore.Qt.WindowModal) dialog.setMinimumDuration(0) dialog.setAutoClose(True) dialog.setAutoReset(True) dialog.setMinimum(0) dialog.setMaximum(0) dialog.show() try: def ask(username, password): d = QuickDialog(self, "Username/password") d.add_text("username", "Username", username) d.add_password("password", "Password", password) values = d.get() if values: return values["username"], values["password"] else: return None t = vaex.samp.fetch_votable(url, ask=ask) if t: dataset = vx.from_astropy_table(t.to_table()) # table = astropy.io.votable.parse_single_table(url) # print("done parsing table") # names = table.array.dtype.names # dataset = DatasetMemoryMapped(table_id, nommap=True) # data = table.array.data # for i in range(len(data.dtype)): # name = data.dtype.names[i] # type = data.dtype[i] # if type.kind in ["f", "i"]: # only store float # #datagroup.create_dataset(name, data=table.array[name].astype(np.float64)) # #dataset.addMemoryColumn(name, table.array[name].astype(np.float64)) # dataset.addColumn(name, array=table.array[name]) dataset.samp_id = table_id dataset.name = table_id self.dataset_selector.add(dataset) return dataset finally: dialog.hide() def message(self, text, index=0): print(text) self.messages[index] = text text = "" keys = list(self.messages.keys()) keys.sort() text_parts = [self.messages[key] for key in keys] self.statusBar().showMessage(" | ".join(text_parts)) def _samp_find_datasets(self, id): print(self.dataset_selector.datasets) try: for dataset in self.dataset_selector.datasets: if dataset.matches_url(id) or (dataset.samp_id == id): yield dataset except: logger.exception("problem") def onSampSend(self): if self.samp is None: self.onSampConnect() dataset = self.dataset_panel.dataset params = {"rows": str(dataset._length), "columns": {}} params['id'] = dataset.filename type_map = {np.float64: "F8_LE", np.float32: "F4_LE", np.int64: "I8_LE", np.int32: "I4_LE", np.uint64: "U8_LE", np.uint32: "U4_LE"} print(type_map) for column_name in dataset.column_names: type = dataset.dtypes[column_name] if hasattr(type, "type"): type = type.type # TODO: why is this needed? bytes_type = np.zeros(1, dtype=type).dtype.itemsize column = { "filename": dataset.filenames[column_name], "type": type_map[type], "byte_offset": str(dataset.offsets[column_name]), "type_stride": str(dataset.strides[column_name]), "byte_stride": str(dataset.strides[column_name] * bytes_type), "bytes_type": str(bytes_type), } params["columns"][column_name] = column self.samp.client.callAll("send_mmap_" + dataset.name, {"samp.mtype": "table.load.memory_mapped_columns", "samp.params": params}) def onLoadTable(self, url, table_id, name): # this is called from a different thread! print("loading table", url, table_id, name) try: self.load(url, table_id, name) except: logger.exception("load table") return def load(self, url, table_id, name): print("parsing table...") table = astropy.io.votable.parse_single_table(url) print("done parsing table") names = table.array.dtype.names dataset = DatasetMemoryMapped(table_id, nommap=True) data = table.array.data for i in range(len(data.dtype)): name = data.dtype.names[i] type = data.dtype[i] if type.kind == "f": # only store float # datagroup.create_dataset(name, data=table.array[name].astype(np.float64)) dataset.addMemoryColumn(name, table.array[name].astype(np.float64)) self.dataset_selector.add(dataset) def center(self): qr = self.frameGeometry() cp = QtGui.QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def closeEvent(self, event): # print("close event") return reply = QtGui.QMessageBox.question(self, 'Message', "Are you sure to quit?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: event.accept() else: event.ignore() def clean_up(self): print("clean up") if self.samp is not None: print("disconnect samp") try: self.samp.client.disconnect() except: logger.exception("error disconnecting from SAMP hub") # event.accept() return app = None kernel = None """ from qtconsole.rich_jupyter_widget import RichJupyterWidget from qtconsole.inprocess import QtInProcessKernelManager from IPython.lib import guisupport """ def print_process_id(): print(('Process ID is:', os.getpid())) class Current(object): pass current = Current() # current.fig = None current.window = None # current.layer = None def main(argv=sys.argv[1:]): global main_thread global vaex global app global kernel global ipython_console global current vaex.set_log_level_warning() if app is None: app = QtGui.QApplication(argv) if not (frozen and darwin): # osx app has its own icon file import vaex.ui.icons icon = QtGui.QIcon(vaex.ui.icons.iconfile('vaex128')) app.setWindowIcon(icon) # import vaex.ipkernel_qtapp # ipython_window = vaex.ipkernel_qtapp.SimpleWindow(app) main_thread = QtCore.QThread.currentThread() # print select_many(None, "lala", ["aap", "noot"] + ["item-%d-%s" % (k, "-" * k) for k in range(30)]) # sys.exit(0) # sys._excepthook = sys.excepthook def qt_exception_hook(exctype, value, traceback): print("qt hook in thread: %r" % threading.currentThread()) sys.__excepthook__(exctype, value, traceback) qt_exception(None, exctype, value, traceback) # sys._excepthook(exctype, value, traceback) # sys.exit(1) sys.excepthook = qt_exception_hook vaex.promise.Promise.unhandled = staticmethod(qt_exception_hook) # raise RuntimeError, "blaat" vaex_app = VaexApp(argv, open_default=True) def plot(*args, **kwargs): vaex_app.plot(*args, **kwargs) def select(*args, **kwargs): vaex_app.select(*args, **kwargs) """if 1: # app = guisupport.get_app_qt4() print_process_id() # Create an in-process kernel # >>> print_process_id( ) # will print the same process ID as the main process kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel = kernel_manager.kernel kernel.gui = 'qt4' kernel.shell.push({'foo': 43, 'print_process_id': print_process_id, "vaex_app":vaex_app, "plot": plot, "current": current, "select": select}) kernel_client = kernel_manager.client() kernel_client.start_channels() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() app.exit() ipython_console = RichJupyterWidget() ipython_console.kernel_manager = kernel_manager ipython_console.kernel_client = kernel_client ipython_console.exit_requested.connect(stop) #ipython_console.show() sys.exit(guisupport.start_event_loop_qt4(app)) """ # w = QtGui.QWidget() # w.resize(250, 150) # w.move(300, 300) # w.setWindowTitle('Simple') # w.show() # ipython_window.show() # ipython_window.ipkernel.start() sys.exit(app.exec_()) def batch_copy_index(from_array, to_array, shuffle_array): N_per_batch = int(1e7) length = len(from_array) batches = int(math.ceil(float(length) / N_per_batch)) print(np.sum(from_array)) for i in range(batches): # print "batch", i, "out of", batches, "" sys.stdout.flush() i1 = i * N_per_batch i2 = min(length, (i + 1) * N_per_batch) # print "reading...", i1, i2 sys.stdout.flush() data = from_array[shuffle_array[i1:i2]] # print "writing..." sys.stdout.flush() to_array[i1:i2] = data<|fim▁end|>
if path.startswith("http") or path.startswith("ws"): dataset = vaex.open(path, thread_mover=self.call_in_main_thread) else: dataset = vaex.open(path)
<|file_name|>test_ldcdns.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import unittest import ldc import uuid class TestLDCDNSInterface(unittest.TestCase): def test_ldcdns(self): rand_str = str(uuid.uuid4()) ldc.dns.add(rand_str, '1.1.1.1') assert ldc.dns.resolve(rand_str) == [ '1.1.1.1' ] ldc.dns.replace_all(rand_str,'2.2.2.2') assert ldc.dns.resolve(rand_str) == [ '2.2.2.2' ]<|fim▁hole|> if __name__ == '__main__': unittest.main()<|fim▁end|>
ldc.dns.delete(rand_str) assert ldc.dns.resolve(rand_str) == []
<|file_name|>fstream.cc<|end_file_name|><|fim▁begin|>// Copyright (C) 2004-2013 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // { dg-require-fileio "" } // 27.6.1.3 unformatted input functions // NB: ostream has a particular "seeks" category. Adopt this for istreams too. // @require@ %-*.tst %-*.txt // @diff@ %-*.tst %-*.txt #include <istream> #include <sstream> #include <fstream> #include <testsuite_hooks.h> // fstreams void test04(void) { typedef std::wistream::off_type off_type; bool test __attribute__((unused)) = true; std::wistream::pos_type pos01, pos02, pos03, pos04, pos05, pos06; std::ios_base::iostate state01, state02; const char str_lit01[] = "wistream_seeks-1.txt"; const char str_lit02[] = "wistream_seeks-2.txt"; std::wifstream if01(str_lit01, std::ios_base::in | std::ios_base::out); std::wifstream if02(str_lit01, std::ios_base::in); std::wifstream if03(str_lit02, std::ios_base::out | std::ios_base::trunc); VERIFY( if01.good() ); VERIFY( if02.good() ); VERIFY( if03.good() ); std::wistream is01(if01.rdbuf()); std::wistream is02(if02.rdbuf()); std::wistream is03(if03.rdbuf()); // pos_type tellg() // in | out pos01 = is01.tellg(); pos02 = is01.tellg(); VERIFY( pos01 == pos02 ); // in pos03 = is02.tellg(); pos04 = is02.tellg();<|fim▁hole|> pos06 = is03.tellg(); VERIFY( pos05 == pos06 ); // cur // NB: see library issues list 136. It's the v-3 interp that seekg // only sets the input buffer, or else istreams with buffers that // have _M_mode == ios_base::out will fail to have consistency // between seekg and tellg. state01 = is01.rdstate(); is01.seekg(10, std::ios_base::cur); state02 = is01.rdstate(); pos01 = is01.tellg(); VERIFY( pos01 == pos02 + off_type(10) ); VERIFY( state01 == state02 ); pos02 = is01.tellg(); VERIFY( pos02 == pos01 ); } int main() { test04(); return 0; }<|fim▁end|>
VERIFY( pos03 == pos04 ); // out pos05 = is03.tellg();
<|file_name|>variable_inspector.js<|end_file_name|><|fim▁begin|>import React from "react"; import ReactDOM from "react-dom"; import VariableInspector from "./components/VariableInspector"; ReactDOM.render( <VariableInspector />, document.getElementById("root")<|fim▁hole|><|fim▁end|>
);
<|file_name|>XBee802.cpp<|end_file_name|><|fim▁begin|>/** * Copyright (c) 2015 Digi International Inc., * All rights not expressly granted are reserved. * * 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/. * * Digi International Inc. 11001 Bren Road East, Minnetonka, MN 55343 * ======================================================================= */ #include "XBee802.h" #include "IO/IOSample802.h" #include "Frames/802_Frames.h" #include "FrameHandlers/FH_ModemStatus.h" using namespace XBeeLib; /* Class constructor */ XBee802::XBee802(PinName tx, PinName rx, PinName reset, PinName rts, PinName cts, int baud) : XBee(tx, rx, reset, rts, cts, baud), _nd_handler(NULL), _rx_64b_handler(NULL), _rx_16b_handler(NULL), _io_data_64b_handler(NULL), _io_data_16b_handler(NULL) { } /* Class destructor */ XBee802::~XBee802() { unregister_node_discovery_cb(); unregister_receive_cb(); unregister_io_sample_cb(); } RadioStatus XBee802::init() { RadioStatus retval = XBee::init(); uint16_t addr16; RadioStatus error = get_network_address(&addr16); if (error == Success) { digi_log(LogLevelInfo, "ADDR16: %04x\r\n", addr16); } else { digi_log(LogLevelInfo, "ADDR16: UNKNOWN\r\n"); } const RadioProtocol radioProtocol = get_radio_protocol(); if (radioProtocol != Raw_802_15_4) { digi_log(LogLevelError, "Radio protocol does not match, needed a %d got a %d\r\n", Raw_802_15_4, radioProtocol); retval = Failure; } assert(radioProtocol == Raw_802_15_4); return retval; } RadioStatus XBee802::set_channel(uint8_t channel) { AtCmdFrame::AtCmdResp cmdresp; if (is_PRO()) { if (channel < 0x0C || channel > 0x17) { return Failure; } } else { if (channel < 0x0B || channel > 0x1A) { return Failure; } } cmdresp = set_param("CH", channel); if (cmdresp != AtCmdFrame::AtCmdRespOk) { return Failure; } return Success; } RadioStatus XBee802::get_channel(uint8_t * const channel) { if (channel == NULL) { return Failure; } AtCmdFrame::AtCmdResp cmdresp; uint32_t var32; cmdresp = get_param("CH", &var32); if (cmdresp != AtCmdFrame::AtCmdRespOk) { return Failure; } *channel = var32; return Success; } RadioStatus XBee802::set_panid(uint16_t panid) { AtCmdFrame::AtCmdResp cmdresp; cmdresp = set_param("ID", panid); if (cmdresp != AtCmdFrame::AtCmdRespOk) { return Failure; } return Success; } RadioStatus XBee802::get_panid(uint16_t * const panid) { if (panid == NULL) { return Failure; } AtCmdFrame::AtCmdResp cmdresp; uint32_t var32; cmdresp = get_param("ID", &var32); if (cmdresp != AtCmdFrame::AtCmdRespOk) { return Failure; } *panid = var32; return Success; } RadioStatus XBee802::set_network_address(uint16_t addr16) { AtCmdFrame::AtCmdResp cmdresp; cmdresp = set_param("MY", addr16); if (cmdresp != AtCmdFrame::AtCmdRespOk) { return Failure; } return Success; } void XBee802::radio_status_update(AtCmdFrame::ModemStatus modem_status) { /* Update the radio status variables */ if (modem_status == AtCmdFrame::HwReset) { _hw_reset_cnt++; } else if (modem_status == AtCmdFrame::WdReset) { _wd_reset_cnt++; } _modem_status = modem_status; digi_log(LogLevelDebug, "\r\nUpdating radio status: %02x\r\n", modem_status); } TxStatus XBee802::send_data(const RemoteXBee& remote, const uint8_t *const data, uint16_t len, bool syncr) { if (remote.is_valid_addr64b()) { const uint64_t remote64 = remote.get_addr64(); digi_log(LogLevelDebug, "send_data ADDR64: %08x:%08x\r\n", UINT64_HI32(remote64), UINT64_LO32(remote64)); TxFrame802 frame = TxFrame802(remote64, _tx_options, data, len); if (syncr) { return send_data(&frame); } else { frame.set_data(0, 0); /* Set frame id to 0 so there is no answer */ send_api_frame(&frame); return TxStatusSuccess; } } if (remote.is_valid_addr16b()) { const uint16_t remote16 = remote.get_addr16(); digi_log(LogLevelDebug, "send_data ADDR16: %04x\r\n", remote16); TxFrame802 frame = TxFrame802(remote16, _tx_options, data, len); if (syncr) { return send_data(&frame); } else { frame.set_data(0, 0); /* Set frame id to 0 so there is no answer */ send_api_frame(&frame); return TxStatusSuccess; } } return TxStatusInvalidAddr; } XBee802::AssocStatus XBee802::get_assoc_status(void) { return (AssocStatus)get_AI(); } RemoteXBee802 XBee802::get_remote_node_by_id(const char * const node_id) { uint64_t addr64; uint16_t addr16; _get_remote_node_by_id(node_id, &addr64, &addr16); return RemoteXBee802(addr64, addr16); } void XBee802::register_node_discovery_cb(node_discovery_802_cb_t function) { if (_nd_handler == NULL) { _nd_handler = new FH_NodeDiscovery802(); register_frame_handler(_nd_handler); } _nd_handler->register_node_discovery_cb(function); } void XBee802::unregister_node_discovery_cb() { if (_nd_handler != NULL) { _nd_handler->unregister_node_discovery_cb(); unregister_frame_handler(_nd_handler); delete _nd_handler; _nd_handler = NULL; /* as delete does not set to NULL */ } } void XBee802::register_receive_cb(receive_802_cb_t function) { if (_rx_64b_handler == NULL) { _rx_64b_handler = new FH_RxPacket64b802(); register_frame_handler(_rx_64b_handler); } _rx_64b_handler->register_receive_cb(function); if (_rx_16b_handler == NULL) { _rx_16b_handler = new FH_RxPacket16b802(); register_frame_handler(_rx_16b_handler); } _rx_16b_handler->register_receive_cb(function); } void XBee802::unregister_receive_cb() { if (_rx_64b_handler != NULL) { _rx_64b_handler->unregister_receive_cb(); unregister_frame_handler(_rx_64b_handler); delete _rx_64b_handler; _rx_64b_handler = NULL; /* as delete does not set to NULL */ } if (_rx_16b_handler != NULL) { _rx_16b_handler->unregister_receive_cb(); unregister_frame_handler(_rx_16b_handler); delete _rx_16b_handler; _rx_16b_handler = NULL; /* as delete does not set to NULL */ } } void XBee802::register_io_sample_cb(io_data_cb_802_t function) { if (_io_data_64b_handler == NULL) { _io_data_64b_handler = new FH_IoDataSampe64b802(); register_frame_handler(_io_data_64b_handler); } _io_data_64b_handler->register_io_data_cb(function); if (_io_data_16b_handler == NULL) { _io_data_16b_handler = new FH_IoDataSampe16b802(); register_frame_handler(_io_data_16b_handler); } _io_data_16b_handler->register_io_data_cb(function); } void XBee802::unregister_io_sample_cb() { if (_io_data_64b_handler != NULL) { _io_data_64b_handler->unregister_io_data_cb(); unregister_frame_handler(_io_data_64b_handler); delete _io_data_64b_handler; _io_data_64b_handler = NULL; /* as delete does not set to NULL */ } if (_io_data_16b_handler != NULL) { _io_data_16b_handler->unregister_io_data_cb(); unregister_frame_handler(_io_data_16b_handler); delete _io_data_16b_handler; _io_data_16b_handler = NULL; /* as delete does not set to NULL */ } } AtCmdFrame::AtCmdResp XBee802::get_param(const RemoteXBee& remote, const char * const param, uint32_t * const data) { uint16_t len = sizeof *data; AtCmdFrame::AtCmdResp atCmdResponse; if (remote.is_valid_addr64b()) { const uint64_t dev_addr64 = remote.get_addr64(); AtCmdFrame cmd_frame = AtCmdFrame(dev_addr64, param); atCmdResponse = send_at_cmd(&cmd_frame, (uint8_t *)data, &len, RadioRemote); } else if (remote.is_valid_addr16b()) { const uint16_t dev_addr16 = remote.get_addr16(); AtCmdFrame cmd_frame = AtCmdFrame(dev_addr16, param); atCmdResponse = send_at_cmd(&cmd_frame, (uint8_t *)data, &len, RadioRemote); } else { return AtCmdFrame::AtCmdRespInvalidAddr; } if (atCmdResponse == AtCmdFrame::AtCmdRespOk && len > sizeof *data) { atCmdResponse = AtCmdFrame::AtCmdRespLenMismatch; } return atCmdResponse; } AtCmdFrame::AtCmdResp XBee802::set_param(const RemoteXBee& remote, const char * const param, uint32_t data) { if (remote.is_valid_addr64b()) { const uint64_t dev_addr64 = remote.get_addr64(); AtCmdFrame cmd_frame = AtCmdFrame(dev_addr64, param, data); return send_at_cmd(&cmd_frame, NULL, NULL, RadioRemote); } if (remote.is_valid_addr16b()) { const uint16_t dev_addr16 = remote.get_addr16(); AtCmdFrame cmd_frame = AtCmdFrame(dev_addr16, param, data); return send_at_cmd(&cmd_frame, NULL, NULL, RadioRemote); } return AtCmdFrame::AtCmdRespInvalidAddr; } AtCmdFrame::AtCmdResp XBee802::set_param(const RemoteXBee& remote, const char * const param, const uint8_t * data, uint16_t len) { if (remote.is_valid_addr64b()) { const uint64_t dev_addr64 = remote.get_addr64(); AtCmdFrame cmd_frame = AtCmdFrame(dev_addr64, param, data, len); return send_at_cmd(&cmd_frame, NULL, NULL, RadioRemote); } if (remote.is_valid_addr16b()) { const uint16_t dev_addr16 = remote.get_addr16(); AtCmdFrame cmd_frame = AtCmdFrame(dev_addr16, param, data, len); return send_at_cmd(&cmd_frame, NULL, NULL, RadioRemote); } return AtCmdFrame::AtCmdRespInvalidAddr; } AtCmdFrame::AtCmdResp XBee802::get_param(const RemoteXBee& remote, const char * const param, uint8_t * const data, uint16_t * const len) { if (remote.is_valid_addr64b()) { uint64_t dev_addr64 = remote.get_addr64(); AtCmdFrame cmd_frame = AtCmdFrame(dev_addr64, param); return send_at_cmd(&cmd_frame, data, len, RadioRemote, false); } if (remote.is_valid_addr16b()) { uint16_t dev_addr16 = remote.get_addr16(); AtCmdFrame cmd_frame = AtCmdFrame(dev_addr16, param); return send_at_cmd(&cmd_frame, data, len, RadioRemote, false); } return AtCmdFrame::AtCmdRespInvalidAddr; } static void get_dio_cmd(XBee802::IoLine line, char * const iocmd) { if (line >= XBee802::PWM0) { iocmd[0] = 'P'; iocmd[1] = '0' + line - XBee802::PWM0; } else { iocmd[0] = 'D'; iocmd[1] = '0' + line; } iocmd[2] = '\0'; } RadioStatus XBee802::set_pin_config(const RemoteXBee& remote, IoLine line, IoMode mode) { AtCmdFrame::AtCmdResp cmdresp; char iocmd[3]; get_dio_cmd(line, iocmd); cmdresp = set_param(remote, iocmd, (uint8_t)mode); if (cmdresp != AtCmdFrame::AtCmdRespOk) { digi_log(LogLevelError, "set_pin_config: set_param returned %d\r\n", cmdresp); return Failure; } return Success; } RadioStatus XBee802::get_pin_config(const RemoteXBee& remote, IoLine line, IoMode * const mode) { AtCmdFrame::AtCmdResp cmdresp; char iocmd[3]; get_dio_cmd(line, iocmd); uint32_t var32; cmdresp = get_param(remote, iocmd, &var32); if (cmdresp != AtCmdFrame::AtCmdRespOk) { return Failure; } *mode = (IoMode)var32; return Success; } RadioStatus XBee802::set_dio(const RemoteXBee& remote, IoLine line, DioVal val) { if (line > DI8) { digi_log(LogLevelError, "set_dio: Pin %d not supported as IO\r\n", line); return Failure; } if (val == Low) { return set_pin_config(remote, line, DigitalOutLow); } else { return set_pin_config(remote, line, DigitalOutHigh); } } RadioStatus XBee802::get_dio(const RemoteXBee& remote, IoLine line, DioVal * const val) { return get_iosample(remote).get_dio(line, val); } RadioStatus XBee802::get_adc(const RemoteXBee& remote, IoLine line, uint16_t * const val) { return get_iosample(remote).get_adc(line, val); } <|fim▁hole|>{ AtCmdFrame::AtCmdResp cmdresp; char iocmd[3] = { 'M', '0', '\0' }; if (line != PWM0 && line != PWM1) { return Failure; } if (line == PWM1) { iocmd[1] = '1'; } uint16_t pwm_val = (uint16_t)(duty_cycle * DR_PWM_MAX_VAL / 100); cmdresp = set_param(remote, iocmd, pwm_val); return cmdresp == AtCmdFrame::AtCmdRespOk ? Success : Failure; } IOSample802 XBee802::get_iosample(const RemoteXBee& remote) { uint8_t io_sample[MAX_IO_SAMPLE_802_LEN]; uint16_t len = sizeof io_sample; RadioStatus resp = _get_iosample(remote, io_sample, &len); if (resp != Success) { digi_log(LogLevelError, "XBee802::get_iosample failed to get an IOSample\r\n"); len = 0; } return IOSample802(io_sample, len); } static uint8_t get_dio_mask(XBee802::IoLine line) { switch (line) { case XBee802::DIO4_AD4: return (1 << 0); case XBee802::DIO3_AD3: return (1 << 1); case XBee802::DIO2_AD2: return (1 << 2); case XBee802::DIO1_AD1: return (1 << 3); case XBee802::DIO0_AD0: return (1 << 4); case XBee802::DIO6: return (1 << 5); case XBee802::DI8: return (1 << 6); default: return 0; } } RadioStatus XBee802::set_pin_pull_up(const RemoteXBee& remote, IoLine line, bool enable) { AtCmdFrame::AtCmdResp cmdresp; uint32_t var32; uint8_t pr; cmdresp = get_param(remote, "PR", &var32); if (cmdresp != AtCmdFrame::AtCmdRespOk) { return Failure; } pr = var32; const uint8_t dio_mask = get_dio_mask(line); if (dio_mask == 0) { digi_log(LogLevelError, "XBee802::set_pin_pull_up: invalid pin %d\r\n", line); return Failure; } if (enable) { pr |= dio_mask; } else { pr &= ~dio_mask; } cmdresp = set_param(remote, "PR", pr); return cmdresp == AtCmdFrame::AtCmdRespOk ? Success : Failure; } static uint8_t get_dio_ic_mask(XBee802::IoLine line) { if (line < XBee802::DI8) { return (1 << line); } return 0; } RadioStatus XBee802::enable_dio_change_detection(const RemoteXBee& remote, IoLine line, bool enable) { if (line > DIO7) { digi_log(LogLevelError, "XBee802::enable_dio_change_detection: pin not supported (%d)\r\n", line); return Failure; } AtCmdFrame::AtCmdResp cmdresp; uint32_t var32; uint8_t ic; cmdresp = get_param(remote, "IC", &var32); if (cmdresp != AtCmdFrame::AtCmdRespOk) { return Failure; } ic = var32; const uint8_t dio_mask = get_dio_ic_mask(line); if (dio_mask == 0) { digi_log(LogLevelError, "XBeeZB::enable_dio_change_detection: invalid pin %d\r\n", line); return Failure; } if (enable) { ic |= dio_mask; } else { ic &= ~dio_mask; } cmdresp = set_param(remote, "IC", ic); return cmdresp == AtCmdFrame::AtCmdRespOk ? Success : Failure; } #ifdef GET_PWM_AVAILABLE RadioStatus XBee802::get_pwm(const RemoteXBee& remote, IoLine line, float * const duty_cycle) { AtCmdFrame::AtCmdResp cmdresp; char iocmd[3] = { 'M', '0', '\0' }; if (line != PWM0 && line != PWM1) { return Failure; } if (line == PWM1) { iocmd[1] = '1'; } uint16_t pwm_val; cmdresp = get_param(remote, iocmd, &pwm_val); if (cmdresp != AtCmdFrame::AtCmdRespOk) { return Failure; } *duty_cycle = (float)(pwm_val * 100 / DR_PWM_MAX_VAL); return Success; } #endif<|fim▁end|>
RadioStatus XBee802::set_pwm(const RemoteXBee& remote, IoLine line, float duty_cycle)
<|file_name|>generator.go<|end_file_name|><|fim▁begin|>package main import ( "bytes" "fmt" "html" "strings" "text/template" b64 "encoding/base64" "github.com/bsm/openrtb" ) const ( //Auction Macros AUCTION_ID = "${AUCTION_ID}" AUCTION_IMP_ID = "${AUCTION_IMP_ID}" AUCTION_SEAT_ID = "${AUCTION_SEAT_ID}" AUCTION_AD_ID = "${AUCTION_AD_ID}" AUCTION_PRICE = "${AUCTION_PRICE}" AUCTION_CURRENCY = "${IMAGE}" // Tempate for One AdUnit AD_TEMPLATE = ` <li> <h3>Bid Response</h3> <h2>{{ .Bid.Id }}</h2> <h3>{{ .Bid.Price }}</h3> <p>{{ .EscapedAdm }}</p> <h3>Rendered Snippet</h3> <iframe src="data:text/html;base64, {{ .Base64Snip }}" scrolling=no marginwidth=0 marginheight=0></iframe> </li>` ) type Bid struct { Bid openrtb.Bid } func (bid Bid) Base64Snip() string { return b64.StdEncoding.EncodeToString([]byte(*bid.Bid.Adm)) } func (bid Bid) EscapedAdm() string { return html.EscapeString(*bid.Bid.Adm) } var ( responseTpl, _ = template.New("Ad").Parse(AD_TEMPLATE) ) //BidSummary can be used as shared bid summary across routines OR create one per routine and //merge stats after all routines have returned type BidSummary struct { BIDS, NOBIDS, ERROR, UNKNOWN int Html string } // take a valid response and turn it into HTML to be rendered func generate(resp *openrtb.Response) string { var buffer bytes.Buffer for _, seatbid := range resp.Seatbid { for _, bid := range seatbid.Bid { replaceMacros(bid.Adm)<|fim▁hole|> responseTpl.Execute(&buffer, Bid{bid}) //TODO: replaceMacros(bid.Adm)) } } return buffer.String() } func replaceMacros(adm *string) { //TODO: write a real func *adm = strings.Replace(*adm, AUCTION_ID, randSeq(10), -1) *adm = strings.Replace(*adm, AUCTION_IMP_ID, randSeq(10), -1) *adm = strings.Replace(*adm, AUCTION_SEAT_ID, randSeq(10), -1) *adm = strings.Replace(*adm, AUCTION_AD_ID, randSeq(10), -1) *adm = strings.Replace(*adm, AUCTION_CURRENCY, randSeq(7), -1) *adm = strings.Replace(*adm, AUCTION_PRICE, randPrice(), -1) } func renderFinalHtml(body string) string { return fmt.Sprintf(`<html> <head> </head> <body> <ul> %s </ul> </body> </html>`, body) }<|fim▁end|>
<|file_name|>test.py<|end_file_name|><|fim▁begin|># # Copyright 2013 eNovance # # 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. """Test alarm notifier.""" from ceilometer.alarm import notifier class TestAlarmNotifier(notifier.AlarmNotifier): "Test alarm notifier.""" <|fim▁hole|> def notify(self, action, alarm_id, alarm_name, severity, previous, current, reason, reason_data): self.notifications.append((action, alarm_id, alarm_name, severity, previous, current, reason, reason_data))<|fim▁end|>
def __init__(self): self.notifications = []
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>""" A collection of Xentica models and experiments. Indended to illustrate how to use the framework. """<|fim▁end|>
<|file_name|>objects.js<|end_file_name|><|fim▁begin|>let obj = { @readonly firstName: "first", @readonly lastName: "last", @nonconfigurable fullName() { return `${this.firstName} ${this.lastName}`; } }; /* // Desugaring // // The following is an approximate down-level desugaring to match the expected semantics. // The actual host implementation would generally be more efficient. let obj = declareObject( // Object literal declaration { firstName: "first", lastName: "last", fullName() { return `${this.firstName} ${this.lastName}`; } }, // Object description { members: [ { kind: "property", name: "firstName", decorations: [readonly] }, { kind: "property", name: "lastName", decorations: [readonly] }, { kind: "method", name: "fullName", decorations: [nonconfigurable] } <|fim▁hole|> ] } ).finishDeclarationInitialization(); */<|fim▁end|>
<|file_name|>main.py<|end_file_name|><|fim▁begin|>from inventory import Inventory import cmd from room import get_room from player import Player import textwrap import time import random class Controls(cmd.Cmd): prompt = '> ' def __init__(self): #----------------------------------------------------------------------- #Here the game is initialized asking for commands via the Cmd module, #the variables given are the first room you start in and prints out the #location cmd.Cmd.__init__(self) self.loc = get_room('intro') self.look() self.pos() self.event = Events() self.inventory = Inventory() self.Player = Player() #------------------------------------------------------------------------ #This checks which room you are in if you can go the way for the command #given and prints out your location def emptyline(self): pass def objects(self, args): objects = self.loc._objects(args) if objects is None: print(('Ther are no ' + repr(args) + ' in the area' )) self.look() else: self.look() def move(self, dir): newroom = self.loc._neighbor(dir) if newroom is None: print('''You cannot go this away''') self.look() else: self.loc = get_room(newroom) self.look() # event.spawnAtPos() def pos(self): position = self.loc.name def look(self): # print((self.loc.name)) for line in textwrap.wrap(self.loc.description, 72): print(line) print('') #----------------------------------------------------------------------- #commands #movement def do_n(self, args): '''goes north''' self.move('n') def do_s(self, args): '''goes south''' self.move('s') def do_e(self, args): '''goes east''' self.move('e') self.move('east') def do_w(self, args): '''goes west''' self.move('w') def do_climb(self, args): '''Climbs where possible''' self.move('climb') def do_get(self, args): '''Gets items from an area or from your bag''' if self.inventory.slots[args] > 0: self.player.right_hand(args) else: print('You do not have this item') def do_enter(self, args): '''Enters rooms, Villages, and caves where possible''' self.move('enter') def do_leave(self, args): '''Exits the current room''' self.move('leave') def help_get(self): for i in (textwrap.wrap(''' If you are trying to grab an item out from your bag type get followed by the item in your bag, this applys to items in an area as well''', 72)): print(('', i)) #prompts def do_sky(self, args): self.event.sky() def do_time(self, args): self.event.timeOfDay()<|fim▁hole|> def do_chop(self, args): self.objects('trees') def do_name(self, args): '''Prints the users name if there is one''' self.player.player_name() def do_hand(self, args): '''Prints what is in hand''' if self.Player.hand() == ' ': print("You are not holding anything") else: print(self.Player.hand()) def do_next(self, args): '''Gets the next event''' self.move('next') def do_look(self, args): '''Prints the current area you are in''' self.look() def do_inventory(self, args): '''Checks Inventory''' self.inventory.bag() self.look() def do_quit(self, args): '''Quits the game''' print("thank you for playing") return True ''' def do_pos(self, args): print(self.loc.name) ''' class Events(object): # In this events class we will handle all game events such as time, # spawning of monsters, and possibly special event occurenses based on date, time of day # I'm thinking of making this games time as the same as the system time. def __init__(self): self.room = Controls.pos self.time = time def timeOfDay(self): print('The time is ' + time.strftime('%I:%M %p')) def sky(self): timeInInt = int(time.strftime("%I")) timeInAmPm = time.strftime("%p") if timeInAmPm == 'AM': print("It is morning") elif timeInAmPm == 'PM': if timeInInt <= 5: print("It is afternoon") elif timeInInt > 5 & timeInInt <= 11: print("It is night") #------------------------------------------------- # creature spawning def spawAtPos(self): chance = random.randrange(100) for i in chance: if i <= 49: print("There is a monster in the area") else: print("The area seems safe for now") if __name__ == '__main__': c = Controls() c.cmdloop()<|fim▁end|>
<|file_name|>tags.py<|end_file_name|><|fim▁begin|>import parsers import tokenizer import context html_escape_table = { "&": "&amp;", '"': "&quot;", "'": "&apos;", ">": "&gt;", "<": "&lt;", } def html_escape(text): """Produce entities within text.""" return "".join(html_escape_table.get(c,c) for c in unicode(text)) class Tag(object): def __init__(self, args): self.args = args def render(self, context): return '' class PairedTag(Tag): def __init__(self, args): self.children = [] super(PairedTag, self).__init__(args) def render(self, context): char_buffer = '' for child in self.children: char_buffer += unicode(child.render(context)) return char_buffer class SingleLineTag(Tag): pass class TemplateContentTag(PairedTag): pass class LiteralContent(Tag): def __init__(self, content): self.content = content def render(self, context): return unicode(self.content) #tags should support expressions, like #index+1 class EscapedContentTag(Tag): def render(self, context): ct = tokenizer.ExpressionTokenizer() parser = parsers.TopDownParser(ct.yield_tokens(' '.join(self.args))) return html_escape(parser.parse().eval(context)) #tags should support expressions, like index+1 class UnescapedContentTag(Tag): def render(self, context): ct = tokenizer.ExpressionTokenizer() parser = parsers.TopDownParser(ct.yield_tokens(' '.join(self.args))) return unicode(parser.parse().eval(context)) class CommentTag(Tag): def render(self, context): return '' <|fim▁hole|> def render(self, context): #if tag can have an else tag too, so we need to first check for that. #this is a stack of groups to evaluate in order expression_groups = [] current_group = [] current_group_conditional = self for child in self.children: if type(child) == ElseTag: expression_groups.append((current_group_conditional, current_group)) current_group_conditional = child current_group = [] else: current_group.append(child) expression_groups.append((current_group_conditional, current_group)) retval = '' for conditional, tag_group in expression_groups: ct = tokenizer.ExpressionTokenizer() parser = parsers.TopDownParser(ct.yield_tokens(' '.join(conditional.args))) if len(parser.tokens): if parser.parse().eval(context): for tag in tag_group: retval += unicode(tag.render(context)) break else: for tag in tag_group: retval += unicode(tag.render(context)) break return retval class ElseTag(Tag): def render(self, context): raise Exception("Cannot call render directly on else tag") class ForTag(PairedTag): closing_literal = 'for' def render(self, var_context): if len(self.args) <> 3: raise Exception('The for tag takes exactly three arguments following the pattern instance_var in iterable') for_child_tags = [] else_child_tags = [] in_else_tag = False for child in self.children: if in_else_tag: else_child_tags.append(child) else: for_child_tags.append(child) if type(child) == ElseTag: in_else_tag = True class_var = self.args[0] iterable = var_context.eval(self.args[2]) retval = '' cnt = 0 if iterable and len(iterable): for item in iterable: #add the current class var in the context dictionary for all children. it could #overlay something already existing, but that's fine. local_context = context.ContextWrap(var_context.context, { class_var: item, '#index' : cnt }) cnt+=1 for child in for_child_tags: retval += child.render(local_context) else: for child in else_child_tags: retval += child.render(var_context) return retval class VerbatimTag(PairedTag): closing_literal = 'verbatim' TagMap = { 'render' : EscapedContentTag, ':' : EscapedContentTag, '>' : UnescapedContentTag, '#' : CommentTag, 'if' : IfTag, 'else' : ElseTag, 'elif' : ElseTag, 'verbatim' : VerbatimTag, 'for' : ForTag, }<|fim▁end|>
class IfTag(PairedTag): closing_literal = 'if'
<|file_name|>text.rs<|end_file_name|><|fim▁begin|>use crate::color::conv::IntoLinSrgba; use crate::draw::drawing::DrawingContext; use crate::draw::primitive::Primitive; use crate::draw::properties::spatial::{self, dimension, orientation, position}; use crate::draw::properties::{ ColorScalar, LinSrgba, SetColor, SetDimensions, SetOrientation, SetPosition, }; use crate::draw::{self, theme, Drawing}; use crate::geom::{self, Vector2}; use crate::math::{BaseFloat, Zero}; use crate::text::{self, Align, Font, FontSize, Justify, Layout, Scalar, Wrap}; /// Properties related to drawing the **Text** primitive. #[derive(Clone, Debug)] pub struct Text<S = geom::scalar::Default> { spatial: spatial::Properties<S>, style: Style, // The byte range into the `Draw` context's text buffer. text: std::ops::Range<usize>, } /// Styling properties for the **Text** primitive. #[derive(Clone, Debug, Default)] pub struct Style { pub color: Option<LinSrgba>, pub glyph_colors: Vec<LinSrgba>, // Overrides `color` if non-empty. pub layout: text::layout::Builder, } /// The drawing context for the **Text** primitive. pub type DrawingText<'a, S = geom::scalar::Default> = Drawing<'a, Text<S>, S>; impl<S> Text<S> { /// Begin drawing some text. pub fn new(ctxt: DrawingContext<S>, text: &str) -> Self where S: Zero, { let start = ctxt.text_buffer.len(); ctxt.text_buffer.push_str(text); let end = ctxt.text_buffer.len(); let text = start..end; let spatial = Default::default(); let style = Default::default(); Text { spatial, style, text, } } // Apply the given function to the inner text layout. fn map_layout<F>(mut self, map: F) -> Self where F: FnOnce(text::layout::Builder) -> text::layout::Builder, { self.style.layout = map(self.style.layout); self } /// The font size to use for the text. pub fn font_size(self, size: FontSize) -> Self { self.map_layout(|l| l.font_size(size)) } /// Specify whether or not text should be wrapped around some width and how to do so. /// /// The default value is `DEFAULT_LINE_WRAP`. pub fn line_wrap(self, line_wrap: Option<Wrap>) -> Self { self.map_layout(|l| l.line_wrap(line_wrap)) } /// Specify that the **Text** should not wrap lines around the width. /// /// Shorthand for `builder.line_wrap(None)`. pub fn no_line_wrap(self) -> Self { self.map_layout(|l| l.no_line_wrap()) } /// Line wrap the **Text** at the beginning of the first word that exceeds the width. /// /// Shorthand for `builder.line_wrap(Some(Wrap::Whitespace))`. pub fn wrap_by_word(self) -> Self { self.map_layout(|l| l.wrap_by_word()) } /// Line wrap the **Text** at the beginning of the first character that exceeds the width. /// /// Shorthand for `builder.line_wrap(Some(Wrap::Character))`. pub fn wrap_by_character(self) -> Self { self.map_layout(|l| l.wrap_by_character()) } /// A method for specifying the `Font` used for displaying the `Text`. pub fn font(self, font: Font) -> Self { self.map_layout(|l| l.font(font)) } /// Describe the end along the *x* axis to which the text should be aligned. pub fn justify(self, justify: Justify) -> Self { self.map_layout(|l| l.justify(justify)) } /// Align the text to the left of its bounding **Rect**'s *x* axis range. pub fn left_justify(self) -> Self { self.map_layout(|l| l.left_justify()) } /// Align the text to the middle of its bounding **Rect**'s *x* axis range. pub fn center_justify(self) -> Self { self.map_layout(|l| l.center_justify()) } /// Align the text to the right of its bounding **Rect**'s *x* axis range. pub fn right_justify(self) -> Self { self.map_layout(|l| l.right_justify()) } /// Specify how much vertical space should separate each line of text. pub fn line_spacing(self, spacing: Scalar) -> Self { self.map_layout(|l| l.line_spacing(spacing)) } /// Specify how the whole text should be aligned along the y axis of its bounding rectangle pub fn y_align(self, align: Align) -> Self { self.map_layout(|l| l.y_align(align)) } /// Align the top edge of the text with the top edge of its bounding rectangle. pub fn align_top(self) -> Self { self.map_layout(|l| l.align_top()) } /// Align the middle of the text with the middle of the bounding rect along the y axis. /// /// This is the default behaviour. pub fn align_middle_y(self) -> Self { self.map_layout(|l| l.align_middle_y()) } /// Align the bottom edge of the text with the bottom edge of its bounding rectangle. pub fn align_bottom(self) -> Self { self.map_layout(|l| l.align_bottom()) } /// Set all the parameters via an existing `Layout` pub fn layout(self, layout: &Layout) -> Self { self.map_layout(|l| l.layout(layout)) } /// Specify the entire styling for the **Text**. pub fn with_style(mut self, style: Style) -> Self { self.style = style; self } /// Set a color for each glyph. /// Colors unspecified glyphs using the drawing color. pub fn glyph_colors(mut self, colors: Vec<LinSrgba>) -> Self { self.style.glyph_colors = colors; self } } impl<'a, S> DrawingText<'a, S> where S: BaseFloat, { /// The font size to use for the text. pub fn font_size(self, size: text::FontSize) -> Self { self.map_ty(|ty| ty.font_size(size)) } /// Specify that the **Text** should not wrap lines around the width. pub fn no_line_wrap(self) -> Self { self.map_ty(|ty| ty.no_line_wrap()) } /// Line wrap the **Text** at the beginning of the first word that exceeds the width. pub fn wrap_by_word(self) -> Self { self.map_ty(|ty| ty.wrap_by_word()) } /// Line wrap the **Text** at the beginning of the first character that exceeds the width. pub fn wrap_by_character(self) -> Self { self.map_ty(|ty| ty.wrap_by_character()) } /// A method for specifying the `Font` used for displaying the `Text`. pub fn font(self, font: text::Font) -> Self { self.map_ty(|ty| ty.font(font)) } /// Build the **Text** with the given **Style**. pub fn with_style(self, style: Style) -> Self { self.map_ty(|ty| ty.with_style(style)) } /// Describe the end along the *x* axis to which the text should be aligned. pub fn justify(self, justify: text::Justify) -> Self { self.map_ty(|ty| ty.justify(justify)) } /// Align the text to the left of its bounding **Rect**'s *x* axis range. pub fn left_justify(self) -> Self { self.map_ty(|ty| ty.left_justify()) } /// Align the text to the middle of its bounding **Rect**'s *x* axis range. pub fn center_justify(self) -> Self { self.map_ty(|ty| ty.center_justify()) } /// Align the text to the right of its bounding **Rect**'s *x* axis range. pub fn right_justify(self) -> Self { self.map_ty(|ty| ty.right_justify()) } /// Specify how much vertical space should separate each line of text. pub fn line_spacing(self, spacing: text::Scalar) -> Self { self.map_ty(|ty| ty.line_spacing(spacing)) } /// Specify how the whole text should be aligned along the y axis of its bounding rectangle pub fn y_align_text(self, align: Align) -> Self { self.map_ty(|ty| ty.y_align(align)) } /// Align the top edge of the text with the top edge of its bounding rectangle. pub fn align_text_top(self) -> Self { self.map_ty(|ty| ty.align_top()) } /// Align the middle of the text with the middle of the bounding rect along the y axis. /// /// This is the default behaviour. pub fn align_text_middle_y(self) -> Self { self.map_ty(|ty| ty.align_middle_y()) } /// Align the bottom edge of the text with the bottom edge of its bounding rectangle. pub fn align_text_bottom(self) -> Self { self.map_ty(|ty| ty.align_bottom()) }<|fim▁hole|> pub fn layout(self, layout: &Layout) -> Self { self.map_ty(|ty| ty.layout(layout)) } /// Set a color for each glyph. /// Colors unspecified glyphs using the drawing color. pub fn glyph_colors<I, C>(self, glyph_colors: I) -> Self where I: IntoIterator<Item = C>, C: IntoLinSrgba<ColorScalar>, { let glyph_colors = glyph_colors .into_iter() .map(|c| c.into_lin_srgba()) .collect(); self.map_ty(|ty| ty.glyph_colors(glyph_colors)) } } impl draw::renderer::RenderPrimitive for Text<f32> { fn render_primitive( self, ctxt: draw::renderer::RenderContext, mesh: &mut draw::Mesh, ) -> draw::renderer::PrimitiveRender { let Text { spatial, style, text, } = self; let Style { color, glyph_colors, layout, } = style; let layout = layout.build(); let (maybe_x, maybe_y, maybe_z) = ( spatial.dimensions.x, spatial.dimensions.y, spatial.dimensions.z, ); assert!( maybe_z.is_none(), "z dimension support for text is unimplemented" ); let w = maybe_x .map(|s| <f32 as crate::math::NumCast>::from(s).unwrap()) .unwrap_or(200.0); let h = maybe_y .map(|s| <f32 as crate::math::NumCast>::from(s).unwrap()) .unwrap_or(200.0); let rect: geom::Rect = geom::Rect::from_wh(Vector2 { x: w, y: h }); let color = color.unwrap_or_else(|| ctxt.theme.fill_lin_srgba(&theme::Primitive::Text)); let text_str = &ctxt.text_buffer[text.clone()]; let text = text::text(text_str).layout(&layout).build(rect); // Queue the glyphs to be cached let font_id = text::font::id(text.font()); let positioned_glyphs: Vec<_> = text .rt_glyphs( ctxt.output_attachment_size, ctxt.output_attachment_scale_factor, ) .collect(); for glyph in positioned_glyphs.iter() { ctxt.glyph_cache.queue_glyph(font_id.index(), glyph.clone()); } // Cache the enqueued glyphs within the pixel buffer. let (glyph_cache_w, _) = ctxt.glyph_cache.dimensions(); { let draw::renderer::RenderContext { glyph_cache: &mut draw::renderer::GlyphCache { ref mut cache, ref mut pixel_buffer, ref mut requires_upload, .. }, .. } = ctxt; let glyph_cache_w = glyph_cache_w as usize; let res = cache.cache_queued(|rect, data| { let width = (rect.max.x - rect.min.x) as usize; let height = (rect.max.y - rect.min.y) as usize; let mut dst_ix = rect.min.y as usize * glyph_cache_w + rect.min.x as usize; let mut src_ix = 0; for _ in 0..height { let dst_range = dst_ix..dst_ix + width; let src_range = src_ix..src_ix + width; let dst_slice = &mut pixel_buffer[dst_range]; let src_slice = &data[src_range]; dst_slice.copy_from_slice(src_slice); dst_ix += glyph_cache_w; src_ix += width; } *requires_upload = true; }); if let Err(err) = res { eprintln!("failed to cache queued glyphs: {}", err); } } // Determine the transform to apply to all points. let global_transform = ctxt.transform; let local_transform = spatial.position.transform() * spatial.orientation.transform(); let transform = global_transform * local_transform; // A function for converting RustType rects to nannou rects. let scale_factor = ctxt.output_attachment_scale_factor; let (out_w, out_h) = ctxt.output_attachment_size.into(); let [half_out_w, half_out_h] = [out_w as f32 / 2.0, out_h as f32 / 2.0]; let to_nannou_rect = |screen_rect: text::rt::Rect<i32>| { let l = screen_rect.min.x as f32 / scale_factor - half_out_w; let r = screen_rect.max.x as f32 / scale_factor - half_out_w; let t = -(screen_rect.min.y as f32 / scale_factor - half_out_h); let b = -(screen_rect.max.y as f32 / scale_factor - half_out_h); geom::Rect::from_corners(geom::pt2(l, b), geom::pt2(r, t)) }; // Extend the mesh with a rect for each displayed glyph. // If `glyph_colors` contains insufficient colors, use `color` for the remaining glyphs. for (g, g_color) in positioned_glyphs .iter() .zip(glyph_colors.iter().chain(std::iter::repeat(&color))) { if let Ok(Some((uv_rect, screen_rect))) = ctxt.glyph_cache.rect_for(font_id.index(), &g) { let rect = to_nannou_rect(screen_rect); // Create a mesh-compatible vertex from the position and tex_coords. let v = |position, tex_coords: [f32; 2]| -> draw::mesh::Vertex { let p = geom::Point3::from(position); let p = cgmath::Transform::transform_point(&transform, p.into()); let point = draw::mesh::vertex::Point::from(p); draw::mesh::vertex::new(point, g_color.to_owned(), tex_coords.into()) }; // The sides of the UV rect. let uv_l = uv_rect.min.x; let uv_t = uv_rect.min.y; let uv_r = uv_rect.max.x; let uv_b = uv_rect.max.y; // Insert the vertices. let bottom_left = v(rect.bottom_left(), [uv_l, uv_b]); let bottom_right = v(rect.bottom_right(), [uv_r, uv_b]); let top_left = v(rect.top_left(), [uv_l, uv_t]); let top_right = v(rect.top_right(), [uv_r, uv_t]); let start_ix = mesh.points().len() as u32; mesh.push_vertex(top_left); mesh.push_vertex(bottom_left); mesh.push_vertex(bottom_right); mesh.push_vertex(top_right); // Now the indices. let tl_ix = start_ix; let bl_ix = start_ix + 1; let br_ix = start_ix + 2; let tr_ix = start_ix + 3; mesh.push_index(tl_ix); mesh.push_index(bl_ix); mesh.push_index(br_ix); mesh.push_index(tl_ix); mesh.push_index(br_ix); mesh.push_index(tr_ix); } } draw::renderer::PrimitiveRender::text() } } impl<S> SetOrientation<S> for Text<S> { fn properties(&mut self) -> &mut orientation::Properties<S> { SetOrientation::properties(&mut self.spatial) } } impl<S> SetPosition<S> for Text<S> { fn properties(&mut self) -> &mut position::Properties<S> { SetPosition::properties(&mut self.spatial) } } impl<S> SetDimensions<S> for Text<S> { fn properties(&mut self) -> &mut dimension::Properties<S> { SetDimensions::properties(&mut self.spatial) } } impl<S> SetColor<ColorScalar> for Text<S> { fn rgba_mut(&mut self) -> &mut Option<LinSrgba> { SetColor::rgba_mut(&mut self.style.color) } } // Primitive conversions. impl<S> From<Text<S>> for Primitive<S> { fn from(prim: Text<S>) -> Self { Primitive::Text(prim) } } impl<S> Into<Option<Text<S>>> for Primitive<S> { fn into(self) -> Option<Text<S>> { match self { Primitive::Text(prim) => Some(prim), _ => None, } } }<|fim▁end|>
/// Set all the parameters via an existing `Layout`
<|file_name|>client.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # author: bambooom ''' My Diary Web App - CLI for client ''' import sys reload(sys) sys.setdefaultencoding('utf-8') import requests from bs4 import BeautifulSoup import re HELP = ''' Input h/help/? for help. Input q/quit to quit the process. Input s/sync to sync the diary log. Input lt/ListTags to list all tags. Input st:TAG to set or delete tags Input FLUSH to clear all diary entries. '''<|fim▁hole|>url = "http://bambooomdiary.sinaapp.com/" def get_log_all(): response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") log = '' for i in soup.find_all('pre'): log += i.get_text()+'\n' return log def get_log_bytag(tags): response = requests.get(url) soup = BeautifulSoup(response.text,"html.parser") ti=list(soup.find_all('i', class_='etime')) ta=list(soup.find_all('i', class_='tags')) di=list(soup.find_all('pre',class_='diary')) for i in range(len(list(ti))): if ta[i].get_text() == 'TAG:'+tags: print "%s %s" %(ti[i].get_text(),di[i].get_text()) def get_tags(): response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") temp =[] for i in soup.find_all('i', class_='tags'): temp.append(i.get_text()) tag_set = list(set(temp)) for i in tag_set: print i def delete_log(): res = raw_input('ARE YOU SURE?(y/n)>') if res.lower() == 'y': response = requests.delete(url) print "All clear!Restart a new diary!" else: print "Well, keep going on!" def write_log(message, tags): values = {'newdiary':message,'tags':tags} response = requests.post(url, data=values) def client(): print HELP tags='' while True: print 'TAG:'+tags message = raw_input('Input>') if message in ['h','help','?']: print HELP elif message in ['s','sync']: get_log_bytag(tags) elif message in ['q','quit']: print 'Bye~' break elif message in ['lt','ListTags']: get_tags() elif message.startswith('st:'): tags = message[3:] elif message == 'FLUSH': delete_log() else: write_log(message,tags) if __name__ == '__main__': client()<|fim▁end|>
<|file_name|>test_api.py<|end_file_name|><|fim▁begin|># encoding: utf-8 """Tests of Branding API """ from __future__ import absolute_import, unicode_literals import mock from django.conf import settings from django.test import TestCase from django.test.utils import override_settings from django.urls import reverse from branding.api import _footer_business_links, get_footer, get_home_url, get_logo_url from edxmako.shortcuts import marketing_link from openedx.core.djangoapps.site_configuration.tests.test_util import with_site_configuration test_config_disabled_contact_us = { # pylint: disable=invalid-name "CONTACT_US_ENABLE": False, } test_config_custom_url_contact_us = { # pylint: disable=invalid-name "CONTACT_US_ENABLE": True, "CONTACT_US_CUSTOM_LINK": "https://open.edx.org/", } class TestHeader(TestCase): """Test API end-point for retrieving the header. """ def test_cdn_urls_for_logo(self): # Ordinarily, we'd use `override_settings()` to override STATIC_URL, # which is what the staticfiles storage backend is using to construct the URL. # Unfortunately, other parts of the system are caching this value on module # load, which can cause other tests to fail. To ensure that this change # doesn't affect other tests, we patch the `url()` method directly instead. cdn_url = "http://cdn.example.com/static/image.png" with mock.patch('branding.api.staticfiles_storage.url', return_value=cdn_url): logo_url = get_logo_url() self.assertEqual(logo_url, cdn_url) def test_home_url_with_mktg_disabled(self): expected_url = get_home_url() self.assertEqual(reverse('dashboard'), expected_url) @mock.patch.dict('django.conf.settings.FEATURES', {'ENABLE_MKTG_SITE': True}) @mock.patch.dict('django.conf.settings.MKTG_URLS', { "ROOT": "https://edx.org", }) def test_home_url_with_mktg_enabled(self): expected_url = get_home_url() self.assertEqual(marketing_link('ROOT'), expected_url) class TestFooter(TestCase): """Test retrieving the footer. """ maxDiff = None @mock.patch.dict('django.conf.settings.FEATURES', {'ENABLE_MKTG_SITE': True}) @mock.patch.dict('django.conf.settings.MKTG_URLS', { "ROOT": "https://edx.org", "ENTERPRISE": "/enterprise" }) @override_settings(ENTERPRISE_MARKETING_FOOTER_QUERY_PARAMS={}, PLATFORM_NAME='\xe9dX') def test_footer_business_links_no_marketing_query_params(self): """ Enterprise marketing page values returned should be a concatenation of ROOT and ENTERPRISE marketing url values when ENTERPRISE_MARKETING_FOOTER_QUERY_PARAMS is not set. """ business_links = _footer_business_links() assert business_links[0]['url'] == 'https://edx.org/enterprise' @mock.patch.dict('django.conf.settings.FEATURES', {'ENABLE_MKTG_SITE': True}) @mock.patch.dict('django.conf.settings.MKTG_URLS', { "ROOT": "https://edx.org", "ABOUT": "/about-us", "NEWS": "/news-announcements", "CONTACT": "/contact", "CAREERS": '/careers', "FAQ": "/student-faq", "BLOG": "/edx-blog", "DONATE": "/donate", "JOBS": "/jobs", "SITE_MAP": "/sitemap", "TRADEMARKS": "/trademarks", "TOS_AND_HONOR": "/edx-terms-service", "PRIVACY": "/edx-privacy-policy", "ACCESSIBILITY": "/accessibility", "AFFILIATES": '/affiliate-program', "MEDIA_KIT": "/media-kit", "ENTERPRISE": "https://business.edx.org" }) @override_settings(PLATFORM_NAME='\xe9dX') def test_get_footer(self): actual_footer = get_footer(is_secure=True) business_url = 'https://business.edx.org/?utm_campaign=edX.org+Referral&utm_source=edX.org&utm_medium=Footer' expected_footer = { 'copyright': '\xa9 \xe9dX. All rights reserved except where noted. ' ' EdX, Open edX and their respective logos are ' 'trademarks or registered trademarks of edX Inc.', 'navigation_links': [ {'url': 'https://edx.org/about-us', 'name': 'about', 'title': 'About'}, {'url': 'https://business.edx.org', 'name': 'enterprise', 'title': '\xe9dX for Business'}, {'url': 'https://edx.org/edx-blog', 'name': 'blog', 'title': 'Blog'}, {'url': 'https://edx.org/news-announcements', 'name': 'news', 'title': 'News'}, {'url': 'https://support.example.com', 'name': 'help-center', 'title': 'Help Center'}, {'url': '/support/contact_us', 'name': 'contact', 'title': 'Contact'}, {'url': 'https://edx.org/careers', 'name': 'careers', 'title': 'Careers'}, {'url': 'https://edx.org/donate', 'name': 'donate', 'title': 'Donate'} ], 'business_links': [ {'url': 'https://edx.org/about-us', 'name': 'about', 'title': 'About'}, {'url': business_url, 'name': 'enterprise', 'title': '\xe9dX for Business'}, {'url': 'https://edx.org/affiliate-program', 'name': 'affiliates', 'title': 'Affiliates'}, {'url': 'http://open.edx.org', 'name': 'openedx', 'title': 'Open edX'}, {'url': 'https://edx.org/careers', 'name': 'careers', 'title': 'Careers'}, {'url': 'https://edx.org/news-announcements', 'name': 'news', 'title': 'News'}, ], 'more_info_links': [ {'url': 'https://edx.org/edx-terms-service', 'name': 'terms_of_service_and_honor_code', 'title': 'Terms of Service & Honor Code'}, {'url': 'https://edx.org/edx-privacy-policy', 'name': 'privacy_policy', 'title': 'Privacy Policy'}, {'url': 'https://edx.org/accessibility', 'name': 'accessibility_policy', 'title': 'Accessibility Policy'}, {'url': 'https://edx.org/trademarks', 'name': 'trademarks', 'title': 'Trademark Policy'}, {'url': 'https://edx.org/sitemap', 'name': 'sitemap', 'title': 'Sitemap'}, ], 'connect_links': [ {'url': 'https://edx.org/edx-blog', 'name': 'blog', 'title': 'Blog'}, # pylint: disable=line-too-long {'url': '{base_url}/support/contact_us'.format(base_url=settings.LMS_ROOT_URL), 'name': 'contact', 'title': 'Contact Us'}, {'url': 'https://support.example.com', 'name': 'help-center', 'title': 'Help Center'}, {'url': 'https://edx.org/media-kit', 'name': 'media_kit', 'title': 'Media Kit'}, {'url': 'https://edx.org/donate', 'name': 'donate', 'title': 'Donate'} ], 'legal_links': [ {'url': 'https://edx.org/edx-terms-service', 'name': 'terms_of_service_and_honor_code', 'title': 'Terms of Service & Honor Code'}, {'url': 'https://edx.org/edx-privacy-policy', 'name': 'privacy_policy', 'title': 'Privacy Policy'}, {'url': 'https://edx.org/accessibility', 'name': 'accessibility_policy', 'title': 'Accessibility Policy'}, {'url': 'https://edx.org/sitemap', 'name': 'sitemap', 'title': 'Sitemap'}, {'name': 'media_kit', 'title': u'Media Kit', 'url': u'https://edx.org/media-kit'} ], 'social_links': [ {'url': '#', 'action': 'Like \xe9dX on Facebook', 'name': 'facebook', 'icon-class': 'fa-facebook-square', 'title': 'Facebook'}, {'url': '#', 'action': 'Follow \xe9dX on Twitter', 'name': 'twitter', 'icon-class': 'fa-twitter-square', 'title': 'Twitter'}, {'url': '#', 'action': 'Subscribe to the \xe9dX YouTube channel', 'name': 'youtube', 'icon-class': 'fa-youtube-square', 'title': 'Youtube'}, {'url': '#', 'action': 'Follow \xe9dX on LinkedIn', 'name': 'linkedin', 'icon-class': 'fa-linkedin-square', 'title': 'LinkedIn'}, {'url': '#', 'action': 'Follow \xe9dX on Google+', 'name': 'google_plus', 'icon-class': 'fa-google-plus-square', 'title': 'Google+'}, {'url': '#', 'action': 'Subscribe to the \xe9dX subreddit', 'name': 'reddit', 'icon-class': 'fa-reddit-square', 'title': 'Reddit'} ], 'mobile_links': [], 'logo_image': 'https://edx.org/static/images/logo.png', 'openedx_link': { 'url': 'http://open.edx.org', 'image': 'https://files.edx.org/openedx-logos/edx-openedx-logo-tag.png', 'title': 'Powered by Open edX' }, 'edx_org_link': { 'url': 'https://www.edx.org/?utm_medium=affiliate_partner&utm_source=opensource-partner&utm_content=open-edx-partner-footer-link&utm_campaign=open-edx-footer', 'text': 'Take free online courses at edX.org', }, } self.assertEqual(actual_footer, expected_footer) @with_site_configuration(configuration=test_config_disabled_contact_us) def test_get_footer_disabled_contact_form(self): """ Test retrieving the footer with disabled contact form. """ actual_footer = get_footer(is_secure=True) self.assertEqual(any(l['name'] == 'contact' for l in actual_footer['connect_links']), False) self.assertEqual(any(l['name'] == 'contact' for l in actual_footer['navigation_links']), False) @with_site_configuration(configuration=test_config_custom_url_contact_us)<|fim▁hole|> """ Test retrieving the footer with custom contact form url. """ actual_footer = get_footer(is_secure=True) contact_us_link = [l for l in actual_footer['connect_links'] if l['name'] == 'contact'][0] self.assertEqual( contact_us_link['url'], test_config_custom_url_contact_us['CONTACT_US_CUSTOM_LINK'] ) navigation_link_contact_us = [l for l in actual_footer['navigation_links'] if l['name'] == 'contact'][0] self.assertEqual( navigation_link_contact_us['url'], test_config_custom_url_contact_us['CONTACT_US_CUSTOM_LINK'] )<|fim▁end|>
def test_get_footer_custom_contact_url(self):
<|file_name|>0002_auto_20151223_1508.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-23 15:08 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('django_ca', '0001_initial'), ] operations = [ migrations.AlterField( model_name='certificate', name='cn', field=models.CharField(max_length=64, verbose_name='CommonName'), ), migrations.AlterField( model_name='certificate', name='csr', field=models.TextField(verbose_name='CSR'), ), migrations.AlterField( model_name='certificate', name='pub', field=models.TextField(verbose_name='Public key'), ),<|fim▁hole|> ), migrations.AlterField( model_name='certificate', name='revoked_reason', field=models.CharField(blank=True, max_length=32, null=True, verbose_name='Reason for revokation'), ), ]<|fim▁end|>
migrations.AlterField( model_name='certificate', name='revoked_date', field=models.DateTimeField(blank=True, null=True, verbose_name='Revoked on'),
<|file_name|>UnlinkResponseCallback.java<|end_file_name|><|fim▁begin|>/** * Copyright 2014 Kakao Corp. * * Redistribution and modification in source or binary forms are not permitted without specific prior written permission.  * * 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.kakao; import com.kakao.helper.Logger; /** * unlink 요청 ({@link UserManagement#requestUnlink(com.kakao.UnlinkResponseCallback)}) 호출할 때 넘겨주고 콜백을 받는다. * @author MJ */ public abstract class UnlinkResponseCallback extends UserResponseCallback { /** * unlink를 성공적으로 마친 경우로 * 일반적으로 로그인창으로 이동하도록 구현한다. * @param userId unlink된 사용자 id */ protected abstract void onSuccess(final long userId); /** * unlink 요청전이나 요청 결과가 세션이 close된 경우로 * 일반적으로 로그인창으로 이동하도록 구현한다. * @param errorResult 세션이 닫힌 이유 */ protected abstract void onSessionClosedFailure(final APIErrorResult errorResult); /** * 세션이 닫힌 경우({@link #onSessionClosedFailure})를 제외한 이유로 가입 요청이 실패한 경우 * 아래 에러 종류에 따라 적절한 처리를 한다. <br/> * {@link ErrorCode#INVALID_PARAM_CODE}, <br/> * {@link ErrorCode#INVALID_SCOPE_CODE}, <br/> * {@link ErrorCode#NOT_SUPPORTED_API_CODE}, <br/> * {@link ErrorCode#INTERNAL_ERROR_CODE}, <br/> * {@link ErrorCode#NOT_REGISTERED_USER_CODE}, <br/> * {@link ErrorCode#CLIENT_ERROR_CODE}, <br/> * {@link ErrorCode#EXCEED_LIMIT_CODE}, <br/> * {@link ErrorCode#KAKAO_MAINTENANCE_CODE} <br/> * @param errorResult unlink를 실패한 이유 */ protected abstract void onFailure(final APIErrorResult errorResult); /** * {@link UserResponseCallback}를 구현한 것으로 unlink 요청이 성공했을 때 호출된다. * 세션을 닫고 케시를 지우고, 사용자 콜백 {@link #onSuccess(long)}을 호출한다. * 결과 User 객체가 비정상이면 에러처리한다. * @param user unlink된 사용자 id를 포함한 사용자 객체 */ @Override protected void onSuccessUser(final User user) { if (user == null || user.getId() <= 0) onError("UnlinkResponseCallback : onSuccessUser is called but the result user is null.", new APIErrorResult(null, "the result of Signup request is null.")); else { Logger.getInstance().d("UnlinkResponseCallback : unlinked successfully. user = " + user); Session.getCurrentSession().close(null); onSuccess(user.getId()); } } /** * {@link com.kakao.http.HttpResponseHandler}를 구현한 것으로 unlink 요청 전 또는 요청 중에 세션이 닫혀 로그인이 필요할 때 호출된다. * 사용자 콜백 {@link #onSessionClosedFailure(APIErrorResult)}을 호출한다. * @param errorResult 세션이 닫히 계기 */ @Override protected void onHttpSessionClosedFailure(final APIErrorResult errorResult) { Logger.getInstance().d("UnlinkResponseCallback : session is closed before requesting unlink. errorResult = " + errorResult); onSessionClosedFailure(errorResult); } /** * {@link com.kakao.http.HttpResponseHandler}를 구현한 것으로 unlink 요청 중에 서버에서 요청을 수행하지 못했다는 결과를 받았을 때 호출된다. * 세션의 상태에 따라 {@link #onSessionClosedFailure(APIErrorResult)} 콜백 또는 {@link #onFailure(APIErrorResult)}} 콜백을 호출한다. * @param errorResult 실패한 결과 */ @Override protected void onHttpFailure(final APIErrorResult errorResult) { onError("UnlinkResponseCallback : server error occurred during requesting unlink.", errorResult); } /**<|fim▁hole|> * 에러가 발생했을 때의 처리로 * 세션이 닫혔으면 {@link #onSessionClosedFailure(APIErrorResult)} 콜백을 아니면 {@link #onFailure(APIErrorResult)}} 콜백을 호출한다. * @param msg 로깅 메시지 * @param errorResult 에러 발생원인 */ private void onError(final String msg, final APIErrorResult errorResult) { Logger.getInstance().d(msg + errorResult); if (!Session.getCurrentSession().isOpened()) onSessionClosedFailure(errorResult); else onFailure(errorResult); } }<|fim▁end|>
<|file_name|>LessonProviderTest.java<|end_file_name|><|fim▁begin|>/* * jMemorize - Learning made easy (and fun) - A Leitner flashcards tool * Copyright(C) 2004-2006 Riad Djemili * * 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 1, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package jmemorize.core.test; import java.io.File; import java.io.IOException; import java.util.List; import jmemorize.core.Card; import jmemorize.core.Lesson; import jmemorize.core.LessonObserver; import jmemorize.core.LessonProvider; import jmemorize.core.Main; import junit.framework.TestCase; public class LessonProviderTest extends TestCase implements LessonObserver { private LessonProvider m_lessonProvider; private StringBuffer m_log; protected void setUp() throws Exception { m_lessonProvider = new Main();<|fim▁hole|> } public void testLessonNewEvent() { m_lessonProvider.createNewLesson(); assertEquals("loaded ", m_log.toString()); } public void testLessonLoadedEvent() throws IOException { m_lessonProvider.loadLesson(new File("test/fixtures/simple_de.jml")); assertEquals("loaded ", m_log.toString()); } public void testLessonLoadedCardsAlwaysHaveExpiration() throws IOException { m_lessonProvider.loadLesson(new File("test/fixtures/no_expiration.jml")); Lesson lesson = m_lessonProvider.getLesson(); List<Card> cards = lesson.getRootCategory().getCards(); for (Card card : cards) { if (card.getLevel() > 0) assertNotNull(card.getDateExpired()); else assertNull(card.getDateExpired()); } } public void testLessonLoadedClosedNewEvents() throws IOException { m_lessonProvider.loadLesson(new File("test/fixtures/simple_de.jml")); m_lessonProvider.createNewLesson(); assertEquals("loaded closed loaded ", m_log.toString()); // TODO also check lesson param } public void testLessonLoadedClosedLoadEvents() throws IOException { m_lessonProvider.loadLesson(new File("test/fixtures/simple_de.jml")); m_lessonProvider.loadLesson(new File("test/fixtures/test.jml")); assertEquals("loaded closed loaded ", m_log.toString()); // TODO also check lesson param } public void testLessonSavedEvent() throws Exception { m_lessonProvider.loadLesson( new File("test/fixtures/simple_de.jml")); Lesson lesson = m_lessonProvider.getLesson(); m_lessonProvider.saveLesson(lesson, new File("./test.jml")); assertEquals("loaded saved ", m_log.toString()); } public void testLessonModifiedEvent() throws Exception { m_lessonProvider.loadLesson( new File("test/fixtures/simple_de.jml")); Lesson lesson = m_lessonProvider.getLesson(); lesson.getRootCategory().addCard(new Card("front", "flip")); assertEquals("loaded modified ", m_log.toString()); } /* (non-Javadoc) * @see jmemorize.core.LessonObserver */ public void lessonLoaded(Lesson lesson) { m_log.append("loaded "); } /* (non-Javadoc) * @see jmemorize.core.LessonObserver */ public void lessonModified(Lesson lesson) { m_log.append("modified "); } /* (non-Javadoc) * @see jmemorize.core.LessonObserver */ public void lessonSaved(Lesson lesson) { m_log.append("saved "); } /* (non-Javadoc) * @see jmemorize.core.LessonObserver */ public void lessonClosed(Lesson lesson) { m_log.append("closed "); } }<|fim▁end|>
m_lessonProvider.addLessonObserver(this); m_log = new StringBuffer();