prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>vga_buffer.rs<|end_file_name|><|fim▁begin|>use core::fmt; use core::ptr::Unique; use volatile::Volatile; use spin::Mutex; #[allow(dead_code)] // Don't complain about unused variables. #[derive(Debug, Clone, Copy)] #[repr(u8)] // Store each value as byte. pub enum Color { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Magenta = 5, Brown = 6, LightGray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, Pink = 13, Yellow = 14, White = 15, } #[derive(Debug, Clone, Copy)] struct ColorCode(u8); impl ColorCode { // Const allows to use this in static initializers. const fn new(foreground: Color, background: Color) -> ColorCode { ColorCode((background as u8) << 4 | (foreground as u8)) } } #[derive(Debug, Clone, Copy)] #[repr(C)] struct ScreenChar { ascii_character: u8, color_code: ColorCode, } const BUFFER_HEIGHT: usize = 25; const BUFFER_WIDTH: usize = 80; struct Buffer { chars: [[Volatile<ScreenChar>; BUFFER_WIDTH]; BUFFER_HEIGHT], } pub struct Writer { column_position: usize, color_code: ColorCode, buffer: Unique<Buffer>, } impl Writer { pub fn write_byte(&mut self, byte: u8) { match byte { b'\n' => self.new_line(), byte => { if self.column_position >= BUFFER_WIDTH { self.new_line(); } let row = BUFFER_HEIGHT - 1; let col = self.column_position; let color_code = self.color_code; self.buffer().chars[row][col].write(ScreenChar { ascii_character: byte, color_code: color_code,<|fim▁hole|> } fn buffer(&mut self) -> &mut Buffer { unsafe { self.buffer.as_mut() } } fn new_line(&mut self) { // Omit 0th row because that's shifted off screen. for row in 1..BUFFER_HEIGHT { for col in 0..BUFFER_WIDTH { let buffer = self.buffer(); let character = buffer.chars[row][col].read(); buffer.chars[row-1][col].write(character); } } self.clear_row(BUFFER_HEIGHT-1); self.column_position = 0; } fn clear_row(&mut self, row:usize) { let blank = ScreenChar { ascii_character: b' ', color_code: self.color_code, }; for col in 0..BUFFER_WIDTH { self.buffer().chars[row][col].write(blank); } } } pub static WRITER: Mutex<Writer> = Mutex::new(Writer { column_position: 0, color_code: ColorCode::new(Color::Cyan, Color::Black), buffer: unsafe { Unique::new(0xb8000 as *mut _) }, }); // Support formatting macros. // write_str doesn't need to be public because trait methods always are. impl fmt::Write for Writer { fn write_str(&mut self, s: &str) -> fmt::Result { for byte in s.bytes() { self.write_byte(byte) } Ok(()) } } // This allows to use simple println! macros for printing to vga buffer. macro_rules! println { ($fmt:expr) => (print!(concat!($fmt, "\n"))); ($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*)); } // Similar to println macro. macro_rules! print { ($($arg:tt)*) => ({ use core::fmt::Write; let mut writer = $crate::vga_buffer::WRITER.lock(); writer.write_fmt(format_args!($($arg)*)).unwrap(); }); } macro_rules! print { ($($arg:tt)*) => ({ $crate::vga_buffer::print(format_args!($($arg)*)); }) } pub fn print(args: fmt::Arguments) { use core::fmt::Write; WRITER.lock().write_fmt(args).unwrap(); } pub fn clear_screen() { for _ in 0..BUFFER_HEIGHT { println!(""); } }<|fim▁end|>
}); self.column_position += 1; } }
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from converters.circle import circle from converters.currency import currency from converters.electric import electric from converters.force import force from converters.pressure import pressure from converters.speed import speed from converters.temperature import temperature class UnitsManager(object): ''' Class responsible to manage the unit converters of this application. ''' _units = [ circle, currency, electric, force, pressure, speed, temperature, ] def __iter__(self): return (x for x in self._units) <|fim▁hole|> Method that receives a new converter and adds it to this manager. Useful to add custom new methods without needing to edit the core of this application. """ if converter is not None and callable(converter): self._units.append(converter) UNITS = UnitsManager()<|fim▁end|>
def register(self, converter): """
<|file_name|>Grid.java<|end_file_name|><|fim▁begin|>public class Grid { public Tile array[][] = new Tile[10][8]; public Grid() { // for(int y = 0; y < getHeight(); y++) { for(int x = 0; x < getWidth(); x++) { array[x][y] = new Tile(); } } } public int getWidth() { return 9; } public int getHeight() { return 7; } public Tile getTile(int x, int y) { Tile mytile = new Tile(); try { //System.out.println("Actual tile returned"); mytile = array[x][y]; } catch(ArrayIndexOutOfBoundsException e) { //System.out.println("Out of bounds tile"); } finally { //System.out.println("Returning false tile"); return mytile; } } public void makeHole() { for(int y = 0; y < getHeight(); y++) { for(int x = 0; x < getWidth(); x++) { if(((y == 1) || (y == 5)) && (x>=3) && (x<=6)) { array[x][y].visible = false; } if(((y == 2) || (y == 4)) && (x>=2) && (x<=6)) { array[x][y].visible = false; } if((y == 3) && (x>=2) && (x<=7)) { array[x][y].visible = false; } } } } <|fim▁hole|> for(int y = 0; y < getHeight(); y++) { for(int x = 0; x < getWidth(); x++) { if((x >= 1+y%2) && (x <= 5+y%2)) { array[x][y].visible = false; } } } } }<|fim▁end|>
public void makeHolierHole() {
<|file_name|>experiments.py<|end_file_name|><|fim▁begin|># This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # experiments.py # Copyright (C) 2015 Fracpete (pythonwekawrapper at gmail dot com) import unittest import weka.core.jvm as jvm import weka.core.converters as converters import weka.classifiers as classifiers import weka.experiments as experiments import weka.plot.experiments as plot import wekatests.tests.weka_test as weka_test class TestExperiments(weka_test.WekaTest): def test_plot_experiment(self): """ Tests the plot_experiment method. """ datasets = [self.datafile("bolts.arff"), self.datafile("bodyfat.arff"), self.datafile("autoPrice.arff")] cls = [ classifiers.Classifier("weka.classifiers.trees.REPTree"), classifiers.Classifier("weka.classifiers.functions.LinearRegression"), classifiers.Classifier("weka.classifiers.functions.SMOreg"), ] outfile = self.tempfile("results-rs.arff") exp = experiments.SimpleRandomSplitExperiment( classification=False, runs=10, percentage=66.6, preserve_order=False, datasets=datasets,<|fim▁hole|> exp.setup() exp.run() # evaluate loader = converters.loader_for_file(outfile) data = loader.load_file(outfile) matrix = experiments.ResultMatrix("weka.experiment.ResultMatrixPlainText") tester = experiments.Tester("weka.experiment.PairedCorrectedTTester") tester.resultmatrix = matrix comparison_col = data.attribute_by_name("Correlation_coefficient").index tester.instances = data tester.header(comparison_col) tester.multi_resultset_full(0, comparison_col) # plot plot.plot_experiment(matrix, title="Random split (w/ StdDev)", measure="Correlation coefficient", show_stdev=True, wait=False) plot.plot_experiment(matrix, title="Random split", measure="Correlation coefficient", wait=False) def suite(): """ Returns the test suite. :return: the test suite :rtype: unittest.TestSuite """ return unittest.TestLoader().loadTestsFromTestCase(TestExperiments) if __name__ == '__main__': jvm.start() unittest.TextTestRunner().run(suite()) jvm.stop()<|fim▁end|>
classifiers=cls, result=outfile)
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>import types def is_string_like(maybe): """Test value to see if it acts like a string""" try: maybe+""<|fim▁hole|> except TypeError: return 0 else: return 1 def is_list_or_tuple(maybe): return isinstance(maybe, (types.TupleType, types.ListType))<|fim▁end|>
<|file_name|>remove.js<|end_file_name|><|fim▁begin|>'use strict' import assert from 'assert' import {remove} from '..' describe('remove', () => { it('throws a TypeError if the first argument is not an array', () => { const targets = [null, true, function() {}, {}] if (global.Map) targets.push(new Map()) targets.forEach(value => { assert.throws(() => { remove(value, 'foo') }, TypeError) }) }) it('remove the value (once) if target is an array', () => { const target = ['bar', 'bar'] remove(target, 'bar') assert.strictEqual(target.length, 1) })<|fim▁hole|> target.add('foo') remove(target, 'foo') assert(!target.has('foo')) assert.strictEqual(target.size, 0) }) } })<|fim▁end|>
if (global.Set) { it('removes the value if target is a set', () => { const target = new Set()
<|file_name|>net_logging.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Ansible by Red Hat, inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["deprecated"], "supported_by": "network", } DOCUMENTATION = """module: net_logging author: Ganesh Nalawade (@ganeshrn) short_description: Manage logging on network devices description: - This module provides declarative management of logging on network devices. deprecated: removed_in: '2.13' alternative: Use platform-specific "[netos]_logging" module why: Updated modules released with more functionality extends_documentation_fragment: - ansible.netcommon.network_agnostic options: dest: description: - Destination of the logs. choices: - console - host name: description: - If value of C(dest) is I(host) it indicates file-name the host name to be notified. facility: description: - Set logging facility. level: description: - Set logging severity levels. aggregate: description: List of logging definitions. purge: description: - Purge logging not defined in the I(aggregate) parameter. default: false state: description: - State of the logging configuration. default: present choices: - present - absent """ EXAMPLES = """ - name: configure console logging net_logging: dest: console facility: any level: critical - name: remove console logging configuration net_logging: dest: console state: absent - name: configure host logging net_logging: dest: host name: 192.0.2.1 facility: kernel level: critical - name: Configure file logging using aggregate net_logging: dest: file aggregate: - name: test-1 facility: pfe level: critical - name: test-2 facility: kernel<|fim▁hole|> level: emergency - name: Delete file logging using aggregate net_logging: dest: file aggregate: - name: test-1 facility: pfe level: critical - name: test-2 facility: kernel level: emergency state: absent """ RETURN = """ commands: description: The list of configuration mode commands to send to the device returned: always, except for the platforms that use Netconf transport to manage the device. type: list sample: - logging console critical """<|fim▁end|>
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>/*! Generates an iterator type `Matcher` that looks roughly like ```ignore mod intern_token { extern crate regex as regex; #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Token<'input>(pub usize, pub &'input str); // ~~~~~~ ~~~~~~~~~~~ // token token // index text // (type) impl<'a> fmt::Display for Token<'a> { ... } pub struct MatcherBuilder { regex_set: regex::RegexSet, regex_vec: Vec<regex::Regex>, } impl MatcherBuilder { fn new() -> MatchBuilder { ... } fn matcher<'input, 'builder>(&'builder self, s: &'input str) -> Matcher<'input, 'builder> { ... } } pub struct Matcher<'input, 'builder> { text: &'input str, consumed: usize, regex_set: &'builder regex::RegexSet, regex_vec: &'builder Vec<regex::Regex>, } impl Matcher<'input> { fn tokenize(&self, text: &str) -> Option<(usize, usize)> { ... } } impl<'input> Iterator for Matcher<'input> { type Item = Result<(usize, Token<'input>, usize), ParseError>; // ~~~~~ ~~~~~~~~~~~~~ ~~~~~ // start token end } } ``` */ use grammar::parse_tree::InternToken; use grammar::repr::{Grammar, TerminalLiteral}; use lexer::re; use rust::RustWrite; use std::io::{self, Write}; pub fn compile<W: Write>( grammar: &Grammar, intern_token: &InternToken, out: &mut RustWrite<W>, ) -> io::Result<()> { let prefix = &grammar.prefix; rust!(out, "#[cfg_attr(rustfmt, rustfmt_skip)]"); rust!(out, "mod {}intern_token {{", prefix); rust!(out, "#![allow(unused_imports)]"); try!(out.write_uses("", &grammar)); rust!(out, "extern crate regex as {}regex;", prefix); rust!(out, "use std::fmt as {}fmt;", prefix); rust!(out, ""); rust!( out, "#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]" ); rust!(out, "pub struct Token<'input>(pub usize, pub &'input str);"); rust!(out, "impl<'a> {}fmt::Display for Token<'a> {{", prefix); rust!( out, "fn fmt<'f>(&self, formatter: &mut {}fmt::Formatter<'f>) -> Result<(), {}fmt::Error> {{", prefix, prefix ); rust!(out, "{}fmt::Display::fmt(self.1, formatter)", prefix); rust!(out, "}}"); rust!(out, "}}"); rust!(out, ""); rust!(out, "pub struct {}MatcherBuilder {{", prefix); rust!(out, "regex_set: {}regex::RegexSet,", prefix); rust!(out, "regex_vec: Vec<{}regex::Regex>,", prefix); rust!(out, "}}"); rust!(out, ""); rust!(out, "impl {}MatcherBuilder {{", prefix); rust!(out, "pub fn new() -> {}MatcherBuilder {{", prefix); // create a vector of rust string literals with the text of each // regular expression let regex_strings: Vec<String> = { intern_token .match_entries .iter() .map(|match_entry| match match_entry.match_literal { TerminalLiteral::Quoted(ref s) => re::parse_literal(&s), TerminalLiteral::Regex(ref s) => re::parse_regex(&s).unwrap(), }) .map(|regex| { // make sure all regex are anchored at the beginning of the input format!("^({})", regex) }) .map(|regex_str| { // create a rust string with text of the regex; the Debug impl // will add quotes and escape format!("{:?}", regex_str) }) .collect() }; rust!(out, "let {}strs: &[&str] = &[", prefix); for literal in &regex_strings { rust!(out, "{},", literal); } rust!(out, "];"); rust!( out, "let {}regex_set = {}regex::RegexSet::new({}strs).unwrap();", prefix, prefix, prefix ); rust!(out, "let {}regex_vec = vec![", prefix);<|fim▁hole|> } rust!(out, "];"); rust!( out, "{0}MatcherBuilder {{ regex_set: {0}regex_set, regex_vec: {0}regex_vec }}", prefix ); rust!(out, "}}"); // fn new() rust!( out, "pub fn matcher<'input, 'builder>(&'builder self, s: &'input str) \ -> {}Matcher<'input, 'builder> {{", prefix ); rust!(out, "{}Matcher {{", prefix); rust!(out, "text: s,"); rust!(out, "consumed: 0,"); rust!(out, "regex_set: &self.regex_set,"); rust!(out, "regex_vec: &self.regex_vec,"); rust!(out, "}}"); // struct literal rust!(out, "}}"); // fn matcher() rust!(out, "}}"); // impl MatcherBuilder rust!(out, ""); rust!(out, "pub struct {}Matcher<'input, 'builder> {{", prefix); rust!(out, "text: &'input str,"); // remaining input rust!(out, "consumed: usize,"); // number of chars consumed thus far rust!(out, "regex_set: &'builder {}regex::RegexSet,", prefix); rust!(out, "regex_vec: &'builder Vec<{}regex::Regex>,", prefix); rust!(out, "}}"); rust!(out, ""); rust!( out, "impl<'input, 'builder> Iterator for {}Matcher<'input, 'builder> {{", prefix ); rust!( out, "type Item = Result<(usize, Token<'input>, usize), \ {}lalrpop_util::ParseError<usize,Token<'input>,{}>>;", prefix, grammar.types.error_type() ); rust!(out, ""); rust!(out, "fn next(&mut self) -> Option<Self::Item> {{"); // start by trimming whitespace from left rust!(out, "#[allow(deprecated)]"); rust!(out, "let {}text = self.text.trim_left();", prefix); rust!( out, "let {}whitespace = self.text.len() - {}text.len();", prefix, prefix ); rust!( out, "let {}start_offset = self.consumed + {}whitespace;", prefix, prefix ); // if nothing left, return None rust!(out, "if {}text.is_empty() {{", prefix); rust!(out, "self.text = {}text;", prefix); rust!(out, "self.consumed = {}start_offset;", prefix); rust!(out, "None"); rust!(out, "}} else {{"); // otherwise, use regex-set to find list of matching tokens rust!( out, "let {}matches = self.regex_set.matches({}text);", prefix, prefix ); // if nothing matched, return an error rust!(out, "if !{}matches.matched_any() {{", prefix); rust!( out, "Some(Err({}lalrpop_util::ParseError::InvalidToken {{", prefix ); rust!(out, "location: {}start_offset,", prefix); rust!(out, "}}))"); rust!(out, "}} else {{"); // otherwise, have to find longest, highest-priority match. We have the literals // sorted in order of increasing precedence, so we'll iterate over them one by one, // checking if each one matches, and remembering the longest one. rust!(out, "let mut {}longest_match = 0;", prefix); // length of longest match rust!(out, "let mut {}index = 0;", prefix); // index of longest match rust!( out, "for {}i in 0 .. {} {{", prefix, intern_token.match_entries.len() ); rust!(out, "if {}matches.matched({}i) {{", prefix, prefix); // re-run the regex to find out how long this particular match // was, then compare that against the longest-match so far. Note // that the order of the tuple is carefully constructed to ensure // that (a) we get the longest-match but (b) if two matches are // equal, we get the largest index. This is because the indices // are sorted in order of increasing priority, and because we know // that indices of equal priority cannot both match (because of // the DFA check). rust!( out, "let {}match = self.regex_vec[{}i].find({}text).unwrap();", prefix, prefix, prefix ); rust!(out, "let {}len = {}match.end();", prefix, prefix); rust!(out, "if {}len >= {}longest_match {{", prefix, prefix); rust!(out, "{}longest_match = {}len;", prefix, prefix); rust!(out, "{}index = {}i;", prefix, prefix); rust!(out, "}}"); // if is longest match rust!(out, "}}"); // if matches.matched(i) rust!(out, "}}"); // for loop // transform the result into the expected return value rust!( out, "let {}result = &{}text[..{}longest_match];", prefix, prefix, prefix ); rust!( out, "let {}remaining = &{}text[{}longest_match..];", prefix, prefix, prefix ); rust!( out, "let {}end_offset = {}start_offset + {}longest_match;", prefix, prefix, prefix ); rust!(out, "self.text = {}remaining;", prefix); rust!(out, "self.consumed = {}end_offset;", prefix); rust!( out, "Some(Ok(({}start_offset, Token({}index, {}result), {}end_offset)))", prefix, prefix, prefix, prefix ); rust!(out, "}}"); // else rust!(out, "}}"); // else rust!(out, "}}"); // fn rust!(out, "}}"); // impl rust!(out, "}}"); // mod Ok(()) }<|fim▁end|>
for literal in &regex_strings { rust!(out, "{}regex::Regex::new({}).unwrap(),", prefix, literal);
<|file_name|>DisableGUILogon.py<|end_file_name|><|fim▁begin|>############################################################################### # # # Copyright 2019. Triad National Security, LLC. All rights reserved. # # This program was produced under U.S. Government contract 89233218CNA000001 # # for Los Alamos National Laboratory (LANL), which is operated by Triad # # National Security, LLC for the U.S. Department of Energy/National Nuclear # # Security Administration. # # # # All rights in the program are reserved by Triad National Security, LLC, and # # the U.S. Department of Energy/National Nuclear Security Administration. The # # Government is granted for itself and others acting on its behalf a # # nonexclusive, paid-up, irrevocable worldwide license in this material to # # reproduce, prepare derivative works, distribute copies to the public, # # perform publicly and display publicly, and to permit others to do so. # # # ############################################################################### ''' Created on 2015/07/01 @author: Eric Ball @change: 2015/12/07 eball Added information about REMOVEX CI to help text @change: 2016/07/06 eball Separated fix into discrete methods @change: 2017/06/02 bgonz12 - Change a conditional in reportUbuntu to search for "manual" using regex instead of direct comparison @change 2017/08/28 rsn Fixing to use new help text methods @change: 2017/10/23 rsn - change to new service helper interface @change: 2017/11/14 bgonz12 - Fix removeX dependency issue for deb systems ''' import os import re import traceback from KVEditorStonix import KVEditorStonix from logdispatcher import LogPriority from pkghelper import Pkghelper from rule import Rule from CommandHelper import CommandHelper from ServiceHelper import ServiceHelper from stonixutilityfunctions import iterate, readFile, writeFile, createFile from stonixutilityfunctions import resetsecon class DisableGUILogon(Rule): def __init__(self, config, environ, logger, statechglogger): Rule.__init__(self, config, environ, logger, statechglogger) self.logger = logger self.rulenumber = 105 self.rulename = "DisableGUILogon" self.formatDetailedResults("initialize") self.mandatory = False self.applicable = {'type': 'white', 'family': ['linux']} # Configuration item instantiation datatype = "bool" key = "DISABLEX" instructions = "To enable this item, set the value of DISABLEX " + \ "to True. When enabled, this rule will disable the automatic " + \ "GUI login, and the system will instead boot to the console " + \ "(runlevel 3). This will not remove any GUI components, and the " + \ "GUI can still be started using the \"startx\" command." default = False self.ci1 = self.initCi(datatype, key, instructions, default) datatype = "bool" key = "LOCKDOWNX" instructions = "To enable this item, set the value of LOCKDOWNX " + \ "to True. When enabled, this item will help secure X Windows by " + \ "disabling the X Font Server (xfs) service and disabling X " + \ "Window System Listening. This item should be enabled if X " + \ "Windows is disabled but will be occasionally started via " + \ "startx, unless there is a mission-critical need for xfs or " + \ "a remote display." default = False self.ci2 = self.initCi(datatype, key, instructions, default) datatype = "bool" key = "REMOVEX" instructions = "To enable this item, set the value of REMOVEX " + \ "to True. When enabled, this item will COMPLETELY remove X " + \ "Windows from the system, and on most platforms will disable " + \ "any currently running display manager. It is therefore " + \ "recommended that this rule be run from a console session " + \ "rather than from the GUI.\nREMOVEX cannot be undone." default = False self.ci3 = self.initCi(datatype, key, instructions, default) self.guidance = ["NSA 3.6.1.1", "NSA 3.6.1.2", "NSA 3.6.1.3", "CCE 4462-8", "CCE 4422-2", "CCE 4448-7", "CCE 4074-1"] self.iditerator = 0 self.ph = Pkghelper(self.logger, self.environ) self.ch = CommandHelper(self.logger) self.sh = ServiceHelper(self.environ, self.logger) self.myos = self.environ.getostype().lower() self.sethelptext() def report(self): '''@author: Eric Ball :param self: essential if you override this definition :returns: bool - True if system is compliant, False if it isn't ''' try: compliant = True results = "" if os.path.exists("/bin/systemctl"): self.initver = "systemd" compliant, results = self.reportSystemd() elif re.search("debian", self.myos): self.initver = "debian" compliant, results = self.reportDebian() elif re.search("ubuntu", self.myos): self.initver = "ubuntu" compliant, results = self.reportUbuntu() else: self.initver = "inittab" compliant, results = self.reportInittab() # NSA guidance specifies disabling of X Font Server (xfs), # however, this guidance seems to be obsolete as of RHEL 6, # and does not apply to the Debian family. if self.sh.auditService("xfs", _="_"): compliant = False results += "xfs is currently enabled\n" xremoved = True self.xservSecure = True if re.search("debian|ubuntu", self.myos): if self.ph.check("xserver-xorg-core"): compliant = False xremoved = False results += "Core X11 components are present\n" elif re.search("opensuse", self.myos): if self.ph.check("xorg-x11-server"): compliant = False xremoved = False results += "Core X11 components are present\n" else: if self.ph.check("xorg-x11-server-Xorg"): compliant = False xremoved = False results += "Core X11 components are present\n" # Removing X will take xserverrc with it. If X is not present, we # do not need to check for xserverrc if not xremoved: self.serverrc = "/etc/X11/xinit/xserverrc" self.xservSecure = False if os.path.exists(self.serverrc): serverrcText = readFile(self.serverrc, self.logger) if re.search("opensuse", self.myos): for line in serverrcText: reSearch = r'exec (/usr/bin/)?X \$dspnum.*\$args' if re.search(reSearch, line): self.xservSecure = True break else: for line in serverrcText: reSearch = r'^exec (/usr/bin/)?X (:0 )?-nolisten tcp ("$@"|.?\$@)' if re.search(reSearch, line): self.xservSecure = True break if not self.xservSecure: compliant = False results += self.serverrc + " does not contain proper " \ + "settings to disable X Window System " + \ "Listening/remote display\n" else: compliant = False results += self.serverrc + " does not exist; X Window " + \ "System Listening/remote display has not " + \ "been disabled\n" self.detailedresults = results self.compliant = compliant except (KeyboardInterrupt, SystemExit): raise except Exception: self.rulesuccess = False self.detailedresults = "\n" + traceback.format_exc() self.logger.log(LogPriority.ERROR, self.detailedresults) self.formatDetailedResults("report", self.compliant, self.detailedresults) self.logger.log(LogPriority.INFO, self.detailedresults) return self.compliant def reportInittab(self): compliant = False results = "" inittab = "/etc/inittab" if os.path.exists(inittab): initData = readFile(inittab, self.logger) for line in initData: if line.strip() == "id:3:initdefault:": compliant = True break else: self.logger.log(LogPriority.ERROR, inittab + " not found, init " + "system unknown") if not compliant: results = "inittab not set to runlevel 3; GUI logon is enabled\n" return compliant, results def reportSystemd(self): compliant = True results = "" cmd = ["/bin/systemctl", "get-default"] self.ch.executeCommand(cmd) defaultTarget = self.ch.getOutputString() if not re.search("multi-user.target", defaultTarget): compliant = False results = "systemd default target is not multi-user.target; " + \<|fim▁hole|> def reportDebian(self): compliant = True results = "" dmlist = ["gdm", "gdm3", "lightdm", "xdm", "kdm"] for dm in dmlist: if self.sh.auditService(dm, _="_"): compliant = False results = dm + \ " is still in init folders; GUI logon is enabled\n" return compliant, results def reportUbuntu(self): compliant = True results = "" ldmover = "/etc/init/lightdm.override" grub = "/etc/default/grub" if os.path.exists(ldmover): lightdmText = readFile(ldmover, self.logger) if not re.search("manual", lightdmText[0], re.IGNORECASE): compliant = False results += ldmover + ' exists, but does not contain text ' + \ '"manual". GUI logon is still enabled\n' else: compliant = False results += ldmover + " does not exist; GUI logon is enabled\n" if os.path.exists(grub): tmppath = grub + ".tmp" data = {"GRUB_CMDLINE_LINUX_DEFAULT": '"quiet"'} editor = KVEditorStonix(self.statechglogger, self.logger, "conf", grub, tmppath, data, "present", "closedeq") if not editor.report(): compliant = False results += grub + " does not contain the correct values: " + \ str(data) else: compliant = False results += "Cannot find file " + grub if not compliant: results += "/etc/init does not contain proper override file " + \ "for lightdm; GUI logon is enabled\n" return compliant, results def fix(self): '''@author: Eric Ball :param self: essential if you override this definition :returns: bool - True if fix is successful, False if it isn't ''' try: if not self.ci1.getcurrvalue() and not self.ci2.getcurrvalue() \ and not self.ci3.getcurrvalue(): return success = True self.detailedresults = "" # Delete past state change records from previous fix self.iditerator = 0 eventlist = self.statechglogger.findrulechanges(self.rulenumber) for event in eventlist: self.statechglogger.deleteentry(event) # If we are doing DISABLEX or REMOVEX, we want to boot to # non-graphical multi-user mode. if self.ci1.getcurrvalue() or self.ci3.getcurrvalue(): success &= self.fixBootMode() # Since LOCKDOWNX depends on having X installed, and REMOVEX # completely removes X from the system, LOCKDOWNX fix will only be # executed if REMOVEX is not. if self.ci3.getcurrvalue(): success &= self.fixRemoveX() elif self.ci2.getcurrvalue(): success &= self.fixLockdownX() self.rulesuccess = success except (KeyboardInterrupt, SystemExit): # User initiated exit raise except Exception: self.rulesuccess = False self.detailedresults += "\n" + traceback.format_exc() self.logdispatch.log(LogPriority.ERROR, self.detailedresults) self.formatDetailedResults("fix", self.rulesuccess, self.detailedresults) self.logdispatch.log(LogPriority.INFO, self.detailedresults) return self.rulesuccess def fixBootMode(self): success = True if self.initver == "systemd": cmd = ["/bin/systemctl", "set-default", "multi-user.target"] if not self.ch.executeCommand(cmd): success = False self.detailedresults += '"systemctl set-default ' \ + 'multi-user.target" did not succeed\n' else: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) commandstring = "/bin/systemctl set-default " + \ "graphical.target" event = {"eventtype": "commandstring", "command": commandstring} self.statechglogger.recordchgevent(myid, event) elif self.initver == "debian": dmlist = ["gdm", "gdm3", "lightdm", "xdm", "kdm"] for dm in dmlist: cmd = ["update-rc.d", "-f", dm, "disable"] if not self.ch.executeCommand(cmd): self.detailedresults += "Failed to disable desktop " + \ "manager " + dm else: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "servicehelper", "servicename": dm, "startstate": "enabled", "endstate": "disabled"} self.statechglogger.recordchgevent(myid, event) elif self.initver == "ubuntu": ldmover = "/etc/init/lightdm.override" tmpfile = ldmover + ".tmp" created = False if not os.path.exists(ldmover): createFile(ldmover, self.logger) self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "creation", "filepath": ldmover} self.statechglogger.recordchgevent(myid, event) created = True writeFile(tmpfile, "manual\n", self.logger) if not created: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "conf", "filepath": ldmover} self.statechglogger.recordchgevent(myid, event) self.statechglogger.recordfilechange(ldmover, tmpfile, myid) os.rename(tmpfile, ldmover) resetsecon(ldmover) grub = "/etc/default/grub" if not os.path.exists(grub): createFile(grub, self.logger) self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "creation", "filepath": grub} self.statechglogger.recordchgevent(myid, event) tmppath = grub + ".tmp" data = {"GRUB_CMDLINE_LINUX_DEFAULT": '"quiet"'} editor = KVEditorStonix(self.statechglogger, self.logger, "conf", grub, tmppath, data, "present", "closedeq") editor.report() if editor.fixables: if editor.fix(): self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) editor.setEventID(myid) debug = "kveditor fix ran successfully\n" self.logger.log(LogPriority.DEBUG, debug) if editor.commit(): debug = "kveditor commit ran successfully\n" self.logger.log(LogPriority.DEBUG, debug) else: error = "kveditor commit did not run " + \ "successfully\n" self.logger.log(LogPriority.ERROR, error) success = False else: error = "kveditor fix did not run successfully\n" self.logger.log(LogPriority.ERROR, error) success = False cmd = "update-grub" self.ch.executeCommand(cmd) else: inittab = "/etc/inittab" tmpfile = inittab + ".tmp" if os.path.exists(inittab): initText = open(inittab, "r").read() initre = r"id:\d:initdefault:" if re.search(initre, initText): initText = re.sub(initre, "id:3:initdefault:", initText) writeFile(tmpfile, initText, self.logger) self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "conf", "filepath": inittab} self.statechglogger.recordchgevent(myid, event) self.statechglogger.recordfilechange(inittab, tmpfile, myid) os.rename(tmpfile, inittab) resetsecon(inittab) else: initText += "\nid:3:initdefault:\n" writeFile(tmpfile, initText, self.logger) self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "conf", "filepath": inittab} self.statechglogger.recordchgevent(myid, event) self.statechglogger.recordfilechange(inittab, tmpfile, myid) os.rename(tmpfile, inittab) resetsecon(inittab) else: self.detailedresults += inittab + " not found, no other " + \ "init system found. If you are using a supported " + \ "Linux OS, please report this as a bug\n" return success def fixRemoveX(self): success = True # Due to automatic removal of dependent packages, the full # removal of X and related packages cannot be undone if re.search("opensuse", self.myos): cmd = ["zypper", "-n", "rm", "-u", "xorg-x11*", "kde*", "xinit*"] self.ch.executeCommand(cmd) elif re.search("debian|ubuntu", self.myos): xpkgs = ["unity.*", "xserver-xorg-video-ati", "xserver-xorg-input-synaptics", "xserver-xorg-input-wacom", "xserver-xorg-core", "xserver-xorg", "lightdm.*", "libx11-data"] for xpkg in xpkgs: self.ph.remove(xpkg) elif re.search("fedora", self.myos): # Fedora does not use the same group packages as other # RHEL-based OSs. Removing this package will remove the X # Windows system, just less efficiently than using a group self.ph.remove("xorg-x11-server-Xorg") self.ph.remove("xorg-x11-xinit*") else: cmd = ["yum", "groups", "mark", "convert"] self.ch.executeCommand(cmd) self.ph.remove("xorg-x11-xinit") self.ph.remove("xorg-x11-server-Xorg") cmd2 = ["yum", "groupremove", "-y", "X Window System"] if not self.ch.executeCommand(cmd2): success = False self.detailedresults += '"yum groupremove -y X Window System" command failed\n' return success def fixLockdownX(self): success = True if self.sh.disableService("xfs", _="_"): self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "servicehelper", "servicename": "xfs", "startstate": "enabled", "endstate": "disabled"} self.statechglogger.recordchgevent(myid, event) else: success = False self.detailedresults += "STONIX was unable to disable the " + \ "xfs service\n" if not self.xservSecure: serverrcString = "exec X :0 -nolisten tcp $@" if not os.path.exists(self.serverrc): createFile(self.serverrc, self.logger) self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "creation", "filepath": self.serverrc} self.statechglogger.recordchgevent(myid, event) writeFile(self.serverrc, serverrcString, self.logger) else: open(self.serverrc, "a").write(serverrcString) return success<|fim▁end|>
"GUI logon is enabled\n" return compliant, results
<|file_name|>CachedObjectKeys.java<|end_file_name|><|fim▁begin|>package org.consumersunion.stories.common.client.util; public class CachedObjectKeys { public static final String OPENED_CONTENT = "openedContent";<|fim▁hole|><|fim▁end|>
public static final String OPENED_STORY = "openedStory"; public static final String OPENED_COLLECTION = "openedCollection"; }
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # coding=utf-8 import flask from flask import flash from flask_login import login_required from rpress.models import SiteSetting from rpress.database import db from rpress.runtimes.rpadmin.template import render_template, navbar from rpress.runtimes.current_session import get_current_site, get_current_site_info from rpress.forms import SettingsForm app = flask.Blueprint('rpadmin_setting', __name__) @app.route('/', methods=['GET', ]) @login_required @navbar(level1='settings') def list(): content = { 'site': get_current_site_info(), } return render_template('rpadmin/settings/list.html', content=content) @app.route('/<string:key>/edit', methods=['GET', 'POST'])<|fim▁hole|>def edit(key): site = get_current_site() site_setting = SiteSetting.query.filter_by(site=site, key=key).order_by('created_time').first() if site_setting is None: site_setting = SiteSetting( site_id=site.id, key=key, value=None, ) form = SettingsForm(obj=site_setting) if form.validate_on_submit(): form.populate_obj(site_setting) db.session.add(site_setting) db.session.commit() flash("settings updated", "success") else: flash('settings edit error') return render_template("rpadmin/settings/edit.html", form=form, site_setting=site_setting)<|fim▁end|>
@login_required @navbar(level1='settings')
<|file_name|>index.ts<|end_file_name|><|fim▁begin|><|fim▁hole|>export * from './authentication.service'; export * from './user.service'; export * from './serviceRequest.service';<|fim▁end|>
export * from './alert.service';
<|file_name|>website.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # © 2015 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from openerp import api, models class WebsiteMenu(models.Model): _inherit = "website.menu" @api.multi def get_parents(self, revert=False, include_self=False): """List current menu's parents. :param bool revert: Indicates if the result must be revert before returning. Activating this will mean that the result will be ordered from parent to child. :param bool include_self: Indicates if the current menu item must be included in the result.<|fim▁hole|> :return list: Menu items ordered from child to parent, unless ``revert=True``. """ result = list() menu = self if include_self else self.parent_id while menu: result.append(menu) menu = menu.parent_id return reversed(result) if revert else result<|fim▁end|>
<|file_name|>nested.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The rust-for-real developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // 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. /** * For more information about tasks' behaviour, please, refer to the README * under std/task. */ extern mod extra; use std::task; use extra::comm::DuplexStream; fn simple_nesting() { do task::spawn { let (parent, child) = DuplexStream::<int, int>(); child.send(0); // Using a supervised task to avoid // propagating linked failures to the // parent task in case it ends before // the child does. do task::spawn_supervised { loop { match child.try_recv() { Some(i) => child.send(i + 1), None => break } } }; loop { if parent.peek() { let start = parent.recv(); println(fmt!("%i", start)); if start == 10 { println("Counter is now 10"); break; } parent.send(start + 1);<|fim▁hole|> } } } } fn supervised_task() { do task::spawn { do task::spawn_supervised { // This won't make the parent // task fail. fail!() } } } fn try_task() { // This task fails but won't make the caller // task fail, instead, it'll return an error result. let failure: Result<(), ()> = do task::try { fail!("BAAAAAAD"); }; assert!(failure.is_err()); // This task won't fail and will return a ~str let success: Result<~str, ()> = do task::try { ~"Yo, you know how to do things" }; assert!(success.is_ok()); println(success.unwrap()); } fn main() { simple_nesting(); supervised_task(); try_task(); }<|fim▁end|>
<|file_name|>codigo27.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python3 # -*- coding:utf-8 -*- # Funciones y parametros arbitrarios<|fim▁hole|> print (type(nombres)) for alumno in nombres: print ("%s es alumno y tiene %d años" % (alumno, nombres[alumno])) return nombres #diccionario = {"Adrian":25, "Niño":25, "Roberto":23, "Celina":23} print (funcion(Adrian = 25, Nino = 25, Roberto = 23, Celina = 23))<|fim▁end|>
def funcion(**nombres):
<|file_name|>responsiveFlexOrder.demo.ts<|end_file_name|><|fim▁begin|>import {Component} from '@angular/core'; @Component({ selector: 'demo-responsive-flex-order', styleUrls : [ '../../assets/css/material2.css' ], template: ` <md-card class="card-demo" > <md-card-title>Responsive Flex Ordering</md-card-title> <md-card-subtitle>Add the flex-order directive to a layout child to set its order position within the layout container:</md-card-subtitle> <md-card-content> <div class="containerX"> <div fxLayout="row" class="coloredContainerX box" > <div fxFlex fxFlexOrder="-1"> <p>[flex-order="-1"]</p> </div> <div fxFlex fxFlexOrder="1" fxFlexOrder.gt-md="3"> <p fxHide="false" fxHide.gt-md> [flex-order="1"] </p> <p fxShow="false" fxShow.gt-md> [flex-order.gt-md="3"] </p> </div> <div fxFlex fxFlexOrder="2"> <p>[flex-order="2"]</p> </div> <div fxFlex fxFlexOrder="3" fxFlexOrder.gt-md="1"> <p fxHide="false" fxHide.gt-md> [flex-order="3"] </p> <p fxShow="false" fxShow.gt-md> [flex-order.gt-md="1"] </p> </div> </div> </div> </md-card-content> <md-card-footer style="width:95%"> <media-query-status></media-query-status> </md-card-footer> </md-card> ` }) export class DemoResponsiveFlexOrder {<|fim▁hole|>}<|fim▁end|>
<|file_name|>bitcoin_es_MX.ts<|end_file_name|><|fim▁begin|><TS language="es_MX" version="2.0"> <context> <name>AddressBookPage</name> <message> <source>Create a new address</source> <translation>Crear una dirección nueva</translation> </message> <message> <source>&amp;New</source> <translation>&amp;Nuevo</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Copiar el domicilio seleccionado al portapapeles del sistema</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Copiar</translation> </message> <message> <source>C&amp;lose</source> <translation>Cerrar</translation> </message> <message> <source>&amp;Copy Address</source> <translation>&amp;Copiar dirección</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Eliminar la dirección actualmente seleccionada de la lista</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportar la información en la tabla actual a un archivo</translation> </message> <message> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Borrar</translation> </message> <message> <source>Choose the address to send coins to</source> <translation>Elija una dirección a la cual enviar monedas</translation> </message> <message> <source>Choose the address to receive coins with</source> <translation>Elija la dirección con la cual recibir monedas</translation> </message> <message> <source>C&amp;hoose</source> <translation>Elegir</translation> </message> <message> <source>Such sending addresses</source> <translation>Enviando direcciones</translation> </message> <message> <source>Much receiving addresses</source> <translation>Recibiendo direcciones</translation> </message> <message> <source>These are your Dogecoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Estas son tus direcciones de Dogecoin para enviar pagos. Siempre revise la cantidad y la dirección receptora antes de enviar monedas</translation> </message> <message> <source>These are your Dogecoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation>Estas son tus direcciones Dogecoin para recibir pagos. Es recomendado usar una nueva dirección receptora para cada transacción.</translation> </message> <message> <source>Copy &amp;Label</source> <translation>Copiar &amp;Etiqueta</translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;Editar</translation> </message> <message> <source>Export Address List</source> <translation>Exportar Lista de direcciones</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Arhchivo separado por comas (*.CSV)</translation> </message> <message> <source>Exporting Failed</source> <translation>Exportación fallida</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <source>Address</source> <translation>Domicilio</translation> </message> <message> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Enter passphrase</source> <translation>Ingrese la contraseña</translation> </message> <message> <source>New passphrase</source> <translation>Nueva contraseña</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Repita la nueva contraseña</translation> </message> <message> <source>Encrypt wallet</source> <translation>Encriptar cartera.</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Esta operación necesita la contraseña de su cartera para desbloquear su cartera.</translation> </message> <message> <source>Unlock wallet</source> <translation>Desbloquear cartera.</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Esta operación necesita la contraseña de su cartera para desencriptar su cartera.</translation> </message> <message> <source>Decrypt wallet</source> <translation>Desencriptar cartera</translation> </message> <message> <source>Change passphrase</source> <translation>Cambiar contraseña</translation> </message> <message> <source>Confirm wallet encryption</source><|fim▁hole|> <translation>Confirmar la encriptación de cartera</translation> </message> <message> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR DOGECOINS&lt;/b&gt;!</source> <translation>Advertencia: Si encripta su cartera y pierde su contraseña, &lt;b&gt;PERDERÁ TODOS SUS DOGECOINS&lt;/b&gt;!</translation> </message> <message> <source>Are you sure you wish to encrypt your wallet?</source> <translation>¿Está seguro que desea encriptar su cartera?</translation> </message> <message> <source>Warning: The Caps Lock key is on!</source> <translation>Advertencia: ¡La tecla Bloq Mayus está activada!</translation> </message> <message> <source>Wallet encrypted</source> <translation>Cartera encriptada</translation> </message> <message> <source>Wallet encryption failed</source> <translation>Encriptación de la cartera fallida</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>La encriptación de la cartera falló debido a un error interno. Su cartera no fue encriptada.</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>Las contraseñas dadas no coinciden</translation> </message> <message> <source>Wallet unlock failed</source> <translation>El desbloqueo de la cartera falló</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>La contraseña ingresada para la desencriptación de la cartera es incorrecto</translation> </message> <message> <source>Wallet decryption failed</source> <translation>La desencriptación de la cartera fallo</translation> </message> <message> <source>Wallet passphrase was successfully changed.</source> <translation>La contraseña de la cartera ha sido exitosamente cambiada.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <source>Sign &amp;message...</source> <translation>Sign &amp;mensaje</translation> </message> <message> <source>Synchronizing with network...</source> <translation>Sincronizando con la red...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;Vista previa</translation> </message> <message> <source>Node</source> <translation>Nodo</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Mostrar la vista previa general de la cartera</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Transacciones</translation> </message> <message> <source>Browse transaction history</source> <translation>Explorar el historial de transacciones</translation> </message> <message> <source>E&amp;xit</source> <translation>S&amp;alir</translation> </message> <message> <source>Quit application</source> <translation>Salir de la aplicación</translation> </message> <message> <source>About &amp;Qt</source> <translation>Acerca de &amp;Qt</translation> </message> <message> <source>Show information about Qt</source> <translation>Mostrar información acerca de Qt</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Opciones</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Encriptar cartera</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>&amp;Respaldar cartera</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>&amp;Cambiar contraseña...</translation> </message> <message> <source>Such &amp;sending addresses...</source> <translation>&amp;Enviando direcciones...</translation> </message> <message> <source>Much &amp;receiving addresses...</source> <translation>&amp;Recibiendo direcciones...</translation> </message> <message> <source>Open &amp;URI...</source> <translation>Abrir &amp;URL...</translation> </message> <message> <source>Importing blocks from disk...</source> <translation>Importando bloques desde el disco...</translation> </message> <message> <source>Reindexing blocks on disk...</source> <translation>Reindexando bloques en el disco...</translation> </message> <message> <source>Send coins to a Dogecoin address</source> <translation>Enviar monedas a una dirección Dogecoin</translation> </message> <message> <source>Backup wallet to another location</source> <translation>Respaldar cartera en otra ubicación</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Cambiar la contraseña usada para la encriptación de la cartera</translation> </message> <message> <source>&amp;Debug window</source> <translation>&amp;Depurar ventana</translation> </message> <message> <source>Open debugging and diagnostic console</source> <translation>Abrir la consola de depuración y disgnostico</translation> </message> <message> <source>&amp;Verify message...</source> <translation>&amp;Verificar mensaje...</translation> </message> <message> <source>&amp;File</source> <translation>&amp;Archivo</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Configuraciones</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Ayuda</translation> </message> <message> <source>Tabs toolbar</source> <translation>Pestañas</translation> </message> <message> <source>Dogecoin Core</source> <translation>nucleo Dogecoin</translation> </message> <message> <source>&amp;Command-line options</source> <translation>opciones de la &amp;Linea de comandos</translation> </message> <message> <source>Show the Dogecoin Core help message to get a list with possible Dogecoin command-line options</source> <translation>Mostrar mensaje de ayuda del nucleo de Dogecoin para optener una lista con los posibles comandos de Dogecoin</translation> </message> <message> <source>Up to date</source> <translation>Actualizado al dia </translation> </message> <message> <source>Catching up...</source> <translation>Resiviendo...</translation> </message> <message> <source>Sent transaction</source> <translation>Enviar Transacción</translation> </message> <message> <source>Incoming transaction</source> <translation>Transacción entrante</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>La cartera esta &lt;b&gt;encriptada&lt;/b&gt; y &lt;b&gt;desbloqueada&lt;/b&gt; actualmente </translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>La cartera esta &lt;b&gt;encriptada&lt;/b&gt; y &lt;b&gt;bloqueada&lt;/b&gt; actualmente </translation> </message> </context> <context> <name>ClientModel</name> </context> <context> <name>CoinControlDialog</name> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>Monto:</translation> </message> <message> <source>Priority:</source> <translation>Prioridad:</translation> </message> <message> <source>Fee:</source> <translation>Cuota:</translation> </message> <message> <source>Amount</source> <translation>Monto</translation> </message> <message> <source>Date</source> <translation>Fecha</translation> </message> <message> <source>Confirmed</source> <translation>Confirmado </translation> </message> <message> <source>Copy address</source> <translation>Copiar dirección </translation> </message> <message> <source>Copy label</source> <translation>Copiar capa </translation> </message> <message> <source>Copy amount</source> <translation>copiar monto</translation> </message> <message> <source>Copy quantity</source> <translation>copiar cantidad</translation> </message> <message> <source>Copy fee</source> <translation>copiar cuota</translation> </message> <message> <source>Copy after fee</source> <translation>copiar despues de cuota</translation> </message> <message> <source>Copy bytes</source> <translation>copiar bytes</translation> </message> <message> <source>Copy priority</source> <translation>copiar prioridad</translation> </message> <message> <source>Copy change</source> <translation>copiar cambio</translation> </message> <message> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Editar dirección</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Etiqueta</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;Dirección</translation> </message> <message> <source>New receiving address</source> <translation>Nueva dirección de entregas</translation> </message> <message> <source>New sending address</source> <translation>Nueva dirección de entregas</translation> </message> <message> <source>Edit receiving address</source> <translation>Editar dirección de entregas</translation> </message> <message> <source>Edit sending address</source> <translation>Editar dirección de envios</translation> </message> <message> <source>The entered address "%1" is already in the address book.</source> <translation>El domicilio ingresado "%1" ya existe en la libreta de direcciones</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>No se puede desbloquear la cartera</translation> </message> <message> <source>New key generation failed.</source> <translation>La generación de la nueva clave fallo</translation> </message> </context> <context> <name>FreespaceChecker</name> </context> <context> <name>HelpMessageDialog</name> <message> <source>Dogecoin Core</source> <translation>nucleo Dogecoin</translation> </message> <message> <source>version</source> <translation>Versión</translation> </message> <message> <source>(%1-bit)</source> <translation>(%1-bit)</translation> </message> <message> <source>About Dogecoin Core</source> <translation>Acerca de Dogecoin Core</translation> </message> <message> <source>Usage:</source> <translation>Uso:</translation> </message> <message> <source>command-line options</source> <translation>Opciones de comando de lineas</translation> </message> </context> <context> <name>Intro</name> <message> <source>Dogecoin Core</source> <translation>nucleo Dogecoin</translation> </message> </context> <context> <name>OpenURIDialog</name> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Opciones</translation> </message> <message> <source>Active command-line options that override above options:</source> <translation>Activar las opciones de linea de comando que sobre escriben las siguientes opciones:</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Formulario</translation> </message> </context> <context> <name>PaymentServer</name> </context> <context> <name>PeerTableModel</name> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>Monto</translation> </message> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Label:</source> <translation>&amp;Etiqueta</translation> </message> <message> <source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Dogecoin network.</source> <translation>Mensaje opcional para agregar a la solicitud de pago, el cual será mostrado cuando la solicitud este abierta. Nota: El mensaje no se manda con el pago a travéz de la red de Dogecoin.</translation> </message> <message> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation>Use este formulario para la solicitud de pagos. Todos los campos son &lt;b&gt;opcionales&lt;/b&gt;</translation> </message> <message> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation>Monto opcional a solicitar. Dejarlo vacion o en cero no solicita un monto especifico.</translation> </message> <message> <source>Copy label</source> <translation>Copiar capa </translation> </message> <message> <source>Copy amount</source> <translation>copiar monto</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>Address</source> <translation>Domicilio</translation> </message> <message> <source>Amount</source> <translation>Monto</translation> </message> <message> <source>Label</source> <translation>Etiqueta</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Date</source> <translation>Fecha</translation> </message> <message> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <source>Amount</source> <translation>Monto</translation> </message> <message> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>Mandar monedas</translation> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>Monto:</translation> </message> <message> <source>Priority:</source> <translation>Prioridad:</translation> </message> <message> <source>Fee:</source> <translation>Cuota:</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>Enviar a múltiples receptores a la vez</translation> </message> <message> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <source>Confirm the send action</source> <translation>Confirme la acción de enviar</translation> </message> <message> <source>Confirm send coins</source> <translation>Confirme para mandar monedas</translation> </message> <message> <source>Copy quantity</source> <translation>copiar cantidad</translation> </message> <message> <source>Copy amount</source> <translation>copiar monto</translation> </message> <message> <source>Copy fee</source> <translation>copiar cuota</translation> </message> <message> <source>Copy after fee</source> <translation>copiar despues de cuota</translation> </message> <message> <source>Copy bytes</source> <translation>copiar bytes</translation> </message> <message> <source>Copy priority</source> <translation>copiar prioridad</translation> </message> <message> <source>Copy change</source> <translation>copiar cambio</translation> </message> <message> <source>Total Amount %1 (= %2)</source> <translation>Monto total %1(=%2)</translation> </message> <message> <source>or</source> <translation>o</translation> </message> <message> <source>The amount to pay must be larger than 0.</source> <translation>El monto a pagar debe ser mayor a 0</translation> </message> <message> <source>Transaction creation failed!</source> <translation>¡La creación de transacion falló!</translation> </message> <message> <source>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>¡La transación fue rechazada! Esto puede ocurrir si algunas de tus monedas en tu cartera han sido gastadas, al igual que si usas una cartera copiada y la monedas fueron gastadas en la copia pero no se marcaron como gastadas.</translation> </message> <message> <source>Warning: Invalid Dogecoin address</source> <translation>Advertencia: Dirección de Dogecoin invalida</translation> </message> <message> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> <message> <source>Warning: Unknown change address</source> <translation>Advertencia: Cambio de dirección desconocido</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>M&amp;onto</translation> </message> <message> <source>Pay &amp;To:</source> <translation>Pagar &amp;a:</translation> </message> <message> <source>Enter a label for this address to add it to your address book</source> <translation>Ingrese una etiqueta para esta dirección para agregarlo en su libreta de direcciones.</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etiqueta</translation> </message> <message> <source>This is a normal payment.</source> <translation>Este es un pago normal</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Pegar dirección del portapapeles</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Remove this entry</source> <translation>Quitar esta entrada</translation> </message> <message> <source>Message:</source> <translation>Mensaje:</translation> </message> <message> <source>Pay To:</source> <translation>Pago para:</translation> </message> </context> <context> <name>ShutdownWindow</name> <message> <source>Dogecoin Core is shutting down...</source> <translation>Apagando el nucleo de Dogecoin...</translation> </message> <message> <source>Do not shut down the computer until this window disappears.</source> <translation>No apague su computadora hasta que esta ventana desaparesca.</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Pegar dirección del portapapeles</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>Dogecoin Core</source> <translation>nucleo Dogecoin</translation> </message> <message> <source>The Dogecoin Core developers</source> <translation>Los desarrolladores de Dogecoin Core</translation> </message> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDesc</name> <message> <source>Open until %1</source> <translation>Abrir hasta %1</translation> </message> <message> <source>%1/unconfirmed</source> <translation>%1/No confirmado</translation> </message> <message> <source>%1 confirmations</source> <translation>%1 confirmaciones</translation> </message> <message> <source>Date</source> <translation>Fecha</translation> </message> <message> <source>Transaction ID</source> <translation>ID</translation> </message> <message> <source>Amount</source> <translation>Monto</translation> </message> <message> <source>, has not been successfully broadcast yet</source> <translation>, no ha sido transmitido aun</translation> </message> <message> <source>unknown</source> <translation>desconocido</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <source>Transaction details</source> <translation>Detalles de la transacción</translation> </message> <message> <source>This pane shows a detailed description of the transaction</source> <translation>Este panel muestras una descripción detallada de la transacción</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <source>Date</source> <translation>Fecha</translation> </message> <message> <source>Type</source> <translation>Tipo</translation> </message> <message> <source>Open until %1</source> <translation>Abrir hasta %1</translation> </message> <message> <source>Confirmed (%1 confirmations)</source> <translation>Confimado (%1 confirmaciones)</translation> </message> <message> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Este bloque no fue recibido por ningun nodo y probablemente no fue aceptado !</translation> </message> <message> <source>Generated but not accepted</source> <translation>Generado pero no aprovado</translation> </message> <message> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <source>Received with</source> <translation>Recivido con</translation> </message> <message> <source>Sent to</source> <translation>Enviar a</translation> </message> <message> <source>Payment to yourself</source> <translation>Pagar a si mismo</translation> </message> <message> <source>Mined</source> <translation>Minado </translation> </message> <message> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <source>Date and time that the transaction was received.</source> <translation>Fecha y hora en que la transacción fue recibida </translation> </message> <message> <source>Type of transaction.</source> <translation>Escriba una transacción</translation> </message> <message> <source>Amount removed from or added to balance.</source> <translation>Cantidad removida del saldo o agregada </translation> </message> </context> <context> <name>TransactionView</name> <message> <source>All</source> <translation>Todo</translation> </message> <message> <source>Today</source> <translation>Hoy</translation> </message> <message> <source>This week</source> <translation>Esta semana </translation> </message> <message> <source>This month</source> <translation>Este mes </translation> </message> <message> <source>Last month</source> <translation>El mes pasado </translation> </message> <message> <source>This year</source> <translation>Este año</translation> </message> <message> <source>Received with</source> <translation>Recivido con</translation> </message> <message> <source>Sent to</source> <translation>Enviar a</translation> </message> <message> <source>To yourself</source> <translation>Para ti mismo</translation> </message> <message> <source>Mined</source> <translation>Minado </translation> </message> <message> <source>Other</source> <translation>Otro</translation> </message> <message> <source>Enter address or label to search</source> <translation>Ingrese dirección o capa a buscar </translation> </message> <message> <source>Min amount</source> <translation>Monto minimo </translation> </message> <message> <source>Copy address</source> <translation>Copiar dirección </translation> </message> <message> <source>Copy label</source> <translation>Copiar capa </translation> </message> <message> <source>Copy amount</source> <translation>copiar monto</translation> </message> <message> <source>Edit label</source> <translation>Editar capa </translation> </message> <message> <source>Export Transaction History</source> <translation>Exportar el historial de transacción</translation> </message> <message> <source>Exporting Failed</source> <translation>Exportación fallida</translation> </message> <message> <source>There was an error trying to save the transaction history to %1.</source> <translation>Ocurrio un error intentando guardar el historial de transaciones a %1</translation> </message> <message> <source>Exporting Successful</source> <translation>Exportacion satisfactoria</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Arhchivo separado por comas (*.CSV)</translation> </message> <message> <source>Confirmed</source> <translation>Confirmado </translation> </message> <message> <source>Date</source> <translation>Fecha</translation> </message> <message> <source>Type</source> <translation>Tipo</translation> </message> <message> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <source>Address</source> <translation>Domicilio</translation> </message> <message> <source>ID</source> <translation>ID</translation> </message> <message> <source>to</source> <translation>Para</translation> </message> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>WalletFrame</name> <message> <source>No wallet has been loaded.</source> <translation>No se há cargado la cartera.</translation> </message> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation>Mandar monedas</translation> </message> </context> <context> <name>WalletView</name> <message> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportar la información en la tabla actual a un archivo</translation> </message> <message> <source>There was an error trying to save the wallet data to %1.</source> <translation>Ocurrio un error tratando de guardar la información de la cartera %1</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <source>&lt;category&gt; can be:</source> <translation>&lt;categoria&gt; puede ser:</translation> </message> <message> <source>Wallet options:</source> <translation>Opciones de cartera:</translation> </message> <message> <source>Choose data directory on startup (default: 0)</source> <translation>Escojer el directorio de información al iniciar (por defecto : 0)</translation> </message> <message> <source>Set language, for example "de_DE" (default: system locale)</source> <translation>Definir idioma, por ejemplo "de_DE" (por defecto: Sistema local)</translation> </message> <message> <source>Show splash screen on startup (default: 1)</source> <translation>Mostrar pantalla de arraque al iniciar (por defecto: 1)</translation> </message> <message> <source>Start minimized</source> <translation>Iniciar minimizado</translation> </message> <message> <source>Loading addresses...</source> <translation>Cargando direcciones...</translation> </message> <message> <source>Loading block index...</source> <translation>Cargando indice de bloques... </translation> </message> <message> <source>Loading wallet...</source> <translation>Cargando billetera...</translation> </message> <message> <source>Done loading</source> <translation>Carga completa</translation> </message> </context> </TS><|fim▁end|>
<|file_name|>Popup.js<|end_file_name|><|fim▁begin|>require( [ 'gui/Button' ], function (Button) { return; var button = new Button({ main: $('#ui-button') }); button.render(); }<|fim▁hole|><|fim▁end|>
);
<|file_name|>basic-example.js<|end_file_name|><|fim▁begin|>var config = { container: "#basic-example", connectors: { type: 'step' }, node: { HTMLclass: 'nodeExample1' } }, ceo = { text: { name: "Mark Hill", title: "Chief executive officer", contact: "Tel: 01 213 123 134", }, image: "../headshots/2.jpg" }, cto = { parent: ceo, text:{ name: "Joe Linux", title: "Chief Technology Officer", }, stackChildren: true, image: "../headshots/1.jpg" }, cbo = { parent: ceo, stackChildren: true, text:{ name: "Linda May", title: "Chief Business Officer", }, image: "../headshots/5.jpg" }, cdo = { parent: ceo, text:{ name: "John Green", title: "Chief accounting officer", contact: "Tel: 01 213 123 134", }, image: "../headshots/6.jpg" }, cio = { parent: cto, text:{ name: "Ron Blomquist", title: "Chief Information Security Officer" }, image: "../headshots/8.jpg" }, ciso = { parent: cto, text:{ name: "Michael Rubin", title: "Chief Innovation Officer", contact: {val: "[email protected]", href: "mailto:[email protected]"} }, image: "../headshots/9.jpg" }, cio2 = { parent: cdo, text:{ name: "Erica Reel", title: "Chief Customer Officer" }, link: { href: "http://www.google.com" }, image: "../headshots/10.jpg" }, ciso2 = { parent: cbo, text:{ name: "Alice Lopez", title: "Chief Communications Officer" }, image: "../headshots/7.jpg" }, ciso3 = { parent: cbo, text:{ name: "Mary Johnson", title: "Chief Brand Officer" }, image: "../headshots/4.jpg" }, ciso4 = { parent: cbo, text:{ name: "Kirk Douglas", title: "Chief Business Development Officer" }, image: "../headshots/11.jpg" } chart_config = [ config, ceo, cto, cbo, cdo, cio, ciso, cio2, ciso2, ciso3, ciso4 ]; // Another approach, same result // JSON approach /* var chart_config = { chart: { container: "#basic-example", connectors: { type: 'step' }, node: { HTMLclass: 'nodeExample1' } }, nodeStructure: { text: { name: "Mark Hill", title: "Chief executive officer", contact: "Tel: 01 213 123 134", }, image: "../headshots/2.jpg", children: [ { text:{ name: "Joe Linux", title: "Chief Technology Officer", }, stackChildren: true, image: "../headshots/1.jpg", children: [ { text:{ name: "Ron Blomquist", title: "Chief Information Security Officer" }, image: "../headshots/8.jpg" }, { text:{ name: "Michael Rubin", title: "Chief Innovation Officer", contact: "[email protected]" }, image: "../headshots/9.jpg" } ] }, { stackChildren: true, text:{ name: "Linda May", title: "Chief Business Officer", }, image: "../headshots/5.jpg", children: [ { text:{ name: "Alice Lopez", title: "Chief Communications Officer" <|fim▁hole|> text:{ name: "Mary Johnson", title: "Chief Brand Officer" }, image: "../headshots/4.jpg" }, { text:{ name: "Kirk Douglas", title: "Chief Business Development Officer" }, image: "../headshots/11.jpg" } ] }, { text:{ name: "John Green", title: "Chief accounting officer", contact: "Tel: 01 213 123 134", }, image: "../headshots/6.jpg", children: [ { text:{ name: "Erica Reel", title: "Chief Customer Officer" }, link: { href: "http://www.google.com" }, image: "../headshots/10.jpg" } ] } ] } }; */<|fim▁end|>
}, image: "../headshots/7.jpg" }, {
<|file_name|>ErrorProperties.java<|end_file_name|><|fim▁begin|>/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.web; import org.springframework.beans.factory.annotation.Value; /** * Configuration properties for web error handling. * * @author Michael Stummvoll * @author Stephane Nicoll * @author Vedran Pavic * @since 1.3.0 */ public class ErrorProperties { /** * Path of the error controller. */ @Value("${error.path:/error}") private String path = "/error"; /** * Include the "exception" attribute. */ private boolean includeException; /** * When to include a "stacktrace" attribute. */<|fim▁hole|> } public void setPath(String path) { this.path = path; } public boolean isIncludeException() { return this.includeException; } public void setIncludeException(boolean includeException) { this.includeException = includeException; } public IncludeStacktrace getIncludeStacktrace() { return this.includeStacktrace; } public void setIncludeStacktrace(IncludeStacktrace includeStacktrace) { this.includeStacktrace = includeStacktrace; } /** * Include Stacktrace attribute options. */ public enum IncludeStacktrace { /** * Never add stacktrace information. */ NEVER, /** * Always add stacktrace information. */ ALWAYS, /** * Add stacktrace information when the "trace" request parameter is "true". */ ON_TRACE_PARAM } }<|fim▁end|>
private IncludeStacktrace includeStacktrace = IncludeStacktrace.NEVER; public String getPath() { return this.path;
<|file_name|>test_admin_actions.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import django_dynamic_fixture as fixture from unittest import mock from django import urls from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.auth.models import User from django.test import TestCase from readthedocs.core.models import UserProfile from readthedocs.projects.models import Project class ProjectAdminActionsTest(TestCase): @classmethod def setUpTestData(cls): cls.owner = fixture.get(User) cls.profile = fixture.get(UserProfile, user=cls.owner, banned=False) cls.admin = fixture.get(User, is_staff=True, is_superuser=True) cls.project = fixture.get( Project, main_language_project=None, users=[cls.owner], ) def setUp(self): self.client.force_login(self.admin) def test_project_ban_owner(self): self.assertFalse(self.owner.profile.banned) action_data = { ACTION_CHECKBOX_NAME: [self.project.pk], 'action': 'ban_owner', 'index': 0, } resp = self.client.post( urls.reverse('admin:projects_project_changelist'), action_data, ) self.assertTrue(self.project.users.filter(profile__banned=True).exists()) self.assertFalse(self.project.users.filter(profile__banned=False).exists()) def test_project_ban_multiple_owners(self): owner_b = fixture.get(User) profile_b = fixture.get(UserProfile, user=owner_b, banned=False)<|fim▁hole|> self.assertFalse(owner_b.profile.banned) action_data = { ACTION_CHECKBOX_NAME: [self.project.pk], 'action': 'ban_owner', 'index': 0, } resp = self.client.post( urls.reverse('admin:projects_project_changelist'), action_data, ) self.assertFalse(self.project.users.filter(profile__banned=True).exists()) self.assertEqual(self.project.users.filter(profile__banned=False).count(), 2) @mock.patch('readthedocs.projects.admin.clean_project_resources') def test_project_delete(self, clean_project_resources): """Test project and artifacts are removed.""" action_data = { ACTION_CHECKBOX_NAME: [self.project.pk], 'action': 'delete_selected', 'index': 0, 'post': 'yes', } resp = self.client.post( urls.reverse('admin:projects_project_changelist'), action_data, ) self.assertFalse(Project.objects.filter(pk=self.project.pk).exists()) clean_project_resources.assert_has_calls([ mock.call( self.project, ), ])<|fim▁end|>
self.project.users.add(owner_b) self.assertFalse(self.owner.profile.banned)
<|file_name|>step_attach_iso.go<|end_file_name|><|fim▁begin|><|fim▁hole|> "fmt" "log" "github.com/hashicorp/packer-plugin-sdk/multistep" packersdk "github.com/hashicorp/packer-plugin-sdk/packer" parallelscommon "github.com/hashicorp/packer/builder/parallels/common" ) // This step attaches the ISO to the virtual machine. // // Uses: // driver Driver // iso_path string // ui packersdk.Ui // vmName string // // Produces: // attachedIso bool type stepAttachISO struct{} func (s *stepAttachISO) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { driver := state.Get("driver").(parallelscommon.Driver) isoPath := state.Get("iso_path").(string) ui := state.Get("ui").(packersdk.Ui) vmName := state.Get("vmName").(string) // Attach the disk to the cdrom0 device. We couldn't use a separated device because it is failed to boot in PD9 [GH-1667] ui.Say("Attaching ISO to the default CD/DVD ROM device...") command := []string{ "set", vmName, "--device-set", "cdrom0", "--image", isoPath, "--enable", "--connect", } if err := driver.Prlctl(command...); err != nil { err := fmt.Errorf("Error attaching ISO: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } // Set some state so we know to remove state.Put("attachedIso", true) return multistep.ActionContinue } func (s *stepAttachISO) Cleanup(state multistep.StateBag) { if _, ok := state.GetOk("attachedIso"); !ok { return } driver := state.Get("driver").(parallelscommon.Driver) ui := state.Get("ui").(packersdk.Ui) vmName := state.Get("vmName").(string) // Detach ISO by setting an empty string image. log.Println("Detaching ISO from the default CD/DVD ROM device...") command := []string{ "set", vmName, "--device-set", "cdrom0", "--image", "", "--disconnect", "--enable", } if err := driver.Prlctl(command...); err != nil { ui.Error(fmt.Sprintf("Error detaching ISO: %s", err)) } }<|fim▁end|>
package iso import ( "context"
<|file_name|>make_datasets.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """ Generate artificial datasets for the multi-step prediction experiments """ import os import random import datetime from optparse import OptionParser from nupic.data.file_record_stream import FileRecordStream def _generateSimple(filename="simple.csv", numSequences=1, elementsPerSeq=3, numRepeats=10): """ Generate a simple dataset. This contains a bunch of non-overlapping sequences. At the end of the dataset, we introduce missing records so that test code can insure that the model didn't get confused by them. Parameters: ---------------------------------------------------- filename: name of the file to produce, including extension. It will be created in a 'datasets' sub-directory within the directory containing this script. numSequences: how many sequences to generate elementsPerSeq: length of each sequence numRepeats: how many times to repeat each sequence in the output """ # Create the output file scriptDir = os.path.dirname(__file__) pathname = os.path.join(scriptDir, 'datasets', filename) print "Creating %s..." % (pathname) fields = [('timestamp', 'datetime', 'T'), ('field1', 'string', ''), ('field2', 'float', '')] outFile = FileRecordStream(pathname, write=True, fields=fields) # Create the sequences sequences = [] for i in range(numSequences): seq = [x for x in range(i*elementsPerSeq, (i+1)*elementsPerSeq)] sequences.append(seq) # Write out the sequences in random order seqIdxs = [] for i in range(numRepeats): seqIdxs += range(numSequences) random.shuffle(seqIdxs) # Put 1 hour between each record timestamp = datetime.datetime(year=2012, month=1, day=1, hour=0, minute=0, second=0) timeDelta = datetime.timedelta(hours=1) # Write out the sequences without missing records for seqIdx in seqIdxs: seq = sequences[seqIdx] for x in seq: outFile.appendRecord([timestamp, str(x), x]) timestamp += timeDelta # Now, write some out with missing records for seqIdx in seqIdxs: seq = sequences[seqIdx]<|fim▁hole|> for i,x in enumerate(seq): if i != 1: outFile.appendRecord([timestamp, str(x), x]) timestamp += timeDelta for seqIdx in seqIdxs: seq = sequences[seqIdx] for i,x in enumerate(seq): if i != 1: outFile.appendRecord([timestamp, str(x), x]) timestamp += timeDelta # Write out some more of the sequences *without* missing records for seqIdx in seqIdxs: seq = sequences[seqIdx] for x in seq: outFile.appendRecord([timestamp, str(x), x]) timestamp += timeDelta outFile.close() if __name__ == '__main__': helpString = \ """%prog [options] Generate artificial datasets for testing multi-step prediction """ # ============================================================================ # Process command line arguments parser = OptionParser(helpString) parser.add_option("--verbosity", default=0, type="int", help="Verbosity level, either 0, 1, 2, or 3 [default: %default].") (options, args) = parser.parse_args() if len(args) != 0: parser.error("No arguments accepted") # Set random seed random.seed(42) # Create the dataset directory if necessary datasetsDir = os.path.join(os.path.dirname(__file__), 'datasets') if not os.path.exists(datasetsDir): os.mkdir(datasetsDir) # Generate the sample datasets _generateSimple('simple_0.csv', numSequences=1, elementsPerSeq=3, numRepeats=10)<|fim▁end|>
<|file_name|>OpenIceThicknessListener.rs<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
energymodels.OpenIceThicknessListener
<|file_name|>a6.rs<|end_file_name|><|fim▁begin|>fn main() { // Ciclos while, for, Enumerate let mut x = 5; let mut completado = false; // La variable mutable completado es de tipo booleano, es decir que solo tiene dos valores: false o true. println!("Ciclo while"); while !completado { // El ciclo while termina cuando la sentencia se cumpla en este caso cuando completado sea diferente a false, es decir verdadero. x += x;<|fim▁hole|> if x == 160 { completado = true; }; }; // El ciclo for de rust luce mas parecido al de ruby. println!("Ciclo for"); for i in 0..6 { // Este ciclo empiza por el primer número y termina uno antes del indicado, para este caso empieza en 0 y termina en 5 println!("{}", i); }; println!("Ciclo for con enumerate()"); for (i,j) in (5..11).enumerate() { // enumerate cuenta las veces que se iterao se hace el ciclo, es importante respetar los parentensis. println!("i = {} y j = {}", i, j); // i imprime el número de iteración y j el rango en el que se esta iterando. }; }<|fim▁end|>
println!("{}", x);
<|file_name|>responsesEvaluate.py<|end_file_name|><|fim▁begin|>import logging import os import math from collections import defaultdict from gensim import corpora # 引入斷詞與停用詞的配置 from .Matcher.matcher import Matcher class Evaluator(Matcher): """ 讀入一串推文串列,計算出當中可靠度最高的推文 """ def __init__(self,segLib="Taiba"): #FIXME 若「線上版本」受記憶體容量限制,需考慮更換為 jieba! super().__init__(segLib) self.responses = [] self.segResponses = [] self.totalWords = 0 self.path = os.path.dirname(__file__) self.debugLog = open(self.path + "/data/EvaluateLog.txt",'w',encoding="utf-8") self.filteredWords = set() # 必須濾除的回應 self.counterDictionary = defaultdict(int) # 用於統計詞頻 self.tokenDictionary = None # 用於分配詞 id,與建置詞袋 # 中文停用詞與特殊符號加載 self.loadStopWords(path=self.path + "/data/stopwords/chinese_sw.txt") self.loadStopWords(path=self.path + "/data/stopwords/specialMarks.txt") self.loadFilterdWord(path=self.path + "/data/stopwords/ptt_words.txt") def cleanFormerResult(self): """ 清空之前回應留下的紀錄 """ self.responses = [] self.segResponses = [] self.totalWords = 0 def getBestResponse(self, responses, topk, debugMode=False): """ 從 self.responses 中挑選出可靠度前 K 高的回應回傳 Return : List of (reply,grade) """ self.cleanFormerResult() <|fim▁hole|> self.buildCounterDictionary() candiateList = self.evaluateByGrade(topk, debug=debugMode) return candiateList def loadFilterdWord(self,path): with open(path, 'r', encoding='utf-8') as sw: for word in sw: self.filteredWords.add(word.strip('\n')) def buildResponses(self, responses): """ 將 json 格式中目前用不上的 user,vote 去除,只留下 Content """ self.responses = [] for response in responses: clean = True r = response["Content"] for word in self.filteredWords: if word in r: clean = False if clean: self.responses.append(response["Content"]) def segmentResponse(self): """ 對 self.responses 中所有的回應斷詞並去除中文停用詞,儲存於 self.segResponses """ self.segResponses = [] for response in self.responses: keywordResponse = [keyword for keyword in self.wordSegmentation(response) if keyword not in self.stopwords and keyword != ' '] self.totalWords += len(keywordResponse) self.segResponses.append(keywordResponse) #logging.info("已完成回應斷詞") def buildCounterDictionary(self): """ 統計 self.segResponses 中每個詞出現的次數 """ for reply in self.segResponses: for word in reply: self.counterDictionary[word] += 1 #logging.info("計數字典建置完成") def buildTokenDictionary(self): """ 為 self.segResponses 中的詞配置一個 id """ self.tokenDictionary = corpora.Dictionary(self.segResponses) logging.info("詞袋字典建置完成,%s" % str(self.tokenDictionary)) def evaluateByGrade(self,topk,debug=False): """ 依照每個詞出現的在該文件出現的情形,給予每個回覆一個分數 若該回覆包含越多高詞頻的詞,其得分越高 Args: - 若 debug 為 True,列出每筆評論的評分與斷詞情形 Return: (BestResponse,Grade) - BestResponse: 得分最高的回覆 - Grade: 該回覆獲得的分數 """ bestResponse = "" candiates = [] avgWords = self.totalWords/len(self.segResponses) for i in range(0, len(self.segResponses)): wordCount = len(self.segResponses[i]) sourceCount = len(self.responses[i]) meanful = 0 if wordCount == 0 or sourceCount > 24: continue cur_grade = 0. for word in self.segResponses[i]: wordWeight = self.counterDictionary[word] if wordWeight > 1: meanful += math.log(wordWeight,10) cur_grade += wordWeight cur_grade = cur_grade * meanful / (math.log(len(self.segResponses[i])+1,avgWords) + 1) candiates.append([self.responses[i],cur_grade]) if debug: result = self.responses[i] + '\t' + str(self.segResponses[i]) + '\t' + str(cur_grade) self.debugLog.write(result+'\n') print(result) candiates = sorted(candiates,key=lambda candiate:candiate[1],reverse=True) return candiates[:topk] class ClusteringEvaluator(Evaluator): """ 基於聚類評比推文可靠度 """ pass<|fim▁end|>
self.buildResponses(responses) self.segmentResponse()
<|file_name|>NavigationDrawerAdapter.java<|end_file_name|><|fim▁begin|>package com.dyhpoon.fodex.navigationDrawer; import android.content.Context; import android.view.View; import android.view.ViewGroup; import com.dyhpoon.fodex.R; /** * Created by darrenpoon on 3/2/15. */ public class NavigationDrawerAdapter extends SectionAdapter { private Context mContext; public class ViewType { public static final int PROFILE = 0; public static final int WHITESPACE = 1; public static final int PAGE = 2; public static final int DIVIDER = 3; public static final int UTILITY = 4; } public NavigationDrawerAdapter(Context context) { mContext = context; } @Override public int getSectionCount() { return 5; // all view types } @Override public Boolean isSectionEnabled(int section) { switch (section) { case ViewType.PROFILE: return false; case ViewType.WHITESPACE: return false; case ViewType.PAGE: return true; case ViewType.DIVIDER: return false; case ViewType.UTILITY: return true; default: throw new IllegalArgumentException( "Unhandled section number in navigation drawer adapter, found: " + section); } } @Override public int getViewCountAtSection(int section) { switch (section) { case ViewType.PROFILE: return 1; case ViewType.WHITESPACE: return 1; case ViewType.PAGE: return NavigationDrawerData.getPageItems(mContext).size(); case ViewType.DIVIDER: return 1; case ViewType.UTILITY: return NavigationDrawerData.getUtilityItems(mContext).size(); default: throw new IllegalArgumentException( "Unhandled section number in navigation drawer adapter, found: " + section); } } @Override public View getView(int section, int position, View convertView, ViewGroup parent) { switch (section) { case 0: convertView = inflateProfile(convertView); break; case 1: convertView = inflateWhiteSpace(convertView); break; case 2: convertView = inflatePageItem(convertView, position); break; case 3:<|fim▁hole|> break; default: throw new IllegalArgumentException( "Unhandled section/position number in navigation drawer adapter, " + "found section: " + section + " position: " + position); } return convertView; } private View inflateProfile(View convertView) { if (convertView == null) { convertView = View.inflate(mContext, R.layout.list_item_profile, null); } return convertView; } private View inflateWhiteSpace(View convertView) { if (convertView == null) { convertView = View.inflate(mContext, R.layout.list_item_whitespace, null); } return convertView; } private View inflatePageItem(View convertView, int position) { if (convertView == null) { convertView = new NavigationDrawerItem(mContext); } NavigationDrawerInfo info = NavigationDrawerData.getPageItem(mContext, position); ((NavigationDrawerItem)convertView).iconImageView.setImageDrawable(info.drawable); ((NavigationDrawerItem)convertView).titleTextView.setText(info.title); return convertView; } private View inflateUtilityItem(View convertView, int position) { if (convertView == null) { convertView = new NavigationDrawerItem(mContext); } NavigationDrawerInfo info = NavigationDrawerData.getUtilityItem(mContext, position); ((NavigationDrawerItem)convertView).iconImageView.setImageDrawable(info.drawable); ((NavigationDrawerItem)convertView).titleTextView.setText(info.title); return convertView; } private View inflateListDivider(View convertView) { if (convertView == null) { convertView = View.inflate(mContext, R.layout.list_item_divider, null); } return convertView; } }<|fim▁end|>
convertView = inflateListDivider(convertView); break; case 4: convertView = inflateUtilityItem(convertView, position);
<|file_name|>jquery.flot.hiddengraphs.js<|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/. */ /* * Plugin to hide series in flot graphs. * * To activate, set legend.hideable to true in the flot options object. * To hide one or more series by default, set legend.hidden to an array of * label strings. * * At the moment, this only works with line and point graphs. * * Example: * * var plotdata = [ * { * data: [[1, 1], [2, 1], [3, 3], [4, 2], [5, 5]], * label: "graph 1" * }, * { * data: [[1, 0], [2, 1], [3, 0], [4, 4], [5, 3]], * label: "graph 2" * } * ]; * * plot = $.plot($("#placeholder"), plotdata, { * series: { * points: { show: true }, * lines: { show: true } * }, * legend: { * hideable: true, * hidden: ["graph 1", "graph 2"] * } * }); * */ (function ($) { var options = { }; var drawnOnce = false; function init(plot) { function findPlotSeries(label) { var plotdata = plot.getData(); for (var i = 0; i < plotdata.length; i++) { if (plotdata[i].label == label) { return plotdata[i]; } } return null; } function plotLabelClicked(label, mouseOut) { var series = findPlotSeries(label); if (!series) { return; } var switchedOff = false; if (typeof series.points.oldShow === "undefined") { series.points.oldShow = false; } if (typeof series.lines.oldShow === "undefined") { series.lines.oldShow = false; } if (series.points.show && !series.points.oldShow) { series.points.show = false; series.points.oldShow = true; switchedOff = true; } if (series.lines.show && !series.lines.oldShow) { series.lines.show = false; series.lines.oldShow = true; switchedOff = true; } if (switchedOff) { series.oldColor = series.color; series.color = "#fff"; } else { var switchedOn = false; if (!series.points.show && series.points.oldShow) { series.points.show = true; series.points.oldShow = false; switchedOn = true; } if (!series.lines.show && series.lines.oldShow) { series.lines.show = true; series.lines.oldShow = false; switchedOn = true; } if (switchedOn) { series.color = series.oldColor; } } // HACK: Reset the data, triggering recalculation of graph bounds plot.setData(plot.getData()); plot.setupGrid(); plot.draw(); } function plotLabelHandlers(plot, options) { $(".graphlabel").mouseenter(function() { $(this).css("cursor", "pointer"); })<|fim▁hole|> .unbind("click").click(function() { plotLabelClicked($(this).parent().text()); }); if (!drawnOnce) { drawnOnce = true; if (options.legend.hidden) { for (var i = 0; i < options.legend.hidden.length; i++) { plotLabelClicked(options.legend.hidden[i], true); } } } } function checkOptions(plot, options) { if (!options.legend.hideable) { return; } options.legend.labelFormatter = function(label, series) { return '<span class="graphlabel">' + label + '</span>'; }; // Really just needed for initial draw; the mouse-enter/leave // functions will call plotLabelHandlers() directly, since they // only call setupGrid(). plot.hooks.draw.push(function (plot, ctx) { plotLabelHandlers(plot, options); }); } plot.hooks.processOptions.push(checkOptions); function hideDatapointsIfNecessary(plot, s, datapoints) { if (!plot.getOptions().legend.hideable) { return; } if (!s.points.show && !s.lines.show) { s.datapoints.format = [ null, null ]; } } plot.hooks.processDatapoints.push(hideDatapointsIfNecessary); } $.plot.plugins.push({ init: init, options: options, name: 'hiddenGraphs', version: '1.0' }); })(jQuery);<|fim▁end|>
.mouseleave(function() { $(this).css("cursor", "default"); })
<|file_name|>resolve.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python from src.sqllist import GLOBALS class BasicResolver(object): """General resolver class""" def __init__(self, conn=None): self.conn = conn pass def resolve(self, detections, sources): """Template resolve function. Returns resolution status and an array of xtrsrcid-runcatid of resolved pairs (if possible)."""<|fim▁hole|>select xtrsrcid, ra, ra_err, decl, decl_err, f_int, f_int_err from extractedsources e where e.image_id = %s and exists (select 1 from temp_associations ta where ta.xtrsrc_id2 = e.xtrsrcid and ta.image_id = e.image_id and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id)) detections = cursor.fetchall() cursor.close() return detections def load_sources(self, group_id): cursor = self.conn.get_cursor(""" select runcatid, wm_ra, wm_ra_err, wm_decl, wm_decl_err, wm_f_int, wm_f_int_err from runningcatalog r, runningcatalog_fluxes f, images i where i.imageid = %s and f.band = i.band and f.stokes = i.stokes and r.runcatid = f.runcat_id and exists (select 1 from temp_associations ta where ta.runcat_id = r.runcatid and ta.image_id = i.imageid and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id)) sources = cursor.fetchall() cursor.close() return sources def run_resolve(self, group_id): """Get data from Database, run resolver, saev results to temp_associations""" #--Run resolver-- is_ok, solutions = self.resolve(self.load_detections(group_id), self.load_sources(group_id)) if is_ok: #"delete" all associations from this group. self.conn.execute(""" update temp_associations set kind = -1 where image_id = %s and group_head_id = %s;""" % (GLOBALS['i'], group_id)) #"restore" associations that are "ok" for solution in solutions: self.conn.execute("""update temp_associations set kind = 1, group_head_id = null where image_id = %s and group_head_id = %s and xtrsrc_id2 = %s and runcat_id = %s;""" % (GLOBALS['i'], group_id, solution[0], solution[1])) return is_ok<|fim▁end|>
return False, [] def load_detections(self, group_id): cursor = self.conn.get_cursor("""
<|file_name|>router.js<|end_file_name|><|fim▁begin|>import { createRouter, createWebHistory } from "vue-router/dist/vue-router.esm.js"; import Home from "./views/Home.vue"; const routerHistory = createWebHistory("/"); let router = createRouter({ history: routerHistory, routes: [ { path: '/', component: Home, name: '' },<|fim▁hole|> { path: '/what', component: Home, name: 'what' }, { path: '/where', component: Home, name: 'where' }, { path: '/when', component: Home, name: 'when' }, { path: '/why', component: Home, name: 'why' } ] }); router.afterEach((to, from) => { console.info((to, from, window.location.pathname)); }) export default router;<|fim▁end|>
{ path: '/who', component: Home, name: 'who' },
<|file_name|>resource_instance.go<|end_file_name|><|fim▁begin|>package opc import ( "bytes" "encoding/json" "fmt" "log" "strconv" "strings" "github.com/hashicorp/go-oracle-terraform/compute" "github.com/r3labs/terraform/helper/hashcode" "github.com/r3labs/terraform/helper/schema" "github.com/r3labs/terraform/helper/validation" ) func resourceInstance() *schema.Resource { return &schema.Resource{ Create: resourceInstanceCreate, Read: resourceInstanceRead, Delete: resourceInstanceDelete, Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { combined := strings.Split(d.Id(), "/") if len(combined) != 2 { return nil, fmt.Errorf("Invalid ID specified. Must be in the form of instance_name/instance_id. Got: %s", d.Id()) } d.Set("name", combined[0]) d.SetId(combined[1]) return []*schema.ResourceData{d}, nil }, }, Schema: map[string]*schema.Schema{ ///////////////////////// // Required Attributes // ///////////////////////// "name": { Type: schema.TypeString, Required: true, ForceNew: true, }, "shape": { Type: schema.TypeString, Required: true, ForceNew: true, }, ///////////////////////// // Optional Attributes // ///////////////////////// "instance_attributes": { Type: schema.TypeString, Optional: true, ForceNew: true, ValidateFunc: validation.ValidateJsonString, }, "boot_order": { Type: schema.TypeList, Optional: true, ForceNew: true, Elem: &schema.Schema{Type: schema.TypeInt}, }, "hostname": { Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, }, "image_list": { Type: schema.TypeString, Optional: true, ForceNew: true, }, "label": { Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, }, "networking_info": { Type: schema.TypeSet, Optional: true, Computed: true, ForceNew: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "dns": { // Required for Shared Network Interface, will default if unspecified, however // Optional for IP Network Interface Type: schema.TypeList, Optional: true, Computed: true, ForceNew: true, Elem: &schema.Schema{Type: schema.TypeString}, }, "index": { Type: schema.TypeInt, ForceNew: true, Required: true, }, "ip_address": { // Optional, IP Network only Type: schema.TypeString, ForceNew: true, Optional: true, }, "ip_network": { // Required for an IP Network Interface Type: schema.TypeString, ForceNew: true, Optional: true, }, "mac_address": { // Optional, IP Network Only Type: schema.TypeString, ForceNew: true, Computed: true, Optional: true, }, "name_servers": { // Optional, IP Network + Shared Network Type: schema.TypeList, Optional: true, ForceNew: true, Elem: &schema.Schema{Type: schema.TypeString}, }, "nat": { // Optional for IP Network // Required for Shared Network Type: schema.TypeList, Optional: true, ForceNew: true, Elem: &schema.Schema{Type: schema.TypeString}, }, "search_domains": { // Optional, IP Network + Shared Network Type: schema.TypeList, Optional: true, ForceNew: true, Elem: &schema.Schema{Type: schema.TypeString}, }, "sec_lists": { // Required, Shared Network only. Will default if unspecified however Type: schema.TypeList, Optional: true, Computed: true, ForceNew: true, Elem: &schema.Schema{Type: schema.TypeString}, }, "shared_network": { Type: schema.TypeBool, Optional: true, ForceNew: true, Default: false, }, "vnic": { // Optional, IP Network only. Type: schema.TypeString, ForceNew: true, Optional: true, }, "vnic_sets": { // Optional, IP Network only. Type: schema.TypeList, Optional: true, ForceNew: true, Elem: &schema.Schema{Type: schema.TypeString}, }, }, }, Set: func(v interface{}) int { var buf bytes.Buffer m := v.(map[string]interface{}) buf.WriteString(fmt.Sprintf("%d-", m["index"].(int))) buf.WriteString(fmt.Sprintf("%s-", m["vnic"].(string))) buf.WriteString(fmt.Sprintf("%s-", m["nat"])) return hashcode.String(buf.String()) }, }, "reverse_dns": { Type: schema.TypeBool, Optional: true, Default: true, ForceNew: true, }, "ssh_keys": { Type: schema.TypeList, Optional: true, ForceNew: true, Elem: &schema.Schema{Type: schema.TypeString}, }, "storage": { Type: schema.TypeSet, Optional: true, ForceNew: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "index": { Type: schema.TypeInt, Required: true, ForceNew: true, ValidateFunc: validation.IntBetween(1, 10), }, "volume": { Type: schema.TypeString, Required: true, ForceNew: true, }, "name": { Type: schema.TypeString, Computed: true, }, }, }, }, "tags": tagsForceNewSchema(), ///////////////////////// // Computed Attributes // ///////////////////////// "attributes": { Type: schema.TypeString, Computed: true, }, "availability_domain": { Type: schema.TypeString, Computed: true, }, "domain": { Type: schema.TypeString, Computed: true, }, "entry": { Type: schema.TypeInt, Computed: true, }, "fingerprint": { Type: schema.TypeString, Computed: true, }, "image_format": { Type: schema.TypeString, Computed: true, }, "ip_address": { Type: schema.TypeString, Computed: true, }, "placement_requirements": { Type: schema.TypeList, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, "platform": { Type: schema.TypeString, Computed: true, }, "priority": { Type: schema.TypeString, Computed: true, }, <|fim▁hole|> "quota_reservation": { Type: schema.TypeString, Computed: true, }, "relationships": { Type: schema.TypeList, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, "resolvers": { Type: schema.TypeList, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, "site": { Type: schema.TypeString, Computed: true, }, "start_time": { Type: schema.TypeString, Computed: true, }, "state": { Type: schema.TypeString, Computed: true, }, "vcable": { Type: schema.TypeString, Computed: true, }, "virtio": { Type: schema.TypeBool, Computed: true, }, "vnc_address": { Type: schema.TypeString, Computed: true, }, }, } } func resourceInstanceCreate(d *schema.ResourceData, meta interface{}) error { client := meta.(*compute.Client).Instances() // Get Required Attributes input := &compute.CreateInstanceInput{ Name: d.Get("name").(string), Shape: d.Get("shape").(string), } // Get optional instance attributes attributes, attrErr := getInstanceAttributes(d) if attrErr != nil { return attrErr } if attributes != nil { input.Attributes = attributes } if bootOrder := getIntList(d, "boot_order"); len(bootOrder) > 0 { input.BootOrder = bootOrder } if v, ok := d.GetOk("hostname"); ok { input.Hostname = v.(string) } if v, ok := d.GetOk("image_list"); ok { input.ImageList = v.(string) } if v, ok := d.GetOk("label"); ok { input.Label = v.(string) } interfaces, err := readNetworkInterfacesFromConfig(d) if err != nil { return err } if interfaces != nil { input.Networking = interfaces } if v, ok := d.GetOk("reverse_dns"); ok { input.ReverseDNS = v.(bool) } if sshKeys := getStringList(d, "ssh_keys"); len(sshKeys) > 0 { input.SSHKeys = sshKeys } storage := getStorageAttachments(d) if len(storage) > 0 { input.Storage = storage } if tags := getStringList(d, "tags"); len(tags) > 0 { input.Tags = tags } result, err := client.CreateInstance(input) if err != nil { return fmt.Errorf("Error creating instance %s: %s", input.Name, err) } log.Printf("[DEBUG] Created instance %s: %#v", input.Name, result.ID) d.SetId(result.ID) return resourceInstanceRead(d, meta) } func resourceInstanceRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*compute.Client).Instances() name := d.Get("name").(string) input := &compute.GetInstanceInput{ ID: d.Id(), Name: name, } log.Printf("[DEBUG] Reading state of instance %s", name) result, err := client.GetInstance(input) if err != nil { // Instance doesn't exist if compute.WasNotFoundError(err) { log.Printf("[DEBUG] Instance %s not found", name) d.SetId("") return nil } return fmt.Errorf("Error reading instance %s: %s", name, err) } log.Printf("[DEBUG] Instance '%s' found", name) // Update attributes return updateInstanceAttributes(d, result) } func updateInstanceAttributes(d *schema.ResourceData, instance *compute.InstanceInfo) error { d.Set("name", instance.Name) d.Set("shape", instance.Shape) if err := setInstanceAttributes(d, instance.Attributes); err != nil { return err } if attrs, ok := d.GetOk("instance_attributes"); ok && attrs != nil { d.Set("instance_attributes", attrs.(string)) } if err := setIntList(d, "boot_order", instance.BootOrder); err != nil { return err } d.Set("hostname", instance.Hostname) d.Set("image_list", instance.ImageList) d.Set("label", instance.Label) if err := readNetworkInterfaces(d, instance.Networking); err != nil { return err } d.Set("reverse_dns", instance.ReverseDNS) if err := setStringList(d, "ssh_keys", instance.SSHKeys); err != nil { return err } if err := readStorageAttachments(d, instance.Storage); err != nil { return err } if err := setStringList(d, "tags", instance.Tags); err != nil { return err } d.Set("availability_domain", instance.AvailabilityDomain) d.Set("domain", instance.Domain) d.Set("entry", instance.Entry) d.Set("fingerprint", instance.Fingerprint) d.Set("image_format", instance.ImageFormat) d.Set("ip_address", instance.IPAddress) if err := setStringList(d, "placement_requirements", instance.PlacementRequirements); err != nil { return err } d.Set("platform", instance.Platform) d.Set("priority", instance.Priority) d.Set("quota_reservation", instance.QuotaReservation) if err := setStringList(d, "relationships", instance.Relationships); err != nil { return err } if err := setStringList(d, "resolvers", instance.Resolvers); err != nil { return err } d.Set("site", instance.Site) d.Set("start_time", instance.StartTime) d.Set("state", instance.State) if err := setStringList(d, "tags", instance.Tags); err != nil { return err } d.Set("vcable", instance.VCableID) d.Set("virtio", instance.Virtio) d.Set("vnc_address", instance.VNC) return nil } func resourceInstanceDelete(d *schema.ResourceData, meta interface{}) error { client := meta.(*compute.Client).Instances() name := d.Get("name").(string) input := &compute.DeleteInstanceInput{ ID: d.Id(), Name: name, } log.Printf("[DEBUG] Deleting instance %s", name) if err := client.DeleteInstance(input); err != nil { return fmt.Errorf("Error deleting instance %s: %s", name, err) } return nil } func getStorageAttachments(d *schema.ResourceData) []compute.StorageAttachmentInput { storageAttachments := []compute.StorageAttachmentInput{} storage := d.Get("storage").(*schema.Set) for _, i := range storage.List() { attrs := i.(map[string]interface{}) storageAttachments = append(storageAttachments, compute.StorageAttachmentInput{ Index: attrs["index"].(int), Volume: attrs["volume"].(string), }) } return storageAttachments } // Parses instance_attributes from a string to a map[string]interface and returns any errors. func getInstanceAttributes(d *schema.ResourceData) (map[string]interface{}, error) { var attrs map[string]interface{} // Empty instance attributes attributes, ok := d.GetOk("instance_attributes") if !ok { return attrs, nil } if err := json.Unmarshal([]byte(attributes.(string)), &attrs); err != nil { return attrs, fmt.Errorf("Cannot parse attributes as json: %s", err) } return attrs, nil } // Reads attributes from the returned instance object, and sets the computed attributes string // as JSON func setInstanceAttributes(d *schema.ResourceData, attributes map[string]interface{}) error { // Shouldn't ever get nil attributes on an instance, but protect against the case either way if attributes == nil { return nil } b, err := json.Marshal(attributes) if err != nil { return fmt.Errorf("Error marshalling returned attributes: %s", err) } return d.Set("attributes", string(b)) } // Populates and validates shared network and ip network interfaces to return the of map // objects needed to create/update an instance's networking_info func readNetworkInterfacesFromConfig(d *schema.ResourceData) (map[string]compute.NetworkingInfo, error) { interfaces := make(map[string]compute.NetworkingInfo) if v, ok := d.GetOk("networking_info"); ok { vL := v.(*schema.Set).List() for _, v := range vL { ni := v.(map[string]interface{}) index, ok := ni["index"].(int) if !ok { return nil, fmt.Errorf("Index not specified for network interface: %v", ni) } deviceIndex := fmt.Sprintf("eth%d", index) // Verify that the network interface doesn't already exist if _, ok := interfaces[deviceIndex]; ok { return nil, fmt.Errorf("Duplicate Network interface at eth%d already specified", index) } // Determine if we're creating a shared network interface or an IP Network interface info := compute.NetworkingInfo{} var err error if ni["shared_network"].(bool) { // Populate shared network parameters info, err = readSharedNetworkFromConfig(ni) // Set 'model' since we're configuring a shared network interface info.Model = compute.NICDefaultModel } else { // Populate IP Network Parameters info, err = readIPNetworkFromConfig(ni) } if err != nil { return nil, err } // And you may find yourself in a beautiful house, with a beautiful wife // And you may ask yourself, well, how did I get here? interfaces[deviceIndex] = info } } return interfaces, nil } // Reads a networking_info config block as a shared network interface func readSharedNetworkFromConfig(ni map[string]interface{}) (compute.NetworkingInfo, error) { info := compute.NetworkingInfo{} // Validate the shared network if err := validateSharedNetwork(ni); err != nil { return info, err } // Populate shared network fields; checking type casting dns := []string{} if v, ok := ni["dns"]; ok && v != nil { for _, d := range v.([]interface{}) { dns = append(dns, d.(string)) } if len(dns) > 0 { info.DNS = dns } } if v, ok := ni["model"].(string); ok && v != "" { info.Model = compute.NICModel(v) } nats := []string{} if v, ok := ni["nat"]; ok && v != nil { for _, nat := range v.([]interface{}) { nats = append(nats, nat.(string)) } if len(nats) > 0 { info.Nat = nats } } slists := []string{} if v, ok := ni["sec_lists"]; ok && v != nil { for _, slist := range v.([]interface{}) { slists = append(slists, slist.(string)) } if len(slists) > 0 { info.SecLists = slists } } nservers := []string{} if v, ok := ni["name_servers"]; ok && v != nil { for _, nserver := range v.([]interface{}) { nservers = append(nservers, nserver.(string)) } if len(nservers) > 0 { info.NameServers = nservers } } sdomains := []string{} if v, ok := ni["search_domains"]; ok && v != nil { for _, sdomain := range v.([]interface{}) { sdomains = append(sdomains, sdomain.(string)) } if len(sdomains) > 0 { info.SearchDomains = sdomains } } return info, nil } // Unfortunately this cannot take place during plan-phase, because we currently cannot have a validation // function based off of multiple fields in the supplied schema. func validateSharedNetwork(ni map[string]interface{}) error { // A Shared Networking Interface MUST have the following attributes set: // - "nat" // The following attributes _cannot_ be set for a shared network: // - "ip_address" // - "ip_network" // - "mac_address" // - "vnic" // - "vnic_sets" if _, ok := ni["nat"]; !ok { return fmt.Errorf("'nat' field needs to be set for a Shared Networking Interface") } // Strings only nilAttrs := []string{ "ip_address", "ip_network", "mac_address", "vnic", } for _, v := range nilAttrs { if d, ok := ni[v]; ok && d.(string) != "" { return fmt.Errorf("%q field cannot be set in a Shared Networking Interface", v) } } if _, ok := ni["vnic_sets"].([]string); ok { return fmt.Errorf("%q field cannot be set in a Shared Networking Interface", "vnic_sets") } return nil } // Populates fields for an IP Network func readIPNetworkFromConfig(ni map[string]interface{}) (compute.NetworkingInfo, error) { info := compute.NetworkingInfo{} // Validate the IP Network if err := validateIPNetwork(ni); err != nil { return info, err } // Populate fields if v, ok := ni["ip_network"].(string); ok && v != "" { info.IPNetwork = v } dns := []string{} if v, ok := ni["dns"]; ok && v != nil { for _, d := range v.([]interface{}) { dns = append(dns, d.(string)) } if len(dns) > 0 { info.DNS = dns } } if v, ok := ni["ip_address"].(string); ok && v != "" { info.IPAddress = v } if v, ok := ni["mac_address"].(string); ok && v != "" { info.MACAddress = v } nservers := []string{} if v, ok := ni["name_servers"]; ok && v != nil { for _, nserver := range v.([]interface{}) { nservers = append(nservers, nserver.(string)) } if len(nservers) > 0 { info.NameServers = nservers } } nats := []string{} if v, ok := ni["nat"]; ok && v != nil { for _, nat := range v.([]interface{}) { nats = append(nats, nat.(string)) } if len(nats) > 0 { info.Nat = nats } } sdomains := []string{} if v, ok := ni["search_domains"]; ok && v != nil { for _, sdomain := range v.([]interface{}) { sdomains = append(sdomains, sdomain.(string)) } if len(sdomains) > 0 { info.SearchDomains = sdomains } } if v, ok := ni["vnic"].(string); ok && v != "" { info.Vnic = v } vnicSets := []string{} if v, ok := ni["vnic_sets"]; ok && v != nil { for _, vnic := range v.([]interface{}) { vnicSets = append(vnicSets, vnic.(string)) } if len(vnicSets) > 0 { info.VnicSets = vnicSets } } return info, nil } // Validates an IP Network config block func validateIPNetwork(ni map[string]interface{}) error { // An IP Networking Interface MUST have the following attributes set: // - "ip_network" // Required to be set if d, ok := ni["ip_network"]; !ok || d.(string) == "" { return fmt.Errorf("'ip_network' field is required for an IP Network interface") } return nil } // Reads network interfaces from the config func readNetworkInterfaces(d *schema.ResourceData, ifaces map[string]compute.NetworkingInfo) error { result := make([]map[string]interface{}, 0) // Nil check for import case if ifaces == nil { return d.Set("networking_info", result) } for index, iface := range ifaces { res := make(map[string]interface{}) // The index returned from the SDK holds the full device_index from the instance. // For users convenience, we simply allow them to specify the integer equivalent of the device_index // so a user could implement several network interfaces via `count`. // Convert the full device_index `ethN` to `N` as an integer. index := strings.TrimPrefix(index, "eth") indexInt, err := strconv.Atoi(index) if err != nil { return err } res["index"] = indexInt // Set the proper attributes for this specific network interface if iface.DNS != nil { res["dns"] = iface.DNS } if iface.IPAddress != "" { res["ip_address"] = iface.IPAddress } if iface.IPNetwork != "" { res["ip_network"] = iface.IPNetwork } if iface.MACAddress != "" { res["mac_address"] = iface.MACAddress } if iface.Model != "" { // Model can only be set on Shared networks res["shared_network"] = true } if iface.NameServers != nil { res["name_servers"] = iface.NameServers } if iface.Nat != nil { res["nat"] = iface.Nat } if iface.SearchDomains != nil { res["search_domains"] = iface.SearchDomains } if iface.SecLists != nil { res["sec_lists"] = iface.SecLists } if iface.Vnic != "" { res["vnic"] = iface.Vnic // VNIC can only be set on an IP Network res["shared_network"] = false } if iface.VnicSets != nil { res["vnic_sets"] = iface.VnicSets } result = append(result, res) } return d.Set("networking_info", result) } // Flattens the returned slice of storage attachments to a map func readStorageAttachments(d *schema.ResourceData, attachments []compute.StorageAttachment) error { result := make([]map[string]interface{}, 0) if attachments == nil || len(attachments) == 0 { return d.Set("storage", nil) } for _, attachment := range attachments { res := make(map[string]interface{}) res["index"] = attachment.Index res["volume"] = attachment.StorageVolumeName res["name"] = attachment.Name result = append(result, res) } return d.Set("storage", result) }<|fim▁end|>
<|file_name|>v1_ingress_class_spec.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: release-1.23 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from kubernetes.client.configuration import Configuration class V1IngressClassSpec(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'controller': 'str', 'parameters': 'V1IngressClassParametersReference' } attribute_map = { 'controller': 'controller', 'parameters': 'parameters' } def __init__(self, controller=None, parameters=None, local_vars_configuration=None): # noqa: E501 """V1IngressClassSpec - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._controller = None self._parameters = None self.discriminator = None if controller is not None: self.controller = controller if parameters is not None: self.parameters = parameters @property def controller(self): """Gets the controller of this V1IngressClassSpec. # noqa: E501 Controller refers to the name of the controller that should handle this class. This allows for different \"flavors\" that are controlled by the same controller. For example, you may have different Parameters for the same implementing controller. This should be specified as a domain-prefixed path no more than 250 characters in length, e.g. \"acme.io/ingress-controller\". This field is immutable. # noqa: E501 :return: The controller of this V1IngressClassSpec. # noqa: E501 :rtype: str """ return self._controller @controller.setter def controller(self, controller): """Sets the controller of this V1IngressClassSpec. Controller refers to the name of the controller that should handle this class. This allows for different \"flavors\" that are controlled by the same controller. For example, you may have different Parameters for the same implementing controller. This should be specified as a domain-prefixed path no more than 250 characters in length, e.g. \"acme.io/ingress-controller\". This field is immutable. # noqa: E501 :param controller: The controller of this V1IngressClassSpec. # noqa: E501 :type: str """ self._controller = controller @property def parameters(self): """Gets the parameters of this V1IngressClassSpec. # noqa: E501 :return: The parameters of this V1IngressClassSpec. # noqa: E501 :rtype: V1IngressClassParametersReference """ return self._parameters<|fim▁hole|> def parameters(self, parameters): """Sets the parameters of this V1IngressClassSpec. :param parameters: The parameters of this V1IngressClassSpec. # noqa: E501 :type: V1IngressClassParametersReference """ self._parameters = parameters def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1IngressClassSpec): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1IngressClassSpec): return True return self.to_dict() != other.to_dict()<|fim▁end|>
@parameters.setter
<|file_name|>pipelines.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html from scrapyproject.models import (Cinema, Showing, ShowingBooking, Movie, db_connect, drop_table_if_exist, create_table, Session) from scrapyproject.items import (CinemaItem, ShowingItem, ShowingBookingItem, MovieItem) from scrapyproject.utils import (use_cinema_database, use_showing_database, use_movie_database) class DataBasePipeline(object): """ pipeline to add item to database will keep exist data if spider has attribute 'keep_old_data' """ def __init__(self, database): self.database = database # keep crawled movie to sum cinema count self.crawled_movies = {} @classmethod def from_crawler(cls, crawler): return cls(database=crawler.settings.get('DATABASE')) def open_spider(self, spider): engine = db_connect() if not spider.keep_old_data: # drop data if use_showing_database(spider): drop_table_if_exist(engine, ShowingBooking) drop_table_if_exist(engine, Showing) elif use_cinema_database(spider): drop_table_if_exist(engine, Cinema) elif use_movie_database(spider): drop_table_if_exist(engine, Movie) create_table(engine) def close_spider(self, spider): for title in self.crawled_movies: self.process_movie_item(self.crawled_movies[title], spider) # close global session when spider ends Session.remove() def process_item(self, item, spider): """ use cinema table if spider has attribute "use_cinema_database" use showing table if spider has attribute "use_showing_database" a spider should not have both attributes """ if isinstance(item, CinemaItem): return self.process_cinema_item(item, spider) elif isinstance(item, ShowingItem): return self.process_showing_item(item, spider) elif isinstance(item, ShowingBookingItem): return self.process_showing_booking_item(item, spider) elif isinstance(item, MovieItem): # sum cinema count for each cinema if item['title'] not in self.crawled_movies:<|fim▁hole|> count = (item['current_cinema_count'] + self.crawled_movies[item['title']]['current_cinema_count']) self.crawled_movies[item['title']]['current_cinema_count'] = count return item def process_cinema_item(self, item, spider): cinema = Cinema(**item) exist_cinema = Cinema.get_cinema_if_exist(cinema) if not exist_cinema: # if data do not exist in database, add it self.add_item_to_database(cinema) else: # otherwise check if it should be merged to exist record # merge strategy: # - if exist data is crawled from other source, only add names # and screens to exist data; # - if cinema do not have site url, item is treated as duplicate # and dropped; # - otherwise, merge all data if cinema.source != exist_cinema.source: # replace when new cinema data crawled more screens if cinema.screen_count > exist_cinema.screen_count: exist_cinema.merge( cinema, merge_method=Cinema.MergeMethod.replace) else: exist_cinema.merge( cinema, merge_method=Cinema.MergeMethod.info_only) self.add_item_to_database(exist_cinema) elif cinema.site: exist_cinema.merge( cinema, merge_method=Cinema.MergeMethod.update_count) self.add_item_to_database(exist_cinema) return item def process_showing_item(self, item, spider): showing = Showing(**item) # if data do not exist in database, add it if not Showing.get_showing_if_exist(showing): self.add_item_to_database(showing) return item def process_showing_booking_item(self, item, spider): showing_booking = ShowingBooking() showing_booking.from_item(item) # if showing exists use its id in database exist_showing = Showing.get_showing_if_exist(showing_booking.showing) if exist_showing: old_showing = showing_booking.showing showing_booking.showing = exist_showing showing_booking.showing.title = old_showing.title showing_booking.showing.title_en = old_showing.title_en showing_booking.showing.start_time = old_showing.start_time showing_booking.showing.end_time = old_showing.end_time showing_booking.showing.cinema_name = old_showing.cinema_name showing_booking.showing.cinema_site = old_showing.cinema_site showing_booking.showing.screen = old_showing.screen showing_booking.showing.seat_type = old_showing.seat_type showing_booking.showing.total_seat_count = \ old_showing.total_seat_count showing_booking.showing.source = old_showing.source # then add self self.add_item_to_database(showing_booking) return item def process_movie_item(self, item, spider): movie = Movie(**item) # if data do not exist in database, add it if not Movie.get_movie_if_exist(movie): self.add_item_to_database(movie) return item def add_item_to_database(self, db_item): try: db_item = Session.merge(db_item) Session.commit() except: Session.rollback() raise<|fim▁end|>
self.crawled_movies[item['title']] = item else:
<|file_name|>0005_auto_20200823_0726.py<|end_file_name|><|fim▁begin|># Generated by Django 2.2.12 on 2020-08-23 07:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('job_board', '0004_jobpost_is_from_recruiting_agency'), ] operations = [ migrations.AlterField(<|fim▁hole|> field=models.CharField(choices=[('CH', 'Chicago'), ('CT', 'Chicago and Temporarily Remote'), ('CR', 'Chicago and Remote'), ('RO', 'Remote Only')], default='CH', help_text='ChiPy is a locally based group. Position must not move candidate out of the Chicago area. Working remote or commuting is acceptable. Any position requiring relocation out of the Chicago land is out of scope of the mission of the group.', max_length=2), ), ]<|fim▁end|>
model_name='jobpost', name='location',
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import uuid from couchdbkit import ResourceConflict from couchdbkit.exceptions import ResourceNotFound from django.test import TestCase from toggle.shortcuts import update_toggle_cache, namespaced_item, clear_toggle_cache from .models import generate_toggle_id, Toggle from .shortcuts import toggle_enabled, set_toggle class ToggleTestCase(TestCase): def setUp(self): super(ToggleTestCase, self).setUp() self.slug = uuid.uuid4().hex def tearDown(self): try: toggle = Toggle.get(self.slug) except ResourceNotFound: pass else: toggle.delete() super(ToggleTestCase, self).tearDown() def test_generate_id(self): self.assertEqual('hqFeatureToggle-sluggy', generate_toggle_id('sluggy')) def test_save_and_get_id(self): users = ['bruce', 'alfred'] toggle = Toggle(slug=self.slug, enabled_users=users) toggle.save() self.assertEqual(generate_toggle_id(self.slug), toggle._id) for id in (toggle._id, self.slug): fromdb = Toggle.get(id) self.assertEqual(self.slug, fromdb.slug) self.assertEqual(users, fromdb.enabled_users) def test_no_overwrite(self): existing = Toggle(slug=self.slug) existing.save() conflict = Toggle(slug=self.slug) try: conflict.save() self.fail('saving a toggle on top of an existing document should not be allowed') except ResourceConflict: pass def test_toggle_enabled(self): users = ['prof', 'logan'] toggle = Toggle(slug=self.slug, enabled_users=users) toggle.save() self.assertTrue(toggle_enabled(self.slug, 'prof')) self.assertTrue(toggle_enabled(self.slug, 'logan')) self.assertFalse(toggle_enabled(self.slug, 'richard')) self.assertFalse(toggle_enabled('gotham', 'prof')) <|fim▁hole|> rev = toggle._rev self.assertTrue('jon' in toggle.enabled_users) self.assertTrue('petyr' in toggle.enabled_users) # removing someone who doesn't exist shouldn't do anything toggle.remove('robert') self.assertEqual(rev, toggle._rev) # removing someone should save it and update toggle toggle.remove('jon') next_rev = toggle._rev self.assertNotEqual(rev, next_rev) self.assertFalse('jon' in toggle.enabled_users) self.assertTrue('petyr' in toggle.enabled_users) # adding someone who already exists should do nothing toggle.add('petyr') self.assertEqual(next_rev, toggle._rev) # adding someone should save it and update toggle toggle.add('ned') self.assertNotEqual(next_rev, toggle._rev) self.assertTrue('ned' in toggle.enabled_users) self.assertTrue('petyr' in toggle.enabled_users) self.assertFalse('jon' in toggle.enabled_users) def test_set_toggle(self): toggle = Toggle(slug=self.slug, enabled_users=['benjen', 'aemon']) toggle.save() self.assertTrue(toggle_enabled(self.slug, 'benjen')) self.assertTrue(toggle_enabled(self.slug, 'aemon')) set_toggle(self.slug, 'benjen', False) self.assertFalse(toggle_enabled(self.slug, 'benjen')) self.assertTrue(toggle_enabled(self.slug, 'aemon')) set_toggle(self.slug, 'jon', True) self.assertTrue(toggle_enabled(self.slug, 'jon')) self.assertFalse(toggle_enabled(self.slug, 'benjen')) self.assertTrue(toggle_enabled(self.slug, 'aemon')) def test_toggle_cache(self): ns = 'ns' toggle = Toggle(slug=self.slug, enabled_users=['mojer', namespaced_item('fizbod', ns)]) toggle.save() self.assertTrue(toggle_enabled(self.slug, 'mojer')) self.assertFalse(toggle_enabled(self.slug, 'fizbod')) self.assertTrue(toggle_enabled(self.slug, 'fizbod', namespace=ns)) update_toggle_cache(self.slug, 'mojer', False) update_toggle_cache(self.slug, 'fizbod', False, namespace=ns) self.assertFalse(toggle_enabled(self.slug, 'mojer')) self.assertFalse(toggle_enabled(self.slug, 'fizbod', namespace=ns)) clear_toggle_cache(self.slug, 'mojer') clear_toggle_cache(self.slug, 'fizbod', namespace=ns) self.assertTrue(toggle_enabled(self.slug, 'mojer')) self.assertTrue(toggle_enabled(self.slug, 'fizbod', namespace=ns))<|fim▁end|>
def test_add_remove(self): toggle = Toggle(slug=self.slug, enabled_users=['petyr', 'jon']) toggle.save()
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// DO NOT EDIT ! // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! //! This documentation was generated from *replicapool* crate version *0.1.8+20150311*, where *20150311* is the exact revision of the *replicapool:v1beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.8*. //! //! Everything else about the *replicapool* *v1_beta2* API can be found at the //! [official documentation site](https://developers.google.com/compute/docs/instance-groups/manager/v1beta2). //! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/replicapool1_beta2). //! # Features //! //! Handle the following *Resources* with ease from the central [hub](struct.Replicapool.html) ... //! //! * [instance group managers](struct.InstanceGroupManager.html) //! * [*abandon instances*](struct.InstanceGroupManagerAbandonInstanceCall.html), [*delete*](struct.InstanceGroupManagerDeleteCall.html), [*delete instances*](struct.InstanceGroupManagerDeleteInstanceCall.html), [*get*](struct.InstanceGroupManagerGetCall.html), [*insert*](struct.InstanceGroupManagerInsertCall.html), [*list*](struct.InstanceGroupManagerListCall.html), [*recreate instances*](struct.InstanceGroupManagerRecreateInstanceCall.html), [*resize*](struct.InstanceGroupManagerResizeCall.html), [*set instance template*](struct.InstanceGroupManagerSetInstanceTemplateCall.html) and [*set target pools*](struct.InstanceGroupManagerSetTargetPoolCall.html) //! * zone operations //! * [*get*](struct.ZoneOperationGetCall.html) and [*list*](struct.ZoneOperationListCall.html) //! //! //! //! //! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). //! //! # Structure of this Library //! //! The API is structured into the following primary items: //! //! * **[Hub](struct.Replicapool.html)** //! * a central object to maintain state and allow accessing all *Activities* //! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn //! allow access to individual [*Call Builders*](trait.CallBuilder.html) //! * **[Resources](trait.Resource.html)** //! * primary types that you can apply *Activities* to //! * a collection of properties and *Parts* //! * **[Parts](trait.Part.html)** //! * a collection of properties //! * never directly used in *Activities* //! * **[Activities](trait.CallBuilder.html)** //! * operations to apply to *Resources* //! //! All *structures* are marked with applicable traits to further categorize them and ease browsing. //! //! Generally speaking, you can invoke *Activities* like this:<|fim▁hole|>//! ``` //! //! Or specifically ... //! //! ```ignore //! let r = hub.instance_group_managers().set_target_pools(...).doit() //! let r = hub.instance_group_managers().list(...).doit() //! let r = hub.instance_group_managers().insert(...).doit() //! let r = hub.instance_group_managers().get(...).doit() //! let r = hub.instance_group_managers().abandon_instances(...).doit() //! let r = hub.instance_group_managers().recreate_instances(...).doit() //! let r = hub.instance_group_managers().delete(...).doit() //! let r = hub.instance_group_managers().set_instance_template(...).doit() //! let r = hub.instance_group_managers().resize(...).doit() //! let r = hub.instance_group_managers().delete_instances(...).doit() //! ``` //! //! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` //! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be //! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. //! The `doit()` method performs the actual communication with the server and returns the respective result. //! //! # Usage //! //! ## Setting up your Project //! //! To use this library, you would put the following lines into your `Cargo.toml` file: //! //! ```toml //! [dependencies] //! google-replicapool1_beta2 = "*" //! ``` //! //! ## A complete example //! //! ```test_harness,no_run //! extern crate hyper; //! extern crate yup_oauth2 as oauth2; //! extern crate google_replicapool1_beta2 as replicapool1_beta2; //! use replicapool1_beta2::{Result, Error}; //! # #[test] fn egal() { //! use std::default::Default; //! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; //! use replicapool1_beta2::Replicapool; //! //! // Get an ApplicationSecret instance by some means. It contains the `client_id` and //! // `client_secret`, among other things. //! let secret: ApplicationSecret = Default::default(); //! // Instantiate the authenticator. It will choose a suitable authentication flow for you, //! // unless you replace `None` with the desired Flow. //! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about //! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and //! // retrieve them from storage. //! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, //! hyper::Client::new(), //! <MemoryStorage as Default>::default(), None); //! let mut hub = Replicapool::new(hyper::Client::new(), auth); //! // You can configure optional parameters by calling the respective setters at will, and //! // execute the final call using `doit()`. //! // Values shown here are possibly random and not representative ! //! let result = hub.instance_group_managers().list("project", "zone") //! .page_token("sanctus") //! .max_results(79) //! .filter("amet") //! .doit(); //! //! match result { //! Err(e) => match e { //! // The Error enum provides details about what exactly happened. //! // You can also just use its `Debug`, `Display` or `Error` traits //! Error::HttpError(_) //! |Error::MissingAPIKey //! |Error::MissingToken(_) //! |Error::Cancelled //! |Error::UploadSizeLimitExceeded(_, _) //! |Error::Failure(_) //! |Error::BadRequest(_) //! |Error::FieldClash(_) //! |Error::JsonDecodeError(_, _) => println!("{}", e), //! }, //! Ok(res) => println!("Success: {:?}", res), //! } //! # } //! ``` //! ## Handling Errors //! //! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of //! the doit() methods, or handed as possibly intermediate results to either the //! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). //! //! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This //! makes the system potentially resilient to all kinds of errors. //! //! ## Uploads and Downloads //! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be //! read by you to obtain the media. //! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. //! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making //! this call: `.param("alt", "media")`. //! //! Methods supporting uploads can do so using up to 2 different protocols: //! *simple* and *resumable*. The distinctiveness of each is represented by customized //! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. //! //! ## Customization and Callbacks //! //! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the //! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. //! Respective methods will be called to provide progress information, as well as determine whether the system should //! retry on failure. //! //! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. //! //! ## Optional Parts in Server-Requests //! //! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and //! [decodable](trait.ResponseResult.html) via *json*. Optionals are used to indicate that partial requests are responses //! are valid. //! Most optionals are are considered [Parts](trait.Part.html) which are identifiable by name, which will be sent to //! the server to indicate either the set parts of the request or the desired parts in the response. //! //! ## Builder Arguments //! //! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. //! These will always take a single argument, for which the following statements are true. //! //! * [PODs][wiki-pod] are handed by copy //! * strings are passed as `&str` //! * [request values](trait.RequestValue.html) are moved //! //! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. //! //! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure //! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern //! [google-go-api]: https://github.com/google/google-api-go-client //! //! // Unused attributes happen thanks to defined, but unused structures // We don't warn about this, as depending on the API, some data structures or facilities are never used. // Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any // unused imports in fully featured APIs. Same with unused_mut ... . #![allow(unused_imports, unused_mut, dead_code)] include!(concat!(env!("OUT_DIR"), "/lib.rs"));<|fim▁end|>
//! //! ```Rust,ignore //! let r = hub.resource().activity(...).doit()
<|file_name|>RefetchWhenApiKeyExpired.tsx<|end_file_name|><|fim▁begin|>import { Search_system$key } from "__generated__/Search_system.graphql" import { SearchQuery } from "__generated__/SearchQuery.graphql" import { useEffect } from "react" import { connectStateResults, StateResultsProvided } from "react-instantsearch-core" import { RefetchFnDynamic } from "react-relay" import { isAlgoliaApiKeyExpiredError } from "./helpers" import { AlgoliaSearchResult } from "./types" interface ContainerProps extends StateResultsProvided<AlgoliaSearchResult> { refetch: RefetchFnDynamic<SearchQuery, Search_system$key> } const Container: React.FC<ContainerProps> = (props) => { const { error, refetch } = props useEffect(() => { if (isAlgoliaApiKeyExpiredError(error)) { refetch({}, { fetchPolicy: "network-only" }) } }, [error?.message]) return null<|fim▁hole|>export const RefetchWhenApiKeyExpiredContainer = connectStateResults(Container)<|fim▁end|>
}
<|file_name|>grating.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """Sinusoidal grating calculated in realtime.""" ############################ # Import various modules # ############################ import VisionEgg VisionEgg.start_default_logging(); VisionEgg.watch_exceptions() from VisionEgg.Core import * from VisionEgg.FlowControl import Presentation from VisionEgg.Gratings import * ##################################### # Initialize OpenGL window/screen # ##################################### screen = get_default_screen() ###################################### # Create sinusoidal grating object # ###################################### stimulus = SinGrating2D(position = ( screen.size[0]/2.0, screen.size[1]/2.0 ), anchor = 'center', size = ( 300.0 , 300.0 ), spatial_freq = 10.0 / screen.size[0], # units of cycles/pixel temporal_freq_hz = 1.0, orientation = 45.0 ) ############################################################### # Create viewport - intermediary between stimuli and screen # ############################################################### viewport = Viewport( screen=screen, stimuli=[stimulus] ) ########################################<|fim▁hole|># Create presentation object and go! # ######################################## p = Presentation(go_duration=(5.0,'seconds'),viewports=[viewport]) p.go()<|fim▁end|>
<|file_name|>index.js<|end_file_name|><|fim▁begin|>/* globals describe, before, beforeEach, after, afterEach, it */ 'use strict'; const chai = require('chai'); const assert = chai.assert; const expect = chai.expect; chai.should(); chai.use(require('chai-things')); //http://chaijs.com/plugins/chai-things chai.use(require('chai-arrays')); describe('<%= pkgName %>', function () { before('before', function () { }); beforeEach('beforeEach', function () { }); afterEach('afterEach', function () { }); after('after', function () { }); describe('Stub test', function () { it('should have unit test', function () { <|fim▁hole|> }); }); });<|fim▁end|>
assert(false, 'Please add unit tests.');
<|file_name|>alertRunner.go<|end_file_name|><|fim▁begin|>package sched import ( "fmt" "time" "bosun.org/cmd/bosun/cache" "bosun.org/cmd/bosun/conf" "bosun.org/slog" ) // Run should be called once (and only once) to start all schedule activity. func (s *Schedule) Run() error { if s.RuleConf == nil || s.SystemConf == nil { return fmt.Errorf("sched: nil configuration") } s.nc = make(chan interface{}, 1) if s.SystemConf.GetPing() { go s.PingHosts() } go s.dispatchNotifications() go s.updateCheckContext() for _, a := range s.RuleConf.GetAlerts() { go s.RunAlert(a) } return nil } func (s *Schedule) updateCheckContext() { for { ctx := &checkContext{utcNow(), cache.New(0)} s.ctx = ctx time.Sleep(s.SystemConf.GetCheckFrequency()) s.Lock("CollectStates") s.CollectStates() s.Unlock() } } func (s *Schedule) RunAlert(a *conf.Alert) { // Add to waitgroup for running alert s.checksRunning.Add(1) // ensure when an alert is done it is removed from the wait group defer s.checksRunning.Done() for { // Calcaulate runEvery based on system default and override if an alert has a // custom runEvery runEvery := s.SystemConf.GetDefaultRunEvery() if a.RunEvery != 0 { runEvery = a.RunEvery } wait := time.After(s.SystemConf.GetCheckFrequency() * time.Duration(runEvery))<|fim▁hole|> select { case <-wait: case <-s.runnerContext.Done(): // If an alert is waiting we cancel it slog.Infof("Stopping alert routine for %v\n", a.Name) return } } } func (s *Schedule) checkAlert(a *conf.Alert) { checkTime := s.ctx.runTime checkCache := s.ctx.checkCache rh := s.NewRunHistory(checkTime, checkCache) // s.CheckAlert will return early if the schedule has been closed cancelled := s.CheckAlert(nil, rh, a) if cancelled { // Don't runHistory for the alert if expression evaluation has been cancelled return } start := utcNow() s.RunHistory(rh) slog.Infof("runHistory on %s took %v\n", a.Name, time.Since(start)) }<|fim▁end|>
s.checkAlert(a) s.LastCheck = utcNow()
<|file_name|>defaultShouldError.spec.js<|end_file_name|><|fim▁begin|>import plain from '../structure/plain' import immutable from '../structure/immutable' import defaultShouldError from '../defaultShouldError' describe('defaultShouldError', () => { it('should validate when initialRender is true', () => { expect( defaultShouldError({ initialRender: true }) ).toBe(true) }) const describeDefaultShouldError = structure => { const { fromJS } = structure it('should validate if values have changed', () => { expect( defaultShouldError({ initialRender: false, structure, values: fromJS({ foo: 'fooInitial' }), nextProps: { values: fromJS({ foo: 'fooChanged' }) } }) ).toBe(true) }) it('should not validate if values have not changed', () => { expect( defaultShouldError({ initialRender: false, structure, values: fromJS({ foo: 'fooInitial' }), nextProps: { values: fromJS({ foo: 'fooInitial' }) } }) ).toBe(false) }) it('should validate if field validator keys have changed', () => { expect( defaultShouldError({ initialRender: false, structure, values: fromJS({ foo: 'fooValue' }), nextProps: { values: fromJS({ foo: 'fooValue' }) }, lastFieldValidatorKeys: [], fieldValidatorKeys: ['foo'] }) ).toBe(true) }) it('should not validate if field validator keys have not changed', () => { expect( defaultShouldError({ initialRender: false, structure, values: fromJS({<|fim▁hole|> nextProps: { values: fromJS({ foo: 'fooInitial' }) }, lastFieldValidatorKeys: ['foo'], fieldValidatorKeys: ['foo'] }) ).toBe(false) }) } describeDefaultShouldError(plain) describeDefaultShouldError(immutable) })<|fim▁end|>
foo: 'fooInitial' }),
<|file_name|>types.go<|end_file_name|><|fim▁begin|>package aspect // Type is the interface that all sql Types must implement type Type interface { Creatable IsPrimaryKey() bool IsRequired() bool<|fim▁hole|><|fim▁end|>
IsUnique() bool Validate(interface{}) (interface{}, error) }
<|file_name|>sequence_roi_gt_propagation.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -------------------------------------------------------- # Test regression propagation on ImageNet VID video # Modified by Kai KANG ([email protected]) # -------------------------------------------------------- """Test a Fast R-CNN network on an image database.""" import argparse import pprint import time import os import os.path as osp import sys import cPickle import numpy as np this_dir = osp.dirname(__file__) # add py-faster-rcnn paths sys.path.insert(0, osp.join(this_dir, '../../external/py-faster-rcnn/lib')) from fast_rcnn.config import cfg, cfg_from_file, cfg_from_list # add external libs sys.path.insert(0, osp.join(this_dir, '../../external')) from vdetlib.utils.protocol import proto_load, proto_dump # add src libs sys.path.insert(0, osp.join(this_dir, '../../src')) from tpn.propagate import gt_motion_propagation from tpn.target import add_track_targets from tpn.data_io import save_track_proto_to_zip def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Test a Fast R-CNN network') parser.add_argument('vid_file') parser.add_argument('box_file') parser.add_argument('annot_file', default=None,<|fim▁hole|> default=1, type=int) parser.add_argument('--length', type=int, default=20, help='Propagation length. [20]') parser.add_argument('--window', type=int, default=5, help='Prediction window. [5]') parser.add_argument('--sample_rate', type=int, default=1, help='Temporal subsampling rate. [1]') parser.add_argument('--offset', type=int, default=0, help='Offset of sampling. [0]') parser.add_argument('--overlap', type=float, default=0.5, help='GT overlap threshold for tracking. [0.5]') parser.add_argument('--wait', dest='wait', help='wait until net file exists', default=True, type=bool) parser.set_defaults(vis=False, zip=False, keep_feat=False) if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() return args if __name__ == '__main__': args = parse_args() print 'Called with args:' print args if osp.isfile(args.save_file): print "{} already exists.".format(args.save_file) sys.exit(1) vid_proto = proto_load(args.vid_file) box_proto = proto_load(args.box_file) annot_proto = proto_load(args.annot_file) track_proto = gt_motion_propagation(vid_proto, box_proto, annot_proto, window=args.window, length=args.length, sample_rate=args.sample_rate, overlap_thres=args.overlap) # add ground truth targets if annotation file is given add_track_targets(track_proto, annot_proto) if args.zip: save_track_proto_to_zip(track_proto, args.save_file) else: proto_dump(track_proto, args.save_file)<|fim▁end|>
help='Ground truth annotation file. [None]') parser.add_argument('save_file', help='Save zip file') parser.add_argument('--job', dest='job_id', help='Job slot, GPU ID + 1. [1]',
<|file_name|>helpers.go<|end_file_name|><|fim▁begin|>package main import ( "encoding/json" "net/http" yaml "gopkg.in/yaml.v2" ) // Respond reads the 'f' url parameter ('f' stands for 'format'), formats the given data // accordingly and sets the required content-type header. Default format is json. func Respond(res http.ResponseWriter, req *http.Request, code int, data interface{}) { var err error var errMesg []byte var out []byte f := "json" format := req.URL.Query()["f"] if len(format) > 0 { f = format[0] } if f == "yaml" { res.Header().Set("Content-Type", "text/yaml; charset=utf-8")<|fim▁hole|> res.Header().Set("Content-Type", "application/json; charset=utf-8") out, err = json.Marshal(data) errMesg = []byte("{ 'error': 'failed while rendering data to json' }") } if err != nil { out = errMesg code = http.StatusInternalServerError } res.WriteHeader(code) res.Write(out) }<|fim▁end|>
out, err = yaml.Marshal(data) errMesg = []byte("--- error: failed while rendering data to yaml") } else {
<|file_name|>github_file.rs<|end_file_name|><|fim▁begin|>/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: [email protected] * Generated by: https://openapi-generator.tech */ #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct GithubFile { #[serde(rename = "content", skip_serializing_if = "Option::is_none")] pub content: Option<Box<crate::models::GithubContent>>, #[serde(rename = "_class", skip_serializing_if = "Option::is_none")] pub _class: Option<String>, } impl GithubFile { pub fn new() -> GithubFile { GithubFile {<|fim▁hole|>}<|fim▁end|>
content: None, _class: None, } }
<|file_name|>Prob3.py<|end_file_name|><|fim▁begin|># Declaring a Function def recurPowerNew(base, exp): # Base case is when exp = 0 if exp <= 0: return 1<|fim▁hole|> # Recursive Call elif exp % 2 == 0: return recurPowerNew(base*base, exp/2) return base * recurPowerNew(base, exp - 1)<|fim▁end|>
<|file_name|>antagonist.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright 2015 gRPC authors.<|fim▁hole|># # 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. """This is used by run_tests.py to create cpu load on a machine""" while True: pass<|fim▁end|>
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json import mock from django.test import TestCase from django.core.urlresolvers import reverse class TestAPI(TestCase): @mock.patch('ldap.initialize') def test_exists(self, mocked_initialize): connection = mock.MagicMock() mocked_initialize.return_value = connection url = reverse('api:exists') response = self.client.get(url) self.assertEqual(response.status_code, 400) # check that 400 Bad Request errors are proper JSON self.assertEqual(response['Content-Type'], 'application/json') self.assertEqual( json.loads(response.content), {'error': "missing key 'mail'"} ) response = self.client.get(url, {'mail': ''}) self.assertEqual(response.status_code, 400) result = { 'abc123': {'uid': 'abc123', 'mail': '[email protected]'}, } def search_s(base, scope, filterstr, *args, **kwargs): if '[email protected]' in filterstr: # if 'hgaccountenabled=TRUE' in filterstr: # return [] return result.items() return [] connection.search_s.side_effect = search_s response = self.client.get(url, {'mail': '[email protected]'}) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') self.assertEqual(json.loads(response.content), True) response = self.client.get(url, {'mail': '[email protected]'}) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.content), False) # response = self.client.get(url, {'mail': '[email protected]', # 'hgaccountenabled': ''}) # self.assertEqual(response.status_code, 200) # self.assertEqual(json.loads(response.content), False) response = self.client.get(url, {'mail': '[email protected]', 'gender': 'male'}) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.content), True) @mock.patch('ldap.initialize') def test_employee(self, mocked_initialize): connection = mock.MagicMock() mocked_initialize.return_value = connection url = reverse('api:employee') response = self.client.get(url) self.assertEqual(response.status_code, 400) response = self.client.get(url, {'mail': ''}) self.assertEqual(response.status_code, 400) result = { 'abc123': {'uid': 'abc123', 'mail': '[email protected]', 'sn': u'B\xe3ngtsson'}, } def search_s(base, scope, filterstr, *args, **kwargs): if '[email protected]' in filterstr: return result.items() return [] connection.search_s.side_effect = search_s response = self.client.get(url, {'mail': '[email protected]'}) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') self.assertEqual(json.loads(response.content), True) response = self.client.get(url, {'mail': '[email protected]'}) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') self.assertEqual(json.loads(response.content), False) @mock.patch('ldap.initialize') def test_ingroup(self, mocked_initialize): connection = mock.MagicMock() mocked_initialize.return_value = connection url = reverse('api:in-group') response = self.client.get(url) self.assertEqual(response.status_code, 400) response = self.client.get(url, {'mail': ''}) self.assertEqual(response.status_code, 400) response = self.client.get(url, {'mail': '[email protected]'}) self.assertEqual(response.status_code, 400) response = self.client.get(url, {'mail': '[email protected]', 'cn': ''}) self.assertEqual(response.status_code, 400) result = { 'abc123': {'uid': 'abc123', 'mail': '[email protected]'}, } def search_s(base, scope, filterstr, *args, **kwargs): if 'ou=groups' in base: if ( '[email protected]' in filterstr and 'cn=CrashStats' in filterstr ): return result.items() else: # basic lookup if '[email protected]' in filterstr: return result.items() return []<|fim▁hole|> 'cn': 'CrashStats'}) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.content), False) response = self.client.get(url, {'mail': '[email protected]', 'cn': 'CrashStats'}) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.content), True) response = self.client.get(url, {'mail': '[email protected]', 'cn': 'NotInGroup'}) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.content), False)<|fim▁end|>
connection.search_s.side_effect = search_s response = self.client.get(url, {'mail': '[email protected]',
<|file_name|>comment.ts<|end_file_name|><|fim▁begin|>/** * This is a module doc comment with legacy behavior. */ /** dummy comment */ import "./comment2"; /** * A Comment for a class * * ## Some Markup * **with more markup** * * An example with decorators that should not parse to tag * ``` * @myDecorator * @FactoryDecorator('a', 'b', 'c') * export class CommentedClass { * myProp: string = 'myProp'; * * @PropDecorator() decoratedProp: string; * * constructor(@ParamDecorator public param: string) { } * * myMethod() { } * } * ``` * @deprecated * @todo something * * @class will be removed * @type {Data<object>} will also be removed */ export class CommentedClass { /** * The main prop */ prop: string; /** * @hidden */ hiddenprop: string; /** * Hidden function * @hidden<|fim▁hole|> /** * Single hidden signature * @hidden */ hiddenWithImplementation(arg: any); hiddenWithImplementation(...args: any[]): void {} /** * Multiple hidden 1 * @hidden */ multipleHidden(arg: any); /** * Multiple hidden 2 * @hidden */ multipleHidden(arg1: any, arg2: any); multipleHidden(...args: any[]): void {} /** * Mixed hidden 1 * @hidden */ mixedHidden(arg: any); /** * Mixed hidden 2 */ mixedHidden(arg1: any, arg2: any); mixedHidden(...args: any[]): void {} /** * @ignore */ ignoredprop: string; }<|fim▁end|>
*/ hidden(...args: any[]): void {}
<|file_name|>disk.py<|end_file_name|><|fim▁begin|>#/usr/bin/python """ Copyright 2014 The Trustees of Princeton University 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 re<|fim▁hole|>import syndicate.ag.curation.crawl as AG_crawl DRIVER_NAME = "disk" # list a directory def disk_listdir( root_dir, dirpath ): return os.listdir( "/" + os.path.join( root_dir.strip("/"), dirpath.strip("/") ) ) # is this a directory? def disk_isdir( root_dir, dirpath ): return os.path.isdir( "/" + os.path.join( root_dir.strip("/"), dirpath.strip("/") ) ) # build a hierarchy, using sensible default callbacks def build_hierarchy( root_dir, include_cb, disk_specfile_cbs, max_retries=1, num_threads=2, allow_partial_failure=False ): disk_crawler_cbs = AG_crawl.crawler_callbacks( include_cb=include_cb, listdir_cb=disk_listdir, isdir_cb=disk_isdir ) hierarchy = AG_crawl.build_hierarchy( [root_dir] * num_threads, "/", DRIVER_NAME, disk_crawler_cbs, disk_specfile_cbs, allow_partial_failure=allow_partial_failure, max_retries=max_retries ) return hierarchy<|fim▁end|>
import sys import time import syndicate.ag.curation.specfile as AG_specfile
<|file_name|>ossource.cpp<|end_file_name|><|fim▁begin|>// //Copyright (C) 2002-2005 3Dlabs Inc. Ltd. //All rights reserved. // //Redistribution and use in source and binary forms, with or without //modification, are permitted provided that the following conditions //are met: // // Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // Neither the name of 3Dlabs Inc. Ltd. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS //"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT //LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS //FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE //COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, //BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; //LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER //CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT //LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN //ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE //POSSIBILITY OF SUCH DAMAGE. // #include "osinclude.h" #define STRICT #define VC_EXTRALEAN 1 #include <windows.h> #include <assert.h> #include <process.h> #include <psapi.h> #include <stdio.h> // // This file contains contains the Window-OS-specific functions // #if !(defined(_WIN32) || defined(_WIN64)) #error Trying to build a windows specific file in a non windows build. #endif namespace glslang { //<|fim▁hole|> DWORD dwIndex = TlsAlloc(); if (dwIndex == TLS_OUT_OF_INDEXES) { assert(0 && "OS_AllocTLSIndex(): Unable to allocate Thread Local Storage"); return OS_INVALID_TLS_INDEX; } return dwIndex; } bool OS_SetTLSValue(OS_TLSIndex nIndex, void *lpvValue) { if (nIndex == OS_INVALID_TLS_INDEX) { assert(0 && "OS_SetTLSValue(): Invalid TLS Index"); return false; } if (TlsSetValue(nIndex, lpvValue)) return true; else return false; } void* OS_GetTLSValue(OS_TLSIndex nIndex) { assert(nIndex != OS_INVALID_TLS_INDEX); return TlsGetValue(nIndex); } bool OS_FreeTLSIndex(OS_TLSIndex nIndex) { if (nIndex == OS_INVALID_TLS_INDEX) { assert(0 && "OS_SetTLSValue(): Invalid TLS Index"); return false; } if (TlsFree(nIndex)) return true; else return false; } HANDLE GlobalLock; void InitGlobalLock() { GlobalLock = CreateMutex(0, false, 0); } void GetGlobalLock() { WaitForSingleObject(GlobalLock, INFINITE); } void ReleaseGlobalLock() { ReleaseMutex(GlobalLock); } void* OS_CreateThread(TThreadEntrypoint entry) { return (void*)_beginthreadex(0, 0, entry, 0, 0, 0); //return CreateThread(0, 0, entry, 0, 0, 0); } void OS_WaitForAllThreads(void* threads, int numThreads) { WaitForMultipleObjects(numThreads, (HANDLE*)threads, true, INFINITE); } void OS_Sleep(int milliseconds) { Sleep(milliseconds); } void OS_DumpMemoryCounters() { #ifdef DUMP_COUNTERS PROCESS_MEMORY_COUNTERS counters; GetProcessMemoryInfo(GetCurrentProcess(), &counters, sizeof(counters)); printf("Working set size: %d\n", counters.WorkingSetSize); #else printf("Recompile with DUMP_COUNTERS defined to see counters.\n"); #endif } } // namespace glslang<|fim▁end|>
// Thread Local Storage Operations // OS_TLSIndex OS_AllocTLSIndex() {
<|file_name|>CWantedSA.cpp<|end_file_name|><|fim▁begin|>/***************************************************************************** * * PROJECT: Multi Theft Auto v1.0 * LICENSE: See LICENSE in the top level directory * FILE: game_sa/CWantedSA.cpp * PURPOSE: Wanted level management * DEVELOPERS: Ed Lyons <[email protected]> * Christian Myhre Lundheim <> * * Multi Theft Auto is available from http://www.multitheftauto.com/ * *****************************************************************************/ #include <main.h> CWantedSA::CWantedSA ( void ) { // TODO: Call GTA's new operator for CWanted. Lack of proper initialization might be causing crashes. internalInterface = new CWantedSAInterface; memset ( internalInterface, 0, sizeof ( CWantedSAInterface ) ); m_bDontDelete = false; } CWantedSA::CWantedSA ( CWantedSAInterface* wantedInterface ) { internalInterface = wantedInterface; m_bDontDelete = true; } CWantedSA::~CWantedSA ( void ) { if ( !m_bDontDelete ) { // TODO: Call GTA's delete operator for CWanted. Lack of proper destruction might be causing crashes. delete internalInterface; } } void CWantedSA::SetMaximumWantedLevel ( DWORD dwWantedLevel ) { DWORD dwFunc = FUNC_SetMaximumWantedLevel; _asm {<|fim▁hole|> } } void CWantedSA::SetWantedLevel ( DWORD dwWantedLevel ) { DWORD dwThis = (DWORD)this->GetInterface(); DWORD dwFunc = FUNC_SetWantedLevel; _asm { mov ecx, dwThis push dwWantedLevel call dwFunc } } void CWantedSA::SetWantedLevelNoDrop ( DWORD dwWantedLevel ) { DWORD dwThis = (DWORD)this->GetInterface(); DWORD dwFunc = FUNC_SetWantedLevelNoDrop; _asm { mov ecx, dwThis push dwWantedLevel call dwFunc } }<|fim▁end|>
push dwWantedLevel call dwFunc add esp, 4
<|file_name|>feeds.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals from django.contrib.syndication.views import Feed from django.shortcuts import get_object_or_404 from .models import Category class CategoryFeed(Feed): def get_object(self, request, slug): return get_object_or_404(Category.objects.categories(), slug=slug) def link(self, obj): return obj.get_absolute_url() def title(self, obj): return obj.name def description(self, obj): return obj.description def items(self, obj): return obj.articles.published() def item_description(self, item): return item.content.rendered def item_pubdate(self, item): return item.created <|fim▁hole|> return item.created_by.username<|fim▁end|>
def item_categories(self, item): return item.tags.all() def item_author_name(self, item):
<|file_name|>CCNVoice.java<|end_file_name|><|fim▁begin|>/* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. You should have received * a copy of the GNU Lesser General Public License along with this library; * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA. */ import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.TargetDataLine; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import org.ccnx.ccn.io.content.ContentEncodingException; import org.ccnx.ccn.protocol.MalformedContentNameStringException; /** * front-end(UI) * GUI for communicate user */ public class CCNVoice extends JFrame implements CCNServiceCallback { private static final long serialVersionUID = -328096355073388654L; public ByteArrayOutputStream out; private static CCNService ccnService = null; public String ChattingRoomName = "ccnx:/"; private boolean isRecorded = false; private boolean isPlayed = false; private String AudioData = null; private AudioFormat format = getFormat(); private String charsetName = "UTF-16"; private int BufferSize = 1024; private DataLine.Info TargetInfo; private static TargetDataLine m_TargetDataLine; // swing based GUI component // based panel private JPanel ConfigPanel = new JPanel(new FlowLayout()); // Forr // congifuring // room name private JPanel ChattingPanel = new JPanel(new BorderLayout()); // For // Message // List private JPanel ControlPanel = new JPanel(new GridLayout(0, 3)); // For // record, // play, // send Btn private JTextField InputRoomName = new JTextField(15); // button image icon private URL imageURL = getClass().getResource("/img/KHU.jpeg"); private URL recordURL = getClass().getResource("/img/record.png"); private URL playURL = getClass().getResource("/img/play.png"); private URL stopURL = getClass().getResource("/img/stop.png"); public ImageIcon imageIcon; private ImageIcon recordIcon; private ImageIcon playIcon; private ImageIcon stopIcon; private JButton okBtn; private JButton recordBtn; private JButton playBtn; private JButton sendBtn; private JTextArea MessageArea = null; // constructor of CCNVoice object public CCNVoice() throws MalformedContentNameStringException { ccnService = new CCNService(this); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { stop(); } }); // the window size of application // window size : maximize or customize your device this.setExtendedState(JFrame.MAXIMIZED_BOTH); setVisible(true); setTitle("[CCN Voice]"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); imageIcon = new ImageIcon(imageURL); recordIcon = new ImageIcon(recordURL); stopIcon = new ImageIcon(stopURL); playIcon = new ImageIcon(playURL); okBtn = new JButton("OK"); sendBtn = new JButton(" Send "); recordBtn = new JButton(recordIcon); playBtn = new JButton(playIcon); MessageArea = new JTextArea(); // add each components JLabel icon = new JLabel(imageIcon); JLabel RoomInfo = new JLabel("Room Name"); ConfigPanel.setBackground(Color.WHITE); ConfigPanel.add(RoomInfo); ConfigPanel.add(InputRoomName); ConfigPanel.add(okBtn); ConfigPanel.add(icon); ConfigPanel.setVisible(true); getContentPane().add(ConfigPanel); // button listener okBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ChattingRoomName += InputRoomName.getText(); if (ChattingRoomName != "ccnx:/") { // When RoomName is normal } else { // When RoomName is abnormal ChattingRoomName = "DefaultRoomName"; } try { ccnService.setNamespace(ChattingRoomName); } catch (MalformedContentNameStringException e1) { e1.printStackTrace(); } getContentPane().removeAll(); getContentPane().add(ChattingPanel); revalidate(); repaint(); // start CCN based networking service(back-end) ccnService.start(); } }); recordBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (isRecorded) { // recordBtn.setText("Record"); recordBtn.setIcon(recordIcon); isRecorded = false; } else { recordAudio(); // recordBtn.setText(" Stop "); recordBtn.setIcon(stopIcon); } } }); sendBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sendAudioData(); } }); playBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(isPlayed) { // playBtn.setText("Play"); playBtn.setIcon(playIcon); isPlayed = false; } else { playAudio(); // playBtn.setText("Stop"); playBtn.setIcon(stopIcon); } } }); MessageArea.setBackground(Color.LIGHT_GRAY); MessageArea.setEditable(false); MessageArea.setLineWrap(true); // set GUI panel ControlPanel.setPreferredSize(new Dimension(50,100)); ControlPanel.add(recordBtn); ControlPanel.add(playBtn); ControlPanel.add(sendBtn); ChattingPanel.add(new JScrollPane(MessageArea), BorderLayout.CENTER); ChattingPanel.add(ControlPanel, BorderLayout.SOUTH); revalidate(); repaint(); setVisible(true); TargetInfo = new DataLine.Info(TargetDataLine.class, format); try { m_TargetDataLine = (TargetDataLine) AudioSystem.getLine(TargetInfo); } catch (LineUnavailableException e1) { e1.printStackTrace(); } } // stop the application protected void stop() { try { ccnService.shutdown(); } catch (IOException e) { e.printStackTrace(); } } // record a audio data(PCM) private void recordAudio() { try { m_TargetDataLine.open(format); m_TargetDataLine.start(); Runnable runner = new Runnable() { byte buffer[] = new byte[BufferSize]; public void run() { out = new ByteArrayOutputStream(); isRecorded = true; try { while (isRecorded) { int count = m_TargetDataLine.read(buffer, 0, buffer.length); if(count > 0) { out.write(buffer, 0, count); } } AudioData = new String(out.toByteArray(), charsetName); out.close(); m_TargetDataLine.close(); } catch (IOException e) { System.err.println("I/O problems: " + e); } } }; Thread captureThread = new Thread(runner); captureThread.start(); } catch (LineUnavailableException e) { System.err.println("Line unavailable: " + e); } } // play a audio data(received audio and sended audio) private void playAudio() { try { byte[] audio = null; isPlayed = true; try { audio = AudioData.getBytes(charsetName); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } InputStream input = new ByteArrayInputStream(audio); final AudioInputStream ais = new AudioInputStream(input, format, audio.length / format.getFrameSize()); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); final SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); line.open(format); line.start(); Runnable runner = new Runnable() { byte buffer[] = new byte[BufferSize]; public void run() { try { int count; while ((count = ais.read(buffer, 0, buffer.length)) != -1) { if (count > 0) { line.write(buffer, 0, count); } } line.drain(); line.close(); setPlayBtnText(); } catch (IOException e) { System.err.println("I/O problems: " + e); } } }; Thread playThread = new Thread(runner); playThread.start(); } catch (LineUnavailableException e) { System.err.println("Line unavailable: " + e); } } // play the parameter data public void playAudio(byte[] data) { try { InputStream input = new ByteArrayInputStream(data); final AudioFormat format = getFormat(); final AudioInputStream ais = new AudioInputStream(input, format, data.length / format.getFrameSize()); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); final SourceDataLine line = (SourceDataLine) AudioSystem .getLine(info); line.open(format); line.start(); Runnable runner = new Runnable() { byte buffer[] = new byte[BufferSize]; public void run() { try { int count; while ((count = ais.read(buffer, 0, buffer.length)) != -1) { if (count > 0) { line.write(buffer, 0, count); } } line.drain(); line.close();<|fim▁hole|> System.err.println("I/O problems: " + e); } } }; Thread playThread = new Thread(runner); playThread.start(); } catch (LineUnavailableException e) { System.err.println("Line unavailable: " + e); } } // send the audio data to back-end(network service part) private void sendAudioData() { try { ccnService.sendMessage(AudioData); } catch (ContentEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Send data to ccn, excepting audio data for example, session info, meta * data * * @param payload */ public void sendData(byte[] payload) { // TODO send data excepting audio } // information about recording audio private AudioFormat getFormat() { float sampleRate = 8000; int sampleSizeInBits = 8; int channels = 1; boolean signed = true; boolean bigEndian = false; return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian); } public static void main(String[] args) { try { System.out.println("[CCNVoice]main"); new CCNVoice(); } catch (MalformedContentNameStringException e) { System.err.println("Not a valid ccn URI: " + args[0] + ": " + e.getMessage()); e.printStackTrace(); } } @Override public void receiveData(String data) { AudioData = data; try { playAudio(AudioData.getBytes(charsetName)); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void receiveMessage(String msg) { MessageArea.insert(msg + "\n", MessageArea.getText().length()); MessageArea.setCaretPosition(MessageArea.getText().length()); } public void setPlayBtnText() { // playBtn.setText("Play"); playBtn.setIcon(playIcon); isPlayed = false; } }<|fim▁end|>
} catch (IOException e) {
<|file_name|>SectionedBaseAdapter.java<|end_file_name|><|fim▁begin|>package com.ybook.app.pinnedheaderlistview; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import com.ybook.app.pinnedheaderlistview.PinnedHeaderListView.PinnedSectionedHeaderAdapter; public abstract class SectionedBaseAdapter extends BaseAdapter implements PinnedSectionedHeaderAdapter { private static int HEADER_VIEW_TYPE = 0; private static int ITEM_VIEW_TYPE = 0; /** * Holds the calculated values of @{link getPositionInSectionForPosition} */ private SparseArray<Integer> mSectionPositionCache; /** * Holds the calculated values of @{link getSectionForPosition} */ private SparseArray<Integer> mSectionCache; /** * Holds the calculated values of @{link getCountForSection} */ private SparseArray<Integer> mSectionCountCache; /** * Caches the item count */ private int mCount; /** * Caches the section count */ private int mSectionCount; public SectionedBaseAdapter() { super(); mSectionCache = new SparseArray<Integer>(); mSectionPositionCache = new SparseArray<Integer>(); mSectionCountCache = new SparseArray<Integer>(); mCount = -1; mSectionCount = -1; } @Override public void notifyDataSetChanged() { mSectionCache.clear(); mSectionPositionCache.clear(); mSectionCountCache.clear(); mCount = -1; mSectionCount = -1; super.notifyDataSetChanged(); } @Override public void notifyDataSetInvalidated() { mSectionCache.clear(); mSectionPositionCache.clear(); mSectionCountCache.clear(); mCount = -1; mSectionCount = -1; super.notifyDataSetInvalidated(); } @Override public final int getCount() { if (mCount >= 0) { return mCount; } int count = 0; for (int i = 0; i < internalGetSectionCount(); i++) { count += internalGetCountForSection(i); count++; // for the header view } mCount = count; return count; } @Override public final Object getItem(int position) { return getItem(getSectionForPosition(position), getPositionInSectionForPosition(position)); } @Override public final long getItemId(int position) { return getItemId(getSectionForPosition(position), getPositionInSectionForPosition(position)); } @Override public final View getView(int position, View convertView, ViewGroup parent) { if (isSectionHeader(position)) { return getSectionHeaderView(getSectionForPosition(position), convertView, parent); } return getItemView(getSectionForPosition(position), getPositionInSectionForPosition(position), convertView, parent); } @Override public final int getItemViewType(int position) { if (isSectionHeader(position)) { return getItemViewTypeCount() + getSectionHeaderViewType(getSectionForPosition(position)); } return getItemViewType(getSectionForPosition(position), getPositionInSectionForPosition(position)); } @Override public final int getViewTypeCount() { return getItemViewTypeCount() + getSectionHeaderViewTypeCount(); } public final int getSectionForPosition(int position) { // first try to retrieve values from cache Integer cachedSection = mSectionCache.get(position); if (cachedSection != null) { return cachedSection; } int sectionStart = 0; for (int i = 0; i < internalGetSectionCount(); i++) { int sectionCount = internalGetCountForSection(i); int sectionEnd = sectionStart + sectionCount + 1; if (position >= sectionStart && position < sectionEnd) { mSectionCache.put(position, i); return i; } sectionStart = sectionEnd; } return 0; } public int getPositionInSectionForPosition(int position) {<|fim▁hole|> if (cachedPosition != null) { return cachedPosition; } int sectionStart = 0; for (int i = 0; i < internalGetSectionCount(); i++) { int sectionCount = internalGetCountForSection(i); int sectionEnd = sectionStart + sectionCount + 1; if (position >= sectionStart && position < sectionEnd) { int positionInSection = position - sectionStart - 1; mSectionPositionCache.put(position, positionInSection); return positionInSection; } sectionStart = sectionEnd; } return 0; } public final boolean isSectionHeader(int position) { int sectionStart = 0; for (int i = 0; i < internalGetSectionCount(); i++) { if (position == sectionStart) { return true; } else if (position < sectionStart) { return false; } sectionStart += internalGetCountForSection(i) + 1; } return false; } public int getItemViewType(int section, int position) { return ITEM_VIEW_TYPE; } public int getItemViewTypeCount() { return 1; } public int getSectionHeaderViewType(int section) { return HEADER_VIEW_TYPE; } public int getSectionHeaderViewTypeCount() { return 1; } public abstract Object getItem(int section, int position); public abstract long getItemId(int section, int position); public abstract int getSectionCount(); public abstract int getCountForSection(int section); public abstract View getItemView(int section, int position, View convertView, ViewGroup parent); public abstract View getSectionHeaderView(int section, View convertView, ViewGroup parent); private int internalGetCountForSection(int section) { Integer cachedSectionCount = mSectionCountCache.get(section); if (cachedSectionCount != null) { return cachedSectionCount; } int sectionCount = getCountForSection(section); mSectionCountCache.put(section, sectionCount); return sectionCount; } private int internalGetSectionCount() { if (mSectionCount >= 0) { return mSectionCount; } mSectionCount = getSectionCount(); return mSectionCount; } }<|fim▁end|>
// first try to retrieve values from cache Integer cachedPosition = mSectionPositionCache.get(position);
<|file_name|>resource.js<|end_file_name|><|fim▁begin|>'use strict'; var _ = require('lodash'); var helpers = require('./helpers'); var responseParser = require('./responseparser'); var request = require('./request'); // A resource on the API, instances of this are used as the prototype of // instances of each API resource. This constructor will build up a method // for each action that can be performed on the resource. // // - @param {Object} options // - @param {Object} schema // // The `options` argument should have the following properties: // // - `resourceDefinition` - the definition of the resource and its actions from // the schema definition. // - `consumerkey` - the oauth consumerkey // - `consumersecret` the oauth consumersecret // - `schema` - the schema defintion // - `format` - the desired response format // - `logger` - for logging output function Resource(options, schema) { this.logger = options.logger; this.resourceName = options.resourceDefinition.resource; this.host = options.resourceDefinition.host || schema.host; this.sslHost = options.resourceDefinition.sslHost || schema.sslHost; this.port = options.resourceDefinition.port || schema.port; this.prefix = options.resourceDefinition.prefix || schema.prefix; this.consumerkey = options.consumerkey; this.consumersecret = options.consumersecret; if(this.logger.silly) { this.logger.silly('Creating constructor for resource: ' + this.resourceName); } _.each(options.resourceDefinition.actions, function processAction(action) { this.createAction(action, options.userManagement); }, this); } // Figure out the appropriate method name for an action on a resource on // the API // // - @param {Mixed} - actionDefinition - Either a string if the action method // name is the same as the action path component on the underlying API call // or a hash if they differ. // - @return {String} Resource.prototype.chooseMethodName = function (actionDefinition) { var fnName; // Default the action name to getXXX if we only have the URL slug as the // action definition. if (_.isString(actionDefinition)) { fnName = 'get' + helpers.capitalize(actionDefinition); } else { fnName = actionDefinition.methodName; } return fnName; }; // Utility method for creating the necessary methods on the Resource for // dispatching the request to the 7digital API. // // - @param {Mixed} actionDefinition - Either a string if the action method // name is the same as the action path component on the underlying API call // or a hash if they differ. Resource.prototype.createAction = function (actionDefinition, isManaged) { var url; var fnName = this.chooseMethodName(actionDefinition); var action = typeof actionDefinition.apiCall === 'undefined' ? actionDefinition : actionDefinition.apiCall; var httpMethod = (actionDefinition.method || 'GET').toUpperCase(); var host = actionDefinition.host || this.host; var sslHost = actionDefinition.sslHost || this.sslHost; var port = actionDefinition.port || this.port; var prefix = actionDefinition.prefix || this.prefix; var authType = (actionDefinition.oauth && actionDefinition.oauth === '3-legged' && isManaged) ? '2-legged' : actionDefinition.oauth; if(this.logger.silly) { this.logger.silly( 'Creating method: ' + fnName + ' for ' + action + ' action with ' + httpMethod + ' HTTP verb'); } /*jshint validthis: true */ function invokeAction(requestData, callback) { var self = this; var endpointInfo = { host: invokeAction.host, sslHost: invokeAction.sslHost || sslHost, port: invokeAction.port, prefix: invokeAction.prefix, authtype: authType, url: helpers.formatPath(invokeAction.prefix, this.resourceName, action) }; var credentials = { consumerkey: this.consumerkey, consumersecret: this.consumersecret }; if (_.isFunction(requestData)) { callback = requestData; requestData = {}; } function checkAndParse(err, data, response) { if (err) { return callback(err); } return responseParser.parse(data, { format: self.format, logger: self.logger, url: endpointInfo.url, params: requestData, contentType: response.headers['content-type'] }, getLocationForRedirectsAndCallback); function getLocationForRedirectsAndCallback(err, parsed) { if (err) { return callback(err); } if (response && response.headers['location']) { parsed.location = response.headers['location']; } return callback(null, parsed); } } _.defaults(requestData, this.defaultParams); if (httpMethod === 'GET') { // Add the default parameters to the request data return request.get(endpointInfo, requestData, this.headers, credentials, this.logger, checkAndParse); } if (httpMethod === 'POST' || httpMethod === 'PUT') { return request.postOrPut(httpMethod, endpointInfo, requestData, this.headers, credentials, this.logger, checkAndParse); } return callback(new Error('Unsupported HTTP verb: ' + httpMethod)); } invokeAction.action = action; invokeAction.authtype = authType; invokeAction.host = host; invokeAction.sslHost = sslHost; invokeAction.port = port;<|fim▁hole|>module.exports = Resource;<|fim▁end|>
invokeAction.prefix = prefix; this[fnName] = invokeAction; };
<|file_name|>EntityManagerJPA.java<|end_file_name|><|fim▁begin|>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package io.github.jass2125.locadora.jpa; import javax.persistence.EntityManager; import javax.persistence.Persistence; /** * * @author Anderson Souza * @email [email protected] * @since 2015, Feb 9, 2016 */ public class EntityManagerJPA { private static EntityManager em; private EntityManagerJPA() { } public static EntityManager getEntityManager(){ if(em == null) { em = Persistence.createEntityManagerFactory("default").createEntityManager();<|fim▁hole|> return em; } }<|fim▁end|>
}
<|file_name|>useless_asref.rs<|end_file_name|><|fim▁begin|>// run-rustfix #![deny(clippy::useless_asref)] use std::fmt::Debug; struct FakeAsRef; #[allow(clippy::should_implement_trait)] impl FakeAsRef { fn as_ref(&self) -> &Self { self } } <|fim▁hole|> impl<'a, 'b, 'c> AsRef<&'a &'b &'c MoreRef> for MoreRef { fn as_ref(&self) -> &&'a &'b &'c MoreRef { &&&&MoreRef } } fn foo_rstr(x: &str) { println!("{:?}", x); } fn foo_rslice(x: &[i32]) { println!("{:?}", x); } fn foo_mrslice(x: &mut [i32]) { println!("{:?}", x); } fn foo_rrrrmr(_: &&&&MoreRef) { println!("so many refs"); } fn not_ok() { let rstr: &str = "hello"; let mut mrslice: &mut [i32] = &mut [1, 2, 3]; { let rslice: &[i32] = &*mrslice; foo_rstr(rstr.as_ref()); foo_rstr(rstr); foo_rslice(rslice.as_ref()); foo_rslice(rslice); } { foo_mrslice(mrslice.as_mut()); foo_mrslice(mrslice); foo_rslice(mrslice.as_ref()); foo_rslice(mrslice); } { let rrrrrstr = &&&&rstr; let rrrrrslice = &&&&&*mrslice; foo_rslice(rrrrrslice.as_ref()); foo_rslice(rrrrrslice); foo_rstr(rrrrrstr.as_ref()); foo_rstr(rrrrrstr); } { let mrrrrrslice = &mut &mut &mut &mut mrslice; foo_mrslice(mrrrrrslice.as_mut()); foo_mrslice(mrrrrrslice); foo_rslice(mrrrrrslice.as_ref()); foo_rslice(mrrrrrslice); } #[allow(unused_parens, clippy::double_parens)] foo_rrrrmr((&&&&MoreRef).as_ref()); generic_not_ok(mrslice); generic_ok(mrslice); } fn ok() { let string = "hello".to_owned(); let mut arr = [1, 2, 3]; let mut vec = vec![1, 2, 3]; { foo_rstr(string.as_ref()); foo_rslice(arr.as_ref()); foo_rslice(vec.as_ref()); } { foo_mrslice(arr.as_mut()); foo_mrslice(vec.as_mut()); } { let rrrrstring = &&&&string; let rrrrarr = &&&&arr; let rrrrvec = &&&&vec; foo_rstr(rrrrstring.as_ref()); foo_rslice(rrrrarr.as_ref()); foo_rslice(rrrrvec.as_ref()); } { let mrrrrarr = &mut &mut &mut &mut arr; let mrrrrvec = &mut &mut &mut &mut vec; foo_mrslice(mrrrrarr.as_mut()); foo_mrslice(mrrrrvec.as_mut()); } FakeAsRef.as_ref(); foo_rrrrmr(MoreRef.as_ref()); generic_not_ok(arr.as_mut()); generic_ok(&mut arr); } fn foo_mrt<T: Debug + ?Sized>(t: &mut T) { println!("{:?}", t); } fn foo_rt<T: Debug + ?Sized>(t: &T) { println!("{:?}", t); } fn generic_not_ok<T: AsMut<T> + AsRef<T> + Debug + ?Sized>(mrt: &mut T) { foo_mrt(mrt.as_mut()); foo_mrt(mrt); foo_rt(mrt.as_ref()); foo_rt(mrt); } fn generic_ok<U: AsMut<T> + AsRef<T> + ?Sized, T: Debug + ?Sized>(mru: &mut U) { foo_mrt(mru.as_mut()); foo_rt(mru.as_ref()); } fn main() { not_ok(); ok(); }<|fim▁end|>
struct MoreRef;
<|file_name|>date.js<|end_file_name|><|fim▁begin|>/*global describe, it */ define( ["underscore", "jquery", "utils/date"], function (_, $, date) { describe("date", function () { describe("formatYearAsTimestamp", function () { it("should pad the year so it is 4 digits when the year is < 100AD", function () { date.formatYearAsTimestamp(99, "").should.equal("0099"); }); it("should pad the year so it is 4 digits when the year is < 1000AD", function () {<|fim▁hole|> it("should format the year appropriately when it is BC", function () { date.formatYearAsTimestamp(-48, "").should.equal("0048 BC"); }); }); }); } );<|fim▁end|>
date.formatYearAsTimestamp(999, "").should.equal("0999"); });
<|file_name|>BlockManager.ts<|end_file_name|><|fim▁begin|>module Oddkyn { export module Engine { export class BlockManager { private _state: State.BaseState; private _blocks: {[part: string]: {[id: string]: Engine.Block}}; constructor(state: State.BaseState) { this._state = state; } public add(part: string, id: string, block: Engine.Block, visible = true): void { block.visibility(visible); this._blocks[part][id] = block; } public update(): void { let percentages: Array<[number, number]> = new Array<[number, number]>(); for(let part in this._blocks) { let tower: {[id: string]: Engine.Block} = this._blocks[part]; for(let id in tower) { percentages.push([tower[id].percentH(), tower[id].percentW()]); break; } } let update: Array<[number, number, number, number]> = this._computeXYHeightWidth(percentages); let idx: number = 0; for(let part in this._blocks) { let tower: {[id: string]: Engine.Block} = this._blocks[part]; for(let id in tower) { tower[id].resize(update[idx][2], update[idx][3]); tower[id].move(update[idx][0], update[idx][1]); } idx ++; } } private _computeXYHeightWidth(percentages: Array<[number, number]>): Array<[number, number, number, number]> { let XYHeightWidth: Array<[number, number, number, number]> = new Array<[number, number, number, number]>(percentages.length); let h: number = this._state.game.height;<|fim▁hole|> let percentageH: Array<number> = new Array<number>(); let resizableH: Array<boolean> = new Array<boolean>(); let nbResizableH: number; let percentageW: Array<number> = new Array<number>(); let resizableW: Array<boolean> = new Array<boolean>(); let nbResizableW: number; for(let p of percentages) { percentageH.push(p[0]); resizableH.push(p[0] == 100); percentageW.push(p[1]); if(p[0] == 100) nbResizableH ++; resizableW.push(p[1] == 100); if(p[1] == 100) nbResizableW ++; } let sumH: number = percentageH.reduce(function(pv, cv) { return pv + cv;}, 0); let toTakeH: number = sumH - 100; let partH: number = toTakeH / nbResizableH; for(let idx in percentageH) { if(resizableH[idx]) percentageH[idx] = percentageH[idx] - partH; } let sumW: number = percentageW.reduce(function(pv, cv) { return pv + cv;}, 0); let toTakeW: number = sumH - 100; let partW: number = toTakeW / nbResizableW; for(let idx in percentageW) { if(resizableW[idx]) percentageW[idx] = percentageW[idx] - partW; } for(let idx in percentageH) { let xyhx: [number, number, number, number] = [x, y, h * percentageH[idx], w * percentageW[idx]]; x = x + w * percentageW[idx]; y = y + h * percentageH[idx]; } return XYHeightWidth; } } } }<|fim▁end|>
let w: number = this._state.game.width; let x: number = 0; let y: number = 0;
<|file_name|>toolbar.js<|end_file_name|><|fim▁begin|>// //{block name="backend/create_backend_order/view/toolbar"} // Ext.define('Shopware.apps.SwagBackendOrder.view.main.Toolbar', { extend: 'Ext.toolbar.Toolbar', alternateClassName: 'SwagBackendOrder.view.main.Toolbar', alias: 'widget.createbackendorder-toolbar', dock: 'top', ui: 'shopware-ui', padding: '0 10 0 10', snippets: { buttons: { openCustomer: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/button/open_customer"}Open Customer{/s}', createCustomer: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/button/create_customer"}Create Customer{/s}', createGuest: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/button/create_guest"}Create Guest{/s}' }, shop: { noCustomer: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/shop/label/no_costumer"}Shop: No customer selected.{/s}', default: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/shop/label/default"}Shop: {/s}' }, currencyLabel: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/currency/label"}Choose currency{/s}', languageLabel: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/language/label"}Language{/s}' }, /** * */ initComponent: function () { var me = this; me.items = me.createToolbarItems(); me.languageStore = Ext.create('Ext.data.Store', { name: 'languageStore', fields: ['id', 'mainId', 'categoryId', 'name', 'title', 'default'] }); /** * automatically selects the standard currency */ me.currencyStore = me.subApplication.getStore('Currency'); me.currencyStore.on('load', function () { me.changeCurrencyComboBox.bindStore(me.currencyStore); var standardCurrency = me.currencyStore.findExact('default', 1); if (standardCurrency > -1) { me.currencyModel = me.currencyStore.getAt(standardCurrency); me.changeCurrencyComboBox.select(me.currencyModel); me.currencyModel.set('selected', 1); } else {<|fim▁hole|> } }); me.customerSearchField.on('valueselect', function () { me.openCustomerButton.setDisabled(false); }); //selects and loads the language sub shops var customerStore = me.subApplication.getStore('Customer'); customerStore.on('load', function () { if (typeof customerStore.getAt(0) !== 'undefined') { var shopName = '', customerModel = customerStore.getAt(0); var languageId = customerModel.get('languageId'); var index = customerModel.languageSubShop().findExact('id', languageId); if (index >= 0) { shopName = customerModel.languageSubShop().getAt(index).get('name'); } else { index = customerModel.shop().findExact('id', languageId); shopName = customerModel.shop().getAt(index).get('name'); } me.shopLabel.setText(me.snippets.shop.default + shopName); me.fireEvent('changeCustomer'); me.getLanguageShops(customerModel.shop().getAt(0).get('id'), customerStore.getAt(0).get('languageId')); } }); me.callParent(arguments); }, /** * register the events */ registerEvents: function () { this.addEvents( 'changeSearchField' ) }, /** * creates the top toolbar items * * @returns [] */ createToolbarItems: function () { var me = this; me.customerSearchField = me.createCustomerSearch('customerName', 'id', 'email'); me.createCustomerButton = Ext.create('Ext.button.Button', { text: me.snippets.buttons.createCustomer, handler: function () { me.fireEvent('createCustomer', false); } }); me.createGuestButton = Ext.create('Ext.button.Button', { text: me.snippets.buttons.createGuest, handler: function () { me.fireEvent('createCustomer', true); } }); me.openCustomerButton = Ext.create('Ext.button.Button', { text: me.snippets.buttons.openCustomer, disabled: true, margin: '0 30 0 0', handler: function () { me.fireEvent('openCustomer'); } }); me.shopLabel = Ext.create('Ext.form.Label', { text: me.snippets.shop.noCustomer, style: { fontWeight: 'bold' } }); me.languageComboBox = Ext.create('Ext.form.field.ComboBox', { fieldLabel: me.snippets.languageLabel, labelWidth: 65, store: me.languageStore, queryMode: 'local', displayField: 'name', width: '20%', valueField: 'id', listeners: { change: { fn: function (comboBox, newValue, oldValue, eOpts) { me.fireEvent('changeLanguage', newValue); } } } }); me.changeCurrencyComboBox = Ext.create('Ext.form.field.ComboBox', { fieldLabel: me.snippets.currencyLabel, stores: me.currencyStore, queryMode: 'local', displayField: 'currency', width: '20%', valueField: 'id', listeners: { change: { fn: function (comboBox, newValue, oldValue, eOpts) { me.fireEvent('changeCurrency', comboBox, newValue, oldValue, eOpts); } } } }); return [ me.changeCurrencyComboBox, me.languageComboBox, me.shopLabel, '->', me.createCustomerButton, me.createGuestButton, me.openCustomerButton, me.customerSearchField ]; }, /** * * @param returnValue * @param hiddenReturnValue * @param name * @return Shopware.form.field.ArticleSearch */ createCustomerSearch: function (returnValue, hiddenReturnValue, name) { var me = this; me.customerStore = me.subApplication.getStore('Customer'); return Ext.create('Shopware.apps.SwagBackendOrder.view.main.CustomerSearch', { name: name, subApplication: me.subApplication, returnValue: returnValue, hiddenReturnValue: hiddenReturnValue, articleStore: me.customerStore, allowBlank: false, getValue: function () { me.store.getAt(me.record.rowIdx).set(name, this.getSearchField().getValue()); return this.getSearchField().getValue(); }, setValue: function (value) { this.getSearchField().setValue(value); } }); }, /** * @param mainShopId * @param languageId */ getLanguageShops: function (mainShopId, languageId) { var me = this; Ext.Ajax.request({ url: '{url action="getLanguageSubShops"}', params: { mainShopId: mainShopId }, success: function (response) { me.languageStore.removeAll(); var languageSubShops = Ext.JSON.decode(response.responseText); languageSubShops.data.forEach(function (record) { me.languageStore.add(record); }); me.languageComboBox.bindStore(me.languageStore); //selects the default language shop var languageIndex = me.languageStore.findExact('mainId', null); me.languageComboBox.setValue(languageId); } }); } }); // //{/block} //<|fim▁end|>
me.changeCurrencyComboBox.select(me.currencyStore.first()); me.currencyStore.first().set('selected', 1);
<|file_name|>test-test.js<|end_file_name|><|fim▁begin|>'use strict'; var assert = require('../../helpers/assert'); var commandOptions = require('../../factories/command-options'); var stub = require('../../helpers/stub').stub; var Promise = require('../../../lib/ext/promise'); var Task = require('../../../lib/models/task'); var TestCommand = require('../../../lib/commands/test'); describe('test command', function() { var tasks; var options; var buildRun; var testRun; beforeEach(function(){ tasks = { Build: Task.extend(), Test: Task.extend() }; options = commandOptions({ tasks: tasks, testing: true }); stub(tasks.Test.prototype, 'run', Promise.resolve()); stub(tasks.Build.prototype, 'run', Promise.resolve()); buildRun = tasks.Build.prototype.run; testRun = tasks.Test.prototype.run; }); it('builds and runs test', function() { return new TestCommand(options).validateAndRun([]).then(function() { assert.equal(buildRun.called, 1, 'expected build task to be called once'); assert.equal(testRun.called, 1, 'expected test task to be called once'); }); }); it('has the correct options', function() { return new TestCommand(options).validateAndRun([]).then(function() { var buildOptions = buildRun.calledWith[0][0]; var testOptions = testRun.calledWith[0][0]; assert.equal(buildOptions.environment, 'development', 'has correct env'); assert.ok(buildOptions.outputPath, 'has outputPath'); assert.equal(testOptions.configFile, './testem.json', 'has config file'); assert.equal(testOptions.port, 7357, 'has config file'); }); }); <|fim▁hole|> assert.equal(testOptions.configFile, 'some-random/path.json'); }); }); it('passes through custom port option', function() { return new TestCommand(options).validateAndRun(['--port=5678']).then(function() { var testOptions = testRun.calledWith[0][0]; assert.equal(testOptions.port, 5678); }); }); });<|fim▁end|>
it('passes through custom configFile option', function() { return new TestCommand(options).validateAndRun(['--config-file=some-random/path.json']).then(function() { var testOptions = testRun.calledWith[0][0];
<|file_name|>legal-routing.module.ts<|end_file_name|><|fim▁begin|>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router';<|fim▁hole|> import { LegalComponent } from './legal.component'; const routes: Routes = [ { path: '', component: LegalComponent } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class LegalRoutingModule { }<|fim▁end|>
<|file_name|>test_rdf_header.py<|end_file_name|><|fim▁begin|>""" test_rdf_header.py -- show the rdf_header <|fim▁hole|>""" __author__ = "Michael Conlon" __copyright__ = "Copyright 2013, University of Florida" __license__ = "BSD 3-Clause license" __version__ = "0.1" import vivotools as vt from datetime import datetime print datetime.now(),"Start" print vt.rdf_header() print datetime.now(),"Finish"<|fim▁end|>
Version 0.1 MC 2013-12-27 -- Initial version.
<|file_name|>traversal.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/. */ //! Traversing the DOM tree; the bloom filter. use animation; use context::{LocalStyleContext, SharedStyleContext, StyleContext}; use dom::{OpaqueNode, TNode, TRestyleDamage, UnsafeNode}; use matching::{ApplicableDeclarations, ElementMatchMethods, MatchMethods, StyleSharingResult}; use selectors::bloom::BloomFilter; use selectors::matching::StyleRelations; use std::cell::RefCell; use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; use tid::tid; use util::opts; /// Every time we do another layout, the old bloom filters are invalid. This is /// detected by ticking a generation number every layout. pub type Generation = u32; /// This enum tells us about whether we can stop restyling or not after styling /// an element. /// /// So far this only happens where a display: none node is found. pub enum RestyleResult { Continue, Stop, } /// Style sharing candidate cache stats. These are only used when /// `-Z style-sharing-stats` is given. pub static STYLE_SHARING_CACHE_HITS: AtomicUsize = ATOMIC_USIZE_INIT; pub static STYLE_SHARING_CACHE_MISSES: AtomicUsize = ATOMIC_USIZE_INIT; /// A pair of the bloom filter used for css selector matching, and the node to /// which it applies. This is used to efficiently do `Descendant` selector /// matches. Thanks to the bloom filter, we can avoid walking up the tree /// looking for ancestors that aren't there in the majority of cases. /// /// As we walk down the DOM tree a thread-local bloom filter is built of all the /// CSS `SimpleSelector`s which are part of a `Descendant` compound selector /// (i.e. paired with a `Descendant` combinator, in the `next` field of a /// `CompoundSelector`. /// /// Before a `Descendant` selector match is tried, it's compared against the /// bloom filter. If the bloom filter can exclude it, the selector is quickly /// rejected. /// /// When done styling a node, all selectors previously inserted into the filter /// are removed. /// /// Since a work-stealing queue is used for styling, sometimes, the bloom filter /// will no longer be the for the parent of the node we're currently on. When /// this happens, the thread local bloom filter will be thrown away and rebuilt. thread_local!( static STYLE_BLOOM: RefCell<Option<(Box<BloomFilter>, UnsafeNode, Generation)>> = RefCell::new(None)); /// Returns the thread local bloom filter. /// /// If one does not exist, a new one will be made for you. If it is out of date, /// it will be cleared and reused. fn take_thread_local_bloom_filter<N>(parent_node: Option<N>, root: OpaqueNode, context: &SharedStyleContext) -> Box<BloomFilter> where N: TNode { STYLE_BLOOM.with(|style_bloom| { match (parent_node, style_bloom.borrow_mut().take()) { // Root node. Needs new bloom filter. (None, _ ) => { debug!("[{}] No parent, but new bloom filter!", tid()); Box::new(BloomFilter::new()) } // No bloom filter for this thread yet. (Some(parent), None) => { let mut bloom_filter = Box::new(BloomFilter::new()); insert_ancestors_into_bloom_filter(&mut bloom_filter, parent, root); bloom_filter } // Found cached bloom filter. (Some(parent), Some((mut bloom_filter, old_node, old_generation))) => { if old_node == parent.to_unsafe() && old_generation == context.generation { // Hey, the cached parent is our parent! We can reuse the bloom filter. debug!("[{}] Parent matches (={}). Reusing bloom filter.", tid(), old_node.0); } else { // Oh no. the cached parent is stale. I guess we need a new one. Reuse the existing // allocation to avoid malloc churn. bloom_filter.clear(); insert_ancestors_into_bloom_filter(&mut bloom_filter, parent, root); } bloom_filter }, } }) } fn put_thread_local_bloom_filter(bf: Box<BloomFilter>, unsafe_node: &UnsafeNode, context: &SharedStyleContext) { STYLE_BLOOM.with(move |style_bloom| { assert!(style_bloom.borrow().is_none(), "Putting into a never-taken thread-local bloom filter"); *style_bloom.borrow_mut() = Some((bf, *unsafe_node, context.generation)); }) } /// "Ancestors" in this context is inclusive of ourselves. fn insert_ancestors_into_bloom_filter<N>(bf: &mut Box<BloomFilter>, mut n: N, root: OpaqueNode) where N: TNode { debug!("[{}] Inserting ancestors.", tid()); let mut ancestors = 0; loop { ancestors += 1; n.insert_into_bloom_filter(&mut **bf); n = match n.layout_parent_node(root) { None => break, Some(p) => p, }; } debug!("[{}] Inserted {} ancestors.", tid(), ancestors); } pub fn remove_from_bloom_filter<'a, N, C>(context: &C, root: OpaqueNode, node: N) where N: TNode, C: StyleContext<'a> { let unsafe_layout_node = node.to_unsafe(); let (mut bf, old_node, old_generation) = STYLE_BLOOM.with(|style_bloom| { style_bloom.borrow_mut() .take() .expect("The bloom filter should have been set by style recalc.") }); assert_eq!(old_node, unsafe_layout_node); assert_eq!(old_generation, context.shared_context().generation); match node.layout_parent_node(root) { None => { debug!("[{}] - {:X}, and deleting BF.", tid(), unsafe_layout_node.0); // If this is the reflow root, eat the thread-local bloom filter. } Some(parent) => { // Otherwise, put it back, but remove this node. node.remove_from_bloom_filter(&mut *bf); let unsafe_parent = parent.to_unsafe(); put_thread_local_bloom_filter(bf, &unsafe_parent, &context.shared_context()); }, }; } pub trait DomTraversalContext<N: TNode> { type SharedContext: Sync + 'static; fn new<'a>(&'a Self::SharedContext, OpaqueNode) -> Self; /// Process `node` on the way down, before its children have been processed. fn process_preorder(&self, node: N) -> RestyleResult; /// Process `node` on the way up, after its children have been processed. /// /// This is only executed if `needs_postorder_traversal` returns true. fn process_postorder(&self, node: N); /// Boolean that specifies whether a bottom up traversal should be /// performed. /// /// If it's false, then process_postorder has no effect at all. fn needs_postorder_traversal(&self) -> bool { true } /// Returns if the node should be processed by the preorder traversal (and /// then by the post-order one). /// /// Note that this is true unconditionally for servo, since it requires to /// bubble the widths bottom-up for all the DOM. fn should_process(&self, node: N) -> bool { opts::get().nonincremental_layout || node.is_dirty() || node.has_dirty_descendants() } /// Do an action over the child before pushing him to the work queue. /// /// By default, propagate the IS_DIRTY flag down the tree. #[allow(unsafe_code)] fn pre_process_child_hook(&self, parent: N, kid: N) { // NOTE: At this point is completely safe to modify either the parent or // the child, since we have exclusive access to both of them. if parent.is_dirty() { unsafe { kid.set_dirty(true); parent.set_dirty_descendants(true); } } } fn local_context(&self) -> &LocalStyleContext; } /// Determines the amount of relations where we're going to share style. #[inline] pub fn relations_are_shareable(relations: &StyleRelations) -> bool { use selectors::matching::*; !relations.intersects(AFFECTED_BY_ID_SELECTOR | AFFECTED_BY_PSEUDO_ELEMENTS | AFFECTED_BY_STATE |<|fim▁hole|> AFFECTED_BY_STYLE_ATTRIBUTE | AFFECTED_BY_PRESENTATIONAL_HINTS) } pub fn ensure_node_styled<'a, N, C>(node: N, context: &'a C) where N: TNode, C: StyleContext<'a> { let mut display_none = false; ensure_node_styled_internal(node, context, &mut display_none); } #[allow(unsafe_code)] fn ensure_node_styled_internal<'a, N, C>(node: N, context: &'a C, parents_had_display_none: &mut bool) where N: TNode, C: StyleContext<'a> { use properties::longhands::display::computed_value as display; // NB: The node data must be initialized here. // We need to go to the root and ensure their style is up to date. // // This means potentially a bit of wasted work (usually not much). We could // add a flag at the node at which point we stopped the traversal to know // where should we stop, but let's not add that complication unless needed. let parent = match node.parent_node() { Some(parent) if parent.is_element() => Some(parent), _ => None, }; if let Some(parent) = parent { ensure_node_styled_internal(parent, context, parents_had_display_none); } // Common case: our style is already resolved and none of our ancestors had // display: none. // // We only need to mark whether we have display none, and forget about it, // our style is up to date. if let Some(ref style) = node.get_existing_style() { if !*parents_had_display_none { *parents_had_display_none = style.get_box().clone_display() == display::T::none; return; } } // Otherwise, our style might be out of date. Time to do selector matching // if appropriate and cascade the node. // // Note that we could add the bloom filter's complexity here, but that's // probably not necessary since we're likely to be matching only a few // nodes, at best. let mut applicable_declarations = ApplicableDeclarations::new(); if let Some(element) = node.as_element() { let stylist = &context.shared_context().stylist; element.match_element(&**stylist, None, &mut applicable_declarations); } unsafe { node.cascade_node(context, parent, &applicable_declarations); } } /// Calculates the style for a single node. #[inline] #[allow(unsafe_code)] pub fn recalc_style_at<'a, N, C>(context: &'a C, root: OpaqueNode, node: N) -> RestyleResult where N: TNode, C: StyleContext<'a> { // Get the parent node. let parent_opt = match node.parent_node() { Some(parent) if parent.is_element() => Some(parent), _ => None, }; // Get the style bloom filter. let mut bf = take_thread_local_bloom_filter(parent_opt, root, context.shared_context()); let nonincremental_layout = opts::get().nonincremental_layout; let mut restyle_result = RestyleResult::Continue; if nonincremental_layout || node.is_dirty() { // Remove existing CSS styles from nodes whose content has changed (e.g. text changed), // to force non-incremental reflow. if node.has_changed() { node.set_style(None); } // Check to see whether we can share a style with someone. let style_sharing_candidate_cache = &mut context.local_context().style_sharing_candidate_cache.borrow_mut(); let sharing_result = match node.as_element() { Some(element) => { unsafe { element.share_style_if_possible(style_sharing_candidate_cache, context.shared_context(), parent_opt.clone()) } }, None => StyleSharingResult::CannotShare, }; // Otherwise, match and cascade selectors. match sharing_result { StyleSharingResult::CannotShare => { let mut applicable_declarations = ApplicableDeclarations::new(); let relations; let shareable_element = match node.as_element() { Some(element) => { if opts::get().style_sharing_stats { STYLE_SHARING_CACHE_MISSES.fetch_add(1, Ordering::Relaxed); } // Perform the CSS selector matching. let stylist = &context.shared_context().stylist; relations = element.match_element(&**stylist, Some(&*bf), &mut applicable_declarations); debug!("Result of selector matching: {:?}", relations); if relations_are_shareable(&relations) { Some(element) } else { None } }, None => { relations = StyleRelations::empty(); if node.has_changed() { node.set_restyle_damage(N::ConcreteRestyleDamage::rebuild_and_reflow()) } None }, }; // Perform the CSS cascade. unsafe { restyle_result = node.cascade_node(context, parent_opt, &applicable_declarations); } // Add ourselves to the LRU cache. if let Some(element) = shareable_element { style_sharing_candidate_cache.insert_if_possible(&element, relations); } } StyleSharingResult::StyleWasShared(index, damage, cached_restyle_result) => { restyle_result = cached_restyle_result; if opts::get().style_sharing_stats { STYLE_SHARING_CACHE_HITS.fetch_add(1, Ordering::Relaxed); } style_sharing_candidate_cache.touch(index); node.set_restyle_damage(damage); } } } else { // Finish any expired transitions. let mut existing_style = node.get_existing_style().unwrap(); let had_animations_to_expire = animation::complete_expired_transitions( node.opaque(), &mut existing_style, context.shared_context() ); if had_animations_to_expire { node.set_style(Some(existing_style)); } } let unsafe_layout_node = node.to_unsafe(); // Before running the children, we need to insert our nodes into the bloom // filter. debug!("[{}] + {:X}", tid(), unsafe_layout_node.0); node.insert_into_bloom_filter(&mut *bf); // NB: flow construction updates the bloom filter on the way up. put_thread_local_bloom_filter(bf, &unsafe_layout_node, context.shared_context()); if nonincremental_layout { RestyleResult::Continue } else { restyle_result } }<|fim▁end|>
AFFECTED_BY_NON_COMMON_STYLE_AFFECTING_ATTRIBUTE_SELECTOR |
<|file_name|>word-search.spec.js<|end_file_name|><|fim▁begin|>import WordSearch from './word-search'; describe('single line grids', () => { test('Should accept an initial game grid', () => { const grid = ['jefblpepre']; const wordSearch = new WordSearch(grid); expect(wordSearch instanceof WordSearch).toEqual(true); }); xtest('can accept a target search word', () => { const grid = ['jefblpepre']; const wordSearch = new WordSearch(grid); expect(wordSearch.find(['glasnost'])).toEqual({ glasnost: undefined }); }); xtest('should locate a word written left to right', () => { const grid = ['clojurermt']; const expectedResults = { clojure: { start: [1, 1], end: [1, 7], }, }; const wordSearch = new WordSearch(grid); expect(wordSearch.find(['clojure'])).toEqual(expectedResults); }); xtest('can locate a left to right word in a different position', () => { const grid = ['mtclojurer']; const expectedResults = { clojure: { start: [1, 3], end: [1, 9], }, }; const wordSearch = new WordSearch(grid); expect(wordSearch.find(['clojure'])).toEqual(expectedResults); }); xtest('can locate a different left to right word', () => { const grid = ['coffeelplx']; const expectedResults = { coffee: { start: [1, 1], end: [1, 6], }, }; const wordSearch = new WordSearch(grid); expect(wordSearch.find(['coffee'])).toEqual(expectedResults); }); xtest('can locate that different left to right word in a different position', () => { const grid = ['xcoffeezlp']; const expectedResults = { coffee: { start: [1, 2], end: [1, 7], }, }; const wordSearch = new WordSearch(grid); expect(wordSearch.find(['coffee'])).toEqual(expectedResults); }); }); describe('multi line grids', () => { xtest('can locate a left to right word in a two line grid', () => { const grid = ['jefblpepre', 'clojurermt']; const expectedResults = { clojure: { start: [2, 1], end: [2, 7], }, }; const wordSearch = new WordSearch(grid); expect(wordSearch.find(['clojure'])).toEqual(expectedResults); }); xtest('can locate a left to right word in a different position in a two line grid', () => { const grid = ['jefblpepre', 'tclojurerm']; const expectedResults = { clojure: { start: [2, 2], end: [2, 8], }, }; const wordSearch = new WordSearch(grid); expect(wordSearch.find(['clojure'])).toEqual(expectedResults); }); xtest('can locate a left to right word in a three line grid', () => { const grid = ['camdcimgtc', 'jefblpepre', 'clojurermt']; const expectedResults = { clojure: { start: [3, 1], end: [3, 7], }, }; const wordSearch = new WordSearch(grid); expect(wordSearch.find(['clojure'])).toEqual(expectedResults); }); xtest('can locate a left to right word in a ten line grid', () => { const grid = [ 'jefblpepre', 'camdcimgtc', 'oivokprjsm', 'pbwasqroua', 'rixilelhrs', 'wolcqlirpc', 'screeaumgr', 'alxhpburyi', 'jalaycalmp', 'clojurermt', ]; const expectedResults = { clojure: { start: [10, 1], end: [10, 7], }, }; const wordSearch = new WordSearch(grid); expect(wordSearch.find(['clojure'])).toEqual(expectedResults); }); xtest('can locate a left to right word in a different position in a ten line grid', () => { const grid = [ 'jefblpepre', 'camdcimgtc', 'oivokprjsm', 'pbwasqroua', 'rixilelhrs', 'wolcqlirpc', 'screeaumgr', 'alxhpburyi', 'clojurermt', 'jalaycalmp', ]; const expectedResults = { clojure: { start: [9, 1], end: [9, 7], }, }; const wordSearch = new WordSearch(grid); expect(wordSearch.find(['clojure'])).toEqual(expectedResults); }); xtest('can locate a different left to right word in a ten line grid', () => { const grid = [ 'jefblpepre', 'camdcimgtc', 'oivokprjsm', 'pbwasqroua', 'rixilelhrs', 'wolcqlirpc', 'screeaumgr', 'alxhpburyi', 'clojurermt', 'jalaycalmp', ]; const expectedResults = { scree: { start: [7, 1], end: [7, 5], }, }; const wordSearch = new WordSearch(grid); expect(wordSearch.find(['scree'])).toEqual(expectedResults); }); }); describe('can find multiple words', () => { xtest('can find two words written left to right', () => { const grid = [ 'aefblpepre', 'camdcimgtc', 'oivokprjsm', 'pbwasqroua', 'rixilelhrs', 'wolcqlirpc', 'screeaumgr', 'alxhpburyi', 'jalaycalmp', 'clojurermt', 'xjavamtzlp', ]; const expectedResults = { clojure: { start: [10, 1], end: [10, 7], }, java: { start: [11, 2], end: [11, 5], }, }; const wordSearch = new WordSearch(grid); expect(wordSearch.find(['java', 'clojure'])).toEqual(expectedResults); }); }); describe('different directions', () => { xtest('should locate a single word written right to left', () => { const grid = ['rixilelhrs']; const expectedResults = { elixir: { start: [1, 6], end: [1, 1], }, }; const wordSearch = new WordSearch(grid); expect(wordSearch.find(['elixir'])).toEqual(expectedResults); }); xtest('should locate multiple words written in different horizontal directions', () => { const grid = [ 'jefblpepre', 'camdcimgtc', 'oivokprjsm', 'pbwasqroua', 'rixilelhrs', 'wolcqlirpc', 'screeaumgr', 'alxhpburyi', 'jalaycalmp', 'clojurermt', ]; const expectedResults = { clojure: { start: [10, 1], end: [10, 7], }, elixir: { start: [5, 6], end: [5, 1], }, }; const wordSearch = new WordSearch(grid); expect(wordSearch.find(['elixir', 'clojure'])).toEqual(expectedResults); }); }); describe('vertical directions', () => { xtest('should locate words written top to bottom', () => { const grid = [ 'jefblpepre', 'camdcimgtc', 'oivokprjsm', 'pbwasqroua', 'rixilelhrs', 'wolcqlirpc', 'screeaumgr', 'alxhpburyi', 'jalaycalmp', 'clojurermt', ]; const expectedResults = { clojure: { start: [10, 1], end: [10, 7], }, elixir: { start: [5, 6], end: [5, 1], }, ecmascript: { start: [1, 10], end: [10, 10], }, }; const wordSearch = new WordSearch(grid); expect(wordSearch.find(['elixir', 'clojure', 'ecmascript'])).toEqual( expectedResults ); }); xtest('should locate words written bottom to top', () => { const grid = [ 'jefblpepre', 'camdcimgtc', 'oivokprjsm', 'pbwasqroua', 'rixilelhrs', 'wolcqlirpc', 'screeaumgr', 'alxhpburyi', 'jalaycalmp', 'clojurermt', ]; const expectedResults = { clojure: { start: [10, 1], end: [10, 7], }, elixir: { start: [5, 6], end: [5, 1], }, ecmascript: { start: [1, 10], end: [10, 10], }, rust: { start: [5, 9], end: [2, 9], }, }; const wordSearch = new WordSearch(grid); expect( wordSearch.find(['elixir', 'clojure', 'ecmascript', 'rust']) ).toEqual(expectedResults); }); xtest('should locate words written top left to bottom right', () => { const grid = [ 'jefblpepre', 'camdcimgtc', 'oivokprjsm', 'pbwasqroua', 'rixilelhrs', 'wolcqlirpc', 'screeaumgr', 'alxhpburyi', 'jalaycalmp', 'clojurermt', ]; const expectedResults = { clojure: { start: [10, 1], end: [10, 7], }, elixir: { start: [5, 6], end: [5, 1], }, ecmascript: { start: [1, 10], end: [10, 10], }, rust: { start: [5, 9], end: [2, 9], }, java: { start: [1, 1], end: [4, 4], }, }; const wordSearch = new WordSearch(grid); expect( wordSearch.find(['clojure', 'elixir', 'ecmascript', 'rust', 'java']) ).toEqual(expectedResults); }); xtest('should locate words written bottom right to top left', () => { const grid = [ 'jefblpepre', 'camdcimgtc', 'oivokprjsm', 'pbwasqroua', 'rixilelhrs', 'wolcqlirpc', 'screeaumgr', 'alxhpburyi', 'jalaycalmp', 'clojurermt', ]; const expectedResults = { clojure: { start: [10, 1], end: [10, 7], }, elixir: { start: [5, 6], end: [5, 1], }, ecmascript: { start: [1, 10], end: [10, 10], }, rust: { start: [5, 9], end: [2, 9], }, java: { start: [1, 1], end: [4, 4], }, lua: { start: [9, 8], end: [7, 6], }, }; const wordSearch = new WordSearch(grid); expect( wordSearch.find([ 'clojure', 'elixir', 'ecmascript', 'rust', 'java', 'lua', ]) ).toEqual(expectedResults); }); xtest('should locate words written bottom left to top right', () => { const grid = [ 'jefblpepre', 'camdcimgtc', 'oivokprjsm', 'pbwasqroua', 'rixilelhrs', 'wolcqlirpc', 'screeaumgr', 'alxhpburyi', 'jalaycalmp', 'clojurermt', ]; const expectedResults = { clojure: { start: [10, 1], end: [10, 7], }, elixir: { start: [5, 6], end: [5, 1], }, ecmascript: { start: [1, 10], end: [10, 10], }, rust: { start: [5, 9], end: [2, 9], }, java: { start: [1, 1], end: [4, 4], }, lua: { start: [9, 8], end: [7, 6], }, lisp: { start: [6, 3], end: [3, 6], }, }; const wordSearch = new WordSearch(grid); expect( wordSearch.find([ 'clojure', 'elixir', 'ecmascript', 'rust', 'java', 'lua', 'lisp', ]) ).toEqual(expectedResults); }); xtest('should locate words written top right to bottom left', () => { const grid = [ 'jefblpepre', 'camdcimgtc', 'oivokprjsm', 'pbwasqroua', 'rixilelhrs', 'wolcqlirpc', 'screeaumgr', 'alxhpburyi', 'jalaycalmp', 'clojurermt', ]; const expectedResults = { clojure: { start: [10, 1], end: [10, 7], }, elixir: { start: [5, 6], end: [5, 1], }, ecmascript: { start: [1, 10], end: [10, 10], }, rust: {<|fim▁hole|> }, java: { start: [1, 1], end: [4, 4], }, lua: { start: [9, 8], end: [7, 6], }, lisp: { start: [6, 3], end: [3, 6], }, ruby: { start: [6, 8], end: [9, 5], }, }; const wordSearch = new WordSearch(grid); expect( wordSearch.find([ 'clojure', 'elixir', 'ecmascript', 'rust', 'java', 'lua', 'lisp', 'ruby', ]) ).toEqual(expectedResults); }); describe("word doesn't exist", () => { xtest('should fail to locate a word that is not in the puzzle', () => { const grid = [ 'jefblpepre', 'camdcimgtc', 'oivokprjsm', 'pbwasqroua', 'rixilelhrs', 'wolcqlirpc', 'screeaumgr', 'alxhpburyi', 'jalaycalmp', 'clojurermt', ]; const expectedResults = { fail: undefined, }; const wordSearch = new WordSearch(grid); expect(wordSearch.find(['fail'])).toEqual(expectedResults); }); }); });<|fim▁end|>
start: [5, 9], end: [2, 9],
<|file_name|>test_enumeration.py<|end_file_name|><|fim▁begin|>from django.test import TestCase, tag from member.tests.test_mixins import MemberMixin from django.contrib.auth.models import User from django.test.client import RequestFactory from django.urls.base import reverse from enumeration.views import DashboardView, ListBoardView class TestEnumeration(MemberMixin, TestCase): def setUp(self): self.factory = RequestFactory() self.user = User.objects.create_user(username='erik') self.household_structure = self.make_household_ready_for_enumeration(make_hoh=False) def test_dashboard_view(self): url = reverse('enumeration:dashboard_url', kwargs=dict( household_identifier=self.household_structure.household.household_identifier, survey=self.household_structure.survey))<|fim▁hole|> response = DashboardView.as_view()(request) self.assertEqual(response.status_code, 200) def test_dashboard_view2(self): url = reverse('enumeration:dashboard_url', kwargs=dict( household_identifier=self.household_structure.household.household_identifier, survey=self.household_structure.survey)) self.client.force_login(self.user) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_list_view1(self): url = reverse('enumeration:listboard_url') request = self.factory.get(url) request.user = self.user response = ListBoardView.as_view()(request) self.assertEqual(response.status_code, 200) def test_list_view2(self): url = reverse('enumeration:listboard_url', kwargs=dict(page=1)) request = self.factory.get(url) request.user = self.user response = ListBoardView.as_view()(request) self.assertEqual(response.status_code, 200) def test_list_view3(self): url = reverse('enumeration:listboard_url', kwargs=dict( household_identifier=self.household_structure.household.household_identifier)) request = self.factory.get(url) request.user = self.user response = ListBoardView.as_view()(request) self.assertEqual(response.status_code, 200) def test_list_view4(self): url = reverse('enumeration:listboard_url', kwargs=dict( household_identifier=self.household_structure.household.household_identifier, survey=self.household_structure.survey)) request = self.factory.get(url) request.user = self.user response = ListBoardView.as_view()(request) self.assertEqual(response.status_code, 200) def test_list_view5(self): url = reverse('enumeration:listboard_url', kwargs=dict( plot_identifier=self.household_structure.household.plot.plot_identifier)) request = self.factory.get(url) request.user = self.user response = ListBoardView.as_view()(request) self.assertEqual(response.status_code, 200)<|fim▁end|>
request = self.factory.get(url) request.user = self.user
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
"""News Tests"""
<|file_name|>JavaPing.java<|end_file_name|><|fim▁begin|>/* * Created on Apr 28, 2005 */ package jsrl.net; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.InetAddress; import java.net.UnknownHostException;<|fim▁hole|> /** * JavaPing * Java Bindings for the SRL Library's Ping Logic */ public class JavaPing implements Runnable, PingListener { public static final int ECHO_REPLY = 0; public static final int DESTINATION_UNREACHABLE = 3; // local listener protected PingListener _listener = null; protected boolean _is_running = false; private static JavaPing __javaping_singleton = null; protected boolean _has_rawsockets = false; static { LoadLibrary.Load(); __javaping_singleton = new JavaPing(); } /** returns an instance of the Java Ping Utility * @throws SocketException */ public static JavaPing getInstance() { return __javaping_singleton; } private JavaPing() { _has_rawsockets = begin(); } public synchronized void startListening(PingListener listener) throws SocketException { if (!_has_rawsockets) throw new SocketException("permission denied attempting to create raw socket!"); _listener = listener; new Thread(this).start(); } public synchronized void stopListening() { _is_running = false; } public boolean isListening() { return _is_running; } protected int counter = 0; public int receivedCount() { return counter; } /** main method for performing reads */ public void run() { counter = 0; _is_running = true; while (_is_running) { try { _listener.ping_result(pong(100)); ++counter; } catch (SocketTimeoutException e) { } catch (SocketException e) { } } _listener = null; } static final PingResult DUMMY_RESULT = new PingResult(); public void clearIncoming() { _pong(0, DUMMY_RESULT); } public PingResult pingpong(String address, int seq, int msg_size, int time_out) throws SocketTimeoutException { return pingpong(address, seq, msg_size, time_out, 200); } public PingResult pingpong(String address, int seq, int msg_size, int time_out, int ttl) throws SocketTimeoutException { PingResult result = new PingResult(); if (!_pingpong(address, seq, msg_size, time_out, ttl, result)) { throw new java.net.SocketTimeoutException("receiving echo reply timed out after " + time_out); } return result; } public synchronized void ping(String address, int seq, int msg_size) { ping(address, seq, msg_size, 200); } /** send a ICMP Echo Request to the specified ip */ public native void ping(String address, int seq, int msg_size, int ttl); /**pthread * recv a ICMP Echo Reply * @param time_out in milliseconds * @throws SocketTimeoutException */ public PingResult pong(int time_out) throws SocketException, SocketTimeoutException { if (!_has_rawsockets) throw new SocketException("permission denied attempting to create raw socket!"); PingResult result = new PingResult(); if (!_pong(time_out, result)) { throw new java.net.SocketTimeoutException("receiving echo reply timeout after " + time_out); } return result; } /** closes the Java Ping utility free resources */ public void close() { synchronized (JavaPing.class) { if (__javaping_singleton != null) { end(); __javaping_singleton = null; } } } /** initialize our cpp code */ private native boolean begin(); /** native call for ping reply */ private native boolean _pong(int timeout, PingResult result); /** native call that will use ICMP.dll on windows */ private native boolean _pingpong(String address, int seq, int msg_size, int timeout, int ttl, PingResult result); /** free pinger resources */ public native void end(); public void ping_result(PingResult result) { if (result.type == ECHO_REPLY) { System.out.println("Reply from: " + result.from + " icmp_seq=" + result.seq + " bytes: " + result.bytes + " time=" + result.rtt + " TTL=" + result.ttl); } else if (result.type == DESTINATION_UNREACHABLE) { System.out.println("DESTINATION UNREACHABLE icmp_seq=" + result.seq); } else { System.out.println("unknown icmp packet received"); } } public static void main(String[] args) throws InterruptedException, UnknownHostException, SocketTimeoutException { if (args.length == 0) { System.out.println("usage: ping host [options]"); return; } String address = "127.0.0.1"; int count = 5; int size = 56; int delay = 1000; for (int i = 0; i < args.length; ++i) { if (args[i].compareToIgnoreCase("-c") == 0) { ++i; if (i < args.length) count = Integer.parseInt(args[i]); } else if (args[i].compareToIgnoreCase("-s") == 0) { ++i; if (i < args.length) size = Integer.parseInt(args[i]); } else if (args[i].compareToIgnoreCase("-d") == 0) { ++i; if (i < args.length) delay = Integer.parseInt(args[i]); } else { address = args[i]; } } System.out.println("count: " + count + " size: " + size + " delay: " + delay); address = InetAddress.getByName(address).getHostAddress(); JavaPing pingman; pingman = getInstance(); //pingman.startListening(pingman); //Thread.sleep(100); for (int i = 0; i < count; ++i) { pingman.ping_result(pingman.pingpong(address, i, size, 500)); Thread.sleep(delay); } if (pingman.receivedCount() < count) System.out.println("DID NOT RECEIVE REPLIES FOR SOME PACKETS!"); pingman.end(); } }<|fim▁end|>
import jsrl.LoadLibrary;
<|file_name|>package-info.java<|end_file_name|><|fim▁begin|>/* * Sonatype Nexus (TM) Open Source Version * Copyright (c) 2008-present Sonatype, Inc. * All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions. * * This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0, * which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html. * * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the * Eclipse Foundation. All other trademarks are the property of their respective owners. */<|fim▁hole|>package org.sonatype.nexus.repository.maven.internal.orient; import org.sonatype.nexus.common.app.FeatureFlag; import static org.sonatype.nexus.common.app.FeatureFlags.ORIENT_ENABLED;<|fim▁end|>
@FeatureFlag(name = ORIENT_ENABLED)
<|file_name|>core.py<|end_file_name|><|fim▁begin|>from abc import ABCMeta, abstractmethod, abstractproperty from contextlib import contextmanager from functools import wraps import gzip from inspect import getargspec from itertools import ( combinations, count, product, ) import operator import os from os.path import abspath, dirname, join, realpath import shutil from sys import _getframe import tempfile from logbook import TestHandler from mock import patch from nose.tools import nottest from numpy.testing import assert_allclose, assert_array_equal import pandas as pd from six import itervalues, iteritems, with_metaclass from six.moves import filter, map from sqlalchemy import create_engine from testfixtures import TempDirectory from toolz import concat, curry from zipline.assets import AssetFinder, AssetDBWriter from zipline.assets.synthetic import make_simple_equity_info from zipline.data.data_portal import DataPortal from zipline.data.loader import get_benchmark_filename, INDEX_MAPPING from zipline.data.minute_bars import ( BcolzMinuteBarReader, BcolzMinuteBarWriter, US_EQUITIES_MINUTES_PER_DAY ) from zipline.data.us_equity_pricing import ( BcolzDailyBarReader, BcolzDailyBarWriter, SQLiteAdjustmentWriter, ) from zipline.finance.blotter import Blotter from zipline.finance.trading import TradingEnvironment from zipline.finance.order import ORDER_STATUS from zipline.lib.labelarray import LabelArray from zipline.pipeline.data import USEquityPricing from zipline.pipeline.engine import SimplePipelineEngine from zipline.pipeline.factors import CustomFactor from zipline.pipeline.loaders.testing import make_seeded_random_loader from zipline.utils import security_list from zipline.utils.calendars import get_calendar from zipline.utils.input_validation import expect_dimensions from zipline.utils.numpy_utils import as_column, isnat from zipline.utils.pandas_utils import timedelta_to_integral_seconds from zipline.utils.paths import ensure_directory from zipline.utils.sentinel import sentinel import numpy as np from numpy import float64 EPOCH = pd.Timestamp(0, tz='UTC') def seconds_to_timestamp(seconds): return pd.Timestamp(seconds, unit='s', tz='UTC') def to_utc(time_str): """Convert a string in US/Eastern time to UTC""" return pd.Timestamp(time_str, tz='US/Eastern').tz_convert('UTC') def str_to_seconds(s): """ Convert a pandas-intelligible string to (integer) seconds since UTC. >>> from pandas import Timestamp >>> (Timestamp('2014-01-01') - Timestamp(0)).total_seconds() 1388534400.0 >>> str_to_seconds('2014-01-01') 1388534400 """ return timedelta_to_integral_seconds(pd.Timestamp(s, tz='UTC') - EPOCH) def drain_zipline(test, zipline): output = [] transaction_count = 0 msg_counter = 0 # start the simulation for update in zipline: msg_counter += 1 output.append(update) if 'daily_perf' in update: transaction_count += \ len(update['daily_perf']['transactions']) return output, transaction_count def check_algo_results(test, results, expected_transactions_count=None, expected_order_count=None, expected_positions_count=None, sid=None): if expected_transactions_count is not None: txns = flatten_list(results["transactions"]) test.assertEqual(expected_transactions_count, len(txns)) if expected_positions_count is not None: raise NotImplementedError if expected_order_count is not None: # de-dup orders on id, because orders are put back into perf packets # whenever they a txn is filled orders = set([order['id'] for order in flatten_list(results["orders"])]) test.assertEqual(expected_order_count, len(orders)) def flatten_list(list): return [item for sublist in list for item in sublist] def assert_single_position(test, zipline): output, transaction_count = drain_zipline(test, zipline) if 'expected_transactions' in test.zipline_test_config: test.assertEqual( test.zipline_test_config['expected_transactions'], transaction_count ) else: test.assertEqual( test.zipline_test_config['order_count'], transaction_count ) # the final message is the risk report, the second to # last is the final day's results. Positions is a list of # dicts. closing_positions = output[-2]['daily_perf']['positions'] # confirm that all orders were filled. # iterate over the output updates, overwriting # orders when they are updated. Then check the status on all. orders_by_id = {} for update in output: if 'daily_perf' in update: if 'orders' in update['daily_perf']: for order in update['daily_perf']['orders']: orders_by_id[order['id']] = order for order in itervalues(orders_by_id): test.assertEqual( order['status'], ORDER_STATUS.FILLED, "") test.assertEqual( len(closing_positions), 1, "Portfolio should have one position." ) sid = test.zipline_test_config['sid'] test.assertEqual( closing_positions[0]['sid'], sid, "Portfolio should have one position in " + str(sid) ) return output, transaction_count @contextmanager def security_list_copy(): old_dir = security_list.SECURITY_LISTS_DIR new_dir = tempfile.mkdtemp() try: for subdir in os.listdir(old_dir): shutil.copytree(os.path.join(old_dir, subdir), os.path.join(new_dir, subdir)) with patch.object(security_list, 'SECURITY_LISTS_DIR', new_dir), \ patch.object(security_list, 'using_copy', True, create=True): yield finally: shutil.rmtree(new_dir, True) def add_security_data(adds, deletes): if not hasattr(security_list, 'using_copy'): raise Exception('add_security_data must be used within ' 'security_list_copy context') directory = os.path.join( security_list.SECURITY_LISTS_DIR, "leveraged_etf_list/20150127/20150125" ) if not os.path.exists(directory): os.makedirs(directory) del_path = os.path.join(directory, "delete") with open(del_path, 'w') as f: for sym in deletes: f.write(sym) f.write('\n') add_path = os.path.join(directory, "add") with open(add_path, 'w') as f: for sym in adds: f.write(sym) f.write('\n') def all_pairs_matching_predicate(values, pred): """ Return an iterator of all pairs, (v0, v1) from values such that `pred(v0, v1) == True` Parameters ---------- values : iterable pred : function Returns ------- pairs_iterator : generator Generator yielding pairs matching `pred`. Examples -------- >>> from zipline.testing import all_pairs_matching_predicate >>> from operator import eq, lt >>> list(all_pairs_matching_predicate(range(5), eq)) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] >>> list(all_pairs_matching_predicate("abcd", lt)) [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')] """ return filter(lambda pair: pred(*pair), product(values, repeat=2)) def product_upper_triangle(values, include_diagonal=False): """ Return an iterator over pairs, (v0, v1), drawn from values. If `include_diagonal` is True, returns all pairs such that v0 <= v1. If `include_diagonal` is False, returns all pairs such that v0 < v1. """ return all_pairs_matching_predicate( values, operator.le if include_diagonal else operator.lt, ) def all_subindices(index): """ Return all valid sub-indices of a pandas Index. """ return ( index[start:stop] for start, stop in product_upper_triangle(range(len(index) + 1)) ) def chrange(start, stop): """ Construct an iterable of length-1 strings beginning with `start` and ending with `stop`. Parameters ---------- start : str The first character. stop : str The last character. Returns ------- chars: iterable[str] Iterable of strings beginning with start and ending with stop. Examples -------- >>> chrange('A', 'C') ['A', 'B', 'C'] """ return list(map(chr, range(ord(start), ord(stop) + 1))) def make_trade_data_for_asset_info(dates, asset_info, price_start, price_step_by_date, price_step_by_sid, volume_start, volume_step_by_date, volume_step_by_sid, frequency, writer=None): """ Convert the asset info dataframe into a dataframe of trade data for each sid, and write to the writer if provided. Write NaNs for locations where assets did not exist. Return a dict of the dataframes, keyed by sid. """ trade_data = {} sids = asset_info.index price_sid_deltas = np.arange(len(sids), dtype=float64) * price_step_by_sid price_date_deltas = (np.arange(len(dates), dtype=float64) * price_step_by_date) prices = (price_sid_deltas + as_column(price_date_deltas)) + price_start volume_sid_deltas = np.arange(len(sids)) * volume_step_by_sid volume_date_deltas = np.arange(len(dates)) * volume_step_by_date volumes = volume_sid_deltas + as_column(volume_date_deltas) + volume_start for j, sid in enumerate(sids): start_date, end_date = asset_info.loc[sid, ['start_date', 'end_date']] # Normalize here so the we still generate non-NaN values on the minutes # for an asset's last trading day. for i, date in enumerate(dates.normalize()): if not (start_date <= date <= end_date): prices[i, j] = 0 volumes[i, j] = 0 df = pd.DataFrame( { "open": prices[:, j], "high": prices[:, j], "low": prices[:, j], "close": prices[:, j], "volume": volumes[:, j], }, index=dates, ) if writer: writer.write_sid(sid, df) trade_data[sid] = df return trade_data def check_allclose(actual, desired, rtol=1e-07, atol=0, err_msg='', verbose=True): """ Wrapper around np.testing.assert_allclose that also verifies that inputs are ndarrays. See Also -------- np.assert_allclose """ if type(actual) != type(desired): raise AssertionError("%s != %s" % (type(actual), type(desired))) return assert_allclose( actual, desired, atol=atol, rtol=rtol, err_msg=err_msg, verbose=verbose, ) def check_arrays(x, y, err_msg='', verbose=True, check_dtypes=True): """ Wrapper around np.testing.assert_array_equal that also verifies that inputs are ndarrays. See Also -------- np.assert_array_equal """ assert type(x) == type(y), "{x} != {y}".format(x=type(x), y=type(y)) assert x.dtype == y.dtype, "{x.dtype} != {y.dtype}".format(x=x, y=y) if isinstance(x, LabelArray): # Check that both arrays have missing values in the same locations... assert_array_equal( x.is_missing(), y.is_missing(), err_msg=err_msg, verbose=verbose, ) # ...then check the actual values as well. x = x.as_string_array() y = y.as_string_array() elif x.dtype.kind in 'mM': x_isnat = isnat(x) y_isnat = isnat(y) assert_array_equal( x_isnat, y_isnat, err_msg="NaTs not equal", verbose=verbose, ) # Fill NaTs with zero for comparison. x = np.where(x_isnat, np.zeros_like(x), x) y = np.where(y_isnat, np.zeros_like(y), y) return assert_array_equal(x, y, err_msg=err_msg, verbose=verbose) class UnexpectedAttributeAccess(Exception): pass class ExplodingObject(object): """ Object that will raise an exception on any attribute access. Useful for verifying that an object is never touched during a function/method call. """ def __getattribute__(self, name): raise UnexpectedAttributeAccess(name) def write_minute_data(trading_calendar, tempdir, minutes, sids): first_session = trading_calendar.minute_to_session_label( minutes[0], direction="none" ) last_session = trading_calendar.minute_to_session_label( minutes[-1], direction="none" ) sessions = trading_calendar.sessions_in_range(first_session, last_session) write_bcolz_minute_data( trading_calendar, sessions, tempdir.path, create_minute_bar_data(minutes, sids), ) return tempdir.path def create_minute_bar_data(minutes, sids): length = len(minutes) for sid_idx, sid in enumerate(sids): yield sid, pd.DataFrame( { 'open': np.arange(length) + 10 + sid_idx, 'high': np.arange(length) + 15 + sid_idx, 'low': np.arange(length) + 8 + sid_idx, 'close': np.arange(length) + 10 + sid_idx, 'volume': 100 + sid_idx, }, index=minutes, ) def create_daily_bar_data(sessions, sids): length = len(sessions) for sid_idx, sid in enumerate(sids): yield sid, pd.DataFrame( { "open": (np.array(range(10, 10 + length)) + sid_idx), "high": (np.array(range(15, 15 + length)) + sid_idx), "low": (np.array(range(8, 8 + length)) + sid_idx), "close": (np.array(range(10, 10 + length)) + sid_idx), "volume": np.array(range(100, 100 + length)) + sid_idx, "day": [session.value for session in sessions] }, index=sessions, ) def write_daily_data(tempdir, sim_params, sids, trading_calendar): path = os.path.join(tempdir.path, "testdaily.bcolz") BcolzDailyBarWriter(path, trading_calendar, sim_params.start_session, sim_params.end_session).write( create_daily_bar_data(sim_params.sessions, sids), ) return path def create_data_portal(asset_finder, tempdir, sim_params, sids, trading_calendar, adjustment_reader=None): if sim_params.data_frequency == "daily": daily_path = write_daily_data(tempdir, sim_params, sids, trading_calendar) equity_daily_reader = BcolzDailyBarReader(daily_path) return DataPortal( asset_finder, trading_calendar, first_trading_day=equity_daily_reader.first_trading_day, equity_daily_reader=equity_daily_reader, adjustment_reader=adjustment_reader ) else: minutes = trading_calendar.minutes_in_range( sim_params.first_open, sim_params.last_close ) minute_path = write_minute_data(trading_calendar, tempdir, minutes, sids) equity_minute_reader = BcolzMinuteBarReader(minute_path) return DataPortal( asset_finder, trading_calendar, first_trading_day=equity_minute_reader.first_trading_day, equity_minute_reader=equity_minute_reader, adjustment_reader=adjustment_reader ) def write_bcolz_minute_data(trading_calendar, days, path, data): BcolzMinuteBarWriter( path, trading_calendar, days[0], days[-1], US_EQUITIES_MINUTES_PER_DAY ).write(data) def create_minute_df_for_asset(trading_calendar, start_dt, end_dt, interval=1, start_val=1, minute_blacklist=None): asset_minutes = trading_calendar.minutes_for_sessions_in_range( start_dt, end_dt ) minutes_count = len(asset_minutes) minutes_arr = np.array(range(start_val, start_val + minutes_count)) df = pd.DataFrame( { "open": minutes_arr + 1, "high": minutes_arr + 2, "low": minutes_arr - 1, "close": minutes_arr, "volume": 100 * minutes_arr, }, index=asset_minutes, ) if interval > 1: counter = 0 while counter < len(minutes_arr): df[counter:(counter + interval - 1)] = 0 counter += interval if minute_blacklist is not None: for minute in minute_blacklist: df.loc[minute] = 0 return df def create_daily_df_for_asset(trading_calendar, start_day, end_day, interval=1): days = trading_calendar.sessions_in_range(start_day, end_day) days_count = len(days) days_arr = np.arange(days_count) + 2 df = pd.DataFrame( { "open": days_arr + 1, "high": days_arr + 2, "low": days_arr - 1, "close": days_arr, "volume": days_arr * 100, }, index=days, ) if interval > 1: # only keep every 'interval' rows for idx, _ in enumerate(days_arr): if (idx + 1) % interval != 0: df["open"].iloc[idx] = 0 df["high"].iloc[idx] = 0 df["low"].iloc[idx] = 0 df["close"].iloc[idx] = 0 df["volume"].iloc[idx] = 0 return df def trades_by_sid_to_dfs(trades_by_sid, index): for sidint, trades in iteritems(trades_by_sid): opens = [] highs = [] lows = [] closes = [] volumes = [] for trade in trades: opens.append(trade.open_price) highs.append(trade.high) lows.append(trade.low) closes.append(trade.close_price) volumes.append(trade.volume) yield sidint, pd.DataFrame( { "open": opens, "high": highs, "low": lows, "close": closes, "volume": volumes, }, index=index, ) def create_data_portal_from_trade_history(asset_finder, trading_calendar, tempdir, sim_params, trades_by_sid): if sim_params.data_frequency == "daily": path = os.path.join(tempdir.path, "testdaily.bcolz") writer = BcolzDailyBarWriter( path, trading_calendar, sim_params.start_session, sim_params.end_session ) writer.write( trades_by_sid_to_dfs(trades_by_sid, sim_params.sessions), ) equity_daily_reader = BcolzDailyBarReader(path) return DataPortal( asset_finder, trading_calendar, first_trading_day=equity_daily_reader.first_trading_day, equity_daily_reader=equity_daily_reader, ) else: minutes = trading_calendar.minutes_in_range( sim_params.first_open, sim_params.last_close ) length = len(minutes) assets = {} for sidint, trades in iteritems(trades_by_sid): opens = np.zeros(length) highs = np.zeros(length) lows = np.zeros(length) closes = np.zeros(length) volumes = np.zeros(length) for trade in trades: # put them in the right place idx = minutes.searchsorted(trade.dt) opens[idx] = trade.open_price * 1000 highs[idx] = trade.high * 1000 lows[idx] = trade.low * 1000 closes[idx] = trade.close_price * 1000 volumes[idx] = trade.volume assets[sidint] = pd.DataFrame({ "open": opens, "high": highs, "low": lows, "close": closes, "volume": volumes, "dt": minutes }).set_index("dt") write_bcolz_minute_data( trading_calendar, sim_params.sessions, tempdir.path, assets ) equity_minute_reader = BcolzMinuteBarReader(tempdir.path) return DataPortal( asset_finder, trading_calendar, first_trading_day=equity_minute_reader.first_trading_day, equity_minute_reader=equity_minute_reader, ) class FakeDataPortal(DataPortal): def __init__(self, env, trading_calendar=None, first_trading_day=None): if trading_calendar is None: trading_calendar = get_calendar("NYSE") super(FakeDataPortal, self).__init__(env.asset_finder, trading_calendar, first_trading_day) def get_spot_value(self, asset, field, dt, data_frequency): if field == "volume": return 100 else: return 1.0 def get_history_window(self, assets, end_dt, bar_count, frequency, field, data_frequency, ffill=True): if frequency == "1d": end_idx = \ self.trading_calendar.all_sessions.searchsorted(end_dt) days = self.trading_calendar.all_sessions[ (end_idx - bar_count + 1):(end_idx + 1) ] df = pd.DataFrame( np.full((bar_count, len(assets)), 100.0), index=days, columns=assets ) return df class FetcherDataPortal(DataPortal): """ Mock dataportal that returns fake data for history and non-fetcher spot value. """ def __init__(self, asset_finder, trading_calendar, first_trading_day=None): super(FetcherDataPortal, self).__init__(asset_finder, trading_calendar, first_trading_day) def get_spot_value(self, asset, field, dt, data_frequency): # if this is a fetcher field, exercise the regular code path if self._is_extra_source(asset, field, self._augmented_sources_map): return super(FetcherDataPortal, self).get_spot_value( asset, field, dt, data_frequency) # otherwise just return a fixed value return int(asset) # XXX: These aren't actually the methods that are used by the superclasses, # so these don't do anything, and this class will likely produce unexpected # results for history(). def _get_daily_window_for_sid(self, asset, field, days_in_window, extra_slot=True): return np.arange(days_in_window, dtype=np.float64) def _get_minute_window_for_asset(self, asset, field, minutes_for_window): return np.arange(minutes_for_window, dtype=np.float64) class tmp_assets_db(object): """Create a temporary assets sqlite database. This is meant to be used as a context manager. Parameters ---------- url : string The URL for the database connection. **frames The frames to pass to the AssetDBWriter. By default this maps equities: ('A', 'B', 'C') -> map(ord, 'ABC') See Also -------- empty_assets_db tmp_asset_finder """ _default_equities = sentinel('_default_equities') def __init__(self, url='sqlite:///:memory:', equities=_default_equities, **frames): self._url = url self._eng = None if equities is self._default_equities: equities = make_simple_equity_info( list(map(ord, 'ABC')), pd.Timestamp(0), pd.Timestamp('2015'), ) frames['equities'] = equities self._frames = frames self._eng = None # set in enter and exit def __enter__(self): self._eng = eng = create_engine(self._url) AssetDBWriter(eng).write(**self._frames) return eng def __exit__(self, *excinfo): assert self._eng is not None, '_eng was not set in __enter__' self._eng.dispose() self._eng = None def empty_assets_db(): """Context manager for creating an empty assets db. See Also -------- tmp_assets_db """ return tmp_assets_db(equities=None) class tmp_asset_finder(tmp_assets_db): """Create a temporary asset finder using an in memory sqlite db. Parameters ---------- url : string The URL for the database connection. finder_cls : type, optional The type of asset finder to create from the assets db. **frames Forwarded to ``tmp_assets_db``. See Also -------- tmp_assets_db """ def __init__(self, url='sqlite:///:memory:', finder_cls=AssetFinder, **frames): self._finder_cls = finder_cls super(tmp_asset_finder, self).__init__(url=url, **frames) def __enter__(self): return self._finder_cls(super(tmp_asset_finder, self).__enter__()) def empty_asset_finder(): """Context manager for creating an empty asset finder. See Also -------- empty_assets_db tmp_assets_db tmp_asset_finder """ return tmp_asset_finder(equities=None) class tmp_trading_env(tmp_asset_finder): """Create a temporary trading environment. Parameters ---------- load : callable, optional Function that returns benchmark returns and treasury curves. finder_cls : type, optional The type of asset finder to create from the assets db. **frames Forwarded to ``tmp_assets_db``. See Also -------- empty_trading_env tmp_asset_finder """ def __init__(self, load=None, *args, **kwargs): super(tmp_trading_env, self).__init__(*args, **kwargs) self._load = load def __enter__(self): return TradingEnvironment( load=self._load, asset_db_path=super(tmp_trading_env, self).__enter__().engine, ) def empty_trading_env(): return tmp_trading_env(equities=None) class SubTestFailures(AssertionError): def __init__(self, *failures): self.failures = failures def __str__(self): return 'failures:\n %s' % '\n '.join( '\n '.join(( ', '.join('%s=%r' % item for item in scope.items()), '%s: %s' % (type(exc).__name__, exc), )) for scope, exc in self.failures, ) @nottest def subtest(iterator, *_names): """ Construct a subtest in a unittest. Consider using ``zipline.testing.parameter_space`` when subtests are constructed over a single input or over the cross-product of multiple inputs. ``subtest`` works by decorating a function as a subtest. The decorated function will be run by iterating over the ``iterator`` and *unpacking the values into the function. If any of the runs fail, the result will be put into a set and the rest of the tests will be run. Finally, if any failed, all of the results will be dumped as one failure. Parameters ---------- iterator : iterable[iterable] The iterator of arguments to pass to the function. *name : iterator[str] The names to use for each element of ``iterator``. These will be used to print the scope when a test fails. If not provided, it will use the integer index of the value as the name. Examples -------- :: class MyTest(TestCase): def test_thing(self): # Example usage inside another test. @subtest(([n] for n in range(100000)), 'n') def subtest(n): self.assertEqual(n % 2, 0, 'n was not even') subtest() @subtest(([n] for n in range(100000)), 'n') def test_decorated_function(self, n): # Example usage to parameterize an entire function. self.assertEqual(n % 2, 1, 'n was not odd') Notes ----- We use this when we: * Will never want to run each parameter individually. * Have a large parameter space we are testing (see tests/utils/test_events.py). ``nose_parameterized.expand`` will create a test for each parameter combination which bloats the test output and makes the travis pages slow. We cannot use ``unittest2.TestCase.subTest`` because nose, pytest, and nose2 do not support ``addSubTest``. See Also -------- zipline.testing.parameter_space """ def dec(f): @wraps(f) def wrapped(*args, **kwargs): names = _names failures = [] for scope in iterator: scope = tuple(scope) try: f(*args + scope, **kwargs) except Exception as e: if not names: names = count() failures.append((dict(zip(names, scope)), e)) if failures: raise SubTestFailures(*failures) return wrapped return dec class MockDailyBarReader(object): def get_value(self, col, sid, dt): return 100 def create_mock_adjustment_data(splits=None, dividends=None, mergers=None): if splits is None: splits = create_empty_splits_mergers_frame() elif not isinstance(splits, pd.DataFrame): splits = pd.DataFrame(splits) if mergers is None: mergers = create_empty_splits_mergers_frame() elif not isinstance(mergers, pd.DataFrame): mergers = pd.DataFrame(mergers) if dividends is None: dividends = create_empty_dividends_frame() elif not isinstance(dividends, pd.DataFrame): dividends = pd.DataFrame(dividends) return splits, mergers, dividends def create_mock_adjustments(tempdir, days, splits=None, dividends=None, mergers=None): path = tempdir.getpath("test_adjustments.db") SQLiteAdjustmentWriter(path, MockDailyBarReader(), days).write( *create_mock_adjustment_data(splits, dividends, mergers) ) return path <|fim▁hole|> """ Assert that two pandas Timestamp objects are the same. Parameters ---------- left, right : pd.Timestamp The values to compare. compare_nat_equal : bool, optional Whether to consider `NaT` values equal. Defaults to True. msg : str, optional A message to forward to `pd.util.testing.assert_equal`. """ if compare_nat_equal and left is pd.NaT and right is pd.NaT: return return pd.util.testing.assert_equal(left, right, msg=msg) def powerset(values): """ Return the power set (i.e., the set of all subsets) of entries in `values`. """ return concat(combinations(values, i) for i in range(len(values) + 1)) def to_series(knowledge_dates, earning_dates): """ Helper for converting a dict of strings to a Series of datetimes. This is just for making the test cases more readable. """ return pd.Series( index=pd.to_datetime(knowledge_dates), data=pd.to_datetime(earning_dates), ) def gen_calendars(start, stop, critical_dates): """ Generate calendars to use as inputs. """ all_dates = pd.date_range(start, stop, tz='utc') for to_drop in map(list, powerset(critical_dates)): # Have to yield tuples. yield (all_dates.drop(to_drop),) # Also test with the trading calendar. trading_days = get_calendar("NYSE").all_days yield (trading_days[trading_days.slice_indexer(start, stop)],) @contextmanager def temp_pipeline_engine(calendar, sids, random_seed, symbols=None): """ A contextManager that yields a SimplePipelineEngine holding a reference to an AssetFinder generated via tmp_asset_finder. Parameters ---------- calendar : pd.DatetimeIndex Calendar to pass to the constructed PipelineEngine. sids : iterable[int] Sids to use for the temp asset finder. random_seed : int Integer used to seed instances of SeededRandomLoader. symbols : iterable[str], optional Symbols for constructed assets. Forwarded to make_simple_equity_info. """ equity_info = make_simple_equity_info( sids=sids, start_date=calendar[0], end_date=calendar[-1], symbols=symbols, ) loader = make_seeded_random_loader(random_seed, calendar, sids) def get_loader(column): return loader with tmp_asset_finder(equities=equity_info) as finder: yield SimplePipelineEngine(get_loader, calendar, finder) def parameter_space(__fail_fast=False, **params): """ Wrapper around subtest that allows passing keywords mapping names to iterables of values. The decorated test function will be called with the cross-product of all possible inputs Examples -------- >>> from unittest import TestCase >>> class SomeTestCase(TestCase): ... @parameter_space(x=[1, 2], y=[2, 3]) ... def test_some_func(self, x, y): ... # Will be called with every possible combination of x and y. ... self.assertEqual(somefunc(x, y), expected_result(x, y)) See Also -------- zipline.testing.subtest """ def decorator(f): argspec = getargspec(f) if argspec.varargs: raise AssertionError("parameter_space() doesn't support *args") if argspec.keywords: raise AssertionError("parameter_space() doesn't support **kwargs") if argspec.defaults: raise AssertionError("parameter_space() doesn't support defaults.") # Skip over implicit self. argnames = argspec.args if argnames[0] == 'self': argnames = argnames[1:] extra = set(params) - set(argnames) if extra: raise AssertionError( "Keywords %s supplied to parameter_space() are " "not in function signature." % extra ) unspecified = set(argnames) - set(params) if unspecified: raise AssertionError( "Function arguments %s were not " "supplied to parameter_space()." % extra ) def make_param_sets(): return product(*(params[name] for name in argnames)) if __fail_fast: @wraps(f) def wrapped(self): for args in make_param_sets(): f(self, *args) return wrapped else: @wraps(f) def wrapped(*args, **kwargs): subtest(make_param_sets(), *argnames)(f)(*args, **kwargs) return wrapped return decorator def create_empty_dividends_frame(): return pd.DataFrame( np.array( [], dtype=[ ('ex_date', 'datetime64[ns]'), ('pay_date', 'datetime64[ns]'), ('record_date', 'datetime64[ns]'), ('declared_date', 'datetime64[ns]'), ('amount', 'float64'), ('sid', 'int32'), ], ), index=pd.DatetimeIndex([], tz='UTC'), ) def create_empty_splits_mergers_frame(): return pd.DataFrame( np.array( [], dtype=[ ('effective_date', 'int64'), ('ratio', 'float64'), ('sid', 'int64'), ], ), index=pd.DatetimeIndex([]), ) def make_alternating_boolean_array(shape, first_value=True): """ Create a 2D numpy array with the given shape containing alternating values of False, True, False, True,... along each row and each column. Examples -------- >>> make_alternating_boolean_array((4,4)) array([[ True, False, True, False], [False, True, False, True], [ True, False, True, False], [False, True, False, True]], dtype=bool) >>> make_alternating_boolean_array((4,3), first_value=False) array([[False, True, False], [ True, False, True], [False, True, False], [ True, False, True]], dtype=bool) """ if len(shape) != 2: raise ValueError( 'Shape must be 2-dimensional. Given shape was {}'.format(shape) ) alternating = np.empty(shape, dtype=np.bool) for row in alternating: row[::2] = first_value row[1::2] = not(first_value) first_value = not(first_value) return alternating def make_cascading_boolean_array(shape, first_value=True): """ Create a numpy array with the given shape containing cascading boolean values, with `first_value` being the top-left value. Examples -------- >>> make_cascading_boolean_array((4,4)) array([[ True, True, True, False], [ True, True, False, False], [ True, False, False, False], [False, False, False, False]], dtype=bool) >>> make_cascading_boolean_array((4,2)) array([[ True, False], [False, False], [False, False], [False, False]], dtype=bool) >>> make_cascading_boolean_array((2,4)) array([[ True, True, True, False], [ True, True, False, False]], dtype=bool) """ if len(shape) != 2: raise ValueError( 'Shape must be 2-dimensional. Given shape was {}'.format(shape) ) cascading = np.full(shape, not(first_value), dtype=np.bool) ending_col = shape[1] - 1 for row in cascading: if ending_col > 0: row[:ending_col] = first_value ending_col -= 1 else: break return cascading @expect_dimensions(array=2) def permute_rows(seed, array): """ Shuffle each row in ``array`` based on permutations generated by ``seed``. Parameters ---------- seed : int Seed for numpy.RandomState array : np.ndarray[ndim=2] Array over which to apply permutations. """ rand = np.random.RandomState(seed) return np.apply_along_axis(rand.permutation, 1, array) @nottest def make_test_handler(testcase, *args, **kwargs): """ Returns a TestHandler which will be used by the given testcase. This handler can be used to test log messages. Parameters ---------- testcase: unittest.TestCase The test class in which the log handler will be used. *args, **kwargs Forwarded to the new TestHandler object. Returns ------- handler: logbook.TestHandler The handler to use for the test case. """ handler = TestHandler(*args, **kwargs) testcase.addCleanup(handler.close) return handler def write_compressed(path, content): """ Write a compressed (gzipped) file to `path`. """ with gzip.open(path, 'wb') as f: f.write(content) def read_compressed(path): """ Write a compressed (gzipped) file from `path`. """ with gzip.open(path, 'rb') as f: return f.read() zipline_git_root = abspath( join(realpath(dirname(__file__)), '..', '..'), ) @nottest def test_resource_path(*path_parts): return os.path.join(zipline_git_root, 'tests', 'resources', *path_parts) @contextmanager def patch_os_environment(remove=None, **values): """ Context manager for patching the operating system environment. """ old_values = {} remove = remove or [] for key in remove: old_values[key] = os.environ.pop(key) for key, value in values.iteritems(): old_values[key] = os.getenv(key) os.environ[key] = value try: yield finally: for old_key, old_value in old_values.iteritems(): if old_value is None: # Value was not present when we entered, so del it out if it's # still present. try: del os.environ[key] except KeyError: pass else: # Restore the old value. os.environ[old_key] = old_value class tmp_dir(TempDirectory, object): """New style class that wrapper for TempDirectory in python 2. """ pass class _TmpBarReader(with_metaclass(ABCMeta, tmp_dir)): """A helper for tmp_bcolz_equity_minute_bar_reader and tmp_bcolz_equity_daily_bar_reader. Parameters ---------- env : TradingEnvironment The trading env. days : pd.DatetimeIndex The days to write for. data : dict[int -> pd.DataFrame] The data to write. path : str, optional The path to the directory to write the data into. If not given, this will be a unique name. """ @abstractproperty def _reader_cls(self): raise NotImplementedError('_reader') @abstractmethod def _write(self, env, days, path, data): raise NotImplementedError('_write') def __init__(self, env, days, data, path=None): super(_TmpBarReader, self).__init__(path=path) self._env = env self._days = days self._data = data def __enter__(self): tmpdir = super(_TmpBarReader, self).__enter__() env = self._env try: self._write( env, self._days, tmpdir.path, self._data, ) return self._reader_cls(tmpdir.path) except: self.__exit__(None, None, None) raise class tmp_bcolz_equity_minute_bar_reader(_TmpBarReader): """A temporary BcolzMinuteBarReader object. Parameters ---------- env : TradingEnvironment The trading env. days : pd.DatetimeIndex The days to write for. data : iterable[(int, pd.DataFrame)] The data to write. path : str, optional The path to the directory to write the data into. If not given, this will be a unique name. See Also -------- tmp_bcolz_equity_daily_bar_reader """ _reader_cls = BcolzMinuteBarReader _write = staticmethod(write_bcolz_minute_data) class tmp_bcolz_equity_daily_bar_reader(_TmpBarReader): """A temporary BcolzDailyBarReader object. Parameters ---------- env : TradingEnvironment The trading env. days : pd.DatetimeIndex The days to write for. data : dict[int -> pd.DataFrame] The data to write. path : str, optional The path to the directory to write the data into. If not given, this will be a unique name. See Also -------- tmp_bcolz_equity_daily_bar_reader """ _reader_cls = BcolzDailyBarReader @staticmethod def _write(env, days, path, data): BcolzDailyBarWriter(path, days).write(data) @contextmanager def patch_read_csv(url_map, module=pd, strict=False): """Patch pandas.read_csv to map lookups from url to another. Parameters ---------- url_map : mapping[str or file-like object -> str or file-like object] The mapping to use to redirect read_csv calls. module : module, optional The module to patch ``read_csv`` on. By default this is ``pandas``. This should be set to another module if ``read_csv`` is early-bound like ``from pandas import read_csv`` instead of late-bound like: ``import pandas as pd; pd.read_csv``. strict : bool, optional If true, then this will assert that ``read_csv`` is only called with elements in the ``url_map``. """ read_csv = pd.read_csv def patched_read_csv(filepath_or_buffer, *args, **kwargs): if filepath_or_buffer in url_map: return read_csv(url_map[filepath_or_buffer], *args, **kwargs) elif not strict: return read_csv(filepath_or_buffer, *args, **kwargs) else: raise AssertionError( 'attempted to call read_csv on %r which not in the url map' % filepath_or_buffer, ) with patch.object(module, 'read_csv', patched_read_csv): yield def copy_market_data(src_market_data_dir, dest_root_dir): symbol = 'SPY' filenames = (get_benchmark_filename(symbol), INDEX_MAPPING[symbol][1]) ensure_directory(os.path.join(dest_root_dir, 'data')) for filename in filenames: shutil.copyfile( os.path.join(src_market_data_dir, filename), os.path.join(dest_root_dir, 'data', filename) ) @curry def ensure_doctest(f, name=None): """Ensure that an object gets doctested. This is useful for instances of objects like curry or partial which are not discovered by default. Parameters ---------- f : any The thing to doctest. name : str, optional The name to use in the doctest function mapping. If this is None, Then ``f.__name__`` will be used. Returns ------- f : any ``f`` unchanged. """ _getframe(2).f_globals.setdefault('__test__', {})[ f.__name__ if name is None else name ] = f return f class RecordBatchBlotter(Blotter): """Blotter that tracks how its batch_order method was called. """ def __init__(self, data_frequency): super(RecordBatchBlotter, self).__init__(data_frequency) self.order_batch_called = [] def batch_order(self, *args, **kwargs): self.order_batch_called.append((args, kwargs)) return super(RecordBatchBlotter, self).batch_order(*args, **kwargs) #################################### # Shared factors for pipeline tests. #################################### class AssetID(CustomFactor): """ CustomFactor that returns the AssetID of each asset. Useful for providing a Factor that produces a different value for each asset. """ window_length = 1 inputs = () def compute(self, today, assets, out): out[:] = assets class AssetIDPlusDay(CustomFactor): window_length = 1 inputs = () def compute(self, today, assets, out): out[:] = assets + today.day class OpenPrice(CustomFactor): window_length = 1 inputs = [USEquityPricing.open] def compute(self, today, assets, out, open): out[:] = open<|fim▁end|>
def assert_timestamp_equal(left, right, compare_nat_equal=True, msg=""):
<|file_name|>npc.py<|end_file_name|><|fim▁begin|># This file is part of PARPG. # PARPG 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. # PARPG 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 PARPG. If not, see <http://www.gnu.org/licenses/>. from random import randrange from fife import fife import base from moving import MovingAgentBehaviour class NPCBehaviour(MovingAgentBehaviour): """This is a basic NPC behaviour""" def __init__(self, parent=None): super(NPCBehaviour, self).__init__() self.parent = parent self.state = base._AGENT_STATE_NONE self.pc = None self.target_loc = None # hard code these for now self.distRange = (2, 4) # these are parameters to lower the rate of wandering # wander rate is the number of "IDLEs" before a wander step # this could be set for individual NPCs at load time # or thrown out altogether. # HACK: 09.Oct.2011 Beliar # I increased the wander rate to 900 since the idle method # gets called way more often now. self.wanderCounter = 0 self.wanderRate = 9 def getTargetLocation(self): """@rtype: fife.Location @return: NPC's position""" x = self.getX() y = self.getY() if self.state == base._AGENT_STATE_WANDER: """ Random Target Location """ l = [0, 0] for i in range(len(l)): sign = randrange(0, 2) dist = randrange(self.distRange[0], self.distRange[1]) if sign == 0: dist *= -1 l[i] = dist x += l[0] y += l[1] # Random walk is # rl = randint(-1, 1);ud = randint(-1, 1);x += rl;y += ud l = fife.Location(self.agent.getLocation()) l.setLayerCoordinates(fife.ModelCoordinate(x, y)) return l <|fim▁hole|> @param instance: self.agent @type action: ??? @param action: ??? @return: None""" if self.state == base._AGENT_STATE_WANDER: self.target_loc = self.getTargetLocation() MovingAgentBehaviour.onInstanceActionFinished(self, instance, action) def idle(self): """Controls the NPC when it is idling. Different actions based on the NPC's state. @return: None""" if self.state == base._AGENT_STATE_NONE: self.state = base._AGENT_STATE_IDLE self.animate('stand') elif self.state == base._AGENT_STATE_IDLE: if self.wanderCounter > self.wanderRate: self.wanderCounter = 0 self.state = base._AGENT_STATE_WANDER else: self.wanderCounter += 1 self.state = base._AGENT_STATE_NONE self.target_loc = self.getTargetLocation() self.animate('stand') elif self.state == base._AGENT_STATE_WANDER: self.wander(self.target_loc) self.state = base._AGENT_STATE_NONE elif self.state == base._AGENT_STATE_TALK: self.animate('stand', self.pc.getLocation()) def wander(self, location): """Nice slow movement for random walking. @type location: fife.Location @param location: Where the NPC will walk to. @return: None""" self.agent.move('walk', location, self.speed) coords = location.getMapCoordinates()<|fim▁end|>
def onInstanceActionFinished(self, instance, action): """What the NPC does when it has finished an action. Called by the engine and required for InstanceActionListeners. @type instance: fife.Instance
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>#![crate_type = "dylib"] #[macro_export] macro_rules! world { ($space:ident ($param:ty), $($name:ident : $component:ty,)*) => { /// A collection of pointers to components #[derive(Clone, Debug, Eq, PartialEq)] pub struct Entity { $( pub $name: Option<$space::Id<$component>>, )* } impl Entity { pub fn new() -> Entity { Entity { $( $name: None, )* } } } /// A collection of component arrays pub struct Components { $( pub $name: $space::Array<$component>, )* } /// Component add_to() wrapper pub struct Adder<'d> { pub entity: Entity, data: &'d mut Components, } impl<'d> Adder<'d> { $( pub fn $name(mut self, value: $component) -> Adder<'d> { debug_assert!(self.entity.$name.is_none()); let id = self.data.$name.add(value); self.entity.$name = Some(id); self } )* } impl Components { pub fn new() -> Components { Components { $( $name: $space::Array::new(), )* } } pub fn add<'d>(&'d mut self) -> Adder<'d> { Adder {entity: Entity::new(), data: self,} } } /// A system responsible for some aspect (physics, rendering, etc) pub trait System: Send { fn process(&mut self, &mut $param, &mut Components, &mut Vec<Entity>); } /// A top level union of entities, their data, and systems pub struct World { pub data: Components, pub entities: Vec<Entity>, pub systems: Vec<Box<System>>, } impl World { pub fn new() -> World { World { data: Components::new(), entities: Vec::new(),<|fim▁hole|> pub fn add_system<S: System + 'static>(&mut self, system: S) { self.systems.push(Box::new(system)); } pub fn update(&mut self, param: &mut $param) { for sys in self.systems.iter_mut() { sys.process(param, &mut self.data, &mut self.entities); } } } } }<|fim▁end|>
systems: Vec::new(), } }
<|file_name|>callback.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python3 """Callback a callable asset.""" import struct import decimal D = decimal.Decimal from . import (util, config, exceptions, litecoin, util) from . import order FORMAT = '>dQ' LENGTH = 8 + 8 ID = 21 def validate (db, source, fraction, asset, block_time, block_index, parse): cursor = db.cursor() problems = [] # TODO if not config.TESTNET: problems.append('callbacks are currently disabled on mainnet') return None, None, None, problems # TODO if fraction > 1: problems.append('fraction greater than one') elif fraction <= 0: problems.append('non‐positive fraction') issuances = list(cursor.execute('''SELECT * FROM issuances WHERE (status = ? AND asset = ?)''', ('valid', asset))) if not issuances: problems.append('no such asset, {}.'.format(asset)) return None, None, None, problems else: last_issuance = issuances[-1] if last_issuance['issuer'] != source:<|fim▁hole|> if not last_issuance['callable']: problems.append('uncallable asset') return None, None, None, problems elif last_issuance['call_date'] > block_time: problems.append('before call date') call_price = round(last_issuance['call_price'], 6) # TODO: arbitrary divisible = last_issuance['divisible'] if not divisible: # Pay per output unit. call_price *= config.UNIT # If parsing, unescrow all funds of asset. (Order of operations is # important here.) if parse: # Cancel pending order matches involving asset. cursor.execute('''SELECT * from order_matches \ WHERE status = ? AND (forward_asset = ? OR backward_asset = ?)''', ('pending', asset, asset)) for order_match in list(cursor): order.cancel_order_match(db, order_match, 'cancelled', block_index) # Cancel open orders involving asset. cursor.execute('''SELECT * from orders \ WHERE status = ? AND (give_asset = ? OR get_asset = ?)''', ('open', asset, asset)) for order_element in list(cursor): order.cancel_order(db, order_element, 'cancelled', block_index) # Calculate callback quantities. holders = util.holders(db, asset) outputs = [] for holder in holders: # If composing (and not parsing), predict funds to be returned from # escrow (instead of cancelling open offers, etc.), by *not* skipping # listing escrowed funds here. if parse and holder['escrow']: continue address = holder['address'] address_quantity = holder['address_quantity'] if address == source or address_quantity == 0: continue callback_quantity = int(address_quantity * fraction) # Round down. fraction_actual = callback_quantity / address_quantity outputs.append({'address': address, 'address_quantity': address_quantity, 'callback_quantity': callback_quantity, 'fraction_actual': fraction_actual}) callback_total = sum([output['callback_quantity'] for output in outputs]) if not callback_total: problems.append('nothing called back') balances = list(cursor.execute('''SELECT * FROM balances WHERE (address = ? AND asset = ?)''', (source, config.XPT))) if not balances or balances[0]['quantity'] < (call_price * callback_total): problems.append('insufficient funds') cursor.close() return call_price, callback_total, outputs, problems def compose (db, source, fraction, asset): call_price, callback_total, outputs, problems = validate(db, source, fraction, asset, util.last_block(db)['block_time'], util.last_block(db)['block_index'], parse=False) if problems: raise exceptions.CallbackError(problems) print('Total quantity to be called back:', util.devise(db, callback_total, asset, 'output'), asset) asset_id = util.asset_id(asset) data = struct.pack(config.TXTYPE_FORMAT, ID) data += struct.pack(FORMAT, fraction, asset_id) return (source, [], data) def parse (db, tx, message): callback_parse_cursor = db.cursor() # Unpack message. try: if len(message) != LENGTH: raise exceptions.UnpackError fraction, asset_id = struct.unpack(FORMAT, message) asset = util.asset_name(asset_id) status = 'valid' except (exceptions.UnpackError, exceptions.AssetNameError, struct.error) as e: fraction, asset = None, None status = 'invalid: could not unpack' if status == 'valid': call_price, callback_total, outputs, problems = validate(db, tx['source'], fraction, asset, tx['block_time'], tx['block_index'], parse=True) if problems: status = 'invalid: ' + '; '.join(problems) if status == 'valid': # Issuer. assert call_price * callback_total == int(call_price * callback_total) util.debit(db, tx['block_index'], tx['source'], config.XPT, int(call_price * callback_total), action='callback', event=tx['tx_hash']) util.credit(db, tx['block_index'], tx['source'], asset, callback_total, action='callback', event=tx['tx_hash']) # Holders. for output in outputs: assert call_price * output['callback_quantity'] == int(call_price * output['callback_quantity']) util.debit(db, tx['block_index'], output['address'], asset, output['callback_quantity'], action='callback', event=tx['tx_hash']) util.credit(db, tx['block_index'], output['address'], config.XPT, int(call_price * output['callback_quantity']), action='callback', event=tx['tx_hash']) # Add parsed transaction to message-type–specific table. bindings = { 'tx_index': tx['tx_index'], 'tx_hash': tx['tx_hash'], 'block_index': tx['block_index'], 'source': tx['source'], 'fraction': fraction, 'asset': asset, 'status': status, } sql='insert into callbacks values(:tx_index, :tx_hash, :block_index, :source, :fraction, :asset, :status)' callback_parse_cursor.execute(sql, bindings) callback_parse_cursor.close() # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4<|fim▁end|>
problems.append('not asset owner') return None, None, None, problems
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import sys import time def make(session): session.execute("make (%(rnd_name.0)s)") a_guid = session.message()[1][-1] assert(session.message() is None) return(a_guid) def link(session, a, l, b): session.execute("make %s -[%s]> %s" % (a, l, b)) assert(session.message() is None) def kill(session, a, l, b=None): if (b is None): session.execute("kill %s -[%s]> ()" % (a, l)) else: session.execute("kill %s -[%s]> %s" % (a, l, b)) assert(session.message() is None) def kattr_put(session, a, name, value, ttl=None): if (ttl is None): ttl = "" else: ttl = " with ttl:%d" % (ttl,) session.execute("attr put %s \"%s\" %s%s" % (a, name, value, ttl)) assert(session.message() is None) def tattr_put(session, a, name, time, value, ttl=None): if (ttl is None): ttl = "" else: ttl = " with ttl:%d" % (ttl,) session.execute("attr put %s \"%s\" [%s] %s%s" % (a, name, time, value, ttl)) assert(session.message() is None) def kattr_del(session, a, name): session.execute("attr del %s \"%s\"" % (a, name)) assert(session.message() is None) def string_value(a): return("\"%s\"" % a) def int32_value(a): return("(int32 %d)" % a) def uint32_value(a): return("(uint32 %d)" % a) def int64_value(a): return("(int64 %d)" % a)<|fim▁hole|>def uint64_value(a): return("(uint64 %d)" % a) def double_value(a): return("(double %s)" % repr(a)) def sleep(t): sys.stdout.write("(time.sleep %d)" % t) sys.stdout.flush() time.sleep(t * 2)<|fim▁end|>
<|file_name|>import_openstack_dns_zone_v2_test.go<|end_file_name|><|fim▁begin|>package openstack import ( "fmt" "testing" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" ) func TestAccDNSV2Zone_importBasic(t *testing.T) { var zoneName = fmt.Sprintf("ACPTTEST%s.com.", acctest.RandString(5)) resourceName := "openstack_dns_zone_v2.zone_1" resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheckDNSZoneV2(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckDNSV2ZoneDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: testAccDNSV2Zone_basic(zoneName), }, resource.TestStep{ ResourceName: resourceName, ImportState: true,<|fim▁hole|> }, }, }) }<|fim▁end|>
ImportStateVerify: true,
<|file_name|>GoogleCloudStorageLocation.java<|end_file_name|><|fim▁begin|>/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.datafactory.v2018_06_01; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; /** * The location of Google Cloud Storage dataset. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = GoogleCloudStorageLocation.class) @JsonTypeName("GoogleCloudStorageLocation") public class GoogleCloudStorageLocation extends DatasetLocation { /** * Specify the bucketName of Google Cloud Storage. Type: string (or * Expression with resultType string). */ @JsonProperty(value = "bucketName") private Object bucketName; /** * Specify the version of Google Cloud Storage. Type: string (or Expression * with resultType string). */ @JsonProperty(value = "version") private Object version; /** * Get specify the bucketName of Google Cloud Storage. Type: string (or Expression with resultType string). *<|fim▁hole|> return this.bucketName; } /** * Set specify the bucketName of Google Cloud Storage. Type: string (or Expression with resultType string). * * @param bucketName the bucketName value to set * @return the GoogleCloudStorageLocation object itself. */ public GoogleCloudStorageLocation withBucketName(Object bucketName) { this.bucketName = bucketName; return this; } /** * Get specify the version of Google Cloud Storage. Type: string (or Expression with resultType string). * * @return the version value */ public Object version() { return this.version; } /** * Set specify the version of Google Cloud Storage. Type: string (or Expression with resultType string). * * @param version the version value to set * @return the GoogleCloudStorageLocation object itself. */ public GoogleCloudStorageLocation withVersion(Object version) { this.version = version; return this; } }<|fim▁end|>
* @return the bucketName value */ public Object bucketName() {
<|file_name|>clientauth_test.go<|end_file_name|><|fim▁begin|>/* Copyright 2014 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package clientauth_test import ( "io/ioutil" "os" "reflect" "testing" "github.com/GoogleCloudPlatform/kubernetes/pkg/clientauth" ) func TestLoadFromFile(t *testing.T) {<|fim▁hole|> }{ { `{"user": "user", "password": "pass"}`, &clientauth.Info{User: "user", Password: "pass"}, false, }, { "", nil, true, }, } for _, loadAuthInfoTest := range loadAuthInfoTests { tt := loadAuthInfoTest aifile, err := ioutil.TempFile("", "testAuthInfo") if err != nil { t.Errorf("Unexpected error: %v", err) } if tt.authData != "missing" { defer os.Remove(aifile.Name()) defer aifile.Close() _, err = aifile.WriteString(tt.authData) if err != nil { t.Errorf("Unexpected error: %v", err) } } else { aifile.Close() os.Remove(aifile.Name()) } authInfo, err := clientauth.LoadFromFile(aifile.Name()) gotErr := err != nil if gotErr != tt.expectErr { t.Errorf("expected errorness: %v, actual errorness: %v", tt.expectErr, gotErr) } if !reflect.DeepEqual(authInfo, tt.authInfo) { t.Errorf("Expected %v, got %v", tt.authInfo, authInfo) } } }<|fim▁end|>
loadAuthInfoTests := []struct { authData string authInfo *clientauth.Info expectErr bool
<|file_name|>EjpSecurityConfigImpl.ts<|end_file_name|><|fim▁begin|>// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. // // Copyright 2016-2018 Pascal ECHEMANN. // // 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<|fim▁hole|>// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {EjpSecurityConfig, EjpConstraintConfig, EjpRoleConfig, EjpStaticResourcesConfig} from "jec-glasscat-config"; /** * The <code>EjpSecurityConfigImpl</code> class is the default implementation of * the <code>EjpSecurityConfig</code> interface. */ export class EjpSecurityConfigImpl implements EjpSecurityConfig { //////////////////////////////////////////////////////////////////////////// // Constructor function //////////////////////////////////////////////////////////////////////////// /** * Creates a new <code>EjpSecurityConfigImpl</code> instance. */ constructor() {} //////////////////////////////////////////////////////////////////////////// // Public properties //////////////////////////////////////////////////////////////////////////// /** * @inheritDoc */ public constraints:EjpConstraintConfig[] = null; /** * @inheritDoc */ public roles:EjpRoleConfig[] = null; /** * @inheritDoc */ public staticResources:EjpStaticResourcesConfig[] = null; }<|fim▁end|>
// // http://www.apache.org/licenses/LICENSE-2.0
<|file_name|>correspondence.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2019 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Samy Bucher <[email protected]> # # The licence is in the file __manifest__.py # ############################################################################## from odoo import models<|fim▁hole|> class Correspondence(models.Model): _inherit = 'correspondence' gift_id = fields.Many2one('sponsorship.gift', 'Gift')<|fim▁end|>
from odoo import fields
<|file_name|>list_comprehension.py<|end_file_name|><|fim▁begin|># Fluent Python Book # List comprehensions are faster than for-loops import time from random import choices symbols = list('abcdefghijklmn') print(symbols) symbols_big = choices(symbols, k=2000000) # print(symbols_big) start = time.time() ord_list1 = [] for sym in symbols_big: ord_list1.append(ord(sym)) # print('ord list1:', ord_list1) end = time.time() print('for loop ran in %f s' % (end - start)) start = time.time() # list comprehension ord_list2 = [ord(sym) for sym in symbols_big] # print('ord list2:', ord_list2) end = time.time() print('for loop ran in %f s' % (end - start)) # let's do a performance benchmark of this list comprehension l_nums = [i for i in range(1000000)] start = time.time() sq_nums = [] for i in l_nums: sq_nums.append(i ** 2) end = time.time() <|fim▁hole|>sq_nums = [i ** 2 for i in range(1000000)] end = time.time() print('list comp ran in %f s' % (end - start))<|fim▁end|>
print('for loop ran in %f s' % (end - start)) start = time.time()
<|file_name|>index.js<|end_file_name|><|fim▁begin|>define([<|fim▁hole|>], function(Vertebrae) { return Vertebrae; });<|fim▁end|>
'./src/vertebrae'
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.shortcuts import render from django.http import HttpResponse from django.utils import simplejson as json import ner def index(request): params = {'current': 'home'}<|fim▁hole|>def name_entity_recognition(request): if request.method == 'GET': #Get the array that contains the list of texts to recognize input_text_array = request.GET.getlist('text[]') data = {} i=0 for text in input_text_array: #Recognize all strings / texts contained in the array data[i] = ner.recognize(text.strip()) i+=1 return HttpResponse(json.dumps(data), content_type = "application/json")<|fim▁end|>
return render(request, 'index.html', params)
<|file_name|>dtos.py<|end_file_name|><|fim▁begin|># ############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core business involves the administration of students, teachers, # courses, programs and so on. # # Copyright (C) 2015-2021 Université catholique de Louvain (http://www.uclouvain.be) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of this license - GNU General Public License - is available # at the root of the source code of this program. If not, # see http://www.gnu.org/licenses/. # # ############################################################################## import attr <|fim▁hole|>from osis_common.ddd import interface @attr.s(frozen=True, slots=True) class EntiteUclDTO(interface.DTO): sigle = attr.ib(type=str) intitule = attr.ib(type=str)<|fim▁end|>
<|file_name|>findall.py<|end_file_name|><|fim▁begin|>"""Findall regex operations in python. findall(string[, pos[, endpos]]) Returns a list: not like search and match which returns objects Otherwise, it returns an empty list. """ import re # look for every word in a string pattern = re.compile(r"\w+") result = pattern.findall("hey bro") print result <|fim▁hole|># returns ['ab', 'ab', 'ab', 'b'] res = patt.findall("abababb") print res # match a group of words onto a tuple p = re.compile(r"(\w+) (\w+)") rv = p.findall("Hello world, i lived") print rv # Using unicode characters print re.findall(ur"\w+", u"这是一个例子", re.UNICODE) # using named groups inside pattern itself patt = re.compile(r"(?P<word>\w+) (?P=word)")<|fim▁end|>
patt = re.compile(r"a*b")
<|file_name|>IllegalPhoneNumberException.java<|end_file_name|><|fim▁begin|>/** * Exception class for illegal phone number format strings. * @author Jonathan Hinkle */ package net.sf.memoranda; /** * This class is thrown when a string is not a valid phone number format. * * @author Jonathan Hinkle * */ @SuppressWarnings("serial") public class IllegalPhoneNumberException extends IllegalArgumentException { /** * IllegalPhoneNumberException constructor. */<|fim▁hole|> * IllegalPhoneNumberException constructor. * * @param message A message String */ public IllegalPhoneNumberException(String message) { super(message); } }<|fim▁end|>
public IllegalPhoneNumberException() {} /**
<|file_name|>FBrowserBase.py<|end_file_name|><|fim▁begin|># # FBrowserBase.py -- Base class for file browser plugin for fits viewer # # Eric Jeschke ([email protected]) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # import os, glob import stat, time from ginga.misc import Bunch from ginga import GingaPlugin from ginga import AstroImage from ginga.util import paths from ginga.util.six.moves import map, zip class FBrowserBase(GingaPlugin.LocalPlugin): def __init__(self, fv, fitsimage): # superclass defines some variables for us, like logger super(FBrowserBase, self).__init__(fv, fitsimage) self.keywords = ['OBJECT', 'UT'] self.columns = [('Name', 'name'), ('Size', 'st_size'),<|fim▁hole|> self.jumpinfo = [] homedir = paths.home self.curpath = os.path.join(homedir, '*') self.do_scanfits = False self.moving_cursor = False def close(self): chname = self.fv.get_channelName(self.fitsimage) self.fv.stop_local_plugin(chname, str(self)) return True def file_icon(self, bnch): if bnch.type == 'dir': pb = self.folderpb elif bnch.type == 'fits': pb = self.fitspb else: pb = self.filepb return pb def open_file(self, path): self.logger.debug("path: %s" % (path)) if path == '..': curdir, curglob = os.path.split(self.curpath) path = os.path.join(curdir, path, curglob) if os.path.isdir(path): path = os.path.join(path, '*') self.browse(path) elif os.path.exists(path): #self.fv.load_file(path) uri = "file://%s" % (path) self.fitsimage.make_callback('drag-drop', [uri]) else: self.browse(path) def get_info(self, path): dirname, filename = os.path.split(path) name, ext = os.path.splitext(filename) ftype = 'file' if os.path.isdir(path): ftype = 'dir' elif os.path.islink(path): ftype = 'link' elif ext.lower() == '.fits': ftype = 'fits' try: filestat = os.stat(path) bnch = Bunch.Bunch(path=path, name=filename, type=ftype, st_mode=filestat.st_mode, st_size=filestat.st_size, st_mtime=filestat.st_mtime) except OSError as e: # TODO: identify some kind of error with this path bnch = Bunch.Bunch(path=path, name=filename, type=ftype, st_mode=0, st_size=0, st_mtime=0) return bnch def browse(self, path): self.logger.debug("path: %s" % (path)) if os.path.isdir(path): dirname = path globname = None else: dirname, globname = os.path.split(path) dirname = os.path.abspath(dirname) # check validity of leading path name if not os.path.isdir(dirname): self.fv.show_error("Not a valid path: %s" % (dirname)) return if not globname: globname = '*' path = os.path.join(dirname, globname) # Make a directory listing self.logger.debug("globbing path: %s" % (path)) filelist = list(glob.glob(path)) filelist.sort(key=str.lower) filelist.insert(0, os.path.join(dirname, '..')) self.jumpinfo = list(map(self.get_info, filelist)) self.curpath = path if self.do_scanfits: self.scan_fits() self.makelisting(path) def scan_fits(self): for bnch in self.jumpinfo: if not bnch.type == 'fits': continue if 'kwds' not in bnch: try: in_f = AstroImage.pyfits.open(bnch.path, 'readonly') try: kwds = {} for kwd in self.keywords: kwds[kwd] = in_f[0].header.get(kwd, 'N/A') bnch.kwds = kwds finally: in_f.close() except Exception as e: continue def refresh(self): self.browse(self.curpath) def scan_headers(self): self.browse(self.curpath) def make_thumbs(self): path = self.curpath self.logger.info("Generating thumbnails for '%s'..." % ( path)) filelist = glob.glob(path) filelist.sort(key=str.lower) # find out our channel chname = self.fv.get_channelName(self.fitsimage) # Invoke the method in this channel's Thumbs plugin # TODO: don't expose gpmon! rsobj = self.fv.gpmon.getPlugin('Thumbs') self.fv.nongui_do(rsobj.make_thumbs, chname, filelist) def start(self): self.win = None self.browse(self.curpath) def pause(self): pass def resume(self): pass def stop(self): pass def redo(self): return True #END<|fim▁end|>
('Mode', 'st_mode'), ('Last Changed', 'st_mtime') ]
<|file_name|>bestaplayer.py<|end_file_name|><|fim▁begin|>__author__ = 'besta' class BestaPlayer: def __init__(self, fichier, player): self.fichier = fichier self.grille = self.getFirstGrid() self.best_hit = 0 self.players = player def getFirstGrid(self): """ Implements function to get the first grid. :return: the grid. """ li = [] with open(self.fichier, 'r') as fi: for line in fi.readlines(): li.append(line) return li def updateGrid(self): """ Implements function to update the grid to alter n-1 round values """ with open(self.fichier, 'r') as fi: for line in fi.readlines(): i = 0 for car in line: j = 0 if car != '\n': self.grille[i][j] = car j += 1 i += 1 def grilleEmpty(self): """ Implement function to check if the grid is empty. """ for line in self.grille: for car in line[:len(line) - 1]: if car != '0': return False return True def checkLines(self, player, inARow): """ Implements function to check the current lines setup to evaluate best combinaison. :param player: check for your numbers (your player number) or those of your opponent. :param inARow: how many tokens in a row (3 or 2). :return: true or false """ count = 0 flag = False for line_number, line in enumerate(self.grille): count = 0 for car_pos, car in enumerate(line[:len(line) - 1]): if int(car) == player and not flag: count = 1 flag = True elif int(car) == player and flag: count += 1 if count == inARow: if car_pos - inARow >= 0 and self.canPlayLine(line_number, car_pos - inARow): return True, car_pos - inARow if car_pos + 1 <= 6 and self.canPlayLine(line_number, car_pos + 1): return True, car_pos + 1 else: count = 0 return False, 0 def canPlayLine(self, line, col): """ Function to check if we can fill the line with a token. :param line: which line :param col: which column :return: true or false """ if line == 5: return self.grille[line][col] == '0' else: return self.grille[line][col] == '0' and self.grille[line + 1][col] != '0' def changeColumnInLines(self): """ Implements function to transform columns in lines to make tests eaiser. :return: a reverse matrice """ column = [] for x in xrange(7): col = '' for y in xrange(6): col += self.grille[y][x] column.append(col) return column def checkColumns(self, player, inARow): """ Implements function to check the current columns setup to evaluate best combinaison. :param player: check for your numbers (your player number) or those of your opponent. :param inARow: how many tokens in a row (3 or 2). :return: true or false """ column = self.changeColumnInLines() count = 0 flag = False for col_number, line in enumerate(column): count = 0 for car_pos, car in enumerate(line): if int(car) == player and not flag: count = 1 flag = True elif int(car) == player and flag: count += 1 if count == inARow and car_pos - inARow >= 0 and self.grille[car_pos - inARow][col_number] == '0': return True, col_number else: count = 0 return False, 0 def checkDiagonalLeftToRight(self, player, inARow): """ Implements function to check the current diagonal to evaluate best combinaison. :param player: check for your numbers or opponent ones. :param inARow: how many tokens in a row (3 or 2). :return: """ x = 3 flag = False while x < 6: count = 0 x_int = x y_int = 0 while x_int >= 0: if int(self.grille[x_int][y_int]) == player and not flag: count = 1 flag = True elif int(self.grille[x_int][y_int]) == player and flag:<|fim▁hole|> count += 1 if count == inARow and y_int + 1 <= 6 and x_int - 1 >= 0 and self.grille[x_int][y_int + 1] != '0': return True, y_int + 1 else: count = 0 flag = False x_int -= 1 y_int += 1 x += 1 y = 1 flag = False while y <= 3: count = 0 x_int = 5 y_int = y while y_int <= 6 and x_int >= 0: if int(self.grille[x_int][y_int]) == player and not flag: count = 1 flag = True elif int(self.grille[x_int][y_int]) == player and flag: count += 1 if count == inARow and y_int + 1 <= 6 and x_int - 1 >= 0 and self.grille[x_int][y + 1] != '0': return True, y_int + 1 else: count = 0 flage = False x_int -= 1 y_int += 1 y += 1 return False, 0 def checkDiagonalRightToLeft(self, player, inARow): """ Implements function to check the current diagonal to evaluate best combinaison. :param player: check for your numbers or opponent ones. :param inARow: how many tokens in a row (3 or 2). :return: """ x = 3 flag = False while x < 6: count = 0 x_int = x y_int = 6 while x_int >= 0: if int(self.grille[x_int][y_int]) == player and not flag: count = 1 flag = True elif int(self.grille[x_int][y_int]) == player and flag: count += 1 if count == inARow and y_int - 1 >= 0 and x_int - 1 >= 0 and self.grille[x_int][y_int - 1] != '0': return True, y_int - 1 else: count = 0 flag = False x_int -= 1 y_int -= 1 x += 1 y = 5 flag = False while y <= 3: count = 0 x_int = 5 y_int = y while y_int >= 3 and x_int >= 0: if int(self.grille[x_int][y_int]) == player and not flag: count = 1 flag = True elif int(self.grille[x_int][y_int]) == player and flag: count += 1 if count == inARow and y_int - 1 >= 0 and x_int - 1 >= 0 and self.grille[x_int][y - 1] != '0': return True, y_int - 1 else: count = 0 flage = False x_int -= 1 y_int -= 1 y -= 1 return False, 0 def checkDiagonals(self, player, inARow): """ Calls two diagonal functional. :return: an int, representing the column where to play or 0 and False if there is no pattern search. """ check = self.checkDiagonalLeftToRight(player, inARow) if check[0]: return check else: return self.checkDiagonalRightToLeft(player, inARow) def playSomeColumn(self, player, inARow): """ Call all function for a player and a number of tokens given. :param player: which player :param inARow: how many token :return: true or false (col number if true) """ methods = {'checklines': self.checkLines, 'checkcolumn': self.checkColumns, 'checkdiagonal': self.checkDiagonals} for key, function in methods.items(): which_col = function(player, inARow) if which_col[0]: return which_col return False, 0 def findFirstColumnEmpty(self): """ Implements function to get the first column where a slot remain. :return: the column """ for col in xrange(7): if self.grille[0][col] == '0': return col return -1 def decideColumn(self): """ Implements main function : to decide what is the better hit to do. :return: an int, representing the column where we play """ if self.grilleEmpty(): return 3 li_sequence = [3, 2, 1] li_players = [self.players[0], self.players[1]] for sequence in li_sequence: for player in li_players: choosen_col = self.playSomeColumn(player, sequence) if choosen_col[0]: return choosen_col[1] return self.findFirstColumnEmpty()<|fim▁end|>
<|file_name|>CAvmCommon.py<|end_file_name|><|fim▁begin|>from PyCA.Core import * import PyCA.Common as common import numpy as np import matplotlib.pyplot as plt def SplatSafe(outMass, g, mass): mType = mass.memType() if mType == MEM_DEVICE: minmaxl = MinMax(mass) maxval = max([abs(x) for x in minmaxl]) if maxval > 2000.00: # print 'Warning, range too big for splatting. Range: ',minmaxl # print 'Temporary downscaling values for splatting. Will scale it back after splatting.' scalefactor = float(100.00)/maxval MulC_I(mass, scalefactor) Splat(outMass, g, mass, False) MulC_I(mass, 1.0/scalefactor) MulC_I(outMass, 1.0/scalefactor) else: Splat(outMass, g, mass, False) else: Splat(outMass,g, mass, False) # end SplatSafe def ComputeVhat(out_v, scratchV, I, Ihat, m, mhat, diffOp): ''' ''' Gradient(out_v, I) MulMulC_I(out_v, Ihat, 1.0) CoAdInf(scratchV, mhat ,m) Sub_I(out_v, scratchV) diffOp.applyInverseOperator(out_v) return out_v # end ComputeVhat def EvaluateRHSFwd(out_v, v, phi): ''' Evaluate RHS for forward integration of \frac{d\phi}{dt}=v\circ\phi ''' ApplyH(out_v, v, phi, BACKGROUND_STRATEGY_PARTIAL_ZERO) return out_v #end EvaluateRHSFwd def EvaluateRHSBwd(out_v, scratchV, v, I, m, mhat, Ihat, g, diffOp): ''' ''' #first compute vhat_t ComputeVhat(out_v, scratchV, I, Ihat, m, mhat, diffOp) #compute Dvmhat JacobianXY(scratchV, v, mhat) #Add both Add_I(scratchV, out_v) #deform ApplyH(out_v, scratchV, g, BACKGROUND_STRATEGY_PARTIAL_ZERO); return out_v #end EvaluateRHSBwd def IntegrateGeodesic(m0,t,diffOp,\ m,g,ginv,\ scratchV1,scratchV2,scratchV3,\ keepstates=None,keepinds=None,\ Ninv=5,integMethod='EULER', startIndex=0, endIndex=0, initializePhi=True,\ RK4=None, scratchG=None): ''' Resulted g and ginv are diffeomorphism and its inverse at end point of shooting. and keepstates is populated with g and ginv at requested timepoints mentioned in keepinds. m is NOT the momentum at the end point. Must call CoAd(m,ginv,m0) after the call to get it. If startTime is anything other than 0, it assumes g and ginv are appropriately initialized. ''' # initial conditions if endIndex == 0: endIndex=len(t)-1 if startIndex == 0: if initializePhi==True: # if t=0 is not the identity diffeomorphisms SetToIdentity(g) SetToIdentity(ginv) Copy(m,m0) else: CoAd(m,ginv,m0) else: CoAd(m,ginv,m0) # assumes ginv is initialized when the function was called # end if # Smooth to get velocity at time t diffOp.applyInverseOperator(m) if (keepinds!=None) & (keepstates!=None): if (0 in keepinds) & (startIndex == 0): # remember to copy everything indx_of_cur_tp = keepinds.index(0) Copy(keepstates[indx_of_cur_tp][0],g) Copy(keepstates[indx_of_cur_tp][1],ginv) # end if # end if # do integration for i in range(startIndex+1,endIndex+1,1): #sys.stdout.write(',') dt = t[i]-t[i-1] # time step if integMethod == "EULER": # print 'Running Euler integration for shooting' # Compute forward step, w for g EvaluateRHSFwd(scratchV1, m, g) MulC_I(scratchV1, dt) # Take the fwd step Add_I(g,scratchV1) # Update ginv corresponding to this fwd step UpdateInverse(scratchV3, scratchV2, ginv, scratchV1, Ninv) Copy(ginv,scratchV3) elif integMethod == "RK4": # RK4 integration two extra fields if scratchG is None: print 'scratchG variable is initialized in geodesic shooting' scratchG = Field3D(m0.grid(),m0.memType()) if RK4 is None: print 'RK4 variable is initialized in geodesic shooting' RK4 = Field3D(m0.grid(),m0.memType()) EvaluateRHSFwd(scratchV1, m, g); MulC_I(scratchV1, dt) # k1 computed Copy(RK4,scratchV1) # for k2 Copy(scratchG, g); MulC_I(scratchV1,0.5); Add_I(scratchG,scratchV1); UpdateInverse(scratchV3, scratchV2, ginv, scratchV1, Ninv); CoAd(m,scratchV3,m0); diffOp.applyInverseOperator(m); EvaluateRHSFwd(scratchV1, m, scratchG); MulC_I(scratchV1, dt) # k2 computed Add_MulC_I(RK4,scratchV1,2.0) # for k3 Copy(scratchG, g); MulC_I(scratchV1,0.5); Add_I(scratchG,scratchV1); UpdateInverse(scratchV3, scratchV2, ginv, scratchV1, Ninv); CoAd(m,scratchV3,m0); diffOp.applyInverseOperator(m); EvaluateRHSFwd(scratchV1, m, scratchG); MulC_I(scratchV1, dt) # k3 computed Add_MulC_I(RK4,scratchV1,2.0) # for k4 Copy(scratchG, g); Add_I(scratchG,scratchV1); UpdateInverse(scratchV3, scratchV2, ginv, scratchV1, Ninv); CoAd(m,scratchV3,m0); diffOp.applyInverseOperator(m); EvaluateRHSFwd(scratchV1, m, scratchG); MulC_I(scratchV1, dt) # k4 computed Add_I(RK4,scratchV1) # final update MulC_I(RK4,1.0/float(6.0)) Add_I(g,RK4) UpdateInverse(scratchV3, scratchV2, ginv, RK4, Ninv) Copy(ginv,scratchV3) else: raise Exception('Unknown integration method: '+integMethod) # end if # common lines of code executed regardless of the integration scheme # check whether we should store this state if (keepinds!=None) & (keepstates!=None): if i in keepinds: # remember to copy everything indx_of_cur_tp = keepinds.index(i) Copy(keepstates[indx_of_cur_tp][0],g) Copy(keepstates[indx_of_cur_tp][1],ginv) # end if # end if # skip if it is the last iteration. if i<endIndex: # Coadjoint action gives us momentum at time t CoAd(m,ginv,m0) # Smooth to get velocity at time t diffOp.applyInverseOperator(m) # end if # end for # end IntegrateGeodesic def IntegrateGeodesicBwdIteration(t,i,m0,g1,ginv1,m1,bwdG,bwdGinv, gprev,ginvprev, m1initialized,prev_was_checkpoint, diffOp, m, scratchV1, scratchV2,scratchV3, Ninv=5,integMethod='EULER', RK4=None, scratchG=None): if m1 is None: print 'm1 variable is initialized in IntegrateGeodesicBwdIteration' m1 = Field3D(m0.grid(),m0.memType()) if bwdG is None: print 'bwdG variable is initialized in IntegrateGeodesicBwdIteration' bwdG = Field3D(m0.grid(),m0.memType()) if bwdGinv is None: print 'bwdGinv variable is initialized in IntegrateGeodesicBwdIteration' bwdGinv = Field3D(m0.grid(),m0.memType()) if ( m1initialized == False ): SetToIdentity(bwdG) SetToIdentity(bwdGinv) CoAd(m1,ginv1,m0) m1initialized = True # end if # If previous iteration had a checkpoint bwdG, bwdGinv would have been updated. If not need an updated ones if (prev_was_checkpoint == True) & (i != (len(t)-2)): ComposeHH(bwdG,gprev,ginv1) ComposeHH(bwdGinv,g1,ginvprev) # end if IntegrateGeodesic(m1,[0,t[i]-t[i+1]],diffOp,\ m,bwdG,bwdGinv,\ scratchV1,scratchV2,scratchV3,\ keepstates=None,keepinds=None,\ Ninv=Ninv,integMethod=integMethod,initializePhi=False,RK4=RK4,scratchG=scratchG) ComposeHH(gprev,bwdG,g1) ComposeHH(ginvprev, ginv1,bwdGinv) prev_was_checkpoint = False # end IntegrateGeodesicBwd def IntegrateAdjoints(Iadj,madj, I,m,Iadjtmp, madjtmp,v, scratchV1,scratchV2, I0,m0, t, checkpointstates, checkpointinds, IGradAtMsmts, msmtInds, diffOp, integMethod='EULER',Ninv=5, scratchV3=None, scratchV4=None,scratchV5=None,scratchV6=None, scratchV7=None, # used when all timepoints are not checkpointed or with RK4 scratchV8=None, scratchV9=None, # used with RK4 only when all are not checkpointed RK4 = None, scratchG = None,scratchGinv = None, # used only with RK4 scratchI = None ): ''' ''' if len(t)-1 not in checkpointinds: raise Exception('Endpoint must be one of the checkpoints passed to IntegrateAdjoints') else: indx_of_last_tp = checkpointinds.index(len(t)-1) # extra reference names used m1 = None bwdG = None bwdGinv = None SetMem(madj,0.0) SetMem(Iadj,0.0) (g, ginv) = checkpointstates[indx_of_last_tp] #I(t) and m(t) at end point CoAd(m,ginv,m0) ApplyH(I,I0,ginv) Copy(v,m) diffOp.applyInverseOperator(v) # has v(t) SetMem(madjtmp,0.0) # will be used for hat version of madj SetMem(Iadjtmp,0.0) # will be used for hat version of Iadj # initial conditions for k in range(len(msmtInds)): if checkpointinds[msmtInds[k]] == (len(t)-1): # there is a measurement at the last time point which will always be the case for matching but not necessarily regression MulC(Iadjtmp,IGradAtMsmts[k],-1) #Splat(Iadj,ginv, Iadjtmp,False) #Also, ginv = checkpointstates[msmtInds[k]][1] SplatSafe(Iadj, ginv, Iadjtmp) # end if # end for prev_was_checkpoint = True m1initialized = False for i in range(len(t)-2,-1,-1): dt = t[i] - t[i+1] if integMethod == "EULER": # print 'Running Euler integration for adjoint integration' EvaluateRHSBwd(scratchV1, scratchV2, v, I, m, madjtmp, Iadjtmp, g, diffOp) # Euler step for madj Add_MulC_I(madj, scratchV1, dt) if i in checkpointinds: indx_of_cur_tp = checkpointinds.index(i) (g, ginv) = checkpointstates[indx_of_cur_tp] prev_was_checkpoint = True elif i > 0: # i=0 need not be calculated # compute g and ginv by backward integrating geodesic # oops we are going to need a lot of scratch variables if scratchV6 is None: print 'scratchV6 variable is initialized in IntegrateAdjoints' scratchV6 = Field3D(I0.grid(),I0.memType()) if scratchV7 is None: print 'scratchV7 variable is initialized in IntegrateAdjoints' scratchV7 = Field3D(I0.grid(),I0.memType()) if (prev_was_checkpoint == True): # so that we do not update checkpointed states Copy(scratchV6,g) Copy(scratchV7,ginv) # update reference g=scratchV6 ginv=scratchV7 # madjtmp and v are used as scratch variables in below call m1 = scratchV3; bwdG = scratchV4; bwdGinv = scratchV5; # update references for ease of reading IntegrateGeodesicBwdIteration(t,i,m0, checkpointstates[indx_of_last_tp][0], checkpointstates[indx_of_last_tp][1],m1, bwdG, bwdGinv, g,ginv, m1initialized,prev_was_checkpoint, diffOp, madjtmp, scratchV1,scratchV2,v, Ninv=Ninv,integMethod=integMethod) # end if # if there is a measurement at this time point (for regression) for k in range(len(msmtInds)): if i>0: if checkpointinds[msmtInds[k]] == i: # I is used as scratch variable #Splat(I, ginv, IGradAtMsmts[k],False) SplatSafe(I, ginv, IGradAtMsmts[k]) Sub_I(Iadj,I) # end if elif msmtInds[k]==-1:# if there is a measurement at time t=0 it won't be checkpointed but HARDCODED to have msmstInds == -1. Note this will be checked only for t==0 Sub_I(Iadj, IGradAtMsmts[k]) # end if<|fim▁hole|> # update variables for next iteration if i > 0: # last iteration skipped CoAd(m,ginv,m0) ApplyH(I,I0,ginv) Copy(v,m) diffOp.applyInverseOperator(v) # has v(t) ApplyH(madjtmp,madj,ginv,BACKGROUND_STRATEGY_PARTIAL_ZERO) # hat version of madj #Splat(Iadjtmp, g, Iadj,False) # hat version of Iadj SplatSafe(Iadjtmp, g, Iadj) # hat version of Iadj # end if elif integMethod == "RK4": if RK4 is None: print 'RK4 variable is initialized' RK4 = Field3D(I0.grid(),I0.memType()) if scratchG is None: print 'scratchG variable is initialized' scratchG = Field3D(I0.grid(),I0.memType()) if scratchGinv is None: print 'scratchGinv variable is initialized' scratchGinv = Field3D(I0.grid(),I0.memType()) if scratchI is None: print 'scratchI variable is initialized' scratchI = Image3D(I0.grid(),I0.memType()) # first get g and ginv for current timepoint if (i in checkpointinds) or (i==0): # assuming g and g inv points to prev # just assign the references if i>0: indx_of_cur_tp = checkpointinds.index(i) (gcur, ginvcur) = checkpointstates[indx_of_cur_tp] # end if note if i==0, gcur and ginvcur are treated as identity prev_was_checkpoint = True # begin rk4 integration for adjoint EvaluateRHSBwd(scratchV1, scratchV2, v, I, m, madjtmp, Iadjtmp, g, diffOp); MulC_I(scratchV1, dt) # k1 computed Copy(RK4,scratchV1) # compute and store phi0t, phit0, v_t, i_t, m_t and i_hat at t+1/2 for computing k2 and k3 if i>0: SubMulC(scratchG,g,gcur,0.5); #scratchG has w UpdateInverse(scratchGinv, scratchV2, ginvcur, scratchG, Ninv) Add_I(scratchG,gcur) else:# add 0.5 times identity HtoV(scratchG,g);MulC_I(scratchG,0.5) #scratchG has w # iteratively update inverse as, g_{1,0} = Id - w\circ g_{1,0} SetToIdentity(scratchGinv) for k in range(Ninv): ApplyH(scratchV2, scratchG, scratchGinv, BACKGROUND_STRATEGY_PARTIAL_ZERO) HtoV(scratchGinv,scratchV2); MulC_I(scratchGinv,-1.0) VtoH_I(scratchG) # end if CoAd(m,scratchGinv,m0); Copy(v,m); diffOp.applyInverseOperator(v); ApplyH(I,I0,scratchGinv) #Splat(Iadjtmp, scratchG, Iadj,False) SplatSafe(Iadjtmp, scratchG, Iadj) # for k2 # mhat_t at t+1/2 for k2 Add_MulC(scratchV2,madj,scratchV1,0.5) # mtilde at t+1/2 ApplyH(madjtmp,scratchV2,scratchGinv, BACKGROUND_STRATEGY_PARTIAL_ZERO); #mhat at t+1/2 EvaluateRHSBwd(scratchV1, scratchV2, v, I, m, madjtmp, Iadjtmp, scratchG, diffOp); MulC_I(scratchV1, dt) # k2 computed Add_MulC_I(RK4, scratchV1, 2.0) # for k3 # mhat_t at t+1/2 for k3 Add_MulC(scratchV2,madj,scratchV1,0.5) # mtilde at t+1/2 ApplyH(madjtmp,scratchV2,scratchGinv, BACKGROUND_STRATEGY_PARTIAL_ZERO); #mhat at t+1/2 EvaluateRHSBwd(scratchV1, scratchV2, v, I, m, madjtmp, Iadjtmp, scratchG, diffOp); MulC_I(scratchV1, dt) # k3 computed Add_MulC_I(RK4, scratchV1, 2.0) # compute v_t, i_t, m_t, i_hat at t for computing k4 if i>0: CoAd(m,ginvcur,m0) #Splat(Iadjtmp, gcur, Iadj,False) SplatSafe(Iadjtmp, gcur, Iadj) ApplyH(I,I0,ginvcur) else: Copy(m,m0) Copy(Iadjtmp,Iadj) Copy(I,I0) Copy(v,m); diffOp.applyInverseOperator(v); # for k4 # mhat_t at t for k4 Add(scratchV2,madj,scratchV1) # mtilde at t if i>0: ApplyH(madjtmp,scratchV2,ginvcur, BACKGROUND_STRATEGY_PARTIAL_ZERO); else: Copy(madjtmp,scratchV2) # end if #mhat at t if i>0: EvaluateRHSBwd(scratchV1, scratchV2, v, I, m, madjtmp, Iadjtmp, gcur, diffOp); MulC_I(scratchV1, dt) # k4 computed else: SetToIdentity(scratchG) EvaluateRHSBwd(scratchV1, scratchV2, v, I, m, madjtmp, Iadjtmp, scratchG, diffOp); MulC_I(scratchV1, dt) # k4 computed Add_I(RK4, scratchV1) # final update MulC_I(RK4,1.0/float(6.0)) Add_I(madj,RK4) #FOR NEXT ITERATION: # compute mhat_t, ihat_t at t to use in k1 computation. Note v_t, i_t and m_t are still stored from this iteration. # if there is a measurement at this time point (for regression) for k in range(len(msmtInds)): if i>0: if checkpointinds[msmtInds[k]] == i: #Splat(scratchV1, ginvcur, IGradAtMsmts[k],False) SplatSafe(scratchI, ginvcur, IGradAtMsmts[k]) Sub_I(Iadj,scratchI) #Splat(Iadjtmp, gcur, Iadj,False) # hat version of Iadj SplatSafe(Iadjtmp, gcur, Iadj) # hat version of Iadj # end if elif msmtInds[k]==-1: # if there is a measurement at time t=0 it won't be checkpointed but HARDCODED to have msmstInds == -1. Note this will be checked only for t==0 Sub_I(Iadj, IGradAtMsmts[k]) # end if # end for if i > 0: # last iteration skipped ApplyH(madjtmp,madj,ginvcur, BACKGROUND_STRATEGY_PARTIAL_ZERO) # hat version of madj # assign g, ginv appropriately for next iteration g = gcur ginv = ginvcur # end if else: # raise Exception('RK4 integration without all checkpoints not yet implemented') # compute gcur and ginvcur by backward integrating geodesic if scratchV6 is None: print 'scratchV6 variable is initialized in IntegrateAdjoints' scratchV6 = Field3D(I0.grid(),I0.memType()) if scratchV7 is None: print 'scratchV7 variable is initialized in IntegrateAdjoints' scratchV7 = Field3D(I0.grid(),I0.memType()) if scratchV8 is None: print 'scratchV8 variable is initialized in IntegrateAdjoints' scratchV8 = Field3D(I0.grid(),I0.memType()) if scratchV9 is None: print 'scratchV9 variable is initialized in IntegrateAdjoints' scratchV9 = Field3D(I0.grid(),I0.memType()) # initialize with previous if prev_was_checkpoint == True: gcur=scratchV8 ginvcur=scratchV9 Copy(gcur,g) Copy(ginvcur,ginv) # endif --previous was not checkpoint scratchV6 and scratch V8 should both have g and scratchV7 and scratch V9 should both have ginv. so no need to copy # scratchG, scratchGinv and v are used as scratch variables in below call m1 = scratchV3; bwdG = scratchV4; bwdGinv = scratchV5; # update references for ease of reading IntegrateGeodesicBwdIteration(t,i,m0, checkpointstates[indx_of_last_tp][0], checkpointstates[indx_of_last_tp][1],m1, bwdG, bwdGinv, gcur,ginvcur, m1initialized,prev_was_checkpoint, diffOp, scratchGinv, scratchV1,scratchV2,v, Ninv=Ninv,integMethod=integMethod, RK4=RK4,scratchG=scratchG) # begin rk4 integration for adjoint Copy(v,m); diffOp.applyInverseOperator(v); EvaluateRHSBwd(scratchV1, scratchV2, v, I, m, madjtmp, Iadjtmp, g, diffOp); MulC_I(scratchV1, dt) # k1 computed Copy(RK4,scratchV1) # compute and store phi0t, phit0, v_t, i_t, m_t and i_hat at t+1/2 for computing k2 and k3 SubMulC(scratchG,g,gcur,0.5); #scratchG has w UpdateInverse(scratchGinv, scratchV2, ginvcur, scratchG, Ninv) Add_I(scratchG,gcur) CoAd(m,scratchGinv,m0); Copy(v,m); diffOp.applyInverseOperator(v); ApplyH(I,I0,scratchGinv) #Splat(Iadjtmp, scratchG, Iadj,False) SplatSafe(Iadjtmp, scratchG, Iadj) # for k2 # mhat_t at t+1/2 for k2 Add_MulC(scratchV2,madj,scratchV1,0.5) # mtilde at t+1/2 ApplyH(madjtmp,scratchV2,scratchGinv, BACKGROUND_STRATEGY_PARTIAL_ZERO); #mhat at t+1/2 EvaluateRHSBwd(scratchV1, scratchV2, v, I, m, madjtmp, Iadjtmp, scratchG, diffOp); MulC_I(scratchV1, dt) # k2 computed Add_MulC_I(RK4, scratchV1, 2.0) # for k3 # mhat_t at t+1/2 for k3 Add_MulC(scratchV2,madj,scratchV1,0.5) # mtilde at t+1/2 ApplyH(madjtmp,scratchV2,scratchGinv, BACKGROUND_STRATEGY_PARTIAL_ZERO); #mhat at t+1/2 EvaluateRHSBwd(scratchV1, scratchV2, v, I, m, madjtmp, Iadjtmp, scratchG, diffOp); MulC_I(scratchV1, dt) # k3 computed Add_MulC_I(RK4, scratchV1, 2.0) # compute v_t, i_t, m_t, i_hat at t for computing k4 CoAd(m,ginvcur,m0) #Splat(Iadjtmp, gcur, Iadj,False) SplatSafe(Iadjtmp, gcur, Iadj) ApplyH(I,I0,ginvcur) Copy(v,m); diffOp.applyInverseOperator(v); # for k4 # mhat_t at t for k4 Add(scratchV2,madj,scratchV1) # mtilde at t ApplyH(madjtmp,scratchV2,ginvcur, BACKGROUND_STRATEGY_PARTIAL_ZERO); EvaluateRHSBwd(scratchV1, scratchV2, v, I, m, madjtmp, Iadjtmp, gcur, diffOp); MulC_I(scratchV1, dt) # k4 computed Add_I(RK4, scratchV1) # final update MulC_I(RK4,1.0/float(6.0)) Add_I(madj,RK4) #FOR NEXT ITERATION: # compute mhat_t, ihat_t at t to use in k1 computation. Note v_t, i_t and m_t are still stored from this iteration. # if there is a measurement at this time point (for regression) for k in range(len(msmtInds)): if i>0: if checkpointinds[msmtInds[k]] == i: #Splat(scratchV1, ginvcur, IGradAtMsmts[k],False) SplatSafe(scratchI, ginvcur, IGradAtMsmts[k]) Sub_I(Iadj,scratchI) #Splat(Iadjtmp, gcur, Iadj,False) # hat version of Iadj SplatSafe(Iadjtmp, gcur, Iadj) # hat version of Iadj # end if elif msmtInds[k]==-1: # if there is a measurement at time t=0 it won't be checkpointed but HARDCODED to have msmstInds == -1. Note this will be checked only for t==0 Sub_I(Iadj,IGradAtMsmts[k]) # end if # end for ApplyH(madjtmp,madj,ginvcur, BACKGROUND_STRATEGY_PARTIAL_ZERO) # hat version of madj # assign g, ginv appropriately for next iteration # first assign references g = scratchV6 ginv = scratchV7 # then copy memory Copy(g,gcur) Copy(ginv,ginvcur) # end if else: raise Exception('Unknown integration method: '+integMethod) #end if # common lines of code executed regardless of the integration scheme # end for return m #end IntegrateAdjoints def ParallelTransport(m1, n0, m0, nTimeSteps, diffOp, Ninv=10, integMethod='RK4',saveOutput=False, mtArray=None, ginvArray=None): ''' Parallel translation of vector momentum, m0 along the geodesic denoted by initial condition, n0 from t=0 to t=1 using given time descritization, nTimeSteps. Returns the parallely tranlated momentum in argument variable m1 at the end point of geodesic at t=1. Also, returns list of norm of m(t), norm(n) and inner product between m and n at all timepoints along the geodesic. ''' t = [x*1./nTimeSteps for x in range(nTimeSteps+1)] mGrid = n0.grid() mType = n0.memType() v = Field3D(mGrid, mType) #m = m1 m = Field3D(mGrid, mType) w = Field3D(mGrid, mType) n = Field3D(mGrid, mType) g = Field3D(mGrid, mType) ginv = Field3D(mGrid, mType) k_n = Field3D(mGrid, mType) k_m = Field3D(mGrid, mType) scratchV1 = Field3D(mGrid, mType) scratchV2 = Field3D(mGrid, mType) scratchG = Field3D(mGrid, mType) scratchM = Field3D(mGrid, mType) RK4_m = Field3D(mGrid, mType) RK4_n = Field3D(mGrid, mType) SetToIdentity(g) SetToIdentity(ginv) Copy(n, n0) Copy(w,n) diffOp.applyInverseOperator(w) Copy(m, m0) Copy(v,m) diffOp.applyInverseOperator(v) #common.DebugHere() mtArray=[] ginvArray=[] if saveOutput: #common.DebugHere() mtArray.append(m.copy()) ginvArray.append(ginv.copy()) norm2_m=[Dot(m,v)] norm2_n=[Dot(n,w)] inner_m_n=[Dot(m,w)] for i in range(1,len(t),1): dt = t[i] - t[i-1] if integMethod == "EULER": raise Exception('Euler integration for parallel transport not implemented: '+integMethod) elif integMethod == "RK4": EvaluateRHSFwd(k_n, w, g); MulC_I(k_n, dt) # k1_n computed Copy(RK4_n,k_n) EvaluateRHSParallelTransport(k_m, scratchV1, n, w, m, v, diffOp); MulC_I(k_m, dt) # k1_m computed Copy(RK4_m,k_m) # for k2_n Copy(scratchG, g); MulC_I(k_n,0.5); Add_I(scratchG,k_n); UpdateInverse(scratchV2, scratchV1, ginv, k_n, Ninv); CoAd(n,scratchV2, n0); Copy(w,n); diffOp.applyInverseOperator(w); EvaluateRHSFwd(k_n, w, scratchG); MulC_I(k_n, dt) # k2 computed Add_MulC_I(RK4_n, k_n, 2.0) # for k2_m Copy(scratchM, m); MulC_I(k_m,0.5); Add_I(scratchM,k_m); Copy(v,scratchM); diffOp.applyInverseOperator(v); EvaluateRHSParallelTransport(k_m, scratchV1, n, w, scratchM, v, diffOp); MulC_I(k_m, dt) # k2_m computed Add_MulC_I(RK4_m, k_m, 2.0) # for k3_n Copy(scratchG, g); MulC_I(k_n,0.5); Add_I(scratchG,k_n); UpdateInverse(scratchV2, scratchV1, ginv, k_n, Ninv); CoAd(n,scratchV2, n0);Copy(w,n); diffOp.applyInverseOperator(w); EvaluateRHSFwd(k_n, w, scratchG); MulC_I(k_n, dt) # k3_n computed Add_MulC_I(RK4_n, k_n, 2.0) # for k3_m Copy(scratchM, m); MulC_I(k_m,0.5); Add_I(scratchM,k_m); Copy(v,scratchM); diffOp.applyInverseOperator(v); EvaluateRHSParallelTransport(k_m, scratchV1, n, w, scratchM, v, diffOp); MulC_I(k_m, dt) # k3_m computed Add_MulC_I(RK4_m, k_m, 2.0) # for k4_n Copy(scratchG, g); Add_I(scratchG,k_n); UpdateInverse(scratchV2, scratchV1, ginv, k_n, Ninv); CoAd(n,scratchV2, n0);Copy(w,n); diffOp.applyInverseOperator(w); EvaluateRHSFwd(k_n, w, scratchG); MulC_I(k_n, dt) # k4_n computed Add_I(RK4_n, k_n) # for k4_m Copy(scratchM, m); Add_I(scratchM,k_m); Copy(v,scratchM); diffOp.applyInverseOperator(v); EvaluateRHSParallelTransport(k_m, scratchV1, n, w, scratchM, v, diffOp); MulC_I(k_m, dt) # k4_m computed Add_I(RK4_m, k_m) # final update MulC_I(RK4_n,1.0/float(6.0)) Add_I(g,RK4_n) UpdateInverse(scratchV2, scratchV1, ginv, RK4_n, Ninv) Copy(ginv,scratchV2) Add_MulC_I(m, RK4_m, 1.0/float(6.0)) else: raise Exception('Unknown integration method: '+integMethod) # end if # Coadjoint action gives us momentum at time t CoAd(n, ginv, n0) Copy(w,n) # Smooth to get velocity at time t diffOp.applyInverseOperator(w) Copy(v,m) diffOp.applyInverseOperator(v) if saveOutput: mtArray.append(m.copy()) ginvArray.append(ginv.copy()) # save norms and inner product norm2_m.append(Dot(m,v)) norm2_n.append(Dot(n,w)) inner_m_n.append(Dot(m,w)) # end for Copy(m1,m) return norm2_m, norm2_n, inner_m_n, mtArray, ginvArray def EvaluateRHSParallelTransport(out_m, scratchV, n, w, m, v, diffOp): ''' Evaluate RHS for parallel transport ''' AdInf(out_m, w, v) diffOp.applyOperator(out_m) CoAdInf(scratchV, w, m) Sub_I(out_m, scratchV) CoAdInf(scratchV, v, n) Sub_I(out_m, scratchV) MulC_I(out_m, 0.5) return out_m #end EvaluateRHSFwd def MyGridPlot(vf, sliceIdx=None, dim='z', every=1, isVF=True, color='g', plotBase=True, colorbase='#A0A0FF'): sliceArr = common.ExtractSliceArrVF(vf, sliceIdx, dim) sz = sliceArr.shape hID = np.mgrid[0:sz[0], 0:sz[1]] d1 = np.squeeze(hID[1, ::every, ::every]) d2 = np.squeeze(hID[0, ::every, ::every]) sliceArr = sliceArr[::every, ::every, :] if plotBase: plt.plot(d1, d2, colorbase) plt.hold(True) plt.plot(d1.T, d2.T, colorbase) if not isVF: d1 = np.zeros(d1.shape) d2 = np.zeros(d2.shape) if dim=='z': plt.plot(d1+np.squeeze(sliceArr[:,:,1]), d2+np.squeeze(sliceArr[:,:,0]), color) plt.hold(True) plt.plot((d1+np.squeeze(sliceArr[:,:,1])).T, (d2+np.squeeze(sliceArr[:,:,0])).T, color) plt.hold(False) elif dim=='x': plt.plot(d1+np.squeeze(sliceArr[:,:,2]), d2+np.squeeze(sliceArr[:,:,1]), color) plt.hold(True) plt.plot((d1+np.squeeze(sliceArr[:,:,2])).T, (d2+np.squeeze(sliceArr[:,:,1])).T, color) plt.hold(False) elif dim=='y': plt.plot(d1+np.squeeze(sliceArr[:,:,2]), d2+np.squeeze(sliceArr[:,:,0]), color) plt.hold(True) plt.plot((d1+np.squeeze(sliceArr[:,:,2])).T, (d2+np.squeeze(sliceArr[:,:,0])).T, color) plt.hold(False) # change axes to match image axes if not plt.gca().yaxis_inverted(): plt.gca().invert_yaxis() # force redraw plt.draw() def MyQuiver(vf, sliceIdx=None, dim='z',every=1,thresh=None,scaleArrows=None,arrowCol='r',lineWidth=None, width=None): sliceArr = common.ExtractSliceArrVF(vf, sliceIdx, dim) if dim=='z': vy = np.squeeze(sliceArr[:,:,0]) vx = np.squeeze(sliceArr[:,:,1]) elif dim=='x': vy = np.squeeze(sliceArr[:,:,1]) vx = np.squeeze(sliceArr[:,:,2]) elif dim=='y': vy = np.squeeze(sliceArr[:,:,0]) vx = np.squeeze(sliceArr[:,:,2]) vxshow = np.zeros(np.shape(vx)) vyshow = np.zeros(np.shape(vy)) vxshow[::every,::every] = vx[::every,::every] vyshow[::every,::every] = vy[::every,::every] valindex = np.zeros(np.shape(vx),dtype=bool) valindex[::every,::every] = True if thresh is not None: valindex[(vx**2+vy**2)<thresh] = False #gridX, gridY = np.meshgrid(range(np.shape(vx)[0]),range(np.shape(vx)[1]-1,-1,-1)) gridX, gridY = np.meshgrid(range(np.shape(vx)[0]),range(np.shape(vx)[1])) quiverhandle = plt.quiver(gridX[valindex],gridY[valindex],vx[valindex],vy[valindex],scale=scaleArrows,color=arrowCol,linewidth=lineWidth,width=width,zorder=4) # change axes to match image axes plt.gca().invert_yaxis() # force redraw plt.draw()<|fim▁end|>
# end for
<|file_name|>bind-by-move-neither-can-live-while-the-other-survives-3.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct X { x: (), }<|fim▁hole|> fn drop(&mut self) { println!("destructor runs"); } } enum double_option<T,U> { some2(T,U), none2 } fn main() { let x = some2(X { x: () }, X { x: () }); match x { some2(ref _y, _z) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern none2 => fail!() } }<|fim▁end|>
impl Drop for X {
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import os from fabric.decorators import task from fabric.api import local, run, cd, env, prefix, hide from fabric.colors import cyan, red, green, yellow import app import git import virtualenv <|fim▁hole|> """Execute init tasks for all components (virtualenv, pip).""" print(yellow("# Setting up development environment...\n", True)) virtualenv.init() virtualenv.update() print(green("\n# DONE.", True)) print(green("Type ") + green("activate", True) + green(" to enable your dev virtual environment.")) @task def update(): """Update virtual env with requirements packages.""" virtualenv.update() @task def dev(): """Setting up Development mode.""" print(yellow("# Setting up development environment...\n", True)) virtualenv.init() virtualenv.update() print(green("\n# DONE.", True)) print(green("Type ") + green("activate", True) + green(" to enable your dev virtual environment.")) @task def clean(): """Clean .pyc files""" app.clean()<|fim▁end|>
@task def init():
<|file_name|>pluginFitSigmoidal.py<|end_file_name|><|fim▁begin|>#-------------------------------------------------- # Revision = $Rev: 20 $ # Date = $Date: 2011-08-05 20:42:24 +0200 (Fri, 05 Aug 2011) $ # Author = $Author: stefan $ #-------------------------------------------------- from pluginInterfaces import PluginFit, Parameter,leastsqFit import numpy as np class PluginFitThreeBodyBeta(PluginFit): def __init__(self): pass def fit(self,array,errarray,param,xmin=0,xmax=0, fitAxes=[]): """return the data that is needed for plotting the fitting result""" """0...a, 1...xc, 2...k, 3...y0""" self.params = [Parameter(v) for v in param] def f(x): return self.params[0]()/(1+np.exp(-(x-self.params[1]())/self.params[2]()))+self.params[3]() self.simpleFitAllAxes(f,array,errarray,xmin,xmax, fitAxes) return self.generateDataFromParameters(f,[np.amin(array[0,:]),np.amax(array[0,:])], np.size(fitAxes)+1, xmin, xmax, fitAxes) def getInitialParameters(self,data): """find the best initial values and return them""" dx = np.abs(data[0,0] - data[0,-1]) mi = np.amin(data[1,:]) ma = np.amax(data[1,:]) xc = (np.amax(data[0,:])-np.amin(data[0,:]))/2+np.amin(data[0,:]) return [ma-mi,xc,dx*2,mi]<|fim▁hole|> def getFitModelStr(self): """return a string of the implemented fitting model, i.e. 'linear fit (y=A*x +B)'""" return "Sigmoidal" def getResultStr(self): """return a special result, i.e. 'Frequency = blabla'""" return "nothing fitted"<|fim▁end|>
def getParameters(self): """return the fit parameters""" return np.array(["a","xc","dx","y0"])
<|file_name|>test_timeout2.js<|end_file_name|><|fim▁begin|>var http = require("http"); var querystring = require("querystring"); // 核心模块 var SBuffer=require("../tools/SBuffer"); var common=require("../tools/common"); var zlib=require("zlib"); var redis_pool=require("../tools/connection_pool"); var events = require('events'); var util = require('util'); function ProxyAgent(preHeaders,preAnalysisFields,logName){ this.headNeeds = preHeaders||""; this.preAnalysisFields = preAnalysisFields||""; this.AnalysisFields = {}; this.logName=logName||""; this.response=null; this.reqConf={}; this.retData=[]; this.redis =null; // redis {} redis_key events.EventEmitter.call(this); } /** * 获取服务配置信息 * @param 服务名 * @return object */ ProxyAgent.prototype.getReqConfig = function(logName){ var _self=this; var Obj={}; Obj=Config[logName]; Obj.logger=Analysis.getLogger(logName); Obj.name=logName; return Obj; } ProxyAgent.prototype.doRequest=function(_req,_res){ var _self=this; _self.reqConf=_self.getReqConfig(this.logName); logger.debug('进入'+_self.reqConf.desc+"服务"); var header_obj =this.packageHeaders(_req.headers,this.headNeeds); var url_obj = url.parse(request.url, true); var query_obj = url_obj.query; var postData = request.body|| ""; // 获取请求参数 _res.setHeader("Content-Type", config.contentType); _res.setHeader(config.headerkey, config.headerval); var opts=_self.packData(header_obj,query_obj,postData); logger.debug(header_obj.mobileid +_self.reqConf.desc+ '接口参数信息:'+opts[0].path +" data:"+ opts[1]); if(typeof(postData) =="object" && postData.redis_key.length>0){ this.getRedis(opts[0],opts[1]); } else{ this.httpProxy(opts[0],opts[1]); } } /** * 封装get post接口 * @param headers * @param query * @param body * @return [] */ ProxyAgent.prototype.packData=function(headers,query,body){ var _self=this; //resType 解释 ""==>GET,"body"==>POST,"json"==>特殊poi,"raw"==>原始数据 var type=_self.reqConf.resType || ""; body = body || ""; var len=0; var query_str=""; var body_str=""; if(type==""){ query=common.extends(query,headers); query_str = querystring.stringify(query, '&', '='); } else if(type=="body"){ body=common.extends(body,headers); body_str = querystring.stringify(body, '&', '='); len=body_str.length; if(body.redis_key){ this.redis={}; this.redis.redis_key=body.redis_key; } } else if(type=="json"){ query=common.extends(query,headers); query_str = 'json='+querystring.stringify(query, '&', '='); } else if(type=="raw"){ len=body.length; body_str=body; } var actionlocation = headers.actionlocation || ""; if(actionlocation==""){ actionlocation=query.actionlocation||""; } var opts=_self.getRequestOptions(len,actionlocation); opts.path+=((opts.path.indexOf("?")>=0)?"&":"?")+query_str; return [opts,body_str]; } /** * 获取请求头信息 * @param len数据长度 * @param actiontion 通用访问地址 * @return object 头信息 */ ProxyAgent.prototype.getRequestOptions=function(len,actionlocation){ var _self=this; var options = { //http请求参数设置 host: _self.reqConf.host, // 远端服务器域名 port: _self.reqConf.port, // 远端服务器端口号 path: _self.reqConf.path||"", headers : {'Connection' : 'keep-alive'} }; if(actionlocation.length>0){ options.path=actionlocation; } var rtype= _self.reqConf.reqType || ""; if(rtype.length>0){ options.headers['Content-Type']=rtype; } if(len>0){ options.headers['Content-Length']=len; } return options; } ProxyAgent.prototype.getRedisOptions=function(options,actionlocation){ var obj={}; return obj; } /** * 获取头部信息进行封装 * @param request.headers * @param need fields ;split with ',' * @return object headers */ ProxyAgent.prototype.packageHeaders = function(headers) { var fields=arguments[1]||""; var query_obj = {}; var reqip = headers['x-real-ip'] || '0'; // 客户端请求的真实ip地址 var forward = headers['x-forwarded-for'] || '0'; // 客户端请求来源 var osversion = headers['osversion'] || '0';// 客户端系统<|fim▁hole|> var imsi = headers['imsi'] || '0'; // 客户端imsi var mobileid = headers['mobileid'] || '0'; // 客户端mibileid var version = headers['version'] || '0';// 客户端版本version var selflon = headers['selflon'] || '0';// 经度 var selflat = headers['selflat'] || '0';// 维度 var uid = headers['uid'] || '0'; // 犬号 var radius=headers['radius']||'0';//误差半径 var platform=headers['platform']||"";//平台 ios ,android var gender= headers['gender'] || '0'; query_obj.gender = gender; query_obj.reqip = reqip; query_obj.forward = forward; query_obj.osversion = osversion; query_obj.devicemodel = devicemodel; query_obj.manufacturername = manufacturername; query_obj.actionlocation = actionlocation; query_obj.dpi = dpi; query_obj.imsi = imsi; query_obj.mobileid = mobileid; query_obj.version = version; query_obj.selflon = selflon; query_obj.selflat = selflat; query_obj.uid = uid; query_obj.radius=radius; query_obj.platform=platform; if(fields.length > 0){ var afields = fields.split(","); var newObj = {}; for(var i = 0; i < afields.length ; i ++){ newObj[afields[i]] = query_obj[afields[i]] || ""; } return newObj; } else{ return query_obj; } } /** * http 请求代理 * @param options 远程接口信息 * @param reqData 请求内容 req.method== get时一般为空 */ ProxyAgent.prototype.httpProxy = function (options,reqData){ var _self=this; var TongjiObj={}; var req = http.request(options, function(res) { TongjiObj.statusCode = res.statusCode ||500; var tmptime=Date.now(); TongjiObj.restime = tmptime; TongjiObj.resEnd =tmptime; TongjiObj.ends = tmptime; TongjiObj.length = 0; TongjiObj.last = tmptime; var sbuffer=new SBuffer(); res.setEncoding("utf-8"); res.on('data', function (trunk) { sbuffer.append(trunk); }); res.on('end', function () { TongjiObj.resEnd = Date.now(); //doRequestCB(response, {"data":sbuffer.toString(),"status":res.statusCode},TongjiObj,redisOpt); _self.emmit("onDone",sbuffer,TongjiObj); }); }); req.setTimeout(timeout,function(){ req.emit('timeOut',{message:'have been timeout...'}); }); req.on('error', function(e) { TongjiObj.statusCode=500; _self.emmit("onDone","",500,TongjiObj); }); req.on('timeOut', function(e) { req.abort(); TongjiObj.statusCode=500; TongjiObj.last = Date.now(); _self.emmit("onDone","",500,TongjiObj); }); req.end(reqData); } /** * 设置缓存 * @param redis_key * @param redis_time * @param resultBuffer */ ProxyAgent.prototype.setRedis = function (redis_key, redis_time, resultBuffer) { redis_pool.acquire(function(err, client) { if (!err) { client.setex(redis_key, redis_time, resultBuffer, function(err, repliy) { redis_pool.release(client); // 链接使用完毕释放链接 }); logger.debug(redis_key + '设置缓存数据成功!'); } else { writeLogs.logs(Analysis.getLogger('error'), 'error', { msg : 'redis_general保存数据到redis缓存数据库时链接redis数据库异常', err : 14 }); logger.debug(redis_key + '设置缓存数据失败!'); } }); } /** * 从缓存中获取数据,如果获取不到,则请求后台返回的数据返回给客户端 并且将返回的数据设置到redis缓存 * redis_key通过self变量中取 * @param options * @param reqData */ ProxyAgent.prototype.getRedis = function ( options, reqData) { var _self=this; var redis_key=this.redis.redis_key || ""; redis_pool.acquire(function(err, client) { if (!err) { client.get(redis_key, function(err, date) { redis_pool.release(client) // 用完之后释放链接 if (!err && date != null) { var resultBuffer = new Buffer(date); _self.response.statusCode = 200; _self.response.setHeader("Content-Length", resultBuffer.length); _self.response.write(resultBuffer); // 以二进制流的方式输出数据 _self.response.end(); logger.debug(redis_key + '通用接口下行缓存数据:' + date); } else { _self.httpProxy(options, reqData); } }); } else { _self.httpProxy(options, reqData); } }); } /** * 输出gzip数据 * response 内置 * @param resultBuffer */ ProxyAgent.prototype.gzipOutPut = function (resultBuffer){ var _self=this; zlib.gzip(resultBuffer, function(code, buffer){ // 对服务器返回的数据进行压缩 if (code != null) { // 如果正常结束 logger.debug('压缩成功,压缩前:'+resultBuffer.length+',压缩后:'+buffer.length); _self.response.setHeader('Content-Encoding', 'gzip'); //压缩标志 } else { buffer = new Buffer( '{"msg":["服务器返回数据非JSON格式"]}'); _self.response.statusCode=500; } _self.response.setHeader("Content-Length", buffer.length); _self.response.write(buffer); _self.response.end(); }); } /** * 请求完毕处理 * @param buffer type buffer/string * @param status 请求http状态 * @param tongji object统计对象 */ ProxyAgent.prototype.onDone =function(buffer,status){ var tongji=arguments[2] ||""; var _self=this; var resultStr = typeof(buffer)=="object"?buffer.toString():buffer; if(this.reqConf.isjson==1){ var resultObj = common.isJson( resultStr, _self.reqConf.logName); // 判断返回结果是否是json格式 if (resultObj) { // 返回结果是json格式 resultStr = JSON.stringify(resultObj); _self.response.statusCode = status; } else { resultStr = '{"msg":["gis服务器返回数据非JSON格式"]}'; _self.response.statusCode = 500; } } else{ _self.response.statusCode = status; } var resultBuffer = new Buffer(resultStr); if(tongji!=""){ tongji.ends = Date.now(); tongji.length = resultBuffer.length; } if(resultBuffer.length > 500 ){ //压缩输出 _self.gzipOutPut(resultBuffer); }else{ _self.response.setHeader("Content-Length", resultBuffer.length); _self.response.write(resultBuffer); // 以二进制流的方式输出数据 _self.response.end(); } if(tongji!=""){ tongji.last= Date.now(); tongji=common.extends(tongji,_self.preAnalysisFields); logger.debug('耗时:' + (tongji.last - tongji.start)+'ms statusCode='+status); writeLogs.logs(poiDetailServer,'poiDetailServer',obj); } }); ProxyAgent.prototype.onDones =function(buffer,status){ var tongji=arguments[2] ||""; this.retData.push([buffer,status,tongji]; }); ProxyAgent.prototype.dealDones =function(){ var tongji=arguments[2] ||""; this.retData.push([buffer,status,tongji]; }); //ProxyAgent 从event 集成 //utils.inherit(ProxyAgent,event); exports.ProxyAgent=ProxyAgent;<|fim▁end|>
var devicemodel = headers['devicemodel'] || '0';// 客户端型号 var manufacturername = headers['manufacturername'] || '0';// 制造厂商 var actionlocation = headers['actionlocation']; // 请求后台地址 var dpi = headers['dpi'] || '2.0';// 密度
<|file_name|>bad-lit-suffixes.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags: -Z parse-only extern "C"suffix //~ ERROR ABI spec with a suffix is invalid fn foo() {} extern "C"suffix //~ ERROR ABI spec with a suffix is invalid {} fn main() { ""suffix; //~ ERROR str literal with a suffix is invalid<|fim▁hole|> br#""#suffix; //~ ERROR binary str literal with a suffix is invalid 'a'suffix; //~ ERROR char literal with a suffix is invalid b'a'suffix; //~ ERROR byte literal with a suffix is invalid 1234u1024; //~ ERROR invalid width `1024` for integer literal 1234i1024; //~ ERROR invalid width `1024` for integer literal 1234f1024; //~ ERROR invalid width `1024` for float literal 1234.5f1024; //~ ERROR invalid width `1024` for float literal 1234suffix; //~ ERROR invalid suffix `suffix` for numeric literal 0b101suffix; //~ ERROR invalid suffix `suffix` for numeric literal 1.0suffix; //~ ERROR invalid suffix `suffix` for float literal 1.0e10suffix; //~ ERROR invalid suffix `suffix` for float literal }<|fim▁end|>
b""suffix; //~ ERROR binary str literal with a suffix is invalid r#""#suffix; //~ ERROR str literal with a suffix is invalid
<|file_name|>app.js<|end_file_name|><|fim▁begin|>(function() { 'use strict'; var express = require('express'); var path = require('path'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes/index'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, '../client')));<|fim▁hole|> console.log('Express server listening on port ' + server.address().port); }); module.exports = app; }());<|fim▁end|>
app.use('/', routes); app.set('port', process.env.PORT || 3000); var server = app.listen(app.get('port'), function() {
<|file_name|>example2.rs<|end_file_name|><|fim▁begin|>// pp-exact:example2.pp<|fim▁hole|><|fim▁end|>
fn main() { }
<|file_name|>opencv_utils.hh<|end_file_name|><|fim▁begin|>#ifndef VPP_OPENCV_UTILS_HH_ # define VPP_OPENCV_UTILS_HH_ # include <iostream> # include <regex> # include <opencv2/highgui/highgui.hpp> # include <vpp/core/boxNd.hh> # include <vpp/core/image2d.hh> inline bool open_videocapture(const char* str, cv::VideoCapture& cap) { if (std::regex_match(str, std::regex("[0-9]+"))) cap.open(atoi(str)); else cap.open(str); if (!cap.isOpened()) { std::cerr << "Error: Cannot open " << str << std::endl; return false; } return true; } inline vpp::box2d videocapture_domain(cv::VideoCapture& cap) { return vpp::make_box2d(cap.get(CV_CAP_PROP_FRAME_HEIGHT), cap.get(CV_CAP_PROP_FRAME_WIDTH)); } inline vpp::box2d videocapture_domain(const char* f) { cv::VideoCapture cap;<|fim▁hole|> return vpp::make_box2d(cap.get(CV_CAP_PROP_FRAME_HEIGHT), cap.get(CV_CAP_PROP_FRAME_WIDTH)); } struct foreach_videoframe { foreach_videoframe(const char* f) { open_videocapture(f, cap_); frame_ = vpp::image2d<vpp::vuchar3>(videocapture_domain(cap_)); cvframe_ = to_opencv(frame_); } template <typename F> void operator| (F f) { while (cap_.read(cvframe_)) f(frame_); } private: cv::Mat cvframe_; vpp::image2d<vpp::vuchar3> frame_; cv::VideoCapture cap_; }; #endif<|fim▁end|>
open_videocapture(f, cap);
<|file_name|>gaussian.py<|end_file_name|><|fim▁begin|># -*- coding: utf8 -*- import math from pycraft.common.util import ndarray, product class GaussianKernel: __slots__ = ['_size', '_kernel'] def __init__(self, size): self._size = size self._kernel = ndarray(2*size + 1, 2*size + 1) bell_size = 1.0 / size bell_height = 2 * size for dx, dz in product(range(-size, size+1), range(-size, size+1)): bx = bell_size * dx bz = bell_size * dz<|fim▁hole|> def get(self, dx, dz): return self._kernel[dx+self._size][dz+self._size]<|fim▁end|>
self._kernel[dx+size][dz+size] = \ bell_height * math.exp(-(bx**2 + bz**2) / 2)
<|file_name|>luci_auth.py<|end_file_name|><|fim▁begin|># Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import re import subprocess import sys import six _RE_INFO_USER_EMAIL = r'Logged in as (?P<email>\S+)\.$' class AuthorizationError(Exception): pass def _RunCommand(command): try:<|fim▁hole|> subprocess.check_output(['luci-auth', command], stderr=subprocess.STDOUT, universal_newlines=True)) except subprocess.CalledProcessError as exc: raise AuthorizationError(exc.output.strip()) def CheckLoggedIn(): """Check that the user is currently logged in. Otherwise sys.exit immediately with the error message from luci-auth instructing the user how to log in. """ try: GetAccessToken() except AuthorizationError as exc: sys.exit(str(exc)) def GetAccessToken(): """Get an access token to make requests on behalf of the logged in user.""" return _RunCommand('token').rstrip() def GetUserEmail(): """Get the email address of the currently logged in user.""" output = _RunCommand('info') m = re.match(_RE_INFO_USER_EMAIL, output, re.MULTILINE) assert m, 'Failed to parse luci-auth info output.' return m.group('email')<|fim▁end|>
return six.ensure_str(
<|file_name|>MainActivity.java<|end_file_name|><|fim▁begin|>package com.mortensickel.measemulator; // http://maps.google.com/maps?q=loc:59.948509,10.602627 import com.google.android.gms.common.api.*; import android.content.Context; import android.text.*; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.view.animation.*; import android.app.*; import android.os.*; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Handler.Callback; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.*; import android.view.View.*; import android.location.Location; import android.util.Log; import com.google.android.gms.location.*; import com.google.android.gms.common.*; import android.preference.*; import android.view.*; import android.content.*; import android.net.Uri; // import org.apache.http.impl.execchain.*; // Todo over a certain treshold, change calibration factor // TODO settable calibration factor // TODO finish icons // DONE location // DONE input background and source. Calculate activity from distance // TODO Use distribution map // DONE add settings menu // TODO generic skin // TODO handle pause and shutdown public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,LocationListener { /* AUTOMESS: 0.44 pps = 0.1uSv/h ca 16. pulser pr nSv */ boolean poweron=false; long shutdowntime=0; long meastime; TextView tvTime,tvPulsedata, tvPause,tvAct, tvDoserate; long starttime = 0; public long pulses=0; Integer mode=0; final Integer MAXMODE=3; final int MODE_OFF=0; final int MODE_MOMENTANDOSE=1; final int MODE_DOSERATE=2; final int MODE_DOSE=3; public final String TAG="measem"; double calibration=4.4; public Integer sourceact=1; protected long lastpulses=0; public boolean gpsenabled = true; public Context context; public Integer gpsinterval=2000; private GoogleApiClient gac; private Location here,there; protected LocationRequest loreq; private LinearLayout llDebuginfo; private Double background=0.0; private float sourcestrength=1000; private boolean showDebug=false; private final String PULSES="pulses"; @Override public void onConnectionFailed(ConnectionResult p1) { // TODO: Implement this method } @Override public void onSaveInstanceState(Bundle savedInstanceState) { // Save the user's current game state savedInstanceState.putLong(PULSES,pulses); //savedInstanceState.putInt(PLAYER_LEVEL, mCurrentLevel); // Always call the superclass so it can save the view hierarchy state super.onSaveInstanceState(savedInstanceState); } public void onRestoreInstanceState(Bundle savedInstanceState) { // Always call the superclass so it can restore the view hierarchy super.onRestoreInstanceState(savedInstanceState); // Restore state members from saved instance pulses = savedInstanceState.getLong(PULSES); //mCurrentLevel = savedInstanceState.getInt(PLAYER_LEVEL); } protected void createLocationRequest(){ loreq = new LocationRequest(); loreq.setInterval(gpsinterval); loreq.setFastestInterval(100); loreq.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } protected void startLocationUpdates(){ if(loreq==null){ createLocationRequest(); } LocationServices.FusedLocationApi.requestLocationUpdates(gac,loreq,this); } public void ConnectionCallbacks(){ } @Override public void onLocationChanged(Location p1) { here=p1; double distance=here.distanceTo(there); sourceact=(int)Math.round(background+sourcestrength/(distance*distance)); tvAct.setText(String.valueOf(sourceact)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // TODO: Implement this method MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.mainmenu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.mnuSettings: Intent intent=new Intent(); intent.setClass(MainActivity.this,SetPreferenceActivity.class); startActivityForResult(intent,0); return true; case R.id.mnuSaveLoc: saveLocation(); return true; case R.id.mnuShowLoc: showLocation(); return true; } return super.onOptionsItemSelected(item); } protected void showLocation(){ String lat=String.valueOf(there.getLatitude()); String lon=String.valueOf(there.getLongitude()); Toast.makeText(getApplicationContext(),getString(R.string.SourceLocation)+lat+','+lon, Toast.LENGTH_LONG).show(); try { Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?q=loc:"+lat+","+lon)); startActivity(myIntent); } catch (ActivityNotFoundException e) { Toast.makeText(this, "No application can handle this request.",Toast.LENGTH_LONG).show(); e.printStackTrace(); } } protected void saveLocation(){ Location LastLocation = LocationServices.FusedLocationApi.getLastLocation( gac); if (LastLocation != null) { String lat=String.valueOf(LastLocation.getLatitude()); String lon=String.valueOf(LastLocation.getLongitude()); Toast.makeText(getApplicationContext(),getString(R.string.SourceLocation)+lat+','+lon, Toast.LENGTH_LONG).show(); there=LastLocation; SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); //SharedPreferences sp=this.getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor ed=sp.edit(); ed.putString("Latitude",lat); ed.putString("Longitude",lon); ed.apply(); ed.commit(); }else{ Toast.makeText(getApplicationContext(),getString(R.string.CouldNotGetLocation), Toast.LENGTH_LONG).show(); } } @Override public void onConnected(Bundle p1) { Location loc = LocationServices.FusedLocationApi.getLastLocation(gac); if(loc != null){ here=loc; } } @Override public void onConnectionSuspended(int p1) { // TODO: Implement this method } protected void onStart(){ gac.connect(); super.onStart(); } protected void onStop(){ gac.disconnect(); super.onStop(); } //this posts a message to the main thread from our timertask //and updates the textfield final Handler h = new Handler(new Callback() { @Override public boolean handleMessage(Message msg) { long millis = System.currentTimeMillis() - starttime; int seconds = (int) (millis / 1000); if(seconds>0){ double display=0; if( mode==MODE_MOMENTANDOSE){ if (lastpulses==0 || (lastpulses>pulses)){ display=0; }else{ display=((pulses-lastpulses)/calibration); } lastpulses=pulses; } if (mode==MODE_DOSERATE){ display=(double)pulses/(double)seconds/calibration; } if (mode==MODE_DOSE){ display=(double)pulses/calibration/3600; } tvDoserate.setText(String.format("%.2f",display)); } if(showDebug){ int minutes = seconds / 60; seconds = seconds % 60; tvTime.setText(String.format("%d:%02d", minutes, seconds)); } return false; } }); //runs without timer - reposting itself after a random interval Handler h2 = new Handler(); Runnable run = new Runnable() { @Override public void run() { int n=1; long pause=pause(getInterval()); h2.postDelayed(run,pause); if(showDebug){ tvPause.setText(String.format("%d",pause)); } receivepulse(n); } }; public Integer getInterval(){ Integer act=sourceact; if(act==0){ act=1; } Integer interval=5000/act; if (interval==0){ interval=1; } return(interval); } public long pause(Integer interval){ double pause=interval; if(interval > 5){ Random rng=new Random(); pause=rng.nextGaussian(); Integer sd=interval/4; pause=pause*sd+interval; if(pause<0){pause=0;} } return((long)pause); } public void receivepulse(int n){ LinearLayout myText = (LinearLayout) findViewById(R.id.llLed ); Animation anim = new AlphaAnimation(0.0f, 1.0f); anim.setDuration(20); //You can manage the time of the blink with this parameter anim.setStartOffset(20); anim.setRepeatMode(Animation.REVERSE); anim.setRepeatCount(0); myText.startAnimation(anim); pulses=pulses+1; Double sdev=Math.sqrt(pulses); if(showDebug){ tvPulsedata.setText(String.format("%d - %.1f - %.0f %%",pulses,sdev,sdev/pulses*100)); } } //tells handler to send a message class firstTask extends TimerTask { @Override public void run() { h.sendEmptyMessage(0); } } @Override protected void onResume() { // TODO: Implement this method super.onResume(); SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); // lowprobCutoff = (double)sharedPref.getFloat("pref_key_lowprobcutoff", 1)/100; readPrefs(); //XlowprobCutoff= } private void readPrefs(){ SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); String ret=sharedPref.getString("Latitude", "10"); Double lat= Double.parseDouble(ret); ret=sharedPref.getString("Longitude", "60"); Double lon= Double.parseDouble(ret); there.setLatitude(lat); there.setLongitude(lon); ret=sharedPref.getString("backgroundValue", "1"); background= Double.parseDouble(ret)/200; showDebug=sharedPref.getBoolean("showDebug", false); debugVisible(showDebug); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); readPrefs(); } Timer timer = new Timer(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); context=this; loadPref(context); /*SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE); double lat = getResources().get; long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue); SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE); // getString(R.string.preference_file_key), Context.MODE_PRIVATE); */ there = new Location("dummyprovider"); there.setLatitude(59.948509); there.setLongitude(10.602627); llDebuginfo=(LinearLayout)findViewById(R.id.llDebuginfo); llDebuginfo.setVisibility(View.GONE); gac=new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build(); tvTime = (TextView)findViewById(R.id.tvTime); tvPulsedata = (TextView)findViewById(R.id.tvPulsedata); tvPause = (TextView)findViewById(R.id.tvPause); tvDoserate = (TextView)findViewById(R.id.etDoserate); tvAct=(EditText)findViewById(R.id.activity); tvAct.addTextChangedListener(activityTW); switchMode(mode); Button b = (Button)findViewById(R.id.btPower); b.setOnClickListener(onOffClick); b=(Button)findViewById(R.id.btMode); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { modechange(v); } }); b=(Button)findViewById(R.id.btLight); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDebug=!showDebug; } }); } @Override public void onPause() { super.onPause(); timer.cancel(); timer.purge(); h2.removeCallbacks(run); } <|fim▁hole|> } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { String act=tvAct.getText().toString(); if(act.equals("")){act="1";} sourceact=Integer.parseInt(act); // TODO better errorchecking. // TODO disable if using geolocation }}; View.OnClickListener onOffClick = new View.OnClickListener() { @Override public void onClick(View v) { if(poweron){ long now=System.currentTimeMillis(); if(now> shutdowntime && now < shutdowntime+500){ timer.cancel(); timer.purge(); h2.removeCallbacks(run); pulses=0; poweron=false; mode=MODE_OFF; switchMode(mode); } shutdowntime = System.currentTimeMillis()+500; }else{ shutdowntime=0; starttime = System.currentTimeMillis(); timer = new Timer(); timer.schedule(new firstTask(), 0,500); startLocationUpdates(); h2.postDelayed(run, pause(getInterval())); mode=1; switchMode(mode); poweron=true; } } }; private void debugVisible(Boolean show){ View debug=findViewById(R.id.llDebuginfo); if(show){ debug.setVisibility(View.VISIBLE); }else{ debug.setVisibility(View.GONE); } } public void loadPref(Context ctx){ //SharedPreferences shpref=PreferenceManager.getDefaultSharedPreferences(ctx); PreferenceManager.setDefaultValues(ctx, R.xml.preferences, false); } public void modechange(View v){ if(mode > 0){ mode++; if (mode > MAXMODE){ mode=1; } switchMode(mode);} } public void switchMode(int mode){ int unit=0; switch(mode){ case MODE_MOMENTANDOSE: unit= R.string.ugyh; break; case MODE_DOSERATE: unit = R.string.ugyhint; break; case MODE_DOSE: unit = R.string.ugy; break; case MODE_OFF: unit= R.string.blank; tvDoserate.setText(""); break; } TextView tv=(TextView)findViewById(R.id.etUnit); tv.setText(unit); } }<|fim▁end|>
TextWatcher activityTW = new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub