code
stringlengths
4
1.01M
language
stringclasses
2 values
# Abutilon densiflorum Walp. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphhopper.jsprit.core.algorithm; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Collection; import java.util.Random; import org.junit.Test; import com.graphhopper.jsprit.core.algorithm.acceptor.SolutionAcceptor; import com.graphhopper.jsprit.core.algorithm.listener.SearchStrategyModuleListener; import com.graphhopper.jsprit.core.algorithm.selector.SolutionSelector; import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem; import com.graphhopper.jsprit.core.problem.solution.SolutionCostCalculator; import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution; public class SearchStrategyTest { @Test(expected = IllegalStateException.class) public void whenANullModule_IsAdded_throwException() { SolutionSelector select = mock(SolutionSelector.class); SolutionAcceptor accept = mock(SolutionAcceptor.class); SolutionCostCalculator calc = mock(SolutionCostCalculator.class); SearchStrategy strat = new SearchStrategy("strat", select, accept, calc); strat.addModule(null); } @Test public void whenStratRunsWithOneModule_runItOnes() { SolutionSelector select = mock(SolutionSelector.class); SolutionAcceptor accept = mock(SolutionAcceptor.class); SolutionCostCalculator calc = mock(SolutionCostCalculator.class); final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class); final VehicleRoutingProblemSolution newSol = mock(VehicleRoutingProblemSolution.class); when(select.selectSolution(null)).thenReturn(newSol); final Collection<Integer> runs = new ArrayList<Integer>(); SearchStrategy strat = new SearchStrategy("strat", select, accept, calc); SearchStrategyModule mod = new SearchStrategyModule() { @Override public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) { runs.add(1); return vrpSolution; } @Override public String getName() { return null; } @Override public void addModuleListener( SearchStrategyModuleListener moduleListener) { } }; strat.addModule(mod); strat.run(vrp, null); assertEquals(runs.size(), 1); } @Test public void whenStratRunsWithTwoModule_runItTwice() { SolutionSelector select = mock(SolutionSelector.class); SolutionAcceptor accept = mock(SolutionAcceptor.class); SolutionCostCalculator calc = mock(SolutionCostCalculator.class); final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class); final VehicleRoutingProblemSolution newSol = mock(VehicleRoutingProblemSolution.class); when(select.selectSolution(null)).thenReturn(newSol); final Collection<Integer> runs = new ArrayList<Integer>(); SearchStrategy strat = new SearchStrategy("strat", select, accept, calc); SearchStrategyModule mod = new SearchStrategyModule() { @Override public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) { runs.add(1); return vrpSolution; } @Override public String getName() { return null; } @Override public void addModuleListener( SearchStrategyModuleListener moduleListener) { } }; SearchStrategyModule mod2 = new SearchStrategyModule() { @Override public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) { runs.add(1); return vrpSolution; } @Override public String getName() { return null; } @Override public void addModuleListener( SearchStrategyModuleListener moduleListener) { } }; strat.addModule(mod); strat.addModule(mod2); strat.run(vrp, null); assertEquals(runs.size(), 2); } @Test public void whenStratRunsWithNModule_runItNTimes() { SolutionSelector select = mock(SolutionSelector.class); SolutionAcceptor accept = mock(SolutionAcceptor.class); SolutionCostCalculator calc = mock(SolutionCostCalculator.class); final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class); final VehicleRoutingProblemSolution newSol = mock(VehicleRoutingProblemSolution.class); when(select.selectSolution(null)).thenReturn(newSol); int N = new Random().nextInt(1000); final Collection<Integer> runs = new ArrayList<Integer>(); SearchStrategy strat = new SearchStrategy("strat", select, accept, calc); for (int i = 0; i < N; i++) { SearchStrategyModule mod = new SearchStrategyModule() { @Override public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) { runs.add(1); return vrpSolution; } @Override public String getName() { return null; } @Override public void addModuleListener( SearchStrategyModuleListener moduleListener) { } }; strat.addModule(mod); } strat.run(vrp, null); assertEquals(runs.size(), N); } @Test(expected = IllegalStateException.class) public void whenSelectorDeliversNullSolution_throwException() { SolutionSelector select = mock(SolutionSelector.class); SolutionAcceptor accept = mock(SolutionAcceptor.class); SolutionCostCalculator calc = mock(SolutionCostCalculator.class); final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class); when(select.selectSolution(null)).thenReturn(null); int N = new Random().nextInt(1000); final Collection<Integer> runs = new ArrayList<Integer>(); SearchStrategy strat = new SearchStrategy("strat", select, accept, calc); for (int i = 0; i < N; i++) { SearchStrategyModule mod = new SearchStrategyModule() { @Override public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) { runs.add(1); return vrpSolution; } @Override public String getName() { return null; } @Override public void addModuleListener( SearchStrategyModuleListener moduleListener) { } }; strat.addModule(mod); } strat.run(vrp, null); assertEquals(runs.size(), N); } }
Java
import { extend } from 'flarum/extend'; import PermissionGrid from 'flarum/components/PermissionGrid'; export default function() { extend(PermissionGrid.prototype, 'moderateItems', items => { items.add('tag', { icon: 'fas fa-tag', label: app.translator.trans('flarum-tags.admin.permissions.tag_discussions_label'), permission: 'discussion.tag' }, 95); }); }
Java
#!/Users/wuga/Documents/website/wuga/env/bin/python2.7 # # The Python Imaging Library # $Id$ # from __future__ import print_function import sys if sys.version_info[0] > 2: import tkinter else: import Tkinter as tkinter from PIL import Image, ImageTk # -------------------------------------------------------------------- # an image animation player class UI(tkinter.Label): def __init__(self, master, im): if isinstance(im, list): # list of images self.im = im[1:] im = self.im[0] else: # sequence self.im = im if im.mode == "1": self.image = ImageTk.BitmapImage(im, foreground="white") else: self.image = ImageTk.PhotoImage(im) tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0) self.update() duration = im.info.get("duration", 100) self.after(duration, self.next) def next(self): if isinstance(self.im, list): try: im = self.im[0] del self.im[0] self.image.paste(im) except IndexError: return # end of list else: try: im = self.im im.seek(im.tell() + 1) self.image.paste(im) except EOFError: return # end of file duration = im.info.get("duration", 100) self.after(duration, self.next) self.update_idletasks() # -------------------------------------------------------------------- # script interface if __name__ == "__main__": if not sys.argv[1:]: print("Syntax: python player.py imagefile(s)") sys.exit(1) filename = sys.argv[1] root = tkinter.Tk() root.title(filename) if len(sys.argv) > 2: # list of images print("loading...") im = [] for filename in sys.argv[1:]: im.append(Image.open(filename)) else: # sequence im = Image.open(filename) UI(root, im).pack() root.mainloop()
Java
package com.apixandru.rummikub.api; /** * @author Alexandru-Constantin Bledea * @since Sep 16, 2015 */ public enum Rank { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, ELEVEN, TWELVE, THIRTEEN; public int asNumber() { return ordinal() + 1; } @Override public String toString() { return String.format("%2d", asNumber()); } }
Java
/* * Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.simulator.provisioner; import com.hazelcast.simulator.common.AgentsFile; import com.hazelcast.simulator.common.SimulatorProperties; import com.hazelcast.simulator.utils.Bash; import com.hazelcast.simulator.utils.jars.HazelcastJARs; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import org.jclouds.compute.ComputeService; import static com.hazelcast.simulator.common.SimulatorProperties.PROPERTIES_FILE_NAME; import static com.hazelcast.simulator.utils.CliUtils.initOptionsWithHelp; import static com.hazelcast.simulator.utils.CliUtils.printHelpAndExit; import static com.hazelcast.simulator.utils.CloudProviderUtils.isStatic; import static com.hazelcast.simulator.utils.SimulatorUtils.loadSimulatorProperties; import static com.hazelcast.simulator.utils.jars.HazelcastJARs.isPrepareRequired; import static com.hazelcast.simulator.utils.jars.HazelcastJARs.newInstance; import static java.util.Collections.singleton; final class ProvisionerCli { private final OptionParser parser = new OptionParser(); private final OptionSpec<Integer> scaleSpec = parser.accepts("scale", "Number of Simulator machines to scale to. If the number of machines already exists, the call is ignored. If the" + " desired number of machines is smaller than the actual number of machines, machines are terminated.") .withRequiredArg().ofType(Integer.class); private final OptionSpec installSpec = parser.accepts("install", "Installs Simulator on all provisioned machines."); private final OptionSpec uploadHazelcastSpec = parser.accepts("uploadHazelcast", "If defined --install will upload the Hazelcast JARs as well."); private final OptionSpec<Boolean> enterpriseEnabledSpec = parser.accepts("enterpriseEnabled", "Use JARs of Hazelcast Enterprise Edition.") .withRequiredArg().ofType(Boolean.class).defaultsTo(false); private final OptionSpec listAgentsSpec = parser.accepts("list", "Lists the provisioned machines (from " + AgentsFile.NAME + " file)."); private final OptionSpec<String> downloadSpec = parser.accepts("download", "Download all files from the remote Worker directories. Use --clean to delete all Worker directories.") .withOptionalArg().ofType(String.class).defaultsTo("workers"); private final OptionSpec cleanSpec = parser.accepts("clean", "Cleans the remote Worker directories on the provisioned machines."); private final OptionSpec killSpec = parser.accepts("kill", "Kills the Java processes on all provisioned machines (via killall -9 java)."); private final OptionSpec terminateSpec = parser.accepts("terminate", "Terminates all provisioned machines."); private final OptionSpec<String> propertiesFileSpec = parser.accepts("propertiesFile", "The file containing the Simulator properties. If no file is explicitly configured, first the local working directory" + " is checked for a file '" + PROPERTIES_FILE_NAME + "'. All missing properties are always loaded from" + " '$SIMULATOR_HOME/conf/" + PROPERTIES_FILE_NAME + "'.") .withRequiredArg().ofType(String.class); private ProvisionerCli() { } static Provisioner init(String[] args) { ProvisionerCli cli = new ProvisionerCli(); OptionSet options = initOptionsWithHelp(cli.parser, args); SimulatorProperties properties = loadSimulatorProperties(options, cli.propertiesFileSpec); ComputeService computeService = isStatic(properties) ? null : new ComputeServiceBuilder(properties).build(); Bash bash = new Bash(properties); HazelcastJARs hazelcastJARs = null; boolean enterpriseEnabled = options.valueOf(cli.enterpriseEnabledSpec); if (options.has(cli.uploadHazelcastSpec)) { String hazelcastVersionSpec = properties.getHazelcastVersionSpec(); if (isPrepareRequired(hazelcastVersionSpec) || !enterpriseEnabled) { hazelcastJARs = newInstance(bash, properties, singleton(hazelcastVersionSpec)); } } return new Provisioner(properties, computeService, bash, hazelcastJARs, enterpriseEnabled); } static void run(String[] args, Provisioner provisioner) { ProvisionerCli cli = new ProvisionerCli(); OptionSet options = initOptionsWithHelp(cli.parser, args); try { if (options.has(cli.scaleSpec)) { int size = options.valueOf(cli.scaleSpec); provisioner.scale(size); } else if (options.has(cli.installSpec)) { provisioner.installSimulator(); } else if (options.has(cli.listAgentsSpec)) { provisioner.listMachines(); } else if (options.has(cli.downloadSpec)) { String dir = options.valueOf(cli.downloadSpec); provisioner.download(dir); } else if (options.has(cli.cleanSpec)) { provisioner.clean(); } else if (options.has(cli.killSpec)) { provisioner.killJavaProcesses(); } else if (options.has(cli.terminateSpec)) { provisioner.terminate(); } else { printHelpAndExit(cli.parser); } } finally { provisioner.shutdown(); } } }
Java
# Aster argyropholis var. niveus Y.Ling VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
package OpenXPKI::Server::Workflow::Activity::Tools::SetAttribute; use strict; use base qw( OpenXPKI::Server::Workflow::Activity ); use OpenXPKI::Server::Context qw( CTX ); use OpenXPKI::Exception; use OpenXPKI::Debug; use OpenXPKI::Serialization::Simple; use Data::Dumper; sub execute { my $self = shift; my $workflow = shift; my $context = $workflow->context(); my $serializer = OpenXPKI::Serialization::Simple->new(); my $params = $self->param(); my $attrib = {}; ##! 32: 'SetAttrbute action parameters ' . Dumper $params foreach my $key (keys %{$params}) { my $val = $params->{$key}; if ($val) { ##! 16: 'Set attrib ' . $key $workflow->attrib({ $key => $val }); CTX('log')->workflow()->debug("Writing workflow attribute $key => $val"); } else { ##! 16: 'Unset attrib ' . $key # translation from empty to undef is required as the # attribute backend will write empty values $workflow->attrib({ $key => undef }); CTX('log')->workflow()->debug("Deleting workflow attribute $key"); } } return; } 1; __END__ =head1 Name OpenXPKI::Server::Workflow::Activity::Tools::SetAttribute =head1 Description Set values in the workflow attribute table. Uses the actions parameter list to determine the key/value pairs to be written. Values that result in an empty string are removed from the attribute table!
Java
package com.cognizant.cognizantits.qcconnection.qcupdation; import com4j.DISPID; import com4j.IID; import com4j.VTID; @IID("{B739B750-BFE1-43AF-8DD7-E8E8EFBBED7D}") public abstract interface IDashboardFolderFactory extends IBaseFactoryEx { @DISPID(9) @VTID(17) public abstract IList getChildPagesWithPrivateItems(IList paramIList); } /* Location: D:\Prabu\jars\QC.jar * Qualified Name: qcupdation.IDashboardFolderFactory * JD-Core Version: 0.7.0.1 */
Java
// 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. use collections::HashMap; use std::fmt; use std::from_str::from_str; use std::str::{MaybeOwned, Owned, Slice}; use compile::Program; use parse; use vm; use vm::{CaptureLocs, MatchKind, Exists, Location, Submatches}; /// Escapes all regular expression meta characters in `text` so that it may be /// safely used in a regular expression as a literal string. pub fn quote(text: &str) -> StrBuf { let mut quoted = StrBuf::with_capacity(text.len()); for c in text.chars() { if parse::is_punct(c) { quoted.push_char('\\') } quoted.push_char(c); } quoted } /// Tests if the given regular expression matches somewhere in the text given. /// /// If there was a problem compiling the regular expression, an error is /// returned. /// /// To find submatches, split or replace text, you'll need to compile an /// expression first. /// /// Note that you should prefer the `regex!` macro when possible. For example, /// `regex!("...").is_match("...")`. pub fn is_match(regex: &str, text: &str) -> Result<bool, parse::Error> { Regex::new(regex).map(|r| r.is_match(text)) } /// Regex is a compiled regular expression, represented as either a sequence /// of bytecode instructions (dynamic) or as a specialized Rust function /// (native). It can be used to search, split /// or replace text. All searching is done with an implicit `.*?` at the /// beginning and end of an expression. To force an expression to match the /// whole string (or a prefix or a suffix), you must use an anchor like `^` or /// `$` (or `\A` and `\z`). /// /// While this crate will handle Unicode strings (whether in the regular /// expression or in the search text), all positions returned are **byte /// indices**. Every byte index is guaranteed to be at a UTF8 codepoint /// boundary. /// /// The lifetimes `'r` and `'t` in this crate correspond to the lifetime of a /// compiled regular expression and text to search, respectively. /// /// The only methods that allocate new strings are the string replacement /// methods. All other methods (searching and splitting) return borrowed /// pointers into the string given. /// /// # Examples /// /// Find the location of a US phone number: /// /// ```rust /// # use regex::Regex; /// let re = match Regex::new("[0-9]{3}-[0-9]{3}-[0-9]{4}") { /// Ok(re) => re, /// Err(err) => fail!("{}", err), /// }; /// assert_eq!(re.find("phone: 111-222-3333"), Some((7, 19))); /// ``` /// /// You can also use the `regex!` macro to compile a regular expression when /// you compile your program: /// /// ```rust /// #![feature(phase)] /// extern crate regex; /// #[phase(syntax)] extern crate regex_macros; /// /// fn main() { /// let re = regex!(r"\d+"); /// assert_eq!(re.find("123 abc"), Some((0, 3))); /// } /// ``` /// /// Given an incorrect regular expression, `regex!` will cause the Rust /// compiler to produce a compile time error. /// Note that `regex!` will compile the expression to native Rust code, which /// makes it much faster when searching text. /// More details about the `regex!` macro can be found in the `regex` crate /// documentation. #[deriving(Clone)] #[allow(visible_private_types)] pub struct Regex { /// The representation of `Regex` is exported to support the `regex!` /// syntax extension. Do not rely on it. /// /// See the comments for the `program` module in `lib.rs` for a more /// detailed explanation for what `regex!` requires. #[doc(hidden)] pub original: StrBuf, #[doc(hidden)] pub names: Vec<Option<StrBuf>>, #[doc(hidden)] pub p: MaybeNative, } impl fmt::Show for Regex { /// Shows the original regular expression. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.original) } } pub enum MaybeNative { Dynamic(Program), Native(fn(MatchKind, &str, uint, uint) -> Vec<Option<uint>>), } impl Clone for MaybeNative { fn clone(&self) -> MaybeNative { match *self { Dynamic(ref p) => Dynamic(p.clone()), Native(fp) => Native(fp), } } } impl Regex { /// Compiles a dynamic regular expression. Once compiled, it can be /// used repeatedly to search, split or replace text in a string. /// /// When possible, you should prefer the `regex!` macro since it is /// safer and always faster. /// /// If an invalid expression is given, then an error is returned. pub fn new(re: &str) -> Result<Regex, parse::Error> { let ast = try!(parse::parse(re)); let (prog, names) = Program::new(ast); Ok(Regex { original: re.to_strbuf(), names: names, p: Dynamic(prog), }) } /// Returns true if and only if the regex matches the string given. /// /// # Example /// /// Test if some text contains at least one word with exactly 13 /// characters: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let text = "I categorically deny having triskaidekaphobia."; /// let matched = regex!(r"\b\w{13}\b").is_match(text); /// assert!(matched); /// # } /// ``` pub fn is_match(&self, text: &str) -> bool { has_match(&exec(self, Exists, text)) } /// Returns the start and end byte range of the leftmost-first match in /// `text`. If no match exists, then `None` is returned. /// /// Note that this should only be used if you want to discover the position /// of the match. Testing the existence of a match is faster if you use /// `is_match`. /// /// # Example /// /// Find the start and end location of every word with exactly 13 /// characters: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let text = "I categorically deny having triskaidekaphobia."; /// let pos = regex!(r"\b\w{13}\b").find(text); /// assert_eq!(pos, Some((2, 15))); /// # } /// ``` pub fn find(&self, text: &str) -> Option<(uint, uint)> { let caps = exec(self, Location, text); if has_match(&caps) { Some((caps.get(0).unwrap(), caps.get(1).unwrap())) } else { None } } /// Returns an iterator for each successive non-overlapping match in /// `text`, returning the start and end byte indices with respect to /// `text`. /// /// # Example /// /// Find the start and end location of the first word with exactly 13 /// characters: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let text = "Retroactively relinquishing remunerations is reprehensible."; /// for pos in regex!(r"\b\w{13}\b").find_iter(text) { /// println!("{}", pos); /// } /// // Output: /// // (0, 13) /// // (14, 27) /// // (28, 41) /// // (45, 58) /// # } /// ``` pub fn find_iter<'r, 't>(&'r self, text: &'t str) -> FindMatches<'r, 't> { FindMatches { re: self, search: text, last_end: 0, last_match: None, } } /// Returns the capture groups corresponding to the leftmost-first /// match in `text`. Capture group `0` always corresponds to the entire /// match. If no match is found, then `None` is returned. /// /// You should only use `captures` if you need access to submatches. /// Otherwise, `find` is faster for discovering the location of the overall /// match. /// /// # Examples /// /// Say you have some text with movie names and their release years, /// like "'Citizen Kane' (1941)". It'd be nice if we could search for text /// looking like that, while also extracting the movie name and its release /// year separately. /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let re = regex!(r"'([^']+)'\s+\((\d{4})\)"); /// let text = "Not my favorite movie: 'Citizen Kane' (1941)."; /// let caps = re.captures(text).unwrap(); /// assert_eq!(caps.at(1), "Citizen Kane"); /// assert_eq!(caps.at(2), "1941"); /// assert_eq!(caps.at(0), "'Citizen Kane' (1941)"); /// # } /// ``` /// /// Note that the full match is at capture group `0`. Each subsequent /// capture group is indexed by the order of its opening `(`. /// /// We can make this example a bit clearer by using *named* capture groups: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let re = regex!(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)"); /// let text = "Not my favorite movie: 'Citizen Kane' (1941)."; /// let caps = re.captures(text).unwrap(); /// assert_eq!(caps.name("title"), "Citizen Kane"); /// assert_eq!(caps.name("year"), "1941"); /// assert_eq!(caps.at(0), "'Citizen Kane' (1941)"); /// # } /// ``` /// /// Here we name the capture groups, which we can access with the `name` /// method. Note that the named capture groups are still accessible with /// `at`. /// /// The `0`th capture group is always unnamed, so it must always be /// accessed with `at(0)`. pub fn captures<'t>(&self, text: &'t str) -> Option<Captures<'t>> { let caps = exec(self, Submatches, text); Captures::new(self, text, caps) } /// Returns an iterator over all the non-overlapping capture groups matched /// in `text`. This is operationally the same as `find_iter` (except it /// yields information about submatches). /// /// # Example /// /// We can use this to find all movie titles and their release years in /// some text, where the movie is formatted like "'Title' (xxxx)": /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let re = regex!(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)"); /// let text = "'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931)."; /// for caps in re.captures_iter(text) { /// println!("Movie: {}, Released: {}", caps.name("title"), caps.name("year")); /// } /// // Output: /// // Movie: Citizen Kane, Released: 1941 /// // Movie: The Wizard of Oz, Released: 1939 /// // Movie: M, Released: 1931 /// # } /// ``` pub fn captures_iter<'r, 't>(&'r self, text: &'t str) -> FindCaptures<'r, 't> { FindCaptures { re: self, search: text, last_match: None, last_end: 0, } } /// Returns an iterator of substrings of `text` delimited by a match /// of the regular expression. /// Namely, each element of the iterator corresponds to text that *isn't* /// matched by the regular expression. /// /// This method will *not* copy the text given. /// /// # Example /// /// To split a string delimited by arbitrary amounts of spaces or tabs: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let re = regex!(r"[ \t]+"); /// let fields: Vec<&str> = re.split("a b \t c\td e").collect(); /// assert_eq!(fields, vec!("a", "b", "c", "d", "e")); /// # } /// ``` pub fn split<'r, 't>(&'r self, text: &'t str) -> RegexSplits<'r, 't> { RegexSplits { finder: self.find_iter(text), last: 0, } } /// Returns an iterator of at most `limit` substrings of `text` delimited /// by a match of the regular expression. (A `limit` of `0` will return no /// substrings.) /// Namely, each element of the iterator corresponds to text that *isn't* /// matched by the regular expression. /// The remainder of the string that is not split will be the last element /// in the iterator. /// /// This method will *not* copy the text given. /// /// # Example /// /// Get the first two words in some text: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let re = regex!(r"\W+"); /// let fields: Vec<&str> = re.splitn("Hey! How are you?", 3).collect(); /// assert_eq!(fields, vec!("Hey", "How", "are you?")); /// # } /// ``` pub fn splitn<'r, 't>(&'r self, text: &'t str, limit: uint) -> RegexSplitsN<'r, 't> { RegexSplitsN { splits: self.split(text), cur: 0, limit: limit, } } /// Replaces the leftmost-first match with the replacement provided. /// The replacement can be a regular string (where `$N` and `$name` are /// expanded to match capture groups) or a function that takes the matches' /// `Captures` and returns the replaced string. /// /// If no match is found, then a copy of the string is returned unchanged. /// /// # Examples /// /// Note that this function is polymorphic with respect to the replacement. /// In typical usage, this can just be a normal string: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let re = regex!("[^01]+"); /// assert_eq!(re.replace("1078910", "").as_slice(), "1010"); /// # } /// ``` /// /// But anything satisfying the `Replacer` trait will work. For example, /// a closure of type `|&Captures| -> StrBuf` provides direct access to the /// captures corresponding to a match. This allows one to access /// submatches easily: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # use regex::Captures; fn main() { /// let re = regex!(r"([^,\s]+),\s+(\S+)"); /// let result = re.replace("Springsteen, Bruce", |caps: &Captures| { /// format_strbuf!("{} {}", caps.at(2), caps.at(1)) /// }); /// assert_eq!(result.as_slice(), "Bruce Springsteen"); /// # } /// ``` /// /// But this is a bit cumbersome to use all the time. Instead, a simple /// syntax is supported that expands `$name` into the corresponding capture /// group. Here's the last example, but using this expansion technique /// with named capture groups: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// let re = regex!(r"(?P<last>[^,\s]+),\s+(?P<first>\S+)"); /// let result = re.replace("Springsteen, Bruce", "$first $last"); /// assert_eq!(result.as_slice(), "Bruce Springsteen"); /// # } /// ``` /// /// Note that using `$2` instead of `$first` or `$1` instead of `$last` /// would produce the same result. To write a literal `$` use `$$`. /// /// Finally, sometimes you just want to replace a literal string with no /// submatch expansion. This can be done by wrapping a string with /// `NoExpand`: /// /// ```rust /// # #![feature(phase)] /// # extern crate regex; #[phase(syntax)] extern crate regex_macros; /// # fn main() { /// use regex::NoExpand; /// /// let re = regex!(r"(?P<last>[^,\s]+),\s+(\S+)"); /// let result = re.replace("Springsteen, Bruce", NoExpand("$2 $last")); /// assert_eq!(result.as_slice(), "$2 $last"); /// # } /// ``` pub fn replace<R: Replacer>(&self, text: &str, rep: R) -> StrBuf { self.replacen(text, 1, rep) } /// Replaces all non-overlapping matches in `text` with the /// replacement provided. This is the same as calling `replacen` with /// `limit` set to `0`. /// /// See the documentation for `replace` for details on how to access /// submatches in the replacement string. pub fn replace_all<R: Replacer>(&self, text: &str, rep: R) -> StrBuf { self.replacen(text, 0, rep) } /// Replaces at most `limit` non-overlapping matches in `text` with the /// replacement provided. If `limit` is 0, then all non-overlapping matches /// are replaced. /// /// See the documentation for `replace` for details on how to access /// submatches in the replacement string. pub fn replacen<R: Replacer> (&self, text: &str, limit: uint, mut rep: R) -> StrBuf { let mut new = StrBuf::with_capacity(text.len()); let mut last_match = 0u; for (i, cap) in self.captures_iter(text).enumerate() { // It'd be nicer to use the 'take' iterator instead, but it seemed // awkward given that '0' => no limit. if limit > 0 && i >= limit { break } let (s, e) = cap.pos(0).unwrap(); // captures only reports matches new.push_str(text.slice(last_match, s)); new.push_str(rep.reg_replace(&cap).as_slice()); last_match = e; } new.append(text.slice(last_match, text.len())) } } /// NoExpand indicates literal string replacement. /// /// It can be used with `replace` and `replace_all` to do a literal /// string replacement without expanding `$name` to their corresponding /// capture groups. /// /// `'r` is the lifetime of the literal text. pub struct NoExpand<'t>(pub &'t str); /// Replacer describes types that can be used to replace matches in a string. pub trait Replacer { /// Returns a possibly owned string that is used to replace the match /// corresponding the the `caps` capture group. /// /// The `'a` lifetime refers to the lifetime of a borrowed string when /// a new owned string isn't needed (e.g., for `NoExpand`). fn reg_replace<'a>(&'a mut self, caps: &Captures) -> MaybeOwned<'a>; } impl<'t> Replacer for NoExpand<'t> { fn reg_replace<'a>(&'a mut self, _: &Captures) -> MaybeOwned<'a> { let NoExpand(s) = *self; Slice(s) } } impl<'t> Replacer for &'t str { fn reg_replace<'a>(&'a mut self, caps: &Captures) -> MaybeOwned<'a> { Owned(caps.expand(*self).into_owned()) } } impl<'a> Replacer for |&Captures|: 'a -> StrBuf { fn reg_replace<'r>(&'r mut self, caps: &Captures) -> MaybeOwned<'r> { Owned((*self)(caps).into_owned()) } } /// Yields all substrings delimited by a regular expression match. /// /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime /// of the string being split. pub struct RegexSplits<'r, 't> { finder: FindMatches<'r, 't>, last: uint, } impl<'r, 't> Iterator<&'t str> for RegexSplits<'r, 't> { fn next(&mut self) -> Option<&'t str> { let text = self.finder.search; match self.finder.next() { None => { if self.last >= text.len() { None } else { let s = text.slice(self.last, text.len()); self.last = text.len(); Some(s) } } Some((s, e)) => { let matched = text.slice(self.last, s); self.last = e; Some(matched) } } } } /// Yields at most `N` substrings delimited by a regular expression match. /// /// The last substring will be whatever remains after splitting. /// /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime /// of the string being split. pub struct RegexSplitsN<'r, 't> { splits: RegexSplits<'r, 't>, cur: uint, limit: uint, } impl<'r, 't> Iterator<&'t str> for RegexSplitsN<'r, 't> { fn next(&mut self) -> Option<&'t str> { let text = self.splits.finder.search; if self.cur >= self.limit { None } else { self.cur += 1; if self.cur >= self.limit { Some(text.slice(self.splits.last, text.len())) } else { self.splits.next() } } } } /// Captures represents a group of captured strings for a single match. /// /// The 0th capture always corresponds to the entire match. Each subsequent /// index corresponds to the next capture group in the regex. /// If a capture group is named, then the matched string is *also* available /// via the `name` method. (Note that the 0th capture is always unnamed and so /// must be accessed with the `at` method.) /// /// Positions returned from a capture group are always byte indices. /// /// `'t` is the lifetime of the matched text. pub struct Captures<'t> { text: &'t str, locs: CaptureLocs, named: Option<HashMap<StrBuf, uint>>, } impl<'t> Captures<'t> { fn new(re: &Regex, search: &'t str, locs: CaptureLocs) -> Option<Captures<'t>> { if !has_match(&locs) { return None } let named = if re.names.len() == 0 { None } else { let mut named = HashMap::new(); for (i, name) in re.names.iter().enumerate() { match name { &None => {}, &Some(ref name) => { named.insert(name.to_strbuf(), i); } } } Some(named) }; Some(Captures { text: search, locs: locs, named: named, }) } /// Returns the start and end positions of the Nth capture group. /// Returns `None` if `i` is not a valid capture group or if the capture /// group did not match anything. /// The positions returned are *always* byte indices with respect to the /// original string matched. pub fn pos(&self, i: uint) -> Option<(uint, uint)> { let (s, e) = (i * 2, i * 2 + 1); if e >= self.locs.len() || self.locs.get(s).is_none() { // VM guarantees that each pair of locations are both Some or None. return None } Some((self.locs.get(s).unwrap(), self.locs.get(e).unwrap())) } /// Returns the matched string for the capture group `i`. /// If `i` isn't a valid capture group or didn't match anything, then the /// empty string is returned. pub fn at(&self, i: uint) -> &'t str { match self.pos(i) { None => "", Some((s, e)) => { self.text.slice(s, e) } } } /// Returns the matched string for the capture group named `name`. /// If `name` isn't a valid capture group or didn't match anything, then /// the empty string is returned. pub fn name(&self, name: &str) -> &'t str { match self.named { None => "", Some(ref h) => { match h.find_equiv(&name) { None => "", Some(i) => self.at(*i), } } } } /// Creates an iterator of all the capture groups in order of appearance /// in the regular expression. pub fn iter(&'t self) -> SubCaptures<'t> { SubCaptures { idx: 0, caps: self, } } /// Creates an iterator of all the capture group positions in order of /// appearance in the regular expression. Positions are byte indices /// in terms of the original string matched. pub fn iter_pos(&'t self) -> SubCapturesPos<'t> { SubCapturesPos { idx: 0, caps: self, } } /// Expands all instances of `$name` in `text` to the corresponding capture /// group `name`. /// /// `name` may be an integer corresponding to the index of the /// capture group (counted by order of opening parenthesis where `0` is the /// entire match) or it can be a name (consisting of letters, digits or /// underscores) corresponding to a named capture group. /// /// If `name` isn't a valid capture group (whether the name doesn't exist or /// isn't a valid index), then it is replaced with the empty string. /// /// To write a literal `$` use `$$`. pub fn expand(&self, text: &str) -> StrBuf { // How evil can you get? // FIXME: Don't use regexes for this. It's completely unnecessary. let re = Regex::new(r"(^|[^$]|\b)\$(\w+)").unwrap(); let text = re.replace_all(text, |refs: &Captures| -> StrBuf { let (pre, name) = (refs.at(1), refs.at(2)); format_strbuf!("{}{}", pre, match from_str::<uint>(name.as_slice()) { None => self.name(name).to_strbuf(), Some(i) => self.at(i).to_strbuf(), }) }); let re = Regex::new(r"\$\$").unwrap(); re.replace_all(text.as_slice(), NoExpand("$")) } } impl<'t> Container for Captures<'t> { /// Returns the number of captured groups. #[inline] fn len(&self) -> uint { self.locs.len() / 2 } } /// An iterator over capture groups for a particular match of a regular /// expression. /// /// `'t` is the lifetime of the matched text. pub struct SubCaptures<'t> { idx: uint, caps: &'t Captures<'t>, } impl<'t> Iterator<&'t str> for SubCaptures<'t> { fn next(&mut self) -> Option<&'t str> { if self.idx < self.caps.len() { self.idx += 1; Some(self.caps.at(self.idx - 1)) } else { None } } } /// An iterator over capture group positions for a particular match of a /// regular expression. /// /// Positions are byte indices in terms of the original string matched. /// /// `'t` is the lifetime of the matched text. pub struct SubCapturesPos<'t> { idx: uint, caps: &'t Captures<'t>, } impl<'t> Iterator<Option<(uint, uint)>> for SubCapturesPos<'t> { fn next(&mut self) -> Option<Option<(uint, uint)>> { if self.idx < self.caps.len() { self.idx += 1; Some(self.caps.pos(self.idx - 1)) } else { None } } } /// An iterator that yields all non-overlapping capture groups matching a /// particular regular expression. The iterator stops when no more matches can /// be found. /// /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime /// of the matched string. pub struct FindCaptures<'r, 't> { re: &'r Regex, search: &'t str, last_match: Option<uint>, last_end: uint, } impl<'r, 't> Iterator<Captures<'t>> for FindCaptures<'r, 't> { fn next(&mut self) -> Option<Captures<'t>> { if self.last_end > self.search.len() { return None } let caps = exec_slice(self.re, Submatches, self.search, self.last_end, self.search.len()); let (s, e) = if !has_match(&caps) { return None } else { (caps.get(0).unwrap(), caps.get(1).unwrap()) }; // Don't accept empty matches immediately following a match. // i.e., no infinite loops please. if e == s && Some(self.last_end) == self.last_match { self.last_end += 1; return self.next() } self.last_end = e; self.last_match = Some(self.last_end); Captures::new(self.re, self.search, caps) } } /// An iterator over all non-overlapping matches for a particular string. /// /// The iterator yields a tuple of integers corresponding to the start and end /// of the match. The indices are byte offsets. The iterator stops when no more /// matches can be found. /// /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime /// of the matched string. pub struct FindMatches<'r, 't> { re: &'r Regex, search: &'t str, last_match: Option<uint>, last_end: uint, } impl<'r, 't> Iterator<(uint, uint)> for FindMatches<'r, 't> { fn next(&mut self) -> Option<(uint, uint)> { if self.last_end > self.search.len() { return None } let caps = exec_slice(self.re, Location, self.search, self.last_end, self.search.len()); let (s, e) = if !has_match(&caps) { return None } else { (caps.get(0).unwrap(), caps.get(1).unwrap()) }; // Don't accept empty matches immediately following a match. // i.e., no infinite loops please. if e == s && Some(self.last_end) == self.last_match { self.last_end += 1; return self.next() } self.last_end = e; self.last_match = Some(self.last_end); Some((s, e)) } } fn exec(re: &Regex, which: MatchKind, input: &str) -> CaptureLocs { exec_slice(re, which, input, 0, input.len()) } fn exec_slice(re: &Regex, which: MatchKind, input: &str, s: uint, e: uint) -> CaptureLocs { match re.p { Dynamic(ref prog) => vm::run(which, prog, input, s, e), Native(exec) => exec(which, input, s, e), } } #[inline] fn has_match(caps: &CaptureLocs) -> bool { caps.len() >= 2 && caps.get(0).is_some() && caps.get(1).is_some() }
Java
@ECHO OFF SET RepoRoot=%~dp0..\..\.. %RepoRoot%\eng\build.cmd -projects %~dp0**\*.csproj /p:SkipIISNewHandlerTests=true /p:SkipIISNewShimTests=true %*
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.6.0_27) on Thu Jan 23 20:22:10 EST 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>Uses of Class org.apache.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory (Solr 4.6.1 API)</title> <meta name="date" content="2014-01-23"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory (Solr 4.6.1 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/solr/update/processor/ParseBooleanFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/solr/update/processor//class-useParseBooleanFieldUpdateProcessorFactory.html" target="_top">FRAMES</a></li> <li><a href="ParseBooleanFieldUpdateProcessorFactory.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory" class="title">Uses of Class<br>org.apache.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory</h2> </div> <div class="classUseContainer">No usage of org.apache.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/solr/update/processor/ParseBooleanFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/solr/update/processor//class-useParseBooleanFieldUpdateProcessorFactory.html" target="_top">FRAMES</a></li> <li><a href="ParseBooleanFieldUpdateProcessorFactory.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2014 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
Java
/* * Copyright (C) 2016 QAware GmbH * * 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 de.qaware.chronix.timeseries.dt; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import java.io.Serializable; import java.util.Arrays; import static de.qaware.chronix.timeseries.dt.ListUtil.*; /** * Implementation of a list with primitive doubles. * * @author f.lautenschlager */ public class DoubleList implements Serializable { private static final long serialVersionUID = -1275724597860546074L; /** * Shared empty array instance used for empty instances. */ private static final double[] EMPTY_ELEMENT_DATA = {}; /** * Shared empty array instance used for default sized empty instances. We * distinguish this from EMPTY_ELEMENT_DATA to know how much to inflate when * first element is added. */ private static final double[] DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA = {}; private double[] doubles; private int size; /** * Constructs an empty list with the specified initial capacity. * * @param initialCapacity the initial capacity of the list * @throws IllegalArgumentException if the specified initial capacity * is negative */ public DoubleList(int initialCapacity) { if (initialCapacity > 0) { this.doubles = new double[initialCapacity]; } else if (initialCapacity == 0) { this.doubles = EMPTY_ELEMENT_DATA; } else { throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity); } } /** * Constructs an empty list with an initial capacity of ten. */ public DoubleList() { this.doubles = DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA; } /** * Constructs a double list from the given values by simple assigning them. * * @param longs the values of the double list. * @param size the index of the last value in the array. */ @SuppressWarnings("all") public DoubleList(double[] longs, int size) { if (longs == null) { throw new IllegalArgumentException("Illegal initial array 'null'"); } if (size < 0) { throw new IllegalArgumentException("Size if negative."); } this.doubles = longs; this.size = size; } /** * Returns the number of elements in this list. * * @return the number of elements in this list */ public int size() { return size; } /** * Returns <tt>true</tt> if this list contains no elements. * * @return <tt>true</tt> if this list contains no elements */ public boolean isEmpty() { return size == 0; } /** * Returns <tt>true</tt> if this list contains the specified element. * More formally, returns <tt>true</tt> if and only if this list contains * at least one element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * * @param o element whose presence in this list is to be tested * @return <tt>true</tt> if this list contains the specified element */ public boolean contains(double o) { return indexOf(o) >= 0; } /** * Returns the index of the first occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the lowest index <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * or -1 if there is no such index. * * @param o the double value * @return the index of the given double element */ public int indexOf(double o) { for (int i = 0; i < size; i++) { if (o == doubles[i]) { return i; } } return -1; } /** * Returns the index of the last occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the highest index <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * or -1 if there is no such index. * * @param o the double value * @return the last index of the given double element */ public int lastIndexOf(double o) { for (int i = size - 1; i >= 0; i--) { if (o == doubles[i]) { return i; } } return -1; } /** * Returns a shallow copy of this <tt>LongList</tt> instance. (The * elements themselves are not copied.) * * @return a clone of this <tt>LongList</tt> instance */ public DoubleList copy() { DoubleList v = new DoubleList(size); v.doubles = Arrays.copyOf(doubles, size); v.size = size; return v; } /** * Returns an array containing all of the elements in this list * in proper sequence (from first to last element). * <p> * <p>The returned array will be "safe" in that no references to it are * maintained by this list. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * <p> * <p>This method acts as bridge between array-based and collection-based * APIs. * * @return an array containing all of the elements in this list in * proper sequence */ public double[] toArray() { return Arrays.copyOf(doubles, size); } private void growIfNeeded(int newCapacity) { if (newCapacity != -1) { doubles = Arrays.copyOf(doubles, newCapacity); } } /** * Returns the element at the specified position in this list. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException */ public double get(int index) { rangeCheck(index, size); return doubles[index]; } /** * Replaces the element at the specified position in this list with * the specified element. * * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position * @throws IndexOutOfBoundsException */ public double set(int index, double element) { rangeCheck(index, size); double oldValue = doubles[index]; doubles[index] = element; return oldValue; } /** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by Collection#add) */ public boolean add(double e) { int newCapacity = calculateNewCapacity(doubles.length, size + 1); growIfNeeded(newCapacity); doubles[size++] = e; return true; } /** * Inserts the specified element at the specified position in this * list. Shifts the element currently at that position (if any) and * any subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException */ public void add(int index, double element) { rangeCheckForAdd(index, size); int newCapacity = calculateNewCapacity(doubles.length, size + 1); growIfNeeded(newCapacity); System.arraycopy(doubles, index, doubles, index + 1, size - index); doubles[index] = element; size++; } /** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * * @param index the index of the element to be removed * @return the element that was removed from the list * @throws IndexOutOfBoundsException */ public double remove(int index) { rangeCheck(index, size); double oldValue = doubles[index]; int numMoved = size - index - 1; if (numMoved > 0) { System.arraycopy(doubles, index + 1, doubles, index, numMoved); } --size; return oldValue; } /** * Removes the first occurrence of the specified element from this list, * if it is present. If the list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt> * (if such an element exists). Returns <tt>true</tt> if this list * contained the specified element (or equivalently, if this list * changed as a result of the call). * * @param o element to be removed from this list, if present * @return <tt>true</tt> if this list contained the specified element */ public boolean remove(double o) { for (int index = 0; index < size; index++) { if (o == doubles[index]) { fastRemove(index); return true; } } return false; } private void fastRemove(int index) { int numMoved = size - index - 1; if (numMoved > 0) { System.arraycopy(doubles, index + 1, doubles, index, numMoved); } --size; } /** * Removes all of the elements from this list. The list will * be empty after this call returns. */ public void clear() { doubles = DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA; size = 0; } /** * Appends all of the elements in the specified collection to the end of * this list, in the order that they are returned by the * specified collection's Iterator. The behavior of this operation is * undefined if the specified collection is modified while the operation * is in progress. (This implies that the behavior of this call is * undefined if the specified collection is this list, and this * list is nonempty.) * * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throws NullPointerException if the specified collection is null */ public boolean addAll(DoubleList c) { double[] a = c.toArray(); int numNew = a.length; int newCapacity = calculateNewCapacity(doubles.length, size + numNew); growIfNeeded(newCapacity); System.arraycopy(a, 0, doubles, size, numNew); size += numNew; return numNew != 0; } /** * Appends the long[] at the end of this long list. * * @param otherDoubles the other double[] that is appended * @return <tt>true</tt> if this list changed as a result of the call * @throws NullPointerException if the specified array is null */ public boolean addAll(double[] otherDoubles) { int numNew = otherDoubles.length; int newCapacity = calculateNewCapacity(doubles.length, size + numNew); growIfNeeded(newCapacity); System.arraycopy(otherDoubles, 0, doubles, size, numNew); size += numNew; return numNew != 0; } /** * Inserts all of the elements in the specified collection into this * list, starting at the specified position. Shifts the element * currently at that position (if any) and any subsequent elements to * the right (increases their indices). The new elements will appear * in the list in the order that they are returned by the * specified collection's iterator. * * @param index index at which to insert the first element from the * specified collection * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throws IndexOutOfBoundsException * @throws NullPointerException if the specified collection is null */ public boolean addAll(int index, DoubleList c) { rangeCheckForAdd(index, size); double[] a = c.toArray(); int numNew = a.length; int newCapacity = calculateNewCapacity(doubles.length, size + numNew); growIfNeeded(newCapacity); int numMoved = size - index; if (numMoved > 0) { System.arraycopy(doubles, index, doubles, index + numNew, numMoved); } System.arraycopy(a, 0, doubles, index, numNew); size += numNew; return numNew != 0; } /** * Removes from this list all of the elements whose index is between * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. * Shifts any succeeding elements to the left (reduces their index). * This call shortens the list by {@code (toIndex - fromIndex)} elements. * (If {@code toIndex==fromIndex}, this operation has no effect.) * * @throws IndexOutOfBoundsException if {@code fromIndex} or * {@code toIndex} is out of range * ({@code fromIndex < 0 || * fromIndex >= size() || * toIndex > size() || * toIndex < fromIndex}) */ public void removeRange(int fromIndex, int toIndex) { int numMoved = size - toIndex; System.arraycopy(doubles, toIndex, doubles, fromIndex, numMoved); size = size - (toIndex - fromIndex); } /** * Trims the capacity of this <tt>ArrayList</tt> instance to be the * list's current size. An application can use this operation to minimize * the storage of an <tt>ArrayList</tt> instance. */ private double[] trimToSize(int size, double[] elements) { double[] copy = Arrays.copyOf(elements, elements.length); if (size < elements.length) { copy = (size == 0) ? EMPTY_ELEMENT_DATA : Arrays.copyOf(elements, size); } return copy; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } DoubleList rhs = (DoubleList) obj; double[] thisTrimmed = trimToSize(this.size, this.doubles); double[] otherTrimmed = trimToSize(rhs.size, rhs.doubles); return new EqualsBuilder() .append(thisTrimmed, otherTrimmed) .append(this.size, rhs.size) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder() .append(doubles) .append(size) .toHashCode(); } @Override public String toString() { return new ToStringBuilder(this) .append("doubles", trimToSize(this.size, doubles)) .append("size", size) .toString(); } /** * @return maximum of the values of the list */ public double max() { if (size <= 0) { return Double.NaN; } double max = Double.MIN_VALUE; for (int i = 0; i < size; i++) { max = doubles[i] > max ? doubles[i] : max; } return max; } /** * @return minimum of the values of the list */ public double min() { if (size <= 0) { return Double.NaN; } double min = Double.MAX_VALUE; for (int i = 0; i < size; i++) { min = doubles[i] < min ? doubles[i] : min; } return min; } /** * @return average of the values of the list */ public double avg() { if (size <= 0) { return Double.NaN; } double current = 0; for (int i = 0; i < size; i++) { current += doubles[i]; } return current / size; } /** * @param scale to be applied to the values of this list * @return a new instance scaled with the given parameter */ public DoubleList scale(double scale) { DoubleList scaled = new DoubleList(size); for (int i = 0; i < size; i++) { scaled.add(doubles[i] * scale); } return scaled; } /** * Calculates the standard deviation * * @return the standard deviation */ public double stdDeviation() { if (isEmpty()) { return Double.NaN; } return Math.sqrt(variance()); } private double mean() { double sum = 0.0; for (int i = 0; i < size(); i++) { sum = sum + get(i); } return sum / size(); } private double variance() { double avg = mean(); double sum = 0.0; for (int i = 0; i < size(); i++) { double value = get(i); sum += (value - avg) * (value - avg); } return sum / (size() - 1); } /** * Implemented the quantile type 7 referred to * http://tolstoy.newcastle.edu.au/R/e17/help/att-1067/Quartiles_in_R.pdf * and * http://stat.ethz.ch/R-manual/R-patched/library/stats/html/quantile.html * as its the default quantile implementation * <p> * <code> * QuantileType7 = function (v, p) { * v = sort(v) * h = ((length(v)-1)*p)+1 * v[floor(h)]+((h-floor(h))*(v[floor(h)+1]- v[floor(h)])) * } * </code> * * @param percentile - the percentile (0 - 1), e.g. 0.25 * @return the value of the n-th percentile */ public double percentile(double percentile) { double[] copy = toArray(); Arrays.sort(copy);// Attention: this is only necessary because this list is not restricted to non-descending values return evaluateForDoubles(copy, percentile); } private static double evaluateForDoubles(double[] points, double percentile) { //For example: //values = [1,2,2,3,3,3,4,5,6], size = 9, percentile (e.g. 0.25) // size - 1 = 8 * 0.25 = 2 (~ 25% from 9) + 1 = 3 => values[3] => 2 double percentileIndex = ((points.length - 1) * percentile) + 1; double rawMedian = points[floor(percentileIndex - 1)]; double weight = percentileIndex - floor(percentileIndex); if (weight > 0) { double pointDistance = points[floor(percentileIndex - 1) + 1] - points[floor(percentileIndex - 1)]; return rawMedian + weight * pointDistance; } else { return rawMedian; } } /** * Wraps the Math.floor function and casts it to an integer * * @param value - the evaluatedValue * @return the floored evaluatedValue */ private static int floor(double value) { return (int) Math.floor(value); } }
Java
# Copyright 2018 Huawei Technologies Co.,LTD. # 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. import copy from oslo_log import log as logging from oslo_versionedobjects import base as object_base from cyborg.common import exception from cyborg.db import api as dbapi from cyborg.objects import base from cyborg.objects import fields as object_fields from cyborg.objects.deployable import Deployable from cyborg.objects.virtual_function import VirtualFunction LOG = logging.getLogger(__name__) @base.CyborgObjectRegistry.register class PhysicalFunction(Deployable): # Version 1.0: Initial version VERSION = '1.0' virtual_function_list = [] def create(self, context): # To ensure the creating type is PF if self.type != 'pf': raise exception.InvalidDeployType() super(PhysicalFunction, self).create(context) def save(self, context): """In addition to save the pf, it should also save the vfs associated with this pf """ # To ensure the saving type is PF if self.type != 'pf': raise exception.InvalidDeployType() for exist_vf in self.virtual_function_list: exist_vf.save(context) super(PhysicalFunction, self).save(context) def add_vf(self, vf): """add a vf object to the virtual_function_list. If the vf already exists, it will ignore, otherwise, the vf will be appended to the list """ if not isinstance(vf, VirtualFunction) or vf.type != 'vf': raise exception.InvalidDeployType() for exist_vf in self.virtual_function_list: if base.obj_equal_prims(vf, exist_vf): LOG.warning("The vf already exists") return None vf.parent_uuid = self.uuid vf.root_uuid = self.root_uuid vf_copy = copy.deepcopy(vf) self.virtual_function_list.append(vf_copy) def delete_vf(self, context, vf): """remove a vf from the virtual_function_list if the vf does not exist, ignore it """ for idx, exist_vf in self.virtual_function_list: if base.obj_equal_prims(vf, exist_vf): removed_vf = self.virtual_function_list.pop(idx) removed_vf.destroy(context) return LOG.warning("The removing vf does not exist!") def destroy(self, context): """Delete a the pf from the DB.""" del self.virtual_function_list[:] super(PhysicalFunction, self).destroy(context) @classmethod def get(cls, context, uuid): """Find a DB Physical Function and return an Obj Physical Function. In addition, it will also finds all the Virtual Functions associated with this Physical Function and place them in virtual_function_list """ db_pf = cls.dbapi.deployable_get(context, uuid) obj_pf = cls._from_db_object(cls(context), db_pf) pf_uuid = obj_pf.uuid query = {"parent_uuid": pf_uuid, "type": "vf"} db_vf_list = cls.dbapi.deployable_get_by_filters(context, query) for db_vf in db_vf_list: obj_vf = VirtualFunction.get(context, db_vf.uuid) obj_pf.virtual_function_list.append(obj_vf) return obj_pf @classmethod def get_by_filter(cls, context, filters, sort_key='created_at', sort_dir='desc', limit=None, marker=None, join=None): obj_dpl_list = [] filters['type'] = 'pf' db_dpl_list = cls.dbapi.deployable_get_by_filters(context, filters, sort_key=sort_key, sort_dir=sort_dir, limit=limit, marker=marker, join_columns=join) for db_dpl in db_dpl_list: obj_dpl = cls._from_db_object(cls(context), db_dpl) query = {"parent_uuid": obj_dpl.uuid} vf_get_list = VirtualFunction.get_by_filter(context, query) obj_dpl.virtual_function_list = vf_get_list obj_dpl_list.append(obj_dpl) return obj_dpl_list @classmethod def _from_db_object(cls, obj, db_obj): """Converts a physical function to a formal object. :param obj: An object of the class. :param db_obj: A DB model of the object :return: The object of the class with the database entity added """ obj = Deployable._from_db_object(obj, db_obj) if cls is PhysicalFunction: obj.virtual_function_list = [] return obj
Java
/* Copyright 2020 Gravitational, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package events import ( "archive/tar" "bufio" "compress/gzip" "context" "encoding/binary" "fmt" "io" "io/ioutil" "os" "path/filepath" "github.com/gravitational/teleport" apievents "github.com/gravitational/teleport/api/types/events" "github.com/gravitational/teleport/lib/session" "github.com/gravitational/teleport/lib/utils" "github.com/gravitational/trace" log "github.com/sirupsen/logrus" ) // Header returns information about playback type Header struct { // Tar detected tar format Tar bool // Proto is for proto format Proto bool // ProtoVersion is a version of the format, valid if Proto is true ProtoVersion int64 } // DetectFormat detects format by reading first bytes // of the header. Callers should call Seek() // to reuse reader after calling this function. func DetectFormat(r io.ReadSeeker) (*Header, error) { version := make([]byte, Int64Size) _, err := io.ReadFull(r, version) if err != nil { return nil, trace.ConvertSystemError(err) } protocolVersion := binary.BigEndian.Uint64(version) if protocolVersion == ProtoStreamV1 { return &Header{ Proto: true, ProtoVersion: int64(protocolVersion), }, nil } _, err = r.Seek(0, 0) if err != nil { return nil, trace.ConvertSystemError(err) } tr := tar.NewReader(r) _, err = tr.Next() if err != nil { return nil, trace.ConvertSystemError(err) } return &Header{Tar: true}, nil } // Export converts session files from binary/protobuf to text/JSON. func Export(ctx context.Context, rs io.ReadSeeker, w io.Writer, exportFormat string) error { switch exportFormat { case teleport.JSON: default: return trace.BadParameter("unsupported format %q, %q is the only supported format", exportFormat, teleport.JSON) } format, err := DetectFormat(rs) if err != nil { return trace.Wrap(err) } _, err = rs.Seek(0, 0) if err != nil { return trace.ConvertSystemError(err) } switch { case format.Proto: protoReader := NewProtoReader(rs) for { event, err := protoReader.Read(ctx) if err != nil { if err == io.EOF { return nil } return trace.Wrap(err) } switch exportFormat { case teleport.JSON: data, err := utils.FastMarshal(event) if err != nil { return trace.ConvertSystemError(err) } _, err = fmt.Fprintln(w, string(data)) if err != nil { return trace.ConvertSystemError(err) } default: return trace.BadParameter("unsupported format %q, %q is the only supported format", exportFormat, teleport.JSON) } } case format.Tar: return trace.BadParameter( "to review the events in format of teleport before version 4.4, extract the tarball and look inside") default: return trace.BadParameter("unsupported format %v", format) } } // WriteForPlayback reads events from audit reader and writes them to the format optimized for playback // this function returns *PlaybackWriter and error func WriteForPlayback(ctx context.Context, sid session.ID, reader AuditReader, dir string) (*PlaybackWriter, error) { w := &PlaybackWriter{ sid: sid, reader: reader, dir: dir, eventIndex: -1, } defer func() { if err := w.Close(); err != nil { log.WithError(err).Warningf("Failed to close writer.") } }() return w, w.Write(ctx) } // SessionEvents returns slice of event fields from gzipped events file. func (w *PlaybackWriter) SessionEvents() ([]EventFields, error) { var sessionEvents []EventFields //events eventFile, err := os.Open(w.EventsPath) if err != nil { return nil, trace.Wrap(err) } defer eventFile.Close() grEvents, err := gzip.NewReader(eventFile) if err != nil { return nil, trace.Wrap(err) } defer grEvents.Close() scanner := bufio.NewScanner(grEvents) for scanner.Scan() { var f EventFields err := utils.FastUnmarshal(scanner.Bytes(), &f) if err != nil { if err == io.EOF { return sessionEvents, nil } return nil, trace.Wrap(err) } sessionEvents = append(sessionEvents, f) } if err := scanner.Err(); err != nil { return nil, trace.Wrap(err) } return sessionEvents, nil } // SessionChunks interprets the file at the given path as gzip-compressed list of session events and returns // the uncompressed contents as a result. func (w *PlaybackWriter) SessionChunks() ([]byte, error) { var stream []byte chunkFile, err := os.Open(w.ChunksPath) if err != nil { return nil, trace.Wrap(err) } defer chunkFile.Close() grChunk, err := gzip.NewReader(chunkFile) if err != nil { return nil, trace.Wrap(err) } defer grChunk.Close() stream, err = ioutil.ReadAll(grChunk) if err != nil { return nil, trace.Wrap(err) } return stream, nil } // PlaybackWriter reads messages from an AuditReader and writes them // to disk in a format suitable for SSH session playback. type PlaybackWriter struct { sid session.ID dir string reader AuditReader indexFile *os.File eventsFile *gzipWriter chunksFile *gzipWriter eventIndex int64 EventsPath string ChunksPath string } // Close closes all files func (w *PlaybackWriter) Close() error { if w.indexFile != nil { if err := w.indexFile.Close(); err != nil { log.Warningf("Failed to close index file: %v.", err) } w.indexFile = nil } if w.chunksFile != nil { if err := w.chunksFile.Flush(); err != nil { log.Warningf("Failed to flush chunks file: %v.", err) } if err := w.chunksFile.Close(); err != nil { log.Warningf("Failed closing chunks file: %v.", err) } } if w.eventsFile != nil { if err := w.eventsFile.Flush(); err != nil { log.Warningf("Failed to flush events file: %v.", err) } if err := w.eventsFile.Close(); err != nil { log.Warningf("Failed closing events file: %v.", err) } } return nil } // Write writes all events from the AuditReader and writes // files to disk in the format optimized for playback. func (w *PlaybackWriter) Write(ctx context.Context) error { if err := w.openIndexFile(); err != nil { return trace.Wrap(err) } for { event, err := w.reader.Read(ctx) if err != nil { if err == io.EOF { return nil } return trace.Wrap(err) } if err := w.writeEvent(event); err != nil { return trace.Wrap(err) } } } func (w *PlaybackWriter) writeEvent(event apievents.AuditEvent) error { switch event.GetType() { // Timing events for TTY playback go to both a chunks file (the raw bytes) as // well as well as the events file (structured events). case SessionPrintEvent: return trace.Wrap(w.writeSessionPrintEvent(event)) // Playback does not use enhanced events at the moment, // so they are skipped case SessionCommandEvent, SessionDiskEvent, SessionNetworkEvent: return nil // PlaybackWriter is not used for desktop playback, so we should never see // these events, but skip them if a user or developer somehow tries to playback // a desktop session using this TTY PlaybackWriter case DesktopRecordingEvent: return nil // All other events get put into the general events file. These are events like // session.join, session.end, etc. default: return trace.Wrap(w.writeRegularEvent(event)) } } func (w *PlaybackWriter) writeSessionPrintEvent(event apievents.AuditEvent) error { print, ok := event.(*apievents.SessionPrint) if !ok { return trace.BadParameter("expected session print event, got %T", event) } w.eventIndex++ event.SetIndex(w.eventIndex) if err := w.openEventsFile(0); err != nil { return trace.Wrap(err) } if err := w.openChunksFile(0); err != nil { return trace.Wrap(err) } data := print.Data print.Data = nil bytes, err := utils.FastMarshal(event) if err != nil { return trace.Wrap(err) } _, err = w.eventsFile.Write(append(bytes, '\n')) if err != nil { return trace.Wrap(err) } _, err = w.chunksFile.Write(data) if err != nil { return trace.Wrap(err) } return nil } func (w *PlaybackWriter) writeRegularEvent(event apievents.AuditEvent) error { w.eventIndex++ event.SetIndex(w.eventIndex) if err := w.openEventsFile(0); err != nil { return trace.Wrap(err) } bytes, err := utils.FastMarshal(event) if err != nil { return trace.Wrap(err) } _, err = w.eventsFile.Write(append(bytes, '\n')) if err != nil { return trace.Wrap(err) } return nil } func (w *PlaybackWriter) openIndexFile() error { if w.indexFile != nil { return nil } var err error w.indexFile, err = os.OpenFile( filepath.Join(w.dir, fmt.Sprintf("%v.index", w.sid.String())), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640) if err != nil { return trace.Wrap(err) } return nil } func (w *PlaybackWriter) openEventsFile(eventIndex int64) error { if w.eventsFile != nil { return nil } w.EventsPath = eventsFileName(w.dir, w.sid, "", eventIndex) // update the index file to write down that new events file has been created data, err := utils.FastMarshal(indexEntry{ FileName: filepath.Base(w.EventsPath), Type: fileTypeEvents, Index: eventIndex, }) if err != nil { return trace.Wrap(err) } _, err = fmt.Fprintf(w.indexFile, "%v\n", string(data)) if err != nil { return trace.Wrap(err) } // open new events file for writing file, err := os.OpenFile(w.EventsPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640) if err != nil { return trace.Wrap(err) } w.eventsFile = newGzipWriter(file) return nil } func (w *PlaybackWriter) openChunksFile(offset int64) error { if w.chunksFile != nil { return nil } w.ChunksPath = chunksFileName(w.dir, w.sid, offset) // Update the index file to write down that new chunks file has been created. data, err := utils.FastMarshal(indexEntry{ FileName: filepath.Base(w.ChunksPath), Type: fileTypeChunks, Offset: offset, }) if err != nil { return trace.Wrap(err) } // index file will contain file name with extension .gz (assuming it was gzipped) _, err = fmt.Fprintf(w.indexFile, "%v\n", string(data)) if err != nil { return trace.Wrap(err) } // open the chunks file for writing, but because the file is written without // compression, remove the .gz file, err := os.OpenFile(w.ChunksPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640) if err != nil { return trace.Wrap(err) } w.chunksFile = newGzipWriter(file) return nil }
Java
package de.devisnik.mine.robot.test; import de.devisnik.mine.robot.AutoPlayerTest; import de.devisnik.mine.robot.ConfigurationTest; import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { public static Test suite() { TestSuite suite = new TestSuite("Tests for de.devisnik.mine.robot"); //$JUnit-BEGIN$ suite.addTestSuite(AutoPlayerTest.class); suite.addTestSuite(ConfigurationTest.class); //$JUnit-END$ return suite; } }
Java
package com.beanu.l2_shareutil.share; import androidx.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Created by shaohui on 2016/11/18. */ public class SharePlatform { @IntDef({ DEFAULT, QQ, QZONE, WEIBO, WX, WX_TIMELINE }) @Retention(RetentionPolicy.SOURCE) public @interface Platform{} public static final int DEFAULT = 0; public static final int QQ = 1; public static final int QZONE = 2; public static final int WX = 3; public static final int WX_TIMELINE = 4; public static final int WEIBO = 5; }
Java
<?php /** * Contains all client objects for the ExchangeRateService * service. * * PHP version 5 * * Copyright 2016, Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @package GoogleApiAdsDfp * @subpackage v201605 * @category WebServices * @copyright 2016, Google Inc. All Rights Reserved. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, * Version 2.0 */ require_once "Google/Api/Ads/Dfp/Lib/DfpSoapClient.php"; if (!class_exists("ApiError", false)) { /** * The API error base class that provides details about an error that occurred * while processing a service request. * * <p>The OGNL field path is provided for parsers to identify the request data * element that may have caused the error.</p> * @package GoogleApiAdsDfp * @subpackage v201605 */ class ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ApiError"; /** * @access public * @var string */ public $fieldPath; /** * @access public * @var string */ public $trigger; /** * @access public * @var string */ public $errorString; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($fieldPath = null, $trigger = null, $errorString = null) { $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("ApiVersionError", false)) { /** * Errors related to the usage of API versions. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ApiVersionError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ApiVersionError"; /** * @access public * @var tnsApiVersionErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("ApplicationException", false)) { /** * Base class for exceptions. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ApplicationException { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ApplicationException"; /** * @access public * @var string */ public $message; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($message = null) { $this->message = $message; } } } if (!class_exists("AuthenticationError", false)) { /** * An error for an exception that occurred when authenticating. * @package GoogleApiAdsDfp * @subpackage v201605 */ class AuthenticationError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "AuthenticationError"; /** * @access public * @var tnsAuthenticationErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("CollectionSizeError", false)) { /** * Error for the size of the collection being too large * @package GoogleApiAdsDfp * @subpackage v201605 */ class CollectionSizeError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "CollectionSizeError"; /** * @access public * @var tnsCollectionSizeErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("CommonError", false)) { /** * A place for common errors that can be used across services. * @package GoogleApiAdsDfp * @subpackage v201605 */ class CommonError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "CommonError"; /** * @access public * @var tnsCommonErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("Date", false)) { /** * Represents a date. * @package GoogleApiAdsDfp * @subpackage v201605 */ class Date { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "Date"; /** * @access public * @var integer */ public $year; /** * @access public * @var integer */ public $month; /** * @access public * @var integer */ public $day; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($year = null, $month = null, $day = null) { $this->year = $year; $this->month = $month; $this->day = $day; } } } if (!class_exists("DfpDateTime", false)) { /** * Represents a date combined with the time of day. * @package GoogleApiAdsDfp * @subpackage v201605 */ class DfpDateTime { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "DateTime"; /** * @access public * @var Date */ public $date; /** * @access public * @var integer */ public $hour; /** * @access public * @var integer */ public $minute; /** * @access public * @var integer */ public $second; /** * @access public * @var string */ public $timeZoneID; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($date = null, $hour = null, $minute = null, $second = null, $timeZoneID = null) { $this->date = $date; $this->hour = $hour; $this->minute = $minute; $this->second = $second; $this->timeZoneID = $timeZoneID; } } } if (!class_exists("ExchangeRateAction", false)) { /** * Represents the actions that can be performed on {@link ExchangeRate} objects. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ExchangeRateAction { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ExchangeRateAction"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ExchangeRate", false)) { /** * An {@code ExchangeRate} represents a currency which is one of the * {@link Network#secondaryCurrencyCodes}, and the latest exchange rate between this currency and * {@link Network#currencyCode}. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ExchangeRate { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ExchangeRate"; /** * @access public * @var integer */ public $id; /** * @access public * @var string */ public $currencyCode; /** * @access public * @var tnsExchangeRateRefreshRate */ public $refreshRate; /** * @access public * @var tnsExchangeRateDirection */ public $direction; /** * @access public * @var integer */ public $exchangeRate; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($id = null, $currencyCode = null, $refreshRate = null, $direction = null, $exchangeRate = null) { $this->id = $id; $this->currencyCode = $currencyCode; $this->refreshRate = $refreshRate; $this->direction = $direction; $this->exchangeRate = $exchangeRate; } } } if (!class_exists("ExchangeRateError", false)) { /** * Lists all errors associated with {@link ExchangeRate} objects. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ExchangeRateError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ExchangeRateError"; /** * @access public * @var tnsExchangeRateErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("ExchangeRatePage", false)) { /** * Captures a page of {@link ExchangeRate} objects. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ExchangeRatePage { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ExchangeRatePage"; /** * @access public * @var ExchangeRate[] */ public $results; /** * @access public * @var integer */ public $startIndex; /** * @access public * @var integer */ public $totalResultSetSize; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($results = null, $startIndex = null, $totalResultSetSize = null) { $this->results = $results; $this->startIndex = $startIndex; $this->totalResultSetSize = $totalResultSetSize; } } } if (!class_exists("FeatureError", false)) { /** * Errors related to feature management. If you attempt using a feature that is not available to * the current network you'll receive a FeatureError with the missing feature as the trigger. * @package GoogleApiAdsDfp * @subpackage v201605 */ class FeatureError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "FeatureError"; /** * @access public * @var tnsFeatureErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("InternalApiError", false)) { /** * Indicates that a server-side error has occured. {@code InternalApiError}s * are generally not the result of an invalid request or message sent by the * client. * @package GoogleApiAdsDfp * @subpackage v201605 */ class InternalApiError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "InternalApiError"; /** * @access public * @var tnsInternalApiErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("NotNullError", false)) { /** * Caused by supplying a null value for an attribute that cannot be null. * @package GoogleApiAdsDfp * @subpackage v201605 */ class NotNullError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "NotNullError"; /** * @access public * @var tnsNotNullErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("ParseError", false)) { /** * Lists errors related to parsing. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ParseError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ParseError"; /** * @access public * @var tnsParseErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("PermissionError", false)) { /** * Errors related to incorrect permission. * @package GoogleApiAdsDfp * @subpackage v201605 */ class PermissionError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "PermissionError"; /** * @access public * @var tnsPermissionErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("PublisherQueryLanguageContextError", false)) { /** * An error that occurs while executing a PQL query contained in * a {@link Statement} object. * @package GoogleApiAdsDfp * @subpackage v201605 */ class PublisherQueryLanguageContextError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "PublisherQueryLanguageContextError"; /** * @access public * @var tnsPublisherQueryLanguageContextErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("PublisherQueryLanguageSyntaxError", false)) { /** * An error that occurs while parsing a PQL query contained in a * {@link Statement} object. * @package GoogleApiAdsDfp * @subpackage v201605 */ class PublisherQueryLanguageSyntaxError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "PublisherQueryLanguageSyntaxError"; /** * @access public * @var tnsPublisherQueryLanguageSyntaxErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("QuotaError", false)) { /** * Describes a client-side error on which a user is attempting * to perform an action to which they have no quota remaining. * @package GoogleApiAdsDfp * @subpackage v201605 */ class QuotaError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "QuotaError"; /** * @access public * @var tnsQuotaErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("RequiredCollectionError", false)) { /** * A list of all errors to be used for validating sizes of collections. * @package GoogleApiAdsDfp * @subpackage v201605 */ class RequiredCollectionError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "RequiredCollectionError"; /** * @access public * @var tnsRequiredCollectionErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("RequiredError", false)) { /** * Errors due to missing required field. * @package GoogleApiAdsDfp * @subpackage v201605 */ class RequiredError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "RequiredError"; /** * @access public * @var tnsRequiredErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("RequiredNumberError", false)) { /** * A list of all errors to be used in conjunction with required number * validators. * @package GoogleApiAdsDfp * @subpackage v201605 */ class RequiredNumberError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "RequiredNumberError"; /** * @access public * @var tnsRequiredNumberErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("ServerError", false)) { /** * Errors related to the server. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ServerError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ServerError"; /** * @access public * @var tnsServerErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("SoapRequestHeader", false)) { /** * Represents the SOAP request header used by API requests. * @package GoogleApiAdsDfp * @subpackage v201605 */ class SoapRequestHeader { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "SoapRequestHeader"; /** * @access public * @var string */ public $networkCode; /** * @access public * @var string */ public $applicationName; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($networkCode = null, $applicationName = null) { $this->networkCode = $networkCode; $this->applicationName = $applicationName; } } } if (!class_exists("SoapResponseHeader", false)) { /** * Represents the SOAP request header used by API responses. * @package GoogleApiAdsDfp * @subpackage v201605 */ class SoapResponseHeader { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "SoapResponseHeader"; /** * @access public * @var string */ public $requestId; /** * @access public * @var integer */ public $responseTime; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($requestId = null, $responseTime = null) { $this->requestId = $requestId; $this->responseTime = $responseTime; } } } if (!class_exists("Statement", false)) { /** * Captures the {@code WHERE}, {@code ORDER BY} and {@code LIMIT} clauses of a * PQL query. Statements are typically used to retrieve objects of a predefined * domain type, which makes SELECT clause unnecessary. * <p> * An example query text might be {@code "WHERE status = 'ACTIVE' ORDER BY id * LIMIT 30"}. * </p> * <p> * Statements support bind variables. These are substitutes for literals * and can be thought of as input parameters to a PQL query. * </p> * <p> * An example of such a query might be {@code "WHERE id = :idValue"}. * </p> * <p> * Statements also support use of the LIKE keyword. This provides partial and * wildcard string matching. * </p> * <p> * An example of such a query might be {@code "WHERE name LIKE 'startswith%'"}. * </p> * The value for the variable idValue must then be set with an object of type * {@link Value}, e.g., {@link NumberValue}, {@link TextValue} or * {@link BooleanValue}. * @package GoogleApiAdsDfp * @subpackage v201605 */ class Statement { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "Statement"; /** * @access public * @var string */ public $query; /** * @access public * @var String_ValueMapEntry[] */ public $values; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($query = null, $values = null) { $this->query = $query; $this->values = $values; } } } if (!class_exists("StatementError", false)) { /** * An error that occurs while parsing {@link Statement} objects. * @package GoogleApiAdsDfp * @subpackage v201605 */ class StatementError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "StatementError"; /** * @access public * @var tnsStatementErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("StringLengthError", false)) { /** * Errors for Strings which do not meet given length constraints. * @package GoogleApiAdsDfp * @subpackage v201605 */ class StringLengthError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "StringLengthError"; /** * @access public * @var tnsStringLengthErrorReason */ public $reason; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("String_ValueMapEntry", false)) { /** * This represents an entry in a map with a key of type String * and value of type Value. * @package GoogleApiAdsDfp * @subpackage v201605 */ class String_ValueMapEntry { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "String_ValueMapEntry"; /** * @access public * @var string */ public $key; /** * @access public * @var Value */ public $value; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($key = null, $value = null) { $this->key = $key; $this->value = $value; } } } if (!class_exists("UniqueError", false)) { /** * An error for a field which must satisfy a uniqueness constraint * @package GoogleApiAdsDfp * @subpackage v201605 */ class UniqueError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "UniqueError"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($fieldPath = null, $trigger = null, $errorString = null) { parent::__construct(); $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; } } } if (!class_exists("UpdateResult", false)) { /** * Represents the result of performing an action on objects. * @package GoogleApiAdsDfp * @subpackage v201605 */ class UpdateResult { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "UpdateResult"; /** * @access public * @var integer */ public $numChanges; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($numChanges = null) { $this->numChanges = $numChanges; } } } if (!class_exists("Value", false)) { /** * {@code Value} represents a value. * @package GoogleApiAdsDfp * @subpackage v201605 */ class Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "Value"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ApiVersionErrorReason", false)) { /** * Indicates that the operation is not allowed in the version the request * was made in. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ApiVersionErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ApiVersionError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("AuthenticationErrorReason", false)) { /** * The SOAP message contains a request header with an ambiguous definition * of the authentication header fields. This means either the {@code * authToken} and {@code oAuthToken} fields were both null or both were * specified. Exactly one value should be specified with each request. * @package GoogleApiAdsDfp * @subpackage v201605 */ class AuthenticationErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "AuthenticationError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("CollectionSizeErrorReason", false)) { /** * The value returned if the actual value is not exposed by the requested API version. * @package GoogleApiAdsDfp * @subpackage v201605 */ class CollectionSizeErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "CollectionSizeError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("CommonErrorReason", false)) { /** * Describes reasons for common errors * @package GoogleApiAdsDfp * @subpackage v201605 */ class CommonErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "CommonError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ExchangeRateDirection", false)) { /** * Determines which direction (from which currency to which currency) the exchange rate is in. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ExchangeRateDirection { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ExchangeRateDirection"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ExchangeRateErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ExchangeRateErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ExchangeRateError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ExchangeRateRefreshRate", false)) { /** * Determines at which rate the exchange rate is refreshed. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ExchangeRateRefreshRate { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ExchangeRateRefreshRate"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("FeatureErrorReason", false)) { /** * A feature is being used that is not enabled on the current network. * @package GoogleApiAdsDfp * @subpackage v201605 */ class FeatureErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "FeatureError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("InternalApiErrorReason", false)) { /** * The single reason for the internal API error. * @package GoogleApiAdsDfp * @subpackage v201605 */ class InternalApiErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "InternalApiError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("NotNullErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201605 */ class NotNullErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "NotNullError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ParseErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ParseErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ParseError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("PermissionErrorReason", false)) { /** * Describes reasons for permission errors. * @package GoogleApiAdsDfp * @subpackage v201605 */ class PermissionErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "PermissionError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("PublisherQueryLanguageContextErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201605 */ class PublisherQueryLanguageContextErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "PublisherQueryLanguageContextError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("PublisherQueryLanguageSyntaxErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201605 */ class PublisherQueryLanguageSyntaxErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "PublisherQueryLanguageSyntaxError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("QuotaErrorReason", false)) { /** * The number of requests made per second is too high and has exceeded the * allowable limit. The recommended approach to handle this error is to wait * about 5 seconds and then retry the request. Note that this does not * guarantee the request will succeed. If it fails again, try increasing the * wait time. * <p> * Another way to mitigate this error is to limit requests to 2 per second for * Small Business networks, or 8 per second for Premium networks. Once again * this does not guarantee that every request will succeed, but may help * reduce the number of times you receive this error. * </p> * @package GoogleApiAdsDfp * @subpackage v201605 */ class QuotaErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "QuotaError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("RequiredCollectionErrorReason", false)) { /** * A required collection is missing. * @package GoogleApiAdsDfp * @subpackage v201605 */ class RequiredCollectionErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "RequiredCollectionError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("RequiredErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201605 */ class RequiredErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "RequiredError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("RequiredNumberErrorReason", false)) { /** * Describes reasons for a number to be invalid. * @package GoogleApiAdsDfp * @subpackage v201605 */ class RequiredNumberErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "RequiredNumberError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ServerErrorReason", false)) { /** * Describes reasons for server errors * @package GoogleApiAdsDfp * @subpackage v201605 */ class ServerErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ServerError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("StatementErrorReason", false)) { /** * A bind variable has not been bound to a value. * @package GoogleApiAdsDfp * @subpackage v201605 */ class StatementErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "StatementError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("StringLengthErrorReason", false)) { /** * The value returned if the actual value is not exposed by the requested API version. * @package GoogleApiAdsDfp * @subpackage v201605 */ class StringLengthErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "StringLengthError.Reason"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("CreateExchangeRates", false)) { /** * Creates new {@link ExchangeRate} objects. * * For each exchange rate, the following fields are required: * <ul> * <li>{@link ExchangeRate#currencyCode}</li> * <li>{@link ExchangeRate#exchangeRate} when {@link ExchangeRate#refreshRate} is * {@link ExchangeRateRefreshRate#FIXED}</li> * </ul> * * @param exchangeRates the exchange rates to create * @return the created exchange rates with their exchange rate values filled in * @package GoogleApiAdsDfp * @subpackage v201605 */ class CreateExchangeRates { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = ""; /** * @access public * @var ExchangeRate[] */ public $exchangeRates; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($exchangeRates = null) { $this->exchangeRates = $exchangeRates; } } } if (!class_exists("CreateExchangeRatesResponse", false)) { /** * * @package GoogleApiAdsDfp * @subpackage v201605 */ class CreateExchangeRatesResponse { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = ""; /** * @access public * @var ExchangeRate[] */ public $rval; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($rval = null) { $this->rval = $rval; } } } if (!class_exists("GetExchangeRatesByStatement", false)) { /** * Gets a {@link ExchangeRatePage} of {@link ExchangeRate} objects that satisfy the given * {@link Statement#query}. The following fields are supported for filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link ExchangeRate#id}</td> * </tr> * <tr> * <td>{@code currencyCode}</td> * <td>{@link ExchangeRate#currencyCode}</td> * </tr> * <tr> * <td>{@code refreshRate}</td> * <td>{@link ExchangeRate#refreshRate}</td> * </tr> * <tr> * <td>{@code direction}</td> * <td>{@link ExchangeRate#direction}</td> * </tr> * <tr> * <td>{@code exchangeRate}</td> * <td>{@link ExchangeRate#exchangeRate}</td> * </tr> * </table> * * @param filterStatement a Publisher Query Language statement used to filter * a set of exchange rates * @return the exchange rates that match the given filter * @package GoogleApiAdsDfp * @subpackage v201605 */ class GetExchangeRatesByStatement { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = ""; /** * @access public * @var Statement */ public $filterStatement; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($filterStatement = null) { $this->filterStatement = $filterStatement; } } } if (!class_exists("GetExchangeRatesByStatementResponse", false)) { /** * * @package GoogleApiAdsDfp * @subpackage v201605 */ class GetExchangeRatesByStatementResponse { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = ""; /** * @access public * @var ExchangeRatePage */ public $rval; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($rval = null) { $this->rval = $rval; } } } if (!class_exists("PerformExchangeRateAction", false)) { /** * Performs an action on {@link ExchangeRate} objects that satisfy the given * {@link Statement#query}. The following fields are supported for filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link ExchangeRate#id}</td> * </tr> * <tr> * <td>{@code currencyCode}</td> * <td>{@link ExchangeRate#currencyCode}</td> * </tr> * <tr> * <td>{@code refreshRate}</td> * <td>{@link ExchangeRate#refreshRate}</td> * </tr> * <tr> * <td>{@code direction}</td> * <td>{@link ExchangeRate#direction}</td> * </tr> * <tr> * <td>{@code exchangeRate}</td> * <td>{@link ExchangeRate#exchangeRate}</td> * </tr> * </table> * * @param exchangeRateAction the action to perform * @param filterStatement a Publisher Query Language statement used to filter * a set of exchange rates * @return the result of the action performed * @package GoogleApiAdsDfp * @subpackage v201605 */ class PerformExchangeRateAction { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = ""; /** * @access public * @var ExchangeRateAction */ public $exchangeRateAction; /** * @access public * @var Statement */ public $filterStatement; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($exchangeRateAction = null, $filterStatement = null) { $this->exchangeRateAction = $exchangeRateAction; $this->filterStatement = $filterStatement; } } } if (!class_exists("PerformExchangeRateActionResponse", false)) { /** * * @package GoogleApiAdsDfp * @subpackage v201605 */ class PerformExchangeRateActionResponse { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = ""; /** * @access public * @var UpdateResult */ public $rval; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($rval = null) { $this->rval = $rval; } } } if (!class_exists("UpdateExchangeRates", false)) { /** * Updates the specified {@link ExchangeRate} objects. * * @param exchangeRates the exchange rates to update * @return the updated exchange rates * @package GoogleApiAdsDfp * @subpackage v201605 */ class UpdateExchangeRates { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = ""; /** * @access public * @var ExchangeRate[] */ public $exchangeRates; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($exchangeRates = null) { $this->exchangeRates = $exchangeRates; } } } if (!class_exists("UpdateExchangeRatesResponse", false)) { /** * * @package GoogleApiAdsDfp * @subpackage v201605 */ class UpdateExchangeRatesResponse { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = ""; /** * @access public * @var ExchangeRate[] */ public $rval; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($rval = null) { $this->rval = $rval; } } } if (!class_exists("ObjectValue", false)) { /** * Contains an object value. * <p> * <b>This object is experimental! * <code>ObjectValue</code> is an experimental, innovative, and rapidly * changing new feature for DFP. Unfortunately, being on the bleeding edge means that we may make * backwards-incompatible changes to * <code>ObjectValue</code>. We will inform the community when this feature * is no longer experimental.</b> * @package GoogleApiAdsDfp * @subpackage v201605 */ class ObjectValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ObjectValue"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { parent::__construct(); } } } if (!class_exists("ApiException", false)) { /** * Exception class for holding a list of service errors. * @package GoogleApiAdsDfp * @subpackage v201605 */ class ApiException extends ApplicationException { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "ApiException"; /** * @access public * @var ApiError[] */ public $errors; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($errors = null, $message = null) { parent::__construct(); $this->errors = $errors; $this->message = $message; } } } if (!class_exists("BooleanValue", false)) { /** * Contains a boolean value. * @package GoogleApiAdsDfp * @subpackage v201605 */ class BooleanValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "BooleanValue"; /** * @access public * @var boolean */ public $value; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null) { parent::__construct(); $this->value = $value; } } } if (!class_exists("DateTimeValue", false)) { /** * Contains a date-time value. * @package GoogleApiAdsDfp * @subpackage v201605 */ class DateTimeValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "DateTimeValue"; /** * @access public * @var DateTime */ public $value; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null) { parent::__construct(); $this->value = $value; } } } if (!class_exists("DateValue", false)) { /** * Contains a date value. * @package GoogleApiAdsDfp * @subpackage v201605 */ class DateValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "DateValue"; /** * @access public * @var Date */ public $value; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null) { parent::__construct(); $this->value = $value; } } } if (!class_exists("DeleteExchangeRates", false)) { /** * The action used to delete {@link ExchangeRate} objects. * @package GoogleApiAdsDfp * @subpackage v201605 */ class DeleteExchangeRates extends ExchangeRateAction { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "DeleteExchangeRates"; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { parent::__construct(); } } } if (!class_exists("NumberValue", false)) { /** * Contains a numeric value. * @package GoogleApiAdsDfp * @subpackage v201605 */ class NumberValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "NumberValue"; /** * @access public * @var string */ public $value; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null) { parent::__construct(); $this->value = $value; } } } if (!class_exists("SetValue", false)) { /** * Contains a set of {@link Value Values}. May not contain duplicates. * @package GoogleApiAdsDfp * @subpackage v201605 */ class SetValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "SetValue"; /** * @access public * @var Value[] */ public $values; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($values = null) { parent::__construct(); $this->values = $values; } } } if (!class_exists("TextValue", false)) { /** * Contains a string value. * @package GoogleApiAdsDfp * @subpackage v201605 */ class TextValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const XSI_TYPE = "TextValue"; /** * @access public * @var string */ public $value; /** * Gets the namesapce of this class * @return string the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return string the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null) { parent::__construct(); $this->value = $value; } } } if (!class_exists("ExchangeRateService", false)) { /** * ExchangeRateService * @package GoogleApiAdsDfp * @subpackage v201605 */ class ExchangeRateService extends DfpSoapClient { const SERVICE_NAME = "ExchangeRateService"; const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605"; const ENDPOINT = "https://ads.google.com/apis/ads/publisher/v201605/ExchangeRateService"; /** * The endpoint of the service * @var string */ public static $endpoint = "https://ads.google.com/apis/ads/publisher/v201605/ExchangeRateService"; /** * Default class map for wsdl=>php * @access private * @var array */ public static $classmap = array( "ObjectValue" => "ObjectValue", "ApiError" => "ApiError", "ApiException" => "ApiException", "ApiVersionError" => "ApiVersionError", "ApplicationException" => "ApplicationException", "AuthenticationError" => "AuthenticationError", "BooleanValue" => "BooleanValue", "CollectionSizeError" => "CollectionSizeError", "CommonError" => "CommonError", "Date" => "Date", "DateTime" => "DfpDateTime", "DateTimeValue" => "DateTimeValue", "DateValue" => "DateValue", "DeleteExchangeRates" => "DeleteExchangeRates", "ExchangeRateAction" => "ExchangeRateAction", "ExchangeRate" => "ExchangeRate", "ExchangeRateError" => "ExchangeRateError", "ExchangeRatePage" => "ExchangeRatePage", "FeatureError" => "FeatureError", "InternalApiError" => "InternalApiError", "NotNullError" => "NotNullError", "NumberValue" => "NumberValue", "ParseError" => "ParseError", "PermissionError" => "PermissionError", "PublisherQueryLanguageContextError" => "PublisherQueryLanguageContextError", "PublisherQueryLanguageSyntaxError" => "PublisherQueryLanguageSyntaxError", "QuotaError" => "QuotaError", "RequiredCollectionError" => "RequiredCollectionError", "RequiredError" => "RequiredError", "RequiredNumberError" => "RequiredNumberError", "ServerError" => "ServerError", "SetValue" => "SetValue", "SoapRequestHeader" => "SoapRequestHeader", "SoapResponseHeader" => "SoapResponseHeader", "Statement" => "Statement", "StatementError" => "StatementError", "StringLengthError" => "StringLengthError", "String_ValueMapEntry" => "String_ValueMapEntry", "TextValue" => "TextValue", "UniqueError" => "UniqueError", "UpdateResult" => "UpdateResult", "Value" => "Value", "ApiVersionError.Reason" => "ApiVersionErrorReason", "AuthenticationError.Reason" => "AuthenticationErrorReason", "CollectionSizeError.Reason" => "CollectionSizeErrorReason", "CommonError.Reason" => "CommonErrorReason", "ExchangeRateDirection" => "ExchangeRateDirection", "ExchangeRateError.Reason" => "ExchangeRateErrorReason", "ExchangeRateRefreshRate" => "ExchangeRateRefreshRate", "FeatureError.Reason" => "FeatureErrorReason", "InternalApiError.Reason" => "InternalApiErrorReason", "NotNullError.Reason" => "NotNullErrorReason", "ParseError.Reason" => "ParseErrorReason", "PermissionError.Reason" => "PermissionErrorReason", "PublisherQueryLanguageContextError.Reason" => "PublisherQueryLanguageContextErrorReason", "PublisherQueryLanguageSyntaxError.Reason" => "PublisherQueryLanguageSyntaxErrorReason", "QuotaError.Reason" => "QuotaErrorReason", "RequiredCollectionError.Reason" => "RequiredCollectionErrorReason", "RequiredError.Reason" => "RequiredErrorReason", "RequiredNumberError.Reason" => "RequiredNumberErrorReason", "ServerError.Reason" => "ServerErrorReason", "StatementError.Reason" => "StatementErrorReason", "StringLengthError.Reason" => "StringLengthErrorReason", "createExchangeRates" => "CreateExchangeRates", "createExchangeRatesResponse" => "CreateExchangeRatesResponse", "getExchangeRatesByStatement" => "GetExchangeRatesByStatement", "getExchangeRatesByStatementResponse" => "GetExchangeRatesByStatementResponse", "performExchangeRateAction" => "PerformExchangeRateAction", "performExchangeRateActionResponse" => "PerformExchangeRateActionResponse", "updateExchangeRates" => "UpdateExchangeRates", "updateExchangeRatesResponse" => "UpdateExchangeRatesResponse", ); /** * Constructor using wsdl location and options array * @param string $wsdl WSDL location for this service * @param array $options Options for the SoapClient */ public function __construct($wsdl, $options, $user) { $options["classmap"] = self::$classmap; parent::__construct($wsdl, $options, $user, self::SERVICE_NAME, self::WSDL_NAMESPACE); } /** * Creates new {@link ExchangeRate} objects. * * For each exchange rate, the following fields are required: * <ul> * <li>{@link ExchangeRate#currencyCode}</li> * <li>{@link ExchangeRate#exchangeRate} when {@link ExchangeRate#refreshRate} is * {@link ExchangeRateRefreshRate#FIXED}</li> * </ul> * * @param exchangeRates the exchange rates to create * @return the created exchange rates with their exchange rate values filled in */ public function createExchangeRates($exchangeRates) { $args = new CreateExchangeRates($exchangeRates); $result = $this->__soapCall("createExchangeRates", array($args)); return $result->rval; } /** * Gets a {@link ExchangeRatePage} of {@link ExchangeRate} objects that satisfy the given * {@link Statement#query}. The following fields are supported for filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link ExchangeRate#id}</td> * </tr> * <tr> * <td>{@code currencyCode}</td> * <td>{@link ExchangeRate#currencyCode}</td> * </tr> * <tr> * <td>{@code refreshRate}</td> * <td>{@link ExchangeRate#refreshRate}</td> * </tr> * <tr> * <td>{@code direction}</td> * <td>{@link ExchangeRate#direction}</td> * </tr> * <tr> * <td>{@code exchangeRate}</td> * <td>{@link ExchangeRate#exchangeRate}</td> * </tr> * </table> * * @param filterStatement a Publisher Query Language statement used to filter * a set of exchange rates * @return the exchange rates that match the given filter */ public function getExchangeRatesByStatement($filterStatement) { $args = new GetExchangeRatesByStatement($filterStatement); $result = $this->__soapCall("getExchangeRatesByStatement", array($args)); return $result->rval; } /** * Performs an action on {@link ExchangeRate} objects that satisfy the given * {@link Statement#query}. The following fields are supported for filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link ExchangeRate#id}</td> * </tr> * <tr> * <td>{@code currencyCode}</td> * <td>{@link ExchangeRate#currencyCode}</td> * </tr> * <tr> * <td>{@code refreshRate}</td> * <td>{@link ExchangeRate#refreshRate}</td> * </tr> * <tr> * <td>{@code direction}</td> * <td>{@link ExchangeRate#direction}</td> * </tr> * <tr> * <td>{@code exchangeRate}</td> * <td>{@link ExchangeRate#exchangeRate}</td> * </tr> * </table> * * @param exchangeRateAction the action to perform * @param filterStatement a Publisher Query Language statement used to filter * a set of exchange rates * @return the result of the action performed */ public function performExchangeRateAction($exchangeRateAction, $filterStatement) { $args = new PerformExchangeRateAction($exchangeRateAction, $filterStatement); $result = $this->__soapCall("performExchangeRateAction", array($args)); return $result->rval; } /** * Updates the specified {@link ExchangeRate} objects. * * @param exchangeRates the exchange rates to update * @return the updated exchange rates */ public function updateExchangeRates($exchangeRates) { $args = new UpdateExchangeRates($exchangeRates); $result = $this->__soapCall("updateExchangeRates", array($args)); return $result->rval; } } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_77) on Mon May 23 19:37:01 EDT 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Uses of Class org.apache.lucene.spatial.prefix.NumberRangePrefixTreeStrategy (Lucene 6.0.1 API)</title> <meta name="date" content="2016-05-23"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.lucene.spatial.prefix.NumberRangePrefixTreeStrategy (Lucene 6.0.1 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/lucene/spatial/prefix/NumberRangePrefixTreeStrategy.html" title="class in org.apache.lucene.spatial.prefix">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/lucene/spatial/prefix/class-use/NumberRangePrefixTreeStrategy.html" target="_top">Frames</a></li> <li><a href="NumberRangePrefixTreeStrategy.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.lucene.spatial.prefix.NumberRangePrefixTreeStrategy" class="title">Uses of Class<br>org.apache.lucene.spatial.prefix.NumberRangePrefixTreeStrategy</h2> </div> <div class="classUseContainer">No usage of org.apache.lucene.spatial.prefix.NumberRangePrefixTreeStrategy</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/lucene/spatial/prefix/NumberRangePrefixTreeStrategy.html" title="class in org.apache.lucene.spatial.prefix">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/lucene/spatial/prefix/class-use/NumberRangePrefixTreeStrategy.html" target="_top">Frames</a></li> <li><a href="NumberRangePrefixTreeStrategy.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2016 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
Java
# This migration comes from grocer (originally 20170119220038) class CreateGrocerExports < ActiveRecord::Migration[5.0] def change create_table :grocer_exports do |t| t.string :pid t.integer :job t.string :status t.datetime :last_error t.datetime :last_success t.string :logfile t.timestamps end add_index :grocer_exports, :pid, unique: true end end
Java
const loopback = require('loopback'); const boot = require('loopback-boot'); const request = require('request-promise'); const config = require('./config.json'); const log = require('log4js').getLogger('server'); const jwt = require('jwt-simple'); var app = module.exports = loopback(); var apiUrl = config.restApiRoot + '/*'; function parseJwt (token) { var base64Url = token.split('.')[1]; var base64 = base64Url.replace('-', '+').replace('_', '/'); var json = new Buffer(base64, 'base64').toString('binary'); return JSON.parse(json); }; app.use(loopback.context()); app.use(['/api/todos'], function(req, res, next) { var accessToken = req.query.access_token || req.headers['Authorization']; if(accessToken) { app.accessTokenProvider.getUserInfo(accessToken) .then(userInfo => { log.debug('userInfo:', userInfo); loopback.getCurrentContext().set('userInfo', userInfo); next(); }).catch(error => { log.error(error); next(error); }); } else { log.debug('missing accessToken'); next({ name: 'MISSING_ACCESS_TOKEN', status: 401, message: 'tenant access token is required to access this endpoint' }); } }); app.start = () => { // start the web server return app.listen(() => { app.emit('started'); var baseUrl = app.get('url').replace(/\/$/, ''); log.info('Web server listening at: %s', baseUrl); if (app.get('loopback-component-explorer')) { var explorerPath = app.get('loopback-component-explorer').mountPath; log.info('Browse your REST API at %s%s', baseUrl, explorerPath); } }); }; // Bootstrap the application, configure models, datasources and middleware. // Sub-apps like REST API are mounted via boot scripts. boot(app, __dirname, function(err) { if (err) throw err; // start the server if `$ node server.js` if (require.main === module) app.start(); });
Java
class TreeBuilderTenants < TreeBuilder has_kids_for Tenant, [:x_get_tree_tenant_kids] def initialize(name, sandbox, build, **params) @additional_tenants = params[:additional_tenants] @selectable = params[:selectable] @ansible_playbook = params[:ansible_playbook] @catalog_bundle = params[:catalog_bundle] super(name, sandbox, build) end private def tree_init_options { :checkboxes => true, :check_url => "/catalog/#{cat_item_or_bundle}/", :open_all => false, :oncheck => @selectable ? tenant_tree_or_generic : nil, :post_check => true, :three_checks => true }.compact end def tenant_tree_or_generic if @ansible_playbook 'miqOnCheckTenantTree' else 'miqOnCheckGeneric' end end def cat_item_or_bundle if @catalog_bundle 'st_form_field_changed' else 'atomic_form_field_changed' end end def root_options text = _('All Tenants') { :text => text, :tooltip => text, :icon => 'pficon pficon-tenant', :hideCheckbox => true } end def x_get_tree_roots if ApplicationHelper.role_allows?(:feature => 'rbac_tenant_view') Tenant.with_current_tenant end end def x_get_tree_tenant_kids(object, count_only) count_only_or_objects(count_only, object.children, 'name') end def override(node, object) node.checked = @additional_tenants.try(:include?, object) node.checkable = @selectable end end
Java
import {NgModule} from '@angular/core'; import {TestimonialService} from "./testimonial.service"; import {TestimonialEditorComponent} from "./testimonial-editor.component"; import {TestimonialComponent} from "./testimonial-list.component"; import {TestimonialRouting} from './testimonial.route'; import {SharedModule} from '../../../shared/shared.module'; import { XhrService } from '../../../shared/services/xhr.service'; @NgModule({ imports: [SharedModule.forRoot(),TestimonialRouting], declarations: [TestimonialComponent, TestimonialEditorComponent], providers: [TestimonialService, XhrService] }) export class TestimonialModule { }
Java
class Solution: def isValidSerialization(self, preorder): """ :type preorder: str :rtype: bool """ arr_pre_order = preorder.split(',') stack = [] for node in arr_pre_order: stack.append(node) while len(stack) > 1 and stack[-1] == '#' and stack[-2] == '#': stack.pop() stack.pop() if len(stack) < 1: return False stack[-1] = '#' if len(stack) == 1 and stack[0] == '#': return True return False
Java
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: violinsolo # Created on 08/03/2018 import tensorflow as tf import numpy as np x_shape = [5, 3, 3, 2] x = np.arange(reduce(lambda t, s: t*s, list(x_shape), 1)) print x x = x.reshape([5, 3, 3, -1]) print x.shape X = tf.Variable(x) with tf.Session() as sess: m = tf.nn.moments(X, axes=[0]) # m = tf.nn.moments(X, axes=[0,1]) # m = tf.nn.moments(X, axes=np.arange(len(x_shape)-1)) mean, variance = m print(sess.run(m, feed_dict={X: x})) # print(sess.run(m, feed_dict={X: x}))
Java
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ #include <sys/types.h> #include <sys/event.h> #include <sys/time.h> #include <string.h> #include <unistd.h> #include <ckit/event.h> #include <ckit/debug.h> #include <ckit/time.h> int event_open(void) { return kqueue(); } void event_close(int efd) { close(efd); } static unsigned short kevent_flags(enum event_ctl ctl, struct event *ev) { unsigned short flags = 0; switch (ctl) { case EVENT_CTL_ADD: case EVENT_CTL_MOD: flags |= EV_ADD; break; case EVENT_CTL_DEL: flags |= EV_DELETE; break; } if (ev->events & EVENT_ONESHOT) flags |= EV_ONESHOT; return flags; } static void kevent_to_event(const struct kevent *kev, struct event *ev) { memset(ev, 0, sizeof(*ev)); if (kev->filter == EVFILT_READ) { //LOG_DBG("EVFILT_READ is set fd=%d\n", (int)kev->ident); ev->events |= EVENT_IN; } if (kev->filter == EVFILT_WRITE) { //LOG_DBG("EVFILT_WRITE is set fd=%d\n", (int)kev->ident); ev->events |= EVENT_OUT; } if (kev->flags & EV_EOF) { //LOG_DBG("EV_EOF set on fd=%d\n", (int)kev->ident); ev->events |= EVENT_RDHUP; } ev->data.fd = (int)kev->ident; ev->data.ptr = kev->udata; } int event_ctl(int efd, enum event_ctl ctl, int fd, struct event *ev) { struct kevent kev[2]; unsigned i = 0; if (ev->events & EVENT_IN) { //LOG_ERR("EVFILT_READ fd=%d\n", fd); EV_SET(&kev[i++], fd, EVFILT_READ, kevent_flags(ctl, ev), 0, 0, ev->data.ptr); } if (ev->events & EVENT_OUT) { //LOG_ERR("EVFILT_WRITE fd=%d\n", fd); EV_SET(&kev[i++], fd, EVFILT_WRITE, kevent_flags(ctl, ev), 0, 0, ev->data.ptr); } return kevent(efd, kev, i, NULL, 0, NULL); } int event_wait(int efd, struct event *events, int maxevents, int timeout) { struct kevent kevents[maxevents]; struct timespec ts = { 0, 0 }; struct timespec *ts_ptr = &ts; int ret; timespec_add_nsec(&ts, timeout * 1000000L); memset(kevents, 0, sizeof(kevents)); if (timeout == -1) ts_ptr = NULL; ret = kevent(efd, NULL, 0, kevents, maxevents, ts_ptr); if (ret == -1) { LOG_ERR("kevent: %s\n", strerror(errno)); } else if (ret > 0) { int i; /* Fill in events */ for (i = 0; i < ret; i++) { /* Check for error. The kevent() call may return either -1 * on error or an error event in the eventlist in case * there is room */ if (kevents[i].flags & EV_ERROR) { errno = kevents[i].data; /* NOTE/WARNING: What happens to other events returned * that aren't errors when we return -1 here? This is * not entirely clear, but since they won't be * processed by the caller of this function (as the * return value is -1) the events should still be * pending and returned in the next call to this * function. This might, however, not be true for edge * triggered events. */ return -1; } kevent_to_event(&kevents[i], &events[i]); } } return ret; }
Java
package com.blp.minotaurus.utils; import com.blp.minotaurus.Minotaurus; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.plugin.RegisteredServiceProvider; /** * @author TheJeterLP */ public class EconomyManager { private static Economy econ = null; public static boolean setupEconomy() { if (!Minotaurus.getInstance().getServer().getPluginManager().isPluginEnabled("Vault")) return false; RegisteredServiceProvider<Economy> rsp = Bukkit.getServicesManager().getRegistration(Economy.class); if (rsp == null || rsp.getProvider() == null) return false; econ = rsp.getProvider(); return true; } public static Economy getEcon() { return econ; } }
Java
package eas.com; public interface SomeInterface { String someMethod(String param1, String param2, String param3, String param4); }
Java
# Pterocaulon globuliferus W.Fitzg. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
'use strict'; angular.module('donetexampleApp') .service('ParseLinks', function () { this.parse = function (header) { if (header.length == 0) { throw new Error("input must not be of zero length"); } // Split parts by comma var parts = header.split(','); var links = {}; // Parse each part into a named link angular.forEach(parts, function (p) { var section = p.split(';'); if (section.length != 2) { throw new Error("section could not be split on ';'"); } var url = section[0].replace(/<(.*)>/, '$1').trim(); var queryString = {}; url.replace( new RegExp("([^?=&]+)(=([^&]*))?", "g"), function($0, $1, $2, $3) { queryString[$1] = $3; } ); var page = queryString['page']; if( angular.isString(page) ) { page = parseInt(page); } var name = section[1].replace(/rel="(.*)"/, '$1').trim(); links[name] = page; }); return links; } });
Java
package com.mobisys.musicplayer.model; import android.os.Parcel; import android.os.Parcelable; /** * Created by Govinda P on 6/3/2016. */ public class MusicFile implements Parcelable { private String title; private String album; private String id; private String singer; private String path; public MusicFile() { } public MusicFile(String title, String album, String id, String singer, String path) { this.title = title; this.album = album; this.id = id; this.singer = singer; this.path = path; } protected MusicFile(Parcel in) { title = in.readString(); album = in.readString(); id = in.readString(); singer = in.readString(); path=in.readString(); } public static final Creator<MusicFile> CREATOR = new Creator<MusicFile>() { @Override public MusicFile createFromParcel(Parcel in) { return new MusicFile(in); } @Override public MusicFile[] newArray(int size) { return new MusicFile[size]; } }; public String getTitle() { return title; } public String getAlbum() { return album; } public String getId() { return id; } public String getSinger() { return singer; } public void setTitle(String title) { this.title = title; } public void setAlbum(String album) { this.album = album; } public void setId(String id) { this.id = id; } public void setSinger(String singer) { this.singer = singer; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } @Override public String toString() { return "MusicFile{" + "title='" + title + '\'' + ", album='" + album + '\'' + ", id='" + id + '\'' + ", singer='" + singer + '\'' + ", path='" + path + '\'' + '}'; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(title); dest.writeString(album); dest.writeString(id); dest.writeString(singer); dest.writeString(path); } }
Java
# Strobilomyces coturnix Bouriquet SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Bull. Acad. malgache 25: 22 (1946) #### Original name Strobilomyces coturnix Bouriquet ### Remarks null
Java
# Cirsium undulatum subsp. helleri (Small) Petr. SUBSPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
<?php /********************************************************************************************************************************** * * Ajax Payment System * * Author: Webbu Design * ***********************************************************************************************************************************/ add_action( 'PF_AJAX_HANDLER_pfget_itemsystem', 'pf_ajax_itemsystem' ); add_action( 'PF_AJAX_HANDLER_nopriv_pfget_itemsystem', 'pf_ajax_itemsystem' ); function pf_ajax_itemsystem(){ check_ajax_referer( 'pfget_itemsystem', 'security'); header('Content-Type: application/json; charset=UTF-8;'); /* Get form variables */ if(isset($_POST['formtype']) && $_POST['formtype']!=''){ $formtype = $processname = esc_attr($_POST['formtype']); } /* Get data*/ $vars = array(); if(isset($_POST['dt']) && $_POST['dt']!=''){ if ($formtype == 'delete') { $pid = sanitize_text_field($_POST['dt']); }else{ $vars = array(); parse_str($_POST['dt'], $vars); if (is_array($vars)) { $vars = PFCleanArrayAttr('PFCleanFilters',$vars); } else { $vars = esc_attr($vars); } } } /* WPML Fix */ $lang_c = ''; if(isset($_POST['lang']) && $_POST['lang']!=''){ $lang_c = sanitize_text_field($_POST['lang']); } if(function_exists('icl_object_id')) { global $sitepress; if (isset($sitepress) && !empty($lang_c)) { $sitepress->switch_lang($lang_c); } } $current_user = wp_get_current_user(); $user_id = $current_user->ID; $returnval = $errorval = $pfreturn_url = $msg_output = $overlay_add = $sccval = ''; $icon_processout = 62; $setup3_pointposttype_pt1 = PFSAIssetControl('setup3_pointposttype_pt1','','pfitemfinder'); if ($formtype == 'delete') { /** *Start: Delete Item for PPP/Membership **/ if($user_id != 0){ $delete_postid = (is_numeric($pid))? $pid:''; if ($delete_postid != '') { $old_status_featured = false; $setup4_membersettings_paymentsystem = PFSAIssetControl('setup4_membersettings_paymentsystem','','1'); if ($setup4_membersettings_paymentsystem == 2) { /*Check if item user s item*/ global $wpdb; $result = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_author FROM $wpdb->posts WHERE ID = %s and post_author = %s and post_type = %s", $delete_postid, $user_id, $setup3_pointposttype_pt1 ) ); if (is_array($result) && count($result)>0) { if ($result[0]->ID == $delete_postid) { $delete_item_images = get_post_meta($delete_postid, 'webbupointfinder_item_images'); if (!empty($delete_item_images)) { foreach ($delete_item_images as $item_image) { wp_delete_attachment(esc_attr($item_image),true); } } wp_delete_attachment(get_post_thumbnail_id( $delete_postid ),true); $old_status_featured = get_post_meta( $delete_postid, 'webbupointfinder_item_featuredmarker', true ); wp_delete_post($delete_postid); $membership_user_activeorder = get_user_meta( $user_id, 'membership_user_activeorder', true ); /* - Creating record for process system. */ PFCreateProcessRecord( array( 'user_id' => $user_id, 'item_post_id' => $membership_user_activeorder, 'processname' => esc_html__('Item deleted by USER.','pointfindert2d'), 'membership' => 1 ) ); /* - Create a record for payment system. */ $sccval .= esc_html__('Item successfully deleted. Refreshing...','pointfindert2d'); } }else{ $icon_processout = 485; $errorval .= esc_html__('Wrong item ID or already deleted. Item can not delete.','pointfindert2d'); } /*Membership limits for item /featured limit*/ $membership_user_item_limit = get_user_meta( $user_id, 'membership_user_item_limit', true ); $membership_user_featureditem_limit = get_user_meta( $user_id, 'membership_user_featureditem_limit', true ); $membership_user_package_id = get_user_meta( $user_id, 'membership_user_package_id', true ); $packageinfox = pointfinder_membership_package_details_get($membership_user_package_id); if ($membership_user_item_limit == -1) { /* Do nothing... */ }else{ if ($membership_user_item_limit >= 0) { $membership_user_item_limit = $membership_user_item_limit + 1; if ($membership_user_item_limit <= $packageinfox['webbupointfinder_mp_itemnumber']) { update_user_meta( $user_id, 'membership_user_item_limit', $membership_user_item_limit); } } } if($old_status_featured != false && $old_status_featured != 0){ $membership_user_featureditem_limit = $membership_user_featureditem_limit + 1; if ($membership_user_featureditem_limit <= $packageinfox['webbupointfinder_mp_fitemnumber']) { update_user_meta( $user_id, 'membership_user_featureditem_limit', $membership_user_featureditem_limit); } } } else { /*Check if item user s item*/ global $wpdb; $result = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_author FROM $wpdb->posts WHERE ID = %s and post_author = %s and post_type = %s", $delete_postid, $user_id, $setup3_pointposttype_pt1 ) ); $result_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = %s and meta_value = %s", 'pointfinder_order_itemid', $delete_postid ) ); $pointfinder_order_recurring = esc_attr(get_post_meta( $result_id, 'pointfinder_order_recurring', true )); if($pointfinder_order_recurring == 1){ $pointfinder_order_recurringid = esc_attr(get_post_meta( $result_id, 'pointfinder_order_recurringid', true )); PF_Cancel_recurring_payment( array( 'user_id' => $user_id, 'profile_id' => $pointfinder_order_recurringid, 'item_post_id' => $delete_postid, 'order_post_id' => $result_id, ) ); } if (is_array($result) && count($result)>0) { if ($result[0]->ID == $delete_postid) { $delete_item_images = get_post_meta($delete_postid, 'webbupointfinder_item_images'); if (!empty($delete_item_images)) { foreach ($delete_item_images as $item_image) { wp_delete_attachment(esc_attr($item_image),true); } } wp_delete_attachment(get_post_thumbnail_id( $delete_postid ),true); wp_delete_post($delete_postid); /* - Creating record for process system. */ PFCreateProcessRecord( array( 'user_id' => $user_id, 'item_post_id' => $delete_postid, 'processname' => esc_html__('Item deleted by USER.','pointfindert2d') ) ); /* - Create a record for payment system. */ $sccval .= esc_html__('Item successfully deleted. Refreshing...','pointfindert2d'); } }else{ $icon_processout = 485; $errorval .= esc_html__('Wrong item ID (Not your item!). Item can not delete.','pointfindert2d'); } } }else{ $icon_processout = 485; $errorval .= esc_html__('Wrong item ID.','pointfindert2d'); } }else{ $icon_processout = 485; $errorval .= esc_html__('Please login again to upload/edit item (Invalid UserID).','pointfindert2d'); } if (!empty($sccval)) { $msg_output .= $sccval; $overlay_add = ' pfoverlayapprove'; }elseif (!empty($errorval)) { $msg_output .= $errorval; } /** *End: Delete Item for PPP/Membership **/ } else { /** *Start: New/Edit Item Form Request **/ if(isset($_POST) && $_POST!='' && count($_POST)>0){ if($user_id != 0){ if($vars['action'] == 'pfget_edititem'){ if (isset($vars['edit_pid']) && !empty($vars['edit_pid'])) { $edit_postid = $vars['edit_pid']; global $wpdb; $result = $wpdb->get_results( $wpdb->prepare( " SELECT ID, post_author FROM $wpdb->posts WHERE ID = %s and post_author = %s and post_type = %s ", $edit_postid, $user_id, $setup3_pointposttype_pt1 ) ); if (is_array($result) && count($result)>0) { if ($result[0]->ID == $edit_postid) { $returnval = PFU_AddorUpdateRecord( array( 'post_id' => $edit_postid, 'order_post_id' => PFU_GetOrderID($edit_postid,1), 'order_title' => PFU_GetOrderID($edit_postid,0), 'vars' => $vars, 'user_id' => $user_id ) ); }else{ $icon_processout = 485; $errorval .= esc_html__('This is not your item.','pointfindert2d'); } }else{ $icon_processout = 485; $errorval .= esc_html__('Wrong Item ID','pointfindert2d'); } }else{ $icon_processout = 485; $errorval .= esc_html__('There is no item ID to edit.','pointfindert2d'); } }elseif ($vars['action'] == 'pfget_uploaditem') { $returnval = PFU_AddorUpdateRecord( array( 'post_id' => '', 'order_post_id' => '', 'order_title' => '', 'vars' => $vars, 'user_id' => $user_id ) ); } }else{ $icon_processout = 485; $errorval .= esc_html__('Please login again to upload/edit item (Invalid UserID).','pointfindert2d'); } } if (is_array($returnval) && !empty($returnval)) { if (isset($returnval['sccval'])) { $msg_output .= $returnval['sccval']; $overlay_add = ' pfoverlayapprove'; }elseif (isset($returnval['errorval'])) { $msg_output .= $returnval['errorval']; } }else{ $msg_output .= $errorval; } /** *End: New/Edit Item Form Request **/ } $setup4_membersettings_dashboard = PFSAIssetControl('setup4_membersettings_dashboard','',''); $setup4_membersettings_dashboard_link = get_permalink($setup4_membersettings_dashboard); $pfmenu_perout = PFPermalinkCheck(); $pfreturn_url = $setup4_membersettings_dashboard_link.$pfmenu_perout.'ua=myitems'; $output_html = ''; $output_html .= '<div class="golden-forms wrapper mini" style="height:200px">'; $output_html .= '<div id="pfmdcontainer-overlay" class="pftrwcontainer-overlay">'; $output_html .= "<div class='pf-overlay-close'><i class='pfadmicon-glyph-707'></i></div>"; $output_html .= "<div class='pfrevoverlaytext".$overlay_add."'><i class='pfadmicon-glyph-".$icon_processout."'></i><span>".$msg_output."</span></div>"; $output_html .= '</div>'; $output_html .= '</div>'; if (!empty($errorval)) { echo json_encode( array( 'process'=>false, 'processname'=>$processname, 'mes'=>$output_html, 'returnurl' => $pfreturn_url ) ); }else{ echo json_encode( array( 'process'=>true, 'processname'=>$processname, 'returnval'=>$returnval, 'mes'=>$output_html, 'returnurl' => $pfreturn_url ) ); } die(); } ?>
Java
// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; using System.Threading; using NetworkCommsDotNet.DPSBase; using NetworkCommsDotNet.Tools; #if NETFX_CORE using NetworkCommsDotNet.Tools.XPlatformHelper; #else using System.Net.Sockets; #endif #if WINDOWS_PHONE || NETFX_CORE using Windows.Networking.Sockets; using Windows.Networking; using System.Runtime.InteropServices.WindowsRuntime; #endif namespace NetworkCommsDotNet.Connections.UDP { /// <summary> /// A connection object which utilises <see href="http://en.wikipedia.org/wiki/User_Datagram_Protocol">UDP</see> to communicate between peers. /// </summary> public sealed partial class UDPConnection : IPConnection { #if WINDOWS_PHONE || NETFX_CORE internal DatagramSocket socket; #else internal UdpClientWrapper udpClient; #endif /// <summary> /// Options associated with this UDPConnection /// </summary> public UDPOptions ConnectionUDPOptions { get; private set; } /// <summary> /// An isolated UDP connection will only accept incoming packets coming from a specific RemoteEndPoint. /// </summary> bool isIsolatedUDPConnection = false; /// <summary> /// Internal constructor for UDP connections /// </summary> /// <param name="connectionInfo"></param> /// <param name="defaultSendReceiveOptions"></param> /// <param name="level"></param> /// <param name="listenForIncomingPackets"></param> /// <param name="existingConnection"></param> internal UDPConnection(ConnectionInfo connectionInfo, SendReceiveOptions defaultSendReceiveOptions, UDPOptions level, bool listenForIncomingPackets, UDPConnection existingConnection = null) : base(connectionInfo, defaultSendReceiveOptions) { if (connectionInfo.ConnectionType != ConnectionType.UDP) throw new ArgumentException("Provided connectionType must be UDP.", "connectionInfo"); if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Creating new UDPConnection with " + connectionInfo); if (connectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Disabled && level != UDPOptions.None) throw new ArgumentException("If the application layer protocol has been disabled the provided UDPOptions can only be UDPOptions.None."); ConnectionUDPOptions = level; if (listenForIncomingPackets && existingConnection != null) throw new Exception("Unable to listen for incoming packets if an existing client has been provided. This is to prevent possible multiple accidently listens on the same client."); if (existingConnection == null) { if (connectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any) || connectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.IPv6Any)) { #if WINDOWS_PHONE || NETFX_CORE //We are creating an unbound endPoint, this is currently the rogue UDP sender and listeners only socket = new DatagramSocket(); if (listenForIncomingPackets) socket.MessageReceived += socket_MessageReceived; socket.BindEndpointAsync(new HostName(ConnectionInfo.LocalIPEndPoint.Address.ToString()), ConnectionInfo.LocalIPEndPoint.Port.ToString()).AsTask().Wait(); #else //We are creating an unbound endPoint, this is currently the rogue UDP sender and listeners only udpClient = new UdpClientWrapper(new UdpClient(ConnectionInfo.LocalIPEndPoint)); #endif } else { //If this is a specific connection we link to a default end point here isIsolatedUDPConnection = true; #if WINDOWS_PHONE || NETFX_CORE if (ConnectionInfo.LocalEndPoint == null || (ConnectionInfo.LocalIPEndPoint.Address == IPAddress.Any && connectionInfo.LocalIPEndPoint.Port == 0) || (ConnectionInfo.LocalIPEndPoint.Address == IPAddress.IPv6Any && connectionInfo.LocalIPEndPoint.Port == 0)) { socket = new DatagramSocket(); if (listenForIncomingPackets) socket.MessageReceived += socket_MessageReceived; socket.ConnectAsync(new HostName(ConnectionInfo.RemoteIPEndPoint.Address.ToString()), ConnectionInfo.RemoteIPEndPoint.Port.ToString()).AsTask().Wait(); } else { socket = new DatagramSocket(); if (listenForIncomingPackets) socket.MessageReceived += socket_MessageReceived; EndpointPair pair = new EndpointPair(new HostName(ConnectionInfo.LocalIPEndPoint.Address.ToString()), ConnectionInfo.LocalIPEndPoint.Port.ToString(), new HostName(ConnectionInfo.RemoteIPEndPoint.Address.ToString()), ConnectionInfo.RemoteIPEndPoint.Port.ToString()); socket.ConnectAsync(pair).AsTask().Wait(); } #else if (ConnectionInfo.LocalEndPoint == null) udpClient = new UdpClientWrapper(new UdpClient(ConnectionInfo.RemoteEndPoint.AddressFamily)); else udpClient = new UdpClientWrapper(new UdpClient(ConnectionInfo.LocalIPEndPoint)); //By calling connect we discard packets from anything other then the provided remoteEndPoint on our localEndPoint udpClient.Connect(ConnectionInfo.RemoteIPEndPoint); #endif } #if !WINDOWS_PHONE && !NETFX_CORE //NAT traversal does not work in .net 2.0 //Mono does not seem to have implemented AllowNatTraversal method and attempting the below method call will throw an exception //if (Type.GetType("Mono.Runtime") == null) //Allow NAT traversal by default for all udp clients // udpClientThreadSafe.AllowNatTraversal(true); if (listenForIncomingPackets) StartIncomingDataListen(); #endif } else { if (!existingConnection.ConnectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any)) throw new Exception("If an existing udpClient is provided it must be unbound to a specific remoteEndPoint"); #if WINDOWS_PHONE || NETFX_CORE //Using an exiting client allows us to send from the same port as for the provided existing connection this.socket = existingConnection.socket; #else //Using an exiting client allows us to send from the same port as for the provided existing connection this.udpClient = existingConnection.udpClient; #endif } IPEndPoint localEndPoint; #if WINDOWS_PHONE || NETFX_CORE localEndPoint = new IPEndPoint(IPAddress.Parse(socket.Information.LocalAddress.DisplayName.ToString()), int.Parse(socket.Information.LocalPort)); #else localEndPoint = udpClient.LocalIPEndPoint; #endif //We can update the localEndPoint so that it is correct if (!ConnectionInfo.LocalEndPoint.Equals(localEndPoint)) { //We should now be able to set the connectionInfo localEndPoint NetworkComms.UpdateConnectionReferenceByEndPoint(this, ConnectionInfo.RemoteIPEndPoint, localEndPoint); ConnectionInfo.UpdateLocalEndPointInfo(localEndPoint); } } /// <inheritdoc /> protected override void EstablishConnectionSpecific() { //If the application layer protocol is enabled and the UDP option is set if (ConnectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled && (ConnectionUDPOptions & UDPOptions.Handshake) == UDPOptions.Handshake) ConnectionHandshake(); else { //If there is no handshake we can now consider the connection established TriggerConnectionEstablishDelegates(); //Trigger any connection setup waits connectionSetupWait.Set(); } } /// <inheritdoc /> protected override void CloseConnectionSpecific(bool closeDueToError, int logLocation = 0) { #if WINDOWS_PHONE || NETFX_CORE //We only call close on the udpClient if this is a specific UDP connection or we are calling close from the parent UDP connection if (socket != null && (isIsolatedUDPConnection || (ConnectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any)))) socket.Dispose(); #else //We only call close on the udpClient if this is a specific UDP connection or we are calling close from the parent UDP connection if (udpClient != null && (isIsolatedUDPConnection || (ConnectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any)))) udpClient.CloseClient(); #endif } /// <summary> /// Send a packet to the specified ipEndPoint. This feature is unique to UDP because of its connectionless structure. /// </summary> /// <param name="packet">Packet to send</param> /// <param name="ipEndPoint">The target ipEndPoint</param> private void SendPacketSpecific<packetObjectType>(IPacket packet, IPEndPoint ipEndPoint) { #if FREETRIAL if (ipEndPoint.Address == IPAddress.Broadcast) throw new NotSupportedException("Unable to send UDP broadcast datagram using this version of NetworkComms.Net. Please purchase a commercial license from www.networkcomms.net which supports UDP broadcast datagrams."); #endif byte[] headerBytes = new byte[0]; if (ConnectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled) { long packetSequenceNumber; lock (sendLocker) { //Set packet sequence number inside sendLocker //Increment the global counter as well to ensure future connections with the same host can not create duplicates Interlocked.Increment(ref NetworkComms.totalPacketSendCount); packetSequenceNumber = packetSequenceCounter++; packet.PacketHeader.SetOption(PacketHeaderLongItems.PacketSequenceNumber, packetSequenceNumber); } headerBytes = packet.SerialiseHeader(NetworkComms.InternalFixedSendReceiveOptions); } else { if (packet.PacketHeader.PacketType != Enum.GetName(typeof(ReservedPacketType), ReservedPacketType.Unmanaged)) throw new UnexpectedPacketTypeException("Only 'Unmanaged' packet types can be used if the NetworkComms.Net application layer protocol is disabled."); if (packet.PacketData.Length == 0) throw new NotSupportedException("Sending a zero length array if the NetworkComms.Net application layer protocol is disabled is not supported."); } //We are limited in size for the isolated send if (headerBytes.Length + packet.PacketData.Length > maximumSingleDatagramSizeBytes) throw new CommunicationException("Attempted to send a UDP packet whose serialised size was " + (headerBytes.Length + packet.PacketData.Length).ToString() + " bytes. The maximum size for a single UDP send is " + maximumSingleDatagramSizeBytes.ToString() + ". Consider using a TCP connection to send this object."); if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Debug("Sending a UDP packet of type '" + packet.PacketHeader.PacketType + "' from " + ConnectionInfo.LocalIPEndPoint.Address + ":" + ConnectionInfo.LocalIPEndPoint.Port.ToString() + " to " + ipEndPoint.Address + ":" + ipEndPoint.Port.ToString() + " containing " + headerBytes.Length.ToString() + " header bytes and " + packet.PacketData.Length.ToString() + " payload bytes."); //Prepare the single byte array to send byte[] udpDatagram; if (ConnectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled) { udpDatagram = packet.PacketData.ThreadSafeStream.ToArray(headerBytes.Length); //Copy the header bytes into the datagram Buffer.BlockCopy(headerBytes, 0, udpDatagram, 0, headerBytes.Length); } else udpDatagram = packet.PacketData.ThreadSafeStream.ToArray(); #if WINDOWS_PHONE || NETFX_CORE var getStreamTask = socket.GetOutputStreamAsync(new HostName(ipEndPoint.Address.ToString()), ipEndPoint.Port.ToString()).AsTask(); getStreamTask.Wait(); var outputStream = getStreamTask.Result; outputStream.WriteAsync(WindowsRuntimeBufferExtensions.AsBuffer(udpDatagram)).AsTask().Wait(); outputStream.FlushAsync().AsTask().Wait(); #else udpClient.Send(udpDatagram, udpDatagram.Length, ipEndPoint); #endif if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Completed send of a UDP packet of type '" + packet.PacketHeader.PacketType + "' from " + ConnectionInfo.LocalIPEndPoint.Address + ":" + ConnectionInfo.LocalIPEndPoint.Port.ToString() + " to " + ipEndPoint.Address + ":" + ipEndPoint.Port.ToString() + "."); } /// <inheritdoc /> protected override double[] SendStreams(StreamTools.StreamSendWrapper[] streamsToSend, double maxSendTimePerKB, long totalBytesToSend) { #if FREETRIAL if (this.ConnectionInfo.RemoteEndPoint.Address == IPAddress.Broadcast) throw new NotSupportedException("Unable to send UDP broadcast datagram using this version of NetworkComms.Net. Please purchase a commercial license from www.networkcomms.net which supports UDP broadcast datagrams."); #endif if (ConnectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any)) throw new CommunicationException("Unable to send packet using this method as remoteEndPoint equals IPAddress.Any"); if (totalBytesToSend > maximumSingleDatagramSizeBytes) throw new CommunicationException("Attempted to send a UDP packet whose length is " + totalBytesToSend.ToString() + " bytes. The maximum size for a single UDP send is " + maximumSingleDatagramSizeBytes.ToString() + ". Consider using a TCP connection to send this object."); byte[] udpDatagram = new byte[totalBytesToSend]; MemoryStream udpDatagramStream = new MemoryStream(udpDatagram, 0, udpDatagram.Length, true); for (int i = 0; i < streamsToSend.Length; i++) { if (streamsToSend[i].Length > 0) { //Write each stream streamsToSend[i].ThreadSafeStream.CopyTo(udpDatagramStream, streamsToSend[i].Start, streamsToSend[i].Length, NetworkComms.SendBufferSizeBytes, maxSendTimePerKB, MinSendTimeoutMS); streamsToSend[i].ThreadSafeStream.Dispose(); } } DateTime startTime = DateTime.Now; #if WINDOWS_PHONE || NETFX_CORE var getStreamTask = socket.GetOutputStreamAsync(new HostName(ConnectionInfo.RemoteIPEndPoint.Address.ToString()), ConnectionInfo.RemoteIPEndPoint.Port.ToString()).AsTask(); getStreamTask.Wait(); var outputStream = getStreamTask.Result; outputStream.WriteAsync(WindowsRuntimeBufferExtensions.AsBuffer(udpDatagram)).AsTask().Wait(); outputStream.FlushAsync().AsTask().Wait(); #else udpClient.Send(udpDatagram, udpDatagram.Length, ConnectionInfo.RemoteIPEndPoint); #endif udpDatagramStream.Dispose(); //Calculate timings based on fractional byte length double[] timings = new double[streamsToSend.Length]; double elapsedMS = (DateTime.Now - startTime).TotalMilliseconds; for (int i = 0; i < streamsToSend.Length; i++) timings[i] = elapsedMS * (streamsToSend[i].Length / (double)totalBytesToSend); return timings; } /// <inheritdoc /> protected override void StartIncomingDataListen() { #if WINDOWS_PHONE || NETFX_CORE throw new NotImplementedException("Not needed for UDP connections on Windows Phone 8"); #else if (NetworkComms.ConnectionListenModeUseSync) { if (incomingDataListenThread == null) { incomingDataListenThread = new Thread(IncomingUDPPacketWorker); incomingDataListenThread.Priority = NetworkComms.timeCriticalThreadPriority; incomingDataListenThread.Name = "UDP_IncomingDataListener"; incomingDataListenThread.IsBackground = true; incomingDataListenThread.Start(); } } else { if (asyncListenStarted) throw new ConnectionSetupException("Async listen already started. Why has this been called twice?."); udpClient.BeginReceive(new AsyncCallback(IncomingUDPPacketHandler), udpClient); asyncListenStarted = true; } #endif } #if WINDOWS_PHONE || NETFX_CORE void socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) { try { var stream = args.GetDataStream().AsStreamForRead(); var dataLength = args.GetDataReader().UnconsumedBufferLength; byte[] receivedBytes = new byte[dataLength]; using (MemoryStream mem = new MemoryStream(receivedBytes)) stream.CopyTo(mem); //Received data after comms shutdown initiated. We should just close the connection if (NetworkComms.commsShutdown) CloseConnection(false, -15); stream = null; if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Received " + receivedBytes.Length + " bytes via UDP from " + args.RemoteAddress + ":" + args.RemotePort + "."); UDPConnection connection; HandshakeUDPDatagram possibleHandshakeUDPDatagram = new HandshakeUDPDatagram(receivedBytes); if (isIsolatedUDPConnection) //This connection was created for a specific remoteEndPoint so we can handle the data internally connection = this; else { IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(args.RemoteAddress.DisplayName.ToString()), int.Parse(args.RemotePort)); IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(sender.Information.LocalAddress.DisplayName.ToString()), int.Parse(sender.Information.LocalPort)); ConnectionInfo desiredConnection = new ConnectionInfo(ConnectionType.UDP, remoteEndPoint, localEndPoint, ConnectionInfo.ApplicationLayerProtocol, ConnectionInfo.ConnectionListener); try { //Look for an existing connection, if one does not exist we will create it //This ensures that all further processing knows about the correct endPoint connection = GetConnection(desiredConnection, ConnectionUDPOptions, ConnectionDefaultSendReceiveOptions, false, this, possibleHandshakeUDPDatagram); } catch (ConnectionShutdownException) { if ((ConnectionUDPOptions & UDPOptions.Handshake) == UDPOptions.Handshake) { if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Attempted to get connection " + desiredConnection + " but this caused a ConnectionShutdownException. Exception caught and ignored as should only happen if the connection was closed shortly after being created."); connection = null; } else throw; } } if (connection != null && !possibleHandshakeUDPDatagram.DatagramHandled) { //We pass the data off to the specific connection //Lock on the packetbuilder locker as we may receive UDP packets in parallel from this host lock (connection.packetBuilder.Locker) { connection.packetBuilder.AddPartialPacket(receivedBytes.Length, receivedBytes); if (connection.packetBuilder.TotalBytesCached > 0) connection.IncomingPacketHandleHandOff(connection.packetBuilder); if (connection.packetBuilder.TotalPartialPacketCount > 0) LogTools.LogException(new Exception("Packet builder had " + connection.packetBuilder.TotalBytesCached + " bytes remaining after a call to IncomingPacketHandleHandOff with connection " + connection.ConnectionInfo + ". Until sequenced packets are implemented this indicates a possible error."), "UDPConnectionError"); } } } //On any error here we close the connection catch (NullReferenceException) { CloseConnection(true, 25); } catch (ArgumentNullException) { CloseConnection(true, 38); } catch (IOException) { CloseConnection(true, 26); } catch (ObjectDisposedException) { CloseConnection(true, 27); } catch (SocketException) { //Receive may throw a SocketException ErrorCode=10054 after attempting to send a datagram to an unreachable target. //We will try to get around this by ignoring the ICMP packet causing these problems on client creation CloseConnection(true, 28); } catch (InvalidOperationException) { CloseConnection(true, 29); } catch (ConnectionSetupException) { //Can occur if data is received as comms is being shutdown. //Method will attempt to create new connection which will throw ConnectionSetupException. CloseConnection(true, 50); } catch (Exception ex) { LogTools.LogException(ex, "Error_UDPConnectionIncomingPacketHandler"); CloseConnection(true, 30); } } #else /// <summary> /// Incoming data listen async method /// </summary> /// <param name="ar">Call back state data</param> private void IncomingUDPPacketHandler(IAsyncResult ar) { try { UdpClientWrapper client = (UdpClientWrapper)ar.AsyncState; IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.None, 0); byte[] receivedBytes = client.EndReceive(ar, ref remoteEndPoint); //Received data after comms shutdown initiated. We should just close the connection if (NetworkComms.commsShutdown) CloseConnection(false, -13); if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Received " + receivedBytes.Length.ToString() + " bytes via UDP from " + remoteEndPoint.Address + ":" + remoteEndPoint.Port.ToString() + "."); UDPConnection connection; HandshakeUDPDatagram possibleHandshakeUDPDatagram = new HandshakeUDPDatagram(receivedBytes); if (isIsolatedUDPConnection) //This connection was created for a specific remoteEndPoint so we can handle the data internally connection = this; else { ConnectionInfo desiredConnection = new ConnectionInfo(ConnectionType.UDP, remoteEndPoint, udpClient.LocalIPEndPoint, ConnectionInfo.ApplicationLayerProtocol, ConnectionInfo.ConnectionListener); try { //Look for an existing connection, if one does not exist we will create it //This ensures that all further processing knows about the correct endPoint connection = GetConnection(desiredConnection, ConnectionUDPOptions, ConnectionDefaultSendReceiveOptions, false, this, possibleHandshakeUDPDatagram); } catch (ConnectionShutdownException) { if ((ConnectionUDPOptions & UDPOptions.Handshake) == UDPOptions.Handshake) { if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Attempted to get connection " + desiredConnection + " but this caused a ConnectionShutdownException. Exception caught and ignored as should only happen if the connection was closed shortly after being created."); connection = null; } else throw; } } if (connection != null && !possibleHandshakeUDPDatagram.DatagramHandled) { //We pass the data off to the specific connection //Lock on the packetbuilder locker as we may receive UDP packets in parallel from this host lock (connection.packetBuilder.Locker) { if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace(" ... " + receivedBytes.Length.ToString() + " bytes added to packetBuilder for " + connection.ConnectionInfo + ". Cached " + connection.packetBuilder.TotalBytesCached.ToString() + " bytes, expecting " + connection.packetBuilder.TotalBytesExpected.ToString() + " bytes."); connection.packetBuilder.AddPartialPacket(receivedBytes.Length, receivedBytes); if (connection.packetBuilder.TotalBytesCached > 0) connection.IncomingPacketHandleHandOff(connection.packetBuilder); if (connection.packetBuilder.TotalPartialPacketCount > 0) LogTools.LogException(new Exception("Packet builder had " + connection.packetBuilder.TotalBytesCached + " bytes remaining after a call to IncomingPacketHandleHandOff with connection " + connection.ConnectionInfo + ". Until sequenced packets are implemented this indicates a possible error."), "UDPConnectionError"); } } client.BeginReceive(new AsyncCallback(IncomingUDPPacketHandler), client); } //On any error here we close the connection catch (NullReferenceException) { CloseConnection(true, 25); } catch (ArgumentNullException) { CloseConnection(true, 36); } catch (IOException) { CloseConnection(true, 26); } catch (ObjectDisposedException) { CloseConnection(true, 27); } catch (SocketException) { //Receive may throw a SocketException ErrorCode=10054 after attempting to send a datagram to an unreachable target. //We will try to get around this by ignoring the ICMP packet causing these problems on client creation CloseConnection(true, 28); } catch (InvalidOperationException) { CloseConnection(true, 29); } catch (ConnectionSetupException) { //Can occur if data is received as comms is being shutdown. //Method will attempt to create new connection which will throw ConnectionSetupException. CloseConnection(true, 50); } catch (Exception ex) { LogTools.LogException(ex, "Error_UDPConnectionIncomingPacketHandler"); CloseConnection(true, 30); } } /// <summary> /// Incoming data listen sync method /// </summary> private void IncomingUDPPacketWorker() { try { while (true) { if (ConnectionInfo.ConnectionState == ConnectionState.Shutdown) break; IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.None, 0); byte[] receivedBytes = udpClient.Receive(ref remoteEndPoint); //Received data after comms shutdown initiated. We should just close the connection if (NetworkComms.commsShutdown) CloseConnection(false, -14); if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Received " + receivedBytes.Length.ToString() + " bytes via UDP from " + remoteEndPoint.Address + ":" + remoteEndPoint.Port.ToString() + "."); UDPConnection connection; HandshakeUDPDatagram possibleHandshakeUDPDatagram = new HandshakeUDPDatagram(receivedBytes); if (isIsolatedUDPConnection) //This connection was created for a specific remoteEndPoint so we can handle the data internally connection = this; else { ConnectionInfo desiredConnection = new ConnectionInfo(ConnectionType.UDP, remoteEndPoint, udpClient.LocalIPEndPoint, ConnectionInfo.ApplicationLayerProtocol, ConnectionInfo.ConnectionListener); try { //Look for an existing connection, if one does not exist we will create it //This ensures that all further processing knows about the correct endPoint connection = GetConnection(desiredConnection, ConnectionUDPOptions, ConnectionDefaultSendReceiveOptions, false, this, possibleHandshakeUDPDatagram); } catch (ConnectionShutdownException) { if ((ConnectionUDPOptions & UDPOptions.Handshake) == UDPOptions.Handshake) { if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Attempted to get connection " + desiredConnection + " but this caused a ConnectionShutdownException. Exception caught and ignored as should only happen if the connection was closed shortly after being created."); connection = null; } else throw; } } if (connection != null && !possibleHandshakeUDPDatagram.DatagramHandled) { //We pass the data off to the specific connection //Lock on the packetbuilder locker as we may receive UDP packets in parallel from this host lock (connection.packetBuilder.Locker) { if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace(" ... " + receivedBytes.Length.ToString() + " bytes added to packetBuilder for " + connection.ConnectionInfo + ". Cached " + connection.packetBuilder.TotalBytesCached.ToString() + " bytes, expecting " + connection.packetBuilder.TotalBytesExpected.ToString() + " bytes."); connection.packetBuilder.AddPartialPacket(receivedBytes.Length, receivedBytes); if (connection.packetBuilder.TotalBytesCached > 0) connection.IncomingPacketHandleHandOff(connection.packetBuilder); if (connection.packetBuilder.TotalPartialPacketCount > 0) LogTools.LogException(new Exception("Packet builder had " + connection.packetBuilder.TotalBytesCached + " bytes remaining after a call to IncomingPacketHandleHandOff with connection " + connection.ConnectionInfo + ". Until sequenced packets are implemented this indicates a possible error."), "UDPConnectionError"); } } } } //On any error here we close the connection catch (NullReferenceException) { CloseConnection(true, 20); } catch (ArgumentNullException) { CloseConnection(true, 37); } catch (IOException) { CloseConnection(true, 21); } catch (ObjectDisposedException) { CloseConnection(true, 22); } catch (SocketException) { //Receive may throw a SocketException ErrorCode=10054 after attempting to send a datagram to an unreachable target. //We will try to get around this by ignoring the ICMP packet causing these problems on client creation CloseConnection(true, 23); } catch (InvalidOperationException) { CloseConnection(true, 24); } catch (ConnectionSetupException) { //Can occur if data is received as comms is being shutdown. //Method will attempt to create new connection which will throw ConnectionSetupException. CloseConnection(true, 50); } catch (Exception ex) { LogTools.LogException(ex, "Error_UDPConnectionIncomingPacketHandler"); CloseConnection(true, 41); } //Clear the listen thread object because the thread is about to end incomingDataListenThread = null; if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Incoming data listen thread ending for " + ConnectionInfo); } #endif } }
Java
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.cognitoidp.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.cognitoidp.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * AnalyticsMetadataType JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AnalyticsMetadataTypeJsonUnmarshaller implements Unmarshaller<AnalyticsMetadataType, JsonUnmarshallerContext> { public AnalyticsMetadataType unmarshall(JsonUnmarshallerContext context) throws Exception { AnalyticsMetadataType analyticsMetadataType = new AnalyticsMetadataType(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("AnalyticsEndpointId", targetDepth)) { context.nextToken(); analyticsMetadataType.setAnalyticsEndpointId(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return analyticsMetadataType; } private static AnalyticsMetadataTypeJsonUnmarshaller instance; public static AnalyticsMetadataTypeJsonUnmarshaller getInstance() { if (instance == null) instance = new AnalyticsMetadataTypeJsonUnmarshaller(); return instance; } }
Java
module Serf.Event where import Serf.Member import Control.Applicative import Control.Monad.IO.Class import System.Environment import System.Exit import System.IO import Text.Parsec type SerfError = String data SerfEvent = MemberJoin Member | MemberLeave Member | MemberFailed Member | MemberUpdate Member | MemberReap Member | User | Query | Unknown String getSerfEvent :: IO (Either SerfError SerfEvent) getSerfEvent = getEnv "SERF_EVENT" >>= fromString where fromString :: String -> IO (Either SerfError SerfEvent) fromString "member-join" = readMemberEvent MemberJoin fromString "member-leave" = readMemberEvent MemberLeave fromString "member-failed" = readMemberEvent MemberFailed fromString "member-update" = readMemberEvent MemberUpdate fromString "member-reap" = readMemberEvent MemberReap fromString "user" = return $ Right User fromString "query" = return $ Right Query fromString unk = return . Right $ Unknown unk readMemberEvent :: (Member -> SerfEvent) -> IO (Either SerfError SerfEvent) readMemberEvent f = addMember f <$> readMember addMember :: (Member -> SerfEvent) -> Either ParseError Member -> Either SerfError SerfEvent addMember _ (Left err) = Left $ show err addMember f (Right m) = Right $ f m readMember :: IO (Either ParseError Member) readMember = memberFromString <$> getLine isMemberEvent :: SerfEvent -> Bool isMemberEvent (MemberJoin _) = True isMemberEvent (MemberLeave _) = True isMemberEvent (MemberFailed _) = True isMemberEvent (MemberUpdate _) = True isMemberEvent (MemberReap _) = True isMemberEvent _ = False type EventHandler m = SerfEvent -> m () handleEventWith :: MonadIO m => EventHandler m -> m () handleEventWith hdlr = do evt <- liftIO getSerfEvent case evt of Left err -> liftIO $ hPutStrLn stderr err >> exitFailure Right ev -> hdlr ev
Java
/* 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 kubelet import ( "bytes" "errors" "fmt" "io" "io/ioutil" "net" "net/http" "os" "path" "reflect" "sort" "strings" "testing" "time" cadvisorApi "github.com/google/cadvisor/info/v1" cadvisorApiv2 "github.com/google/cadvisor/info/v2" "k8s.io/kubernetes/pkg/api" apierrors "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/testapi" "k8s.io/kubernetes/pkg/capabilities" "k8s.io/kubernetes/pkg/client/unversioned/record" "k8s.io/kubernetes/pkg/client/unversioned/testclient" "k8s.io/kubernetes/pkg/kubelet/cadvisor" "k8s.io/kubernetes/pkg/kubelet/container" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/network" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util/bandwidth" "k8s.io/kubernetes/pkg/version" "k8s.io/kubernetes/pkg/volume" _ "k8s.io/kubernetes/pkg/volume/host_path" ) func init() { api.ForTesting_ReferencesAllowBlankSelfLinks = true util.ReallyCrash = true } const testKubeletHostname = "127.0.0.1" type fakeHTTP struct { url string err error } func (f *fakeHTTP) Get(url string) (*http.Response, error) { f.url = url return nil, f.err } type TestKubelet struct { kubelet *Kubelet fakeRuntime *kubecontainer.FakeRuntime fakeCadvisor *cadvisor.Mock fakeKubeClient *testclient.Fake fakeMirrorClient *fakeMirrorClient } func newTestKubelet(t *testing.T) *TestKubelet { fakeRuntime := &kubecontainer.FakeRuntime{} fakeRuntime.VersionInfo = "1.15" fakeRecorder := &record.FakeRecorder{} fakeKubeClient := &testclient.Fake{} kubelet := &Kubelet{} kubelet.kubeClient = fakeKubeClient kubelet.os = kubecontainer.FakeOS{} kubelet.hostname = testKubeletHostname kubelet.nodeName = testKubeletHostname kubelet.runtimeUpThreshold = maxWaitForContainerRuntime kubelet.networkPlugin, _ = network.InitNetworkPlugin([]network.NetworkPlugin{}, "", network.NewFakeHost(nil)) if tempDir, err := ioutil.TempDir("/tmp", "kubelet_test."); err != nil { t.Fatalf("can't make a temp rootdir: %v", err) } else { kubelet.rootDirectory = tempDir } if err := os.MkdirAll(kubelet.rootDirectory, 0750); err != nil { t.Fatalf("can't mkdir(%q): %v", kubelet.rootDirectory, err) } kubelet.sourcesReady = func() bool { return true } kubelet.masterServiceNamespace = api.NamespaceDefault kubelet.serviceLister = testServiceLister{} kubelet.nodeLister = testNodeLister{} kubelet.readinessManager = kubecontainer.NewReadinessManager() kubelet.recorder = fakeRecorder kubelet.statusManager = newStatusManager(fakeKubeClient) if err := kubelet.setupDataDirs(); err != nil { t.Fatalf("can't initialize kubelet data dirs: %v", err) } mockCadvisor := &cadvisor.Mock{} kubelet.cadvisor = mockCadvisor podManager, fakeMirrorClient := newFakePodManager() kubelet.podManager = podManager kubelet.containerRefManager = kubecontainer.NewRefManager() diskSpaceManager, err := newDiskSpaceManager(mockCadvisor, DiskSpacePolicy{}) if err != nil { t.Fatalf("can't initialize disk space manager: %v", err) } kubelet.diskSpaceManager = diskSpaceManager kubelet.containerRuntime = fakeRuntime kubelet.runtimeCache = kubecontainer.NewFakeRuntimeCache(kubelet.containerRuntime) kubelet.podWorkers = &fakePodWorkers{ syncPodFn: kubelet.syncPod, runtimeCache: kubelet.runtimeCache, t: t, } kubelet.volumeManager = newVolumeManager() kubelet.containerManager, _ = newContainerManager(mockCadvisor, "", "", "") kubelet.networkConfigured = true fakeClock := &util.FakeClock{Time: time.Now()} kubelet.backOff = util.NewBackOff(time.Second, time.Minute) kubelet.backOff.Clock = fakeClock kubelet.podKillingCh = make(chan *kubecontainer.Pod, 20) return &TestKubelet{kubelet, fakeRuntime, mockCadvisor, fakeKubeClient, fakeMirrorClient} } func newTestPods(count int) []*api.Pod { pods := make([]*api.Pod, count) for i := 0; i < count; i++ { pods[i] = &api.Pod{ ObjectMeta: api.ObjectMeta{ Name: fmt.Sprintf("pod%d", i), }, } } return pods } func TestKubeletDirs(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet root := kubelet.rootDirectory var exp, got string got = kubelet.getPodsDir() exp = path.Join(root, "pods") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPluginsDir() exp = path.Join(root, "plugins") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPluginDir("foobar") exp = path.Join(root, "plugins/foobar") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodDir("abc123") exp = path.Join(root, "pods/abc123") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodVolumesDir("abc123") exp = path.Join(root, "pods/abc123/volumes") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodVolumeDir("abc123", "plugin", "foobar") exp = path.Join(root, "pods/abc123/volumes/plugin/foobar") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodPluginsDir("abc123") exp = path.Join(root, "pods/abc123/plugins") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodPluginDir("abc123", "foobar") exp = path.Join(root, "pods/abc123/plugins/foobar") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodContainerDir("abc123", "def456") exp = path.Join(root, "pods/abc123/containers/def456") if got != exp { t.Errorf("expected %q', got %q", exp, got) } } func TestKubeletDirsCompat(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet root := kubelet.rootDirectory if err := os.MkdirAll(root, 0750); err != nil { t.Fatalf("can't mkdir(%q): %s", root, err) } var exp, got string // Old-style pod dir. if err := os.MkdirAll(fmt.Sprintf("%s/oldpod", root), 0750); err != nil { t.Fatalf("can't mkdir(%q): %s", root, err) } // New-style pod dir. if err := os.MkdirAll(fmt.Sprintf("%s/pods/newpod", root), 0750); err != nil { t.Fatalf("can't mkdir(%q): %s", root, err) } // Both-style pod dir. if err := os.MkdirAll(fmt.Sprintf("%s/bothpod", root), 0750); err != nil { t.Fatalf("can't mkdir(%q): %s", root, err) } if err := os.MkdirAll(fmt.Sprintf("%s/pods/bothpod", root), 0750); err != nil { t.Fatalf("can't mkdir(%q): %s", root, err) } got = kubelet.getPodDir("oldpod") exp = path.Join(root, "oldpod") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodDir("newpod") exp = path.Join(root, "pods/newpod") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodDir("bothpod") exp = path.Join(root, "pods/bothpod") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodDir("neitherpod") exp = path.Join(root, "pods/neitherpod") if got != exp { t.Errorf("expected %q', got %q", exp, got) } root = kubelet.getPodDir("newpod") // Old-style container dir. if err := os.MkdirAll(fmt.Sprintf("%s/oldctr", root), 0750); err != nil { t.Fatalf("can't mkdir(%q): %s", root, err) } // New-style container dir. if err := os.MkdirAll(fmt.Sprintf("%s/containers/newctr", root), 0750); err != nil { t.Fatalf("can't mkdir(%q): %s", root, err) } // Both-style container dir. if err := os.MkdirAll(fmt.Sprintf("%s/bothctr", root), 0750); err != nil { t.Fatalf("can't mkdir(%q): %s", root, err) } if err := os.MkdirAll(fmt.Sprintf("%s/containers/bothctr", root), 0750); err != nil { t.Fatalf("can't mkdir(%q): %s", root, err) } got = kubelet.getPodContainerDir("newpod", "oldctr") exp = path.Join(root, "oldctr") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodContainerDir("newpod", "newctr") exp = path.Join(root, "containers/newctr") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodContainerDir("newpod", "bothctr") exp = path.Join(root, "containers/bothctr") if got != exp { t.Errorf("expected %q', got %q", exp, got) } got = kubelet.getPodContainerDir("newpod", "neitherctr") exp = path.Join(root, "containers/neitherctr") if got != exp { t.Errorf("expected %q', got %q", exp, got) } } var emptyPodUIDs map[types.UID]SyncPodType func TestSyncLoopTimeUpdate(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) kubelet := testKubelet.kubelet loopTime1 := kubelet.LatestLoopEntryTime() if !loopTime1.IsZero() { t.Errorf("Unexpected sync loop time: %s, expected 0", loopTime1) } kubelet.syncLoopIteration(make(chan PodUpdate), kubelet) loopTime2 := kubelet.LatestLoopEntryTime() if loopTime2.IsZero() { t.Errorf("Unexpected sync loop time: 0, expected non-zero value.") } kubelet.syncLoopIteration(make(chan PodUpdate), kubelet) loopTime3 := kubelet.LatestLoopEntryTime() if !loopTime3.After(loopTime1) { t.Errorf("Sync Loop Time was not updated correctly. Second update timestamp should be greater than first update timestamp") } } func TestSyncLoopAbort(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) kubelet := testKubelet.kubelet kubelet.lastTimestampRuntimeUp = time.Now() kubelet.networkConfigured = true ch := make(chan PodUpdate) close(ch) // sanity check (also prevent this test from hanging in the next step) ok := kubelet.syncLoopIteration(ch, kubelet) if ok { t.Fatalf("expected syncLoopIteration to return !ok since update chan was closed") } // this should terminate immediately; if it hangs then the syncLoopIteration isn't aborting properly kubelet.syncLoop(ch, kubelet) } func TestSyncPodsStartPod(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "bar"}, }, }, }, } kubelet.podManager.SetPods(pods) kubelet.HandlePodSyncs(pods) fakeRuntime.AssertStartedPods([]string{string(pods[0].UID)}) } func TestSyncPodsDeletesWhenSourcesAreReady(t *testing.T) { ready := false testKubelet := newTestKubelet(t) fakeRuntime := testKubelet.fakeRuntime testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) kubelet := testKubelet.kubelet kubelet.sourcesReady = func() bool { return ready } fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "12345678", Name: "foo", Namespace: "new", Containers: []*kubecontainer.Container{ {Name: "bar"}, }, }, } kubelet.HandlePodCleanups() // Sources are not ready yet. Don't remove any pods. fakeRuntime.AssertKilledPods([]string{}) ready = true kubelet.HandlePodCleanups() // Sources are ready. Remove unwanted pods. fakeRuntime.AssertKilledPods([]string{"12345678"}) } func TestMountExternalVolumes(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet kubelet.volumePluginMgr.InitPlugins([]volume.VolumePlugin{&volume.FakeVolumePlugin{PluginName: "fake", Host: nil}}, &volumeHost{kubelet}) pod := api.Pod{ ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "test", }, Spec: api.PodSpec{ Volumes: []api.Volume{ { Name: "vol1", VolumeSource: api.VolumeSource{}, }, }, }, } podVolumes, err := kubelet.mountExternalVolumes(&pod) if err != nil { t.Errorf("Expected success: %v", err) } expectedPodVolumes := []string{"vol1"} if len(expectedPodVolumes) != len(podVolumes) { t.Errorf("Unexpected volumes. Expected %#v got %#v. Manifest was: %#v", expectedPodVolumes, podVolumes, pod) } for _, name := range expectedPodVolumes { if _, ok := podVolumes[name]; !ok { t.Errorf("api.Pod volumes map is missing key: %s. %#v", name, podVolumes) } } } func TestGetPodVolumesFromDisk(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet plug := &volume.FakeVolumePlugin{PluginName: "fake", Host: nil} kubelet.volumePluginMgr.InitPlugins([]volume.VolumePlugin{plug}, &volumeHost{kubelet}) volsOnDisk := []struct { podUID types.UID volName string }{ {"pod1", "vol1"}, {"pod1", "vol2"}, {"pod2", "vol1"}, } expectedPaths := []string{} for i := range volsOnDisk { fv := volume.FakeVolume{PodUID: volsOnDisk[i].podUID, VolName: volsOnDisk[i].volName, Plugin: plug} fv.SetUp() expectedPaths = append(expectedPaths, fv.GetPath()) } volumesFound := kubelet.getPodVolumesFromDisk() if len(volumesFound) != len(expectedPaths) { t.Errorf("Expected to find %d cleaners, got %d", len(expectedPaths), len(volumesFound)) } for _, ep := range expectedPaths { found := false for _, cl := range volumesFound { if ep == cl.GetPath() { found = true break } } if !found { t.Errorf("Could not find a volume with path %s", ep) } } } type stubVolume struct { path string } func (f *stubVolume) GetPath() string { return f.path } func TestMakeVolumeMounts(t *testing.T) { container := api.Container{ VolumeMounts: []api.VolumeMount{ { MountPath: "/mnt/path", Name: "disk", ReadOnly: false, }, { MountPath: "/mnt/path3", Name: "disk", ReadOnly: true, }, { MountPath: "/mnt/path4", Name: "disk4", ReadOnly: false, }, { MountPath: "/mnt/path5", Name: "disk5", ReadOnly: false, }, }, } podVolumes := kubecontainer.VolumeMap{ "disk": &stubVolume{"/mnt/disk"}, "disk4": &stubVolume{"/mnt/host"}, "disk5": &stubVolume{"/var/lib/kubelet/podID/volumes/empty/disk5"}, } mounts := makeMounts(&container, podVolumes) expectedMounts := []kubecontainer.Mount{ { "disk", "/mnt/path", "/mnt/disk", false, }, { "disk", "/mnt/path3", "/mnt/disk", true, }, { "disk4", "/mnt/path4", "/mnt/host", false, }, { "disk5", "/mnt/path5", "/var/lib/kubelet/podID/volumes/empty/disk5", false, }, } if !reflect.DeepEqual(mounts, expectedMounts) { t.Errorf("Unexpected mounts: Expected %#v got %#v. Container was: %#v", expectedMounts, mounts, container) } } func TestGetContainerInfo(t *testing.T) { containerID := "ab2cdf" containerPath := fmt.Sprintf("/docker/%v", containerID) containerInfo := cadvisorApi.ContainerInfo{ ContainerReference: cadvisorApi.ContainerReference{ Name: containerPath, }, } testKubelet := newTestKubelet(t) fakeRuntime := testKubelet.fakeRuntime kubelet := testKubelet.kubelet cadvisorReq := &cadvisorApi.ContainerInfoRequest{} mockCadvisor := testKubelet.fakeCadvisor mockCadvisor.On("DockerContainer", containerID, cadvisorReq).Return(containerInfo, nil) fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "12345678", Name: "qux", Namespace: "ns", Containers: []*kubecontainer.Container{ { Name: "foo", ID: types.UID(containerID), }, }, }, } stats, err := kubelet.GetContainerInfo("qux_ns", "", "foo", cadvisorReq) if err != nil { t.Errorf("unexpected error: %v", err) } if stats == nil { t.Fatalf("stats should not be nil") } mockCadvisor.AssertExpectations(t) } func TestGetRawContainerInfoRoot(t *testing.T) { containerPath := "/" containerInfo := &cadvisorApi.ContainerInfo{ ContainerReference: cadvisorApi.ContainerReference{ Name: containerPath, }, } testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet mockCadvisor := testKubelet.fakeCadvisor cadvisorReq := &cadvisorApi.ContainerInfoRequest{} mockCadvisor.On("ContainerInfo", containerPath, cadvisorReq).Return(containerInfo, nil) _, err := kubelet.GetRawContainerInfo(containerPath, cadvisorReq, false) if err != nil { t.Errorf("unexpected error: %v", err) } mockCadvisor.AssertExpectations(t) } func TestGetRawContainerInfoSubcontainers(t *testing.T) { containerPath := "/kubelet" containerInfo := map[string]*cadvisorApi.ContainerInfo{ containerPath: { ContainerReference: cadvisorApi.ContainerReference{ Name: containerPath, }, }, "/kubelet/sub": { ContainerReference: cadvisorApi.ContainerReference{ Name: "/kubelet/sub", }, }, } testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet mockCadvisor := testKubelet.fakeCadvisor cadvisorReq := &cadvisorApi.ContainerInfoRequest{} mockCadvisor.On("SubcontainerInfo", containerPath, cadvisorReq).Return(containerInfo, nil) result, err := kubelet.GetRawContainerInfo(containerPath, cadvisorReq, true) if err != nil { t.Errorf("unexpected error: %v", err) } if len(result) != 2 { t.Errorf("Expected 2 elements, received: %+v", result) } mockCadvisor.AssertExpectations(t) } func TestGetContainerInfoWhenCadvisorFailed(t *testing.T) { containerID := "ab2cdf" testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet mockCadvisor := testKubelet.fakeCadvisor fakeRuntime := testKubelet.fakeRuntime cadvisorApiFailure := fmt.Errorf("cAdvisor failure") containerInfo := cadvisorApi.ContainerInfo{} cadvisorReq := &cadvisorApi.ContainerInfoRequest{} mockCadvisor.On("DockerContainer", containerID, cadvisorReq).Return(containerInfo, cadvisorApiFailure) fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "uuid", Name: "qux", Namespace: "ns", Containers: []*kubecontainer.Container{ {Name: "foo", ID: types.UID(containerID), }, }, }, } stats, err := kubelet.GetContainerInfo("qux_ns", "uuid", "foo", cadvisorReq) if stats != nil { t.Errorf("non-nil stats on error") } if err == nil { t.Errorf("expect error but received nil error") return } if err.Error() != cadvisorApiFailure.Error() { t.Errorf("wrong error message. expect %v, got %v", cadvisorApiFailure, err) } mockCadvisor.AssertExpectations(t) } func TestGetContainerInfoOnNonExistContainer(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet mockCadvisor := testKubelet.fakeCadvisor fakeRuntime := testKubelet.fakeRuntime fakeRuntime.PodList = []*kubecontainer.Pod{} stats, _ := kubelet.GetContainerInfo("qux", "", "foo", nil) if stats != nil { t.Errorf("non-nil stats on non exist container") } mockCadvisor.AssertExpectations(t) } func TestGetContainerInfoWhenContainerRuntimeFailed(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet mockCadvisor := testKubelet.fakeCadvisor fakeRuntime := testKubelet.fakeRuntime expectedErr := fmt.Errorf("List containers error") fakeRuntime.Err = expectedErr stats, err := kubelet.GetContainerInfo("qux", "", "foo", nil) if err == nil { t.Errorf("expected error from dockertools, got none") } if err.Error() != expectedErr.Error() { t.Errorf("expected error %v got %v", expectedErr.Error(), err.Error()) } if stats != nil { t.Errorf("non-nil stats when dockertools failed") } mockCadvisor.AssertExpectations(t) } func TestGetContainerInfoWithNoContainers(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet mockCadvisor := testKubelet.fakeCadvisor stats, err := kubelet.GetContainerInfo("qux_ns", "", "foo", nil) if err == nil { t.Errorf("expected error from cadvisor client, got none") } if err != ErrContainerNotFound { t.Errorf("expected error %v, got %v", ErrContainerNotFound.Error(), err.Error()) } if stats != nil { t.Errorf("non-nil stats when dockertools returned no containers") } mockCadvisor.AssertExpectations(t) } func TestGetContainerInfoWithNoMatchingContainers(t *testing.T) { testKubelet := newTestKubelet(t) fakeRuntime := testKubelet.fakeRuntime kubelet := testKubelet.kubelet mockCadvisor := testKubelet.fakeCadvisor fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "12345678", Name: "qux", Namespace: "ns", Containers: []*kubecontainer.Container{ {Name: "bar", ID: types.UID("fakeID"), }, }}, } stats, err := kubelet.GetContainerInfo("qux_ns", "", "foo", nil) if err == nil { t.Errorf("Expected error from cadvisor client, got none") } if err != ErrContainerNotFound { t.Errorf("Expected error %v, got %v", ErrContainerNotFound.Error(), err.Error()) } if stats != nil { t.Errorf("non-nil stats when dockertools returned no containers") } mockCadvisor.AssertExpectations(t) } type fakeContainerCommandRunner struct { Cmd []string ID string PodID types.UID E error Stdin io.Reader Stdout io.WriteCloser Stderr io.WriteCloser TTY bool Port uint16 Stream io.ReadWriteCloser } func (f *fakeContainerCommandRunner) RunInContainer(id string, cmd []string) ([]byte, error) { f.Cmd = cmd f.ID = id return []byte{}, f.E } func (f *fakeContainerCommandRunner) ExecInContainer(id string, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool) error { f.Cmd = cmd f.ID = id f.Stdin = in f.Stdout = out f.Stderr = err f.TTY = tty return f.E } func (f *fakeContainerCommandRunner) PortForward(pod *kubecontainer.Pod, port uint16, stream io.ReadWriteCloser) error { f.PodID = pod.ID f.Port = port f.Stream = stream return nil } func TestRunInContainerNoSuchPod(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime fakeRuntime.PodList = []*kubecontainer.Pod{} podName := "podFoo" podNamespace := "nsFoo" containerName := "containerFoo" output, err := kubelet.RunInContainer( kubecontainer.GetPodFullName(&api.Pod{ObjectMeta: api.ObjectMeta{Name: podName, Namespace: podNamespace}}), "", containerName, []string{"ls"}) if output != nil { t.Errorf("unexpected non-nil command: %v", output) } if err == nil { t.Error("unexpected non-error") } } func TestRunInContainer(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime fakeCommandRunner := fakeContainerCommandRunner{} kubelet.runner = &fakeCommandRunner containerID := "abc1234" fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "12345678", Name: "podFoo", Namespace: "nsFoo", Containers: []*kubecontainer.Container{ {Name: "containerFoo", ID: types.UID(containerID), }, }, }, } cmd := []string{"ls"} _, err := kubelet.RunInContainer("podFoo_nsFoo", "", "containerFoo", cmd) if fakeCommandRunner.ID != containerID { t.Errorf("unexpected Name: %s", fakeCommandRunner.ID) } if !reflect.DeepEqual(fakeCommandRunner.Cmd, cmd) { t.Errorf("unexpected command: %s", fakeCommandRunner.Cmd) } if err != nil { t.Errorf("unexpected error: %v", err) } } func TestParseResolvConf(t *testing.T) { testCases := []struct { data string nameservers []string searches []string }{ {"", []string{}, []string{}}, {" ", []string{}, []string{}}, {"\n", []string{}, []string{}}, {"\t\n\t", []string{}, []string{}}, {"#comment\n", []string{}, []string{}}, {" #comment\n", []string{}, []string{}}, {"#comment\n#comment", []string{}, []string{}}, {"#comment\nnameserver", []string{}, []string{}}, {"#comment\nnameserver\nsearch", []string{}, []string{}}, {"nameserver 1.2.3.4", []string{"1.2.3.4"}, []string{}}, {" nameserver 1.2.3.4", []string{"1.2.3.4"}, []string{}}, {"\tnameserver 1.2.3.4", []string{"1.2.3.4"}, []string{}}, {"nameserver\t1.2.3.4", []string{"1.2.3.4"}, []string{}}, {"nameserver \t 1.2.3.4", []string{"1.2.3.4"}, []string{}}, {"nameserver 1.2.3.4\nnameserver 5.6.7.8", []string{"1.2.3.4", "5.6.7.8"}, []string{}}, {"search foo", []string{}, []string{"foo"}}, {"search foo bar", []string{}, []string{"foo", "bar"}}, {"search foo bar bat\n", []string{}, []string{"foo", "bar", "bat"}}, {"search foo\nsearch bar", []string{}, []string{"bar"}}, {"nameserver 1.2.3.4\nsearch foo bar", []string{"1.2.3.4"}, []string{"foo", "bar"}}, {"nameserver 1.2.3.4\nsearch foo\nnameserver 5.6.7.8\nsearch bar", []string{"1.2.3.4", "5.6.7.8"}, []string{"bar"}}, {"#comment\nnameserver 1.2.3.4\n#comment\nsearch foo\ncomment", []string{"1.2.3.4"}, []string{"foo"}}, } for i, tc := range testCases { ns, srch, err := parseResolvConf(strings.NewReader(tc.data)) if err != nil { t.Errorf("expected success, got %v", err) continue } if !reflect.DeepEqual(ns, tc.nameservers) { t.Errorf("[%d] expected nameservers %#v, got %#v", i, tc.nameservers, ns) } if !reflect.DeepEqual(srch, tc.searches) { t.Errorf("[%d] expected searches %#v, got %#v", i, tc.searches, srch) } } } func TestDNSConfigurationParams(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet clusterNS := "203.0.113.1" kubelet.clusterDomain = "kubernetes.io" kubelet.clusterDNS = net.ParseIP(clusterNS) pods := newTestPods(2) pods[0].Spec.DNSPolicy = api.DNSClusterFirst pods[1].Spec.DNSPolicy = api.DNSDefault options := make([]*kubecontainer.RunContainerOptions, 2) for i, pod := range pods { var err error kubelet.volumeManager.SetVolumes(pod.UID, make(kubecontainer.VolumeMap, 0)) options[i], err = kubelet.GenerateRunContainerOptions(pod, &api.Container{}) if err != nil { t.Fatalf("failed to generate container options: %v", err) } } if len(options[0].DNS) != 1 || options[0].DNS[0] != clusterNS { t.Errorf("expected nameserver %s, got %+v", clusterNS, options[0].DNS) } if len(options[0].DNSSearch) == 0 || options[0].DNSSearch[0] != ".svc."+kubelet.clusterDomain { t.Errorf("expected search %s, got %+v", ".svc."+kubelet.clusterDomain, options[0].DNSSearch) } if len(options[1].DNS) != 1 || options[1].DNS[0] != "127.0.0.1" { t.Errorf("expected nameserver 127.0.0.1, got %+v", options[1].DNS) } if len(options[1].DNSSearch) != 1 || options[1].DNSSearch[0] != "." { t.Errorf("expected search \".\", got %+v", options[1].DNSSearch) } kubelet.resolverConfig = "/etc/resolv.conf" for i, pod := range pods { var err error options[i], err = kubelet.GenerateRunContainerOptions(pod, &api.Container{}) if err != nil { t.Fatalf("failed to generate container options: %v", err) } } t.Logf("nameservers %+v", options[1].DNS) if len(options[0].DNS) != len(options[1].DNS)+1 { t.Errorf("expected prepend of cluster nameserver, got %+v", options[0].DNS) } else if options[0].DNS[0] != clusterNS { t.Errorf("expected nameserver %s, got %v", clusterNS, options[0].DNS[0]) } if len(options[0].DNSSearch) != len(options[1].DNSSearch)+3 { t.Errorf("expected prepend of cluster domain, got %+v", options[0].DNSSearch) } else if options[0].DNSSearch[0] != ".svc."+kubelet.clusterDomain { t.Errorf("expected domain %s, got %s", ".svc."+kubelet.clusterDomain, options[0].DNSSearch) } } type testServiceLister struct { services []api.Service } func (ls testServiceLister) List() (api.ServiceList, error) { return api.ServiceList{ Items: ls.services, }, nil } type testNodeLister struct { nodes []api.Node } func (ls testNodeLister) GetNodeInfo(id string) (*api.Node, error) { return nil, errors.New("not implemented") } func (ls testNodeLister) List() (api.NodeList, error) { return api.NodeList{ Items: ls.nodes, }, nil } type envs []kubecontainer.EnvVar func (e envs) Len() int { return len(e) } func (e envs) Swap(i, j int) { e[i], e[j] = e[j], e[i] } func (e envs) Less(i, j int) bool { return e[i].Name < e[j].Name } func TestMakeEnvironmentVariables(t *testing.T) { services := []api.Service{ { ObjectMeta: api.ObjectMeta{Name: "kubernetes", Namespace: api.NamespaceDefault}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8081, }}, ClusterIP: "1.2.3.1", }, }, { ObjectMeta: api.ObjectMeta{Name: "test", Namespace: "test1"}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8083, }}, ClusterIP: "1.2.3.3", }, }, { ObjectMeta: api.ObjectMeta{Name: "kubernetes", Namespace: "test2"}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8084, }}, ClusterIP: "1.2.3.4", }, }, { ObjectMeta: api.ObjectMeta{Name: "test", Namespace: "test2"}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8085, }}, ClusterIP: "1.2.3.5", }, }, { ObjectMeta: api.ObjectMeta{Name: "test", Namespace: "test2"}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8085, }}, ClusterIP: "None", }, }, { ObjectMeta: api.ObjectMeta{Name: "test", Namespace: "test2"}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8085, }}, }, }, { ObjectMeta: api.ObjectMeta{Name: "kubernetes", Namespace: "kubernetes"}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8086, }}, ClusterIP: "1.2.3.6", }, }, { ObjectMeta: api.ObjectMeta{Name: "not-special", Namespace: "kubernetes"}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8088, }}, ClusterIP: "1.2.3.8", }, }, { ObjectMeta: api.ObjectMeta{Name: "not-special", Namespace: "kubernetes"}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8088, }}, ClusterIP: "None", }, }, { ObjectMeta: api.ObjectMeta{Name: "not-special", Namespace: "kubernetes"}, Spec: api.ServiceSpec{ Ports: []api.ServicePort{{ Protocol: "TCP", Port: 8088, }}, ClusterIP: "", }, }, } testCases := []struct { name string // the name of the test case ns string // the namespace to generate environment for container *api.Container // the container to use masterServiceNs string // the namespace to read master service info from nilLister bool // whether the lister should be nil expectedEnvs []kubecontainer.EnvVar // a set of expected environment vars }{ { name: "api server = Y, kubelet = Y", ns: "test1", container: &api.Container{ Env: []api.EnvVar{ {Name: "FOO", Value: "BAR"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, {Name: "TEST_SERVICE_PORT", Value: "8083"}, {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, }, }, masterServiceNs: api.NamespaceDefault, nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ {Name: "FOO", Value: "BAR"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, {Name: "TEST_SERVICE_PORT", Value: "8083"}, {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, {Name: "KUBERNETES_SERVICE_PORT", Value: "8081"}, {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.1"}, {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.1:8081"}, {Name: "KUBERNETES_PORT_8081_TCP", Value: "tcp://1.2.3.1:8081"}, {Name: "KUBERNETES_PORT_8081_TCP_PROTO", Value: "tcp"}, {Name: "KUBERNETES_PORT_8081_TCP_PORT", Value: "8081"}, {Name: "KUBERNETES_PORT_8081_TCP_ADDR", Value: "1.2.3.1"}, }, }, { name: "api server = Y, kubelet = N", ns: "test1", container: &api.Container{ Env: []api.EnvVar{ {Name: "FOO", Value: "BAR"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, {Name: "TEST_SERVICE_PORT", Value: "8083"}, {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, }, }, masterServiceNs: api.NamespaceDefault, nilLister: true, expectedEnvs: []kubecontainer.EnvVar{ {Name: "FOO", Value: "BAR"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, {Name: "TEST_SERVICE_PORT", Value: "8083"}, {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, }, }, { name: "api server = N; kubelet = Y", ns: "test1", container: &api.Container{ Env: []api.EnvVar{ {Name: "FOO", Value: "BAZ"}, }, }, masterServiceNs: api.NamespaceDefault, nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ {Name: "FOO", Value: "BAZ"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, {Name: "TEST_SERVICE_PORT", Value: "8083"}, {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.1"}, {Name: "KUBERNETES_SERVICE_PORT", Value: "8081"}, {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.1:8081"}, {Name: "KUBERNETES_PORT_8081_TCP", Value: "tcp://1.2.3.1:8081"}, {Name: "KUBERNETES_PORT_8081_TCP_PROTO", Value: "tcp"}, {Name: "KUBERNETES_PORT_8081_TCP_PORT", Value: "8081"}, {Name: "KUBERNETES_PORT_8081_TCP_ADDR", Value: "1.2.3.1"}, }, }, { name: "master service in pod ns", ns: "test2", container: &api.Container{ Env: []api.EnvVar{ {Name: "FOO", Value: "ZAP"}, }, }, masterServiceNs: "kubernetes", nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ {Name: "FOO", Value: "ZAP"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.5"}, {Name: "TEST_SERVICE_PORT", Value: "8085"}, {Name: "TEST_PORT", Value: "tcp://1.2.3.5:8085"}, {Name: "TEST_PORT_8085_TCP", Value: "tcp://1.2.3.5:8085"}, {Name: "TEST_PORT_8085_TCP_PROTO", Value: "tcp"}, {Name: "TEST_PORT_8085_TCP_PORT", Value: "8085"}, {Name: "TEST_PORT_8085_TCP_ADDR", Value: "1.2.3.5"}, {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.4"}, {Name: "KUBERNETES_SERVICE_PORT", Value: "8084"}, {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.4:8084"}, {Name: "KUBERNETES_PORT_8084_TCP", Value: "tcp://1.2.3.4:8084"}, {Name: "KUBERNETES_PORT_8084_TCP_PROTO", Value: "tcp"}, {Name: "KUBERNETES_PORT_8084_TCP_PORT", Value: "8084"}, {Name: "KUBERNETES_PORT_8084_TCP_ADDR", Value: "1.2.3.4"}, }, }, { name: "pod in master service ns", ns: "kubernetes", container: &api.Container{}, masterServiceNs: "kubernetes", nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ {Name: "NOT_SPECIAL_SERVICE_HOST", Value: "1.2.3.8"}, {Name: "NOT_SPECIAL_SERVICE_PORT", Value: "8088"}, {Name: "NOT_SPECIAL_PORT", Value: "tcp://1.2.3.8:8088"}, {Name: "NOT_SPECIAL_PORT_8088_TCP", Value: "tcp://1.2.3.8:8088"}, {Name: "NOT_SPECIAL_PORT_8088_TCP_PROTO", Value: "tcp"}, {Name: "NOT_SPECIAL_PORT_8088_TCP_PORT", Value: "8088"}, {Name: "NOT_SPECIAL_PORT_8088_TCP_ADDR", Value: "1.2.3.8"}, {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.6"}, {Name: "KUBERNETES_SERVICE_PORT", Value: "8086"}, {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.6:8086"}, {Name: "KUBERNETES_PORT_8086_TCP", Value: "tcp://1.2.3.6:8086"}, {Name: "KUBERNETES_PORT_8086_TCP_PROTO", Value: "tcp"}, {Name: "KUBERNETES_PORT_8086_TCP_PORT", Value: "8086"}, {Name: "KUBERNETES_PORT_8086_TCP_ADDR", Value: "1.2.3.6"}, }, }, { name: "downward api pod", ns: "downward-api", container: &api.Container{ Env: []api.EnvVar{ { Name: "POD_NAME", ValueFrom: &api.EnvVarSource{ FieldRef: &api.ObjectFieldSelector{ APIVersion: testapi.Version(), FieldPath: "metadata.name", }, }, }, { Name: "POD_NAMESPACE", ValueFrom: &api.EnvVarSource{ FieldRef: &api.ObjectFieldSelector{ APIVersion: testapi.Version(), FieldPath: "metadata.namespace", }, }, }, { Name: "POD_IP", ValueFrom: &api.EnvVarSource{ FieldRef: &api.ObjectFieldSelector{ APIVersion: testapi.Version(), FieldPath: "status.podIP", }, }, }, }, }, masterServiceNs: "nothing", nilLister: true, expectedEnvs: []kubecontainer.EnvVar{ {Name: "POD_NAME", Value: "dapi-test-pod-name"}, {Name: "POD_NAMESPACE", Value: "downward-api"}, {Name: "POD_IP", Value: "1.2.3.4"}, }, }, { name: "env expansion", ns: "test1", container: &api.Container{ Env: []api.EnvVar{ { Name: "TEST_LITERAL", Value: "test-test-test", }, { Name: "POD_NAME", ValueFrom: &api.EnvVarSource{ FieldRef: &api.ObjectFieldSelector{ APIVersion: testapi.Version(), FieldPath: "metadata.name", }, }, }, { Name: "OUT_OF_ORDER_TEST", Value: "$(OUT_OF_ORDER_TARGET)", }, { Name: "OUT_OF_ORDER_TARGET", Value: "FOO", }, { Name: "EMPTY_VAR", }, { Name: "EMPTY_TEST", Value: "foo-$(EMPTY_VAR)", }, { Name: "POD_NAME_TEST2", Value: "test2-$(POD_NAME)", }, { Name: "POD_NAME_TEST3", Value: "$(POD_NAME_TEST2)-3", }, { Name: "LITERAL_TEST", Value: "literal-$(TEST_LITERAL)", }, { Name: "SERVICE_VAR_TEST", Value: "$(TEST_SERVICE_HOST):$(TEST_SERVICE_PORT)", }, { Name: "TEST_UNDEFINED", Value: "$(UNDEFINED_VAR)", }, }, }, masterServiceNs: "nothing", nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ { Name: "TEST_LITERAL", Value: "test-test-test", }, { Name: "POD_NAME", Value: "dapi-test-pod-name", }, { Name: "POD_NAME_TEST2", Value: "test2-dapi-test-pod-name", }, { Name: "POD_NAME_TEST3", Value: "test2-dapi-test-pod-name-3", }, { Name: "LITERAL_TEST", Value: "literal-test-test-test", }, { Name: "TEST_SERVICE_HOST", Value: "1.2.3.3", }, { Name: "TEST_SERVICE_PORT", Value: "8083", }, { Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083", }, { Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083", }, { Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp", }, { Name: "TEST_PORT_8083_TCP_PORT", Value: "8083", }, { Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3", }, { Name: "SERVICE_VAR_TEST", Value: "1.2.3.3:8083", }, { Name: "OUT_OF_ORDER_TEST", Value: "$(OUT_OF_ORDER_TARGET)", }, { Name: "OUT_OF_ORDER_TARGET", Value: "FOO", }, { Name: "TEST_UNDEFINED", Value: "$(UNDEFINED_VAR)", }, { Name: "EMPTY_VAR", }, { Name: "EMPTY_TEST", Value: "foo-", }, }, }, } for i, tc := range testCases { testKubelet := newTestKubelet(t) kl := testKubelet.kubelet kl.masterServiceNamespace = tc.masterServiceNs if tc.nilLister { kl.serviceLister = nil } else { kl.serviceLister = testServiceLister{services} } testPod := &api.Pod{ ObjectMeta: api.ObjectMeta{ Namespace: tc.ns, Name: "dapi-test-pod-name", }, } testPod.Status.PodIP = "1.2.3.4" result, err := kl.makeEnvironmentVariables(testPod, tc.container) if err != nil { t.Errorf("[%v] Unexpected error: %v", tc.name, err) } sort.Sort(envs(result)) sort.Sort(envs(tc.expectedEnvs)) if !reflect.DeepEqual(result, tc.expectedEnvs) { t.Errorf("%d: [%v] Unexpected env entries; expected {%v}, got {%v}", i, tc.name, tc.expectedEnvs, result) } } } func runningState(cName string) api.ContainerStatus { return api.ContainerStatus{ Name: cName, State: api.ContainerState{ Running: &api.ContainerStateRunning{}, }, } } func stoppedState(cName string) api.ContainerStatus { return api.ContainerStatus{ Name: cName, State: api.ContainerState{ Terminated: &api.ContainerStateTerminated{}, }, } } func succeededState(cName string) api.ContainerStatus { return api.ContainerStatus{ Name: cName, State: api.ContainerState{ Terminated: &api.ContainerStateTerminated{ ExitCode: 0, }, }, } } func failedState(cName string) api.ContainerStatus { return api.ContainerStatus{ Name: cName, State: api.ContainerState{ Terminated: &api.ContainerStateTerminated{ ExitCode: -1, }, }, } } func TestPodPhaseWithRestartAlways(t *testing.T) { desiredState := api.PodSpec{ NodeName: "machine", Containers: []api.Container{ {Name: "containerA"}, {Name: "containerB"}, }, RestartPolicy: api.RestartPolicyAlways, } tests := []struct { pod *api.Pod status api.PodPhase test string }{ {&api.Pod{Spec: desiredState, Status: api.PodStatus{}}, api.PodPending, "waiting"}, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ runningState("containerA"), runningState("containerB"), }, }, }, api.PodRunning, "all running", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ stoppedState("containerA"), stoppedState("containerB"), }, }, }, api.PodRunning, "all stopped with restart always", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ runningState("containerA"), stoppedState("containerB"), }, }, }, api.PodRunning, "mixed state #1 with restart always", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ runningState("containerA"), }, }, }, api.PodPending, "mixed state #2 with restart always", }, } for _, test := range tests { if status := GetPhase(&test.pod.Spec, test.pod.Status.ContainerStatuses); status != test.status { t.Errorf("In test %s, expected %v, got %v", test.test, test.status, status) } } } func TestPodPhaseWithRestartNever(t *testing.T) { desiredState := api.PodSpec{ NodeName: "machine", Containers: []api.Container{ {Name: "containerA"}, {Name: "containerB"}, }, RestartPolicy: api.RestartPolicyNever, } tests := []struct { pod *api.Pod status api.PodPhase test string }{ {&api.Pod{Spec: desiredState, Status: api.PodStatus{}}, api.PodPending, "waiting"}, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ runningState("containerA"), runningState("containerB"), }, }, }, api.PodRunning, "all running with restart never", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ succeededState("containerA"), succeededState("containerB"), }, }, }, api.PodSucceeded, "all succeeded with restart never", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ failedState("containerA"), failedState("containerB"), }, }, }, api.PodFailed, "all failed with restart never", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ runningState("containerA"), succeededState("containerB"), }, }, }, api.PodRunning, "mixed state #1 with restart never", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ runningState("containerA"), }, }, }, api.PodPending, "mixed state #2 with restart never", }, } for _, test := range tests { if status := GetPhase(&test.pod.Spec, test.pod.Status.ContainerStatuses); status != test.status { t.Errorf("In test %s, expected %v, got %v", test.test, test.status, status) } } } func TestPodPhaseWithRestartOnFailure(t *testing.T) { desiredState := api.PodSpec{ NodeName: "machine", Containers: []api.Container{ {Name: "containerA"}, {Name: "containerB"}, }, RestartPolicy: api.RestartPolicyOnFailure, } tests := []struct { pod *api.Pod status api.PodPhase test string }{ {&api.Pod{Spec: desiredState, Status: api.PodStatus{}}, api.PodPending, "waiting"}, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ runningState("containerA"), runningState("containerB"), }, }, }, api.PodRunning, "all running with restart onfailure", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ succeededState("containerA"), succeededState("containerB"), }, }, }, api.PodSucceeded, "all succeeded with restart onfailure", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ failedState("containerA"), failedState("containerB"), }, }, }, api.PodRunning, "all failed with restart never", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ runningState("containerA"), succeededState("containerB"), }, }, }, api.PodRunning, "mixed state #1 with restart onfailure", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ ContainerStatuses: []api.ContainerStatus{ runningState("containerA"), }, }, }, api.PodPending, "mixed state #2 with restart onfailure", }, } for _, test := range tests { if status := GetPhase(&test.pod.Spec, test.pod.Status.ContainerStatuses); status != test.status { t.Errorf("In test %s, expected %v, got %v", test.test, test.status, status) } } } func getReadyStatus(cName string) api.ContainerStatus { return api.ContainerStatus{ Name: cName, Ready: true, } } func getNotReadyStatus(cName string) api.ContainerStatus { return api.ContainerStatus{ Name: cName, Ready: false, } } func TestGetPodReadyCondition(t *testing.T) { ready := []api.PodCondition{{ Type: api.PodReady, Status: api.ConditionTrue, }} unready := []api.PodCondition{{ Type: api.PodReady, Status: api.ConditionFalse, }} tests := []struct { spec *api.PodSpec info []api.ContainerStatus expected []api.PodCondition }{ { spec: nil, info: nil, expected: unready, }, { spec: &api.PodSpec{}, info: []api.ContainerStatus{}, expected: ready, }, { spec: &api.PodSpec{ Containers: []api.Container{ {Name: "1234"}, }, }, info: []api.ContainerStatus{}, expected: unready, }, { spec: &api.PodSpec{ Containers: []api.Container{ {Name: "1234"}, }, }, info: []api.ContainerStatus{ getReadyStatus("1234"), }, expected: ready, }, { spec: &api.PodSpec{ Containers: []api.Container{ {Name: "1234"}, {Name: "5678"}, }, }, info: []api.ContainerStatus{ getReadyStatus("1234"), getReadyStatus("5678"), }, expected: ready, }, { spec: &api.PodSpec{ Containers: []api.Container{ {Name: "1234"}, {Name: "5678"}, }, }, info: []api.ContainerStatus{ getReadyStatus("1234"), }, expected: unready, }, { spec: &api.PodSpec{ Containers: []api.Container{ {Name: "1234"}, {Name: "5678"}, }, }, info: []api.ContainerStatus{ getReadyStatus("1234"), getNotReadyStatus("5678"), }, expected: unready, }, } for i, test := range tests { condition := getPodReadyCondition(test.spec, test.info) if !reflect.DeepEqual(condition, test.expected) { t.Errorf("On test case %v, expected:\n%+v\ngot\n%+v\n", i, test.expected, condition) } } } func TestExecInContainerNoSuchPod(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime fakeCommandRunner := fakeContainerCommandRunner{} kubelet.runner = &fakeCommandRunner fakeRuntime.PodList = []*kubecontainer.Pod{} podName := "podFoo" podNamespace := "nsFoo" containerID := "containerFoo" err := kubelet.ExecInContainer( kubecontainer.GetPodFullName(&api.Pod{ObjectMeta: api.ObjectMeta{Name: podName, Namespace: podNamespace}}), "", containerID, []string{"ls"}, nil, nil, nil, false, ) if err == nil { t.Fatal("unexpected non-error") } if fakeCommandRunner.ID != "" { t.Fatal("unexpected invocation of runner.ExecInContainer") } } func TestExecInContainerNoSuchContainer(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime fakeCommandRunner := fakeContainerCommandRunner{} kubelet.runner = &fakeCommandRunner podName := "podFoo" podNamespace := "nsFoo" containerID := "containerFoo" fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "12345678", Name: podName, Namespace: podNamespace, Containers: []*kubecontainer.Container{ {Name: "bar", ID: "barID"}, }, }, } err := kubelet.ExecInContainer( kubecontainer.GetPodFullName(&api.Pod{ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: podName, Namespace: podNamespace, }}), "", containerID, []string{"ls"}, nil, nil, nil, false, ) if err == nil { t.Fatal("unexpected non-error") } if fakeCommandRunner.ID != "" { t.Fatal("unexpected invocation of runner.ExecInContainer") } } type fakeReadWriteCloser struct{} func (f *fakeReadWriteCloser) Write(data []byte) (int, error) { return 0, nil } func (f *fakeReadWriteCloser) Read(data []byte) (int, error) { return 0, nil } func (f *fakeReadWriteCloser) Close() error { return nil } func TestExecInContainer(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime fakeCommandRunner := fakeContainerCommandRunner{} kubelet.runner = &fakeCommandRunner podName := "podFoo" podNamespace := "nsFoo" containerID := "containerFoo" command := []string{"ls"} stdin := &bytes.Buffer{} stdout := &fakeReadWriteCloser{} stderr := &fakeReadWriteCloser{} tty := true fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "12345678", Name: podName, Namespace: podNamespace, Containers: []*kubecontainer.Container{ {Name: containerID, ID: types.UID(containerID), }, }, }, } err := kubelet.ExecInContainer( kubecontainer.GetPodFullName(&api.Pod{ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: podName, Namespace: podNamespace, }}), "", containerID, []string{"ls"}, stdin, stdout, stderr, tty, ) if err != nil { t.Fatalf("unexpected error: %s", err) } if e, a := containerID, fakeCommandRunner.ID; e != a { t.Fatalf("container name: expected %q, got %q", e, a) } if e, a := command, fakeCommandRunner.Cmd; !reflect.DeepEqual(e, a) { t.Fatalf("command: expected '%v', got '%v'", e, a) } if e, a := stdin, fakeCommandRunner.Stdin; e != a { t.Fatalf("stdin: expected %#v, got %#v", e, a) } if e, a := stdout, fakeCommandRunner.Stdout; e != a { t.Fatalf("stdout: expected %#v, got %#v", e, a) } if e, a := stderr, fakeCommandRunner.Stderr; e != a { t.Fatalf("stderr: expected %#v, got %#v", e, a) } if e, a := tty, fakeCommandRunner.TTY; e != a { t.Fatalf("tty: expected %t, got %t", e, a) } } func TestPortForwardNoSuchPod(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime fakeRuntime.PodList = []*kubecontainer.Pod{} fakeCommandRunner := fakeContainerCommandRunner{} kubelet.runner = &fakeCommandRunner podName := "podFoo" podNamespace := "nsFoo" var port uint16 = 5000 err := kubelet.PortForward( kubecontainer.GetPodFullName(&api.Pod{ObjectMeta: api.ObjectMeta{Name: podName, Namespace: podNamespace}}), "", port, nil, ) if err == nil { t.Fatal("unexpected non-error") } if fakeCommandRunner.ID != "" { t.Fatal("unexpected invocation of runner.PortForward") } } func TestPortForward(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime podName := "podFoo" podNamespace := "nsFoo" podID := types.UID("12345678") fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: podID, Name: podName, Namespace: podNamespace, Containers: []*kubecontainer.Container{ { Name: "foo", ID: "containerFoo", }, }, }, } fakeCommandRunner := fakeContainerCommandRunner{} kubelet.runner = &fakeCommandRunner var port uint16 = 5000 stream := &fakeReadWriteCloser{} err := kubelet.PortForward( kubecontainer.GetPodFullName(&api.Pod{ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: podName, Namespace: podNamespace, }}), "", port, stream, ) if err != nil { t.Fatalf("unexpected error: %s", err) } if e, a := podID, fakeCommandRunner.PodID; e != a { t.Fatalf("container id: expected %q, got %q", e, a) } if e, a := port, fakeCommandRunner.Port; e != a { t.Fatalf("port: expected %v, got %v", e, a) } if e, a := stream, fakeCommandRunner.Stream; e != a { t.Fatalf("stream: expected %v, got %v", e, a) } } // Tests that identify the host port conflicts are detected correctly. func TestGetHostPortConflicts(t *testing.T) { pods := []*api.Pod{ {Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 80}}}}}}, {Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 81}}}}}}, {Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 82}}}}}}, {Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 83}}}}}}, } // Pods should not cause any conflict. if hasHostPortConflicts(pods) { t.Errorf("expected no conflicts, Got conflicts") } expected := &api.Pod{ Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 81}}}}}, } // The new pod should cause conflict and be reported. pods = append(pods, expected) if !hasHostPortConflicts(pods) { t.Errorf("expected no conflict, Got no conflicts") } } // Tests that we handle port conflicts correctly by setting the failed status in status map. func TestHandlePortConflicts(t *testing.T) { testKubelet := newTestKubelet(t) kl := testKubelet.kubelet testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) spec := api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 80}}}}} pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "123456789", Name: "newpod", Namespace: "foo", }, Spec: spec, }, { ObjectMeta: api.ObjectMeta{ UID: "987654321", Name: "oldpod", Namespace: "foo", }, Spec: spec, }, } // Make sure the Pods are in the reverse order of creation time. pods[1].CreationTimestamp = util.NewTime(time.Now()) pods[0].CreationTimestamp = util.NewTime(time.Now().Add(1 * time.Second)) // The newer pod should be rejected. conflictedPod := pods[0] kl.HandlePodAdditions(pods) // Check pod status stored in the status map. status, found := kl.statusManager.GetPodStatus(conflictedPod.UID) if !found { t.Fatalf("status of pod %q is not found in the status map", conflictedPod.UID) } if status.Phase != api.PodFailed { t.Fatalf("expected pod status %q. Got %q.", api.PodFailed, status.Phase) } } // Tests that we handle not matching labels selector correctly by setting the failed status in status map. func TestHandleNodeSelector(t *testing.T) { testKubelet := newTestKubelet(t) kl := testKubelet.kubelet kl.nodeLister = testNodeLister{nodes: []api.Node{ {ObjectMeta: api.ObjectMeta{Name: testKubeletHostname, Labels: map[string]string{"key": "B"}}}, }} testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "123456789", Name: "podA", Namespace: "foo", }, Spec: api.PodSpec{NodeSelector: map[string]string{"key": "A"}}, }, { ObjectMeta: api.ObjectMeta{ UID: "987654321", Name: "podB", Namespace: "foo", }, Spec: api.PodSpec{NodeSelector: map[string]string{"key": "B"}}, }, } // The first pod should be rejected. notfittingPod := pods[0] kl.HandlePodAdditions(pods) // Check pod status stored in the status map. status, found := kl.statusManager.GetPodStatus(notfittingPod.UID) if !found { t.Fatalf("status of pod %q is not found in the status map", notfittingPod.UID) } if status.Phase != api.PodFailed { t.Fatalf("expected pod status %q. Got %q.", api.PodFailed, status.Phase) } } // Tests that we handle exceeded resources correctly by setting the failed status in status map. func TestHandleMemExceeded(t *testing.T) { testKubelet := newTestKubelet(t) kl := testKubelet.kubelet testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{MemoryCapacity: 100}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) spec := api.PodSpec{Containers: []api.Container{{Resources: api.ResourceRequirements{ Requests: api.ResourceList{ "memory": resource.MustParse("90"), }, }}}} pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "123456789", Name: "newpod", Namespace: "foo", }, Spec: spec, }, { ObjectMeta: api.ObjectMeta{ UID: "987654321", Name: "oldpod", Namespace: "foo", }, Spec: spec, }, } // Make sure the Pods are in the reverse order of creation time. pods[1].CreationTimestamp = util.NewTime(time.Now()) pods[0].CreationTimestamp = util.NewTime(time.Now().Add(1 * time.Second)) // The newer pod should be rejected. notfittingPod := pods[0] kl.HandlePodAdditions(pods) // Check pod status stored in the status map. status, found := kl.statusManager.GetPodStatus(notfittingPod.UID) if !found { t.Fatalf("status of pod %q is not found in the status map", notfittingPod.UID) } if status.Phase != api.PodFailed { t.Fatalf("expected pod status %q. Got %q.", api.PodFailed, status.Phase) } } // TODO(filipg): This test should be removed once StatusSyncer can do garbage collection without external signal. func TestPurgingObsoleteStatusMapEntries(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) kl := testKubelet.kubelet pods := []*api.Pod{ {ObjectMeta: api.ObjectMeta{Name: "pod1", UID: "1234"}, Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 80}}}}}}, {ObjectMeta: api.ObjectMeta{Name: "pod2", UID: "4567"}, Spec: api.PodSpec{Containers: []api.Container{{Ports: []api.ContainerPort{{HostPort: 80}}}}}}, } podToTest := pods[1] // Run once to populate the status map. kl.HandlePodAdditions(pods) if _, found := kl.statusManager.GetPodStatus(podToTest.UID); !found { t.Fatalf("expected to have status cached for pod2") } // Sync with empty pods so that the entry in status map will be removed. kl.podManager.SetPods([]*api.Pod{}) kl.HandlePodCleanups() if _, found := kl.statusManager.GetPodStatus(podToTest.UID); found { t.Fatalf("expected to not have status cached for pod2") } } func TestValidatePodStatus(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet testCases := []struct { podPhase api.PodPhase success bool }{ {api.PodRunning, true}, {api.PodSucceeded, true}, {api.PodFailed, true}, {api.PodPending, false}, {api.PodUnknown, false}, } for i, tc := range testCases { err := kubelet.validatePodPhase(&api.PodStatus{Phase: tc.podPhase}) if tc.success { if err != nil { t.Errorf("[case %d]: unexpected failure - %v", i, err) } } else if err == nil { t.Errorf("[case %d]: unexpected success", i) } } } func TestValidateContainerStatus(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet containerName := "x" testCases := []struct { statuses []api.ContainerStatus success bool }{ { statuses: []api.ContainerStatus{ { Name: containerName, State: api.ContainerState{ Running: &api.ContainerStateRunning{}, }, LastTerminationState: api.ContainerState{ Terminated: &api.ContainerStateTerminated{}, }, }, }, success: true, }, { statuses: []api.ContainerStatus{ { Name: containerName, State: api.ContainerState{ Terminated: &api.ContainerStateTerminated{}, }, }, }, success: true, }, { statuses: []api.ContainerStatus{ { Name: containerName, State: api.ContainerState{ Waiting: &api.ContainerStateWaiting{}, }, }, }, success: false, }, } for i, tc := range testCases { _, err := kubelet.validateContainerStatus(&api.PodStatus{ ContainerStatuses: tc.statuses, }, containerName, false) if tc.success { if err != nil { t.Errorf("[case %d]: unexpected failure - %v", i, err) } } else if err == nil { t.Errorf("[case %d]: unexpected success", i) } } if _, err := kubelet.validateContainerStatus(&api.PodStatus{ ContainerStatuses: testCases[0].statuses, }, "blah", false); err == nil { t.Errorf("expected error with invalid container name") } if _, err := kubelet.validateContainerStatus(&api.PodStatus{ ContainerStatuses: testCases[0].statuses, }, containerName, true); err != nil { t.Errorf("unexpected error with for previous terminated container - %v", err) } if _, err := kubelet.validateContainerStatus(&api.PodStatus{ ContainerStatuses: testCases[1].statuses, }, containerName, true); err == nil { t.Errorf("expected error with for previous terminated container") } } func TestUpdateNewNodeStatus(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet kubeClient := testKubelet.fakeKubeClient kubeClient.ReactionChain = testclient.NewSimpleFake(&api.NodeList{Items: []api.Node{ {ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}}, }}).ReactionChain machineInfo := &cadvisorApi.MachineInfo{ MachineID: "123", SystemUUID: "abc", BootID: "1b3", NumCores: 2, MemoryCapacity: 1024, } mockCadvisor := testKubelet.fakeCadvisor mockCadvisor.On("MachineInfo").Return(machineInfo, nil) versionInfo := &cadvisorApi.VersionInfo{ KernelVersion: "3.16.0-0.bpo.4-amd64", ContainerOsVersion: "Debian GNU/Linux 7 (wheezy)", DockerVersion: "1.5.0", } mockCadvisor.On("VersionInfo").Return(versionInfo, nil) expectedNode := &api.Node{ ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, Spec: api.NodeSpec{}, Status: api.NodeStatus{ Conditions: []api.NodeCondition{ { Type: api.NodeReady, Status: api.ConditionTrue, Reason: fmt.Sprintf("kubelet is posting ready status"), LastHeartbeatTime: util.Time{}, LastTransitionTime: util.Time{}, }, }, NodeInfo: api.NodeSystemInfo{ MachineID: "123", SystemUUID: "abc", BootID: "1b3", KernelVersion: "3.16.0-0.bpo.4-amd64", OsImage: "Debian GNU/Linux 7 (wheezy)", ContainerRuntimeVersion: "docker://1.5.0", KubeletVersion: version.Get().String(), KubeProxyVersion: version.Get().String(), }, Capacity: api.ResourceList{ api.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), api.ResourceMemory: *resource.NewQuantity(1024, resource.BinarySI), api.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), }, Addresses: []api.NodeAddress{ {Type: api.NodeLegacyHostIP, Address: "127.0.0.1"}, {Type: api.NodeInternalIP, Address: "127.0.0.1"}, }, }, } kubelet.updateRuntimeUp() if err := kubelet.updateNodeStatus(); err != nil { t.Errorf("unexpected error: %v", err) } actions := kubeClient.Actions() if len(actions) != 2 { t.Fatalf("unexpected actions: %v", actions) } if !actions[1].Matches("update", "nodes") || actions[1].GetSubresource() != "status" { t.Fatalf("unexpected actions: %v", actions) } updatedNode, ok := actions[1].(testclient.UpdateAction).GetObject().(*api.Node) if !ok { t.Errorf("unexpected object type") } if updatedNode.Status.Conditions[0].LastHeartbeatTime.IsZero() { t.Errorf("unexpected zero last probe timestamp") } if updatedNode.Status.Conditions[0].LastTransitionTime.IsZero() { t.Errorf("unexpected zero last transition timestamp") } updatedNode.Status.Conditions[0].LastHeartbeatTime = util.Time{} updatedNode.Status.Conditions[0].LastTransitionTime = util.Time{} if !reflect.DeepEqual(expectedNode, updatedNode) { t.Errorf("unexpected objects: %s", util.ObjectDiff(expectedNode, updatedNode)) } } func TestUpdateExistingNodeStatus(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet kubeClient := testKubelet.fakeKubeClient kubeClient.ReactionChain = testclient.NewSimpleFake(&api.NodeList{Items: []api.Node{ { ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, Spec: api.NodeSpec{}, Status: api.NodeStatus{ Conditions: []api.NodeCondition{ { Type: api.NodeReady, Status: api.ConditionTrue, Reason: fmt.Sprintf("kubelet is posting ready status"), LastHeartbeatTime: util.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), LastTransitionTime: util.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), }, }, Capacity: api.ResourceList{ api.ResourceCPU: *resource.NewMilliQuantity(3000, resource.DecimalSI), api.ResourceMemory: *resource.NewQuantity(2048, resource.BinarySI), api.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), }, }, }, }}).ReactionChain mockCadvisor := testKubelet.fakeCadvisor machineInfo := &cadvisorApi.MachineInfo{ MachineID: "123", SystemUUID: "abc", BootID: "1b3", NumCores: 2, MemoryCapacity: 1024, } mockCadvisor.On("MachineInfo").Return(machineInfo, nil) versionInfo := &cadvisorApi.VersionInfo{ KernelVersion: "3.16.0-0.bpo.4-amd64", ContainerOsVersion: "Debian GNU/Linux 7 (wheezy)", DockerVersion: "1.5.0", } mockCadvisor.On("VersionInfo").Return(versionInfo, nil) expectedNode := &api.Node{ ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, Spec: api.NodeSpec{}, Status: api.NodeStatus{ Conditions: []api.NodeCondition{ { Type: api.NodeReady, Status: api.ConditionTrue, Reason: fmt.Sprintf("kubelet is posting ready status"), LastHeartbeatTime: util.Time{}, // placeholder LastTransitionTime: util.Time{}, // placeholder }, }, NodeInfo: api.NodeSystemInfo{ MachineID: "123", SystemUUID: "abc", BootID: "1b3", KernelVersion: "3.16.0-0.bpo.4-amd64", OsImage: "Debian GNU/Linux 7 (wheezy)", ContainerRuntimeVersion: "docker://1.5.0", KubeletVersion: version.Get().String(), KubeProxyVersion: version.Get().String(), }, Capacity: api.ResourceList{ api.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), api.ResourceMemory: *resource.NewQuantity(1024, resource.BinarySI), api.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), }, Addresses: []api.NodeAddress{ {Type: api.NodeLegacyHostIP, Address: "127.0.0.1"}, {Type: api.NodeInternalIP, Address: "127.0.0.1"}, }, }, } kubelet.updateRuntimeUp() if err := kubelet.updateNodeStatus(); err != nil { t.Errorf("unexpected error: %v", err) } actions := kubeClient.Actions() if len(actions) != 2 { t.Errorf("unexpected actions: %v", actions) } updateAction, ok := actions[1].(testclient.UpdateAction) if !ok { t.Errorf("unexpected action type. expected UpdateAction, got %#v", actions[1]) } updatedNode, ok := updateAction.GetObject().(*api.Node) if !ok { t.Errorf("unexpected object type") } // Expect LastProbeTime to be updated to Now, while LastTransitionTime to be the same. if reflect.DeepEqual(updatedNode.Status.Conditions[0].LastHeartbeatTime.Rfc3339Copy().UTC(), util.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC).Time) { t.Errorf("expected \n%v\n, got \n%v", util.Now(), util.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC)) } if !reflect.DeepEqual(updatedNode.Status.Conditions[0].LastTransitionTime.Rfc3339Copy().UTC(), util.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC).Time) { t.Errorf("expected \n%#v\n, got \n%#v", updatedNode.Status.Conditions[0].LastTransitionTime.Rfc3339Copy(), util.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC)) } updatedNode.Status.Conditions[0].LastHeartbeatTime = util.Time{} updatedNode.Status.Conditions[0].LastTransitionTime = util.Time{} if !reflect.DeepEqual(expectedNode, updatedNode) { t.Errorf("expected \n%v\n, got \n%v", expectedNode, updatedNode) } } func TestUpdateNodeStatusWithoutContainerRuntime(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet kubeClient := testKubelet.fakeKubeClient fakeRuntime := testKubelet.fakeRuntime // This causes returning an error from GetContainerRuntimeVersion() which // simulates that container runtime is down. fakeRuntime.VersionInfo = "" kubeClient.ReactionChain = testclient.NewSimpleFake(&api.NodeList{Items: []api.Node{ {ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}}, }}).ReactionChain mockCadvisor := testKubelet.fakeCadvisor machineInfo := &cadvisorApi.MachineInfo{ MachineID: "123", SystemUUID: "abc", BootID: "1b3", NumCores: 2, MemoryCapacity: 1024, } mockCadvisor.On("MachineInfo").Return(machineInfo, nil) versionInfo := &cadvisorApi.VersionInfo{ KernelVersion: "3.16.0-0.bpo.4-amd64", ContainerOsVersion: "Debian GNU/Linux 7 (wheezy)", DockerVersion: "1.5.0", } mockCadvisor.On("VersionInfo").Return(versionInfo, nil) expectedNode := &api.Node{ ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, Spec: api.NodeSpec{}, Status: api.NodeStatus{ Conditions: []api.NodeCondition{ { Type: api.NodeReady, Status: api.ConditionFalse, Reason: fmt.Sprintf("container runtime is down"), LastHeartbeatTime: util.Time{}, LastTransitionTime: util.Time{}, }, }, NodeInfo: api.NodeSystemInfo{ MachineID: "123", SystemUUID: "abc", BootID: "1b3", KernelVersion: "3.16.0-0.bpo.4-amd64", OsImage: "Debian GNU/Linux 7 (wheezy)", ContainerRuntimeVersion: "docker://1.5.0", KubeletVersion: version.Get().String(), KubeProxyVersion: version.Get().String(), }, Capacity: api.ResourceList{ api.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), api.ResourceMemory: *resource.NewQuantity(1024, resource.BinarySI), api.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), }, Addresses: []api.NodeAddress{ {Type: api.NodeLegacyHostIP, Address: "127.0.0.1"}, {Type: api.NodeInternalIP, Address: "127.0.0.1"}, }, }, } kubelet.runtimeUpThreshold = time.Duration(0) kubelet.updateRuntimeUp() if err := kubelet.updateNodeStatus(); err != nil { t.Errorf("unexpected error: %v", err) } actions := kubeClient.Actions() if len(actions) != 2 { t.Fatalf("unexpected actions: %v", actions) } if !actions[1].Matches("update", "nodes") || actions[1].GetSubresource() != "status" { t.Fatalf("unexpected actions: %v", actions) } updatedNode, ok := actions[1].(testclient.UpdateAction).GetObject().(*api.Node) if !ok { t.Errorf("unexpected action type. expected UpdateAction, got %#v", actions[1]) } if updatedNode.Status.Conditions[0].LastHeartbeatTime.IsZero() { t.Errorf("unexpected zero last probe timestamp") } if updatedNode.Status.Conditions[0].LastTransitionTime.IsZero() { t.Errorf("unexpected zero last transition timestamp") } updatedNode.Status.Conditions[0].LastHeartbeatTime = util.Time{} updatedNode.Status.Conditions[0].LastTransitionTime = util.Time{} if !reflect.DeepEqual(expectedNode, updatedNode) { t.Errorf("unexpected objects: %s", util.ObjectDiff(expectedNode, updatedNode)) } } func TestUpdateNodeStatusError(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet // No matching node for the kubelet testKubelet.fakeKubeClient.ReactionChain = testclient.NewSimpleFake(&api.NodeList{Items: []api.Node{}}).ReactionChain if err := kubelet.updateNodeStatus(); err == nil { t.Errorf("unexpected non error: %v", err) } if len(testKubelet.fakeKubeClient.Actions()) != nodeStatusUpdateRetry { t.Errorf("unexpected actions: %v", testKubelet.fakeKubeClient.Actions()) } } func TestCreateMirrorPod(t *testing.T) { for _, updateType := range []SyncPodType{SyncPodCreate, SyncPodUpdate} { testKubelet := newTestKubelet(t) kl := testKubelet.kubelet manager := testKubelet.fakeMirrorClient pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "bar", Namespace: "foo", Annotations: map[string]string{ ConfigSourceAnnotationKey: "file", }, }, } pods := []*api.Pod{pod} kl.podManager.SetPods(pods) err := kl.syncPod(pod, nil, container.Pod{}, updateType) if err != nil { t.Errorf("unexpected error: %v", err) } podFullName := kubecontainer.GetPodFullName(pod) if !manager.HasPod(podFullName) { t.Errorf("expected mirror pod %q to be created", podFullName) } if manager.NumOfPods() != 1 || !manager.HasPod(podFullName) { t.Errorf("expected one mirror pod %q, got %v", podFullName, manager.GetPods()) } } } func TestDeleteOutdatedMirrorPod(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) kl := testKubelet.kubelet manager := testKubelet.fakeMirrorClient pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "ns", Annotations: map[string]string{ ConfigSourceAnnotationKey: "file", }, }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "1234", Image: "foo"}, }, }, } // Mirror pod has an outdated spec. mirrorPod := &api.Pod{ ObjectMeta: api.ObjectMeta{ UID: "11111111", Name: "foo", Namespace: "ns", Annotations: map[string]string{ ConfigSourceAnnotationKey: "api", ConfigMirrorAnnotationKey: "mirror", }, }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "1234", Image: "bar"}, }, }, } pods := []*api.Pod{pod, mirrorPod} kl.podManager.SetPods(pods) err := kl.syncPod(pod, mirrorPod, container.Pod{}, SyncPodUpdate) if err != nil { t.Errorf("unexpected error: %v", err) } name := kubecontainer.GetPodFullName(pod) creates, deletes := manager.GetCounts(name) if creates != 0 || deletes != 1 { t.Errorf("expected 0 creation and 1 deletion of %q, got %d, %d", name, creates, deletes) } } func TestDeleteOrphanedMirrorPods(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) kl := testKubelet.kubelet manager := testKubelet.fakeMirrorClient orphanPods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "pod1", Namespace: "ns", Annotations: map[string]string{ ConfigSourceAnnotationKey: "api", ConfigMirrorAnnotationKey: "mirror", }, }, }, { ObjectMeta: api.ObjectMeta{ UID: "12345679", Name: "pod2", Namespace: "ns", Annotations: map[string]string{ ConfigSourceAnnotationKey: "api", ConfigMirrorAnnotationKey: "mirror", }, }, }, } kl.podManager.SetPods(orphanPods) // Sync with an empty pod list to delete all mirror pods. kl.HandlePodCleanups() if manager.NumOfPods() != 0 { t.Errorf("expected zero mirror pods, got %v", manager.GetPods()) } for _, pod := range orphanPods { name := kubecontainer.GetPodFullName(pod) creates, deletes := manager.GetCounts(name) if creates != 0 || deletes != 1 { t.Errorf("expected 0 creation and one deletion of %q, got %d, %d", name, creates, deletes) } } } func TestGetContainerInfoForMirrorPods(t *testing.T) { // pods contain one static and one mirror pod with the same name but // different UIDs. pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "1234", Name: "qux", Namespace: "ns", Annotations: map[string]string{ ConfigSourceAnnotationKey: "file", }, }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "foo"}, }, }, }, { ObjectMeta: api.ObjectMeta{ UID: "5678", Name: "qux", Namespace: "ns", Annotations: map[string]string{ ConfigSourceAnnotationKey: "api", ConfigMirrorAnnotationKey: "mirror", }, }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "foo"}, }, }, }, } containerID := "ab2cdf" containerPath := fmt.Sprintf("/docker/%v", containerID) containerInfo := cadvisorApi.ContainerInfo{ ContainerReference: cadvisorApi.ContainerReference{ Name: containerPath, }, } testKubelet := newTestKubelet(t) fakeRuntime := testKubelet.fakeRuntime mockCadvisor := testKubelet.fakeCadvisor cadvisorReq := &cadvisorApi.ContainerInfoRequest{} mockCadvisor.On("DockerContainer", containerID, cadvisorReq).Return(containerInfo, nil) kubelet := testKubelet.kubelet fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "1234", Name: "qux", Namespace: "ns", Containers: []*kubecontainer.Container{ { Name: "foo", ID: types.UID(containerID), }, }, }, } kubelet.podManager.SetPods(pods) // Use the mirror pod UID to retrieve the stats. stats, err := kubelet.GetContainerInfo("qux_ns", "5678", "foo", cadvisorReq) if err != nil { t.Errorf("unexpected error: %v", err) } if stats == nil { t.Fatalf("stats should not be nil") } mockCadvisor.AssertExpectations(t) } func TestDoNotCacheStatusForStaticPods(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) kubelet := testKubelet.kubelet pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "staticFoo", Namespace: "new", Annotations: map[string]string{ ConfigSourceAnnotationKey: "file", }, }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "bar"}, }, }, }, } kubelet.podManager.SetPods(pods) kubelet.HandlePodSyncs(kubelet.podManager.GetPods()) status, ok := kubelet.statusManager.GetPodStatus(pods[0].UID) if ok { t.Errorf("unexpected status %#v found for static pod %q", status, pods[0].UID) } } func TestHostNetworkAllowed(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet capabilities.SetForTests(capabilities.Capabilities{ PrivilegedSources: capabilities.PrivilegedSources{ HostNetworkSources: []string{ApiserverSource, FileSource}, }, }) pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", Annotations: map[string]string{ ConfigSourceAnnotationKey: FileSource, }, }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "foo"}, }, HostNetwork: true, }, } kubelet.podManager.SetPods([]*api.Pod{pod}) err := kubelet.syncPod(pod, nil, container.Pod{}, SyncPodUpdate) if err != nil { t.Errorf("expected pod infra creation to succeed: %v", err) } } func TestHostNetworkDisallowed(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet capabilities.SetForTests(capabilities.Capabilities{ PrivilegedSources: capabilities.PrivilegedSources{ HostNetworkSources: []string{}, }, }) pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", Annotations: map[string]string{ ConfigSourceAnnotationKey: FileSource, }, }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "foo"}, }, HostNetwork: true, }, } err := kubelet.syncPod(pod, nil, container.Pod{}, SyncPodUpdate) if err == nil { t.Errorf("expected pod infra creation to fail") } } func TestPrivilegeContainerAllowed(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet capabilities.SetForTests(capabilities.Capabilities{ AllowPrivileged: true, }) privileged := true pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "foo", SecurityContext: &api.SecurityContext{Privileged: &privileged}}, }, }, } kubelet.podManager.SetPods([]*api.Pod{pod}) err := kubelet.syncPod(pod, nil, container.Pod{}, SyncPodUpdate) if err != nil { t.Errorf("expected pod infra creation to succeed: %v", err) } } func TestPrivilegeContainerDisallowed(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet capabilities.SetForTests(capabilities.Capabilities{ AllowPrivileged: false, }) privileged := true pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "foo", Namespace: "new", }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "foo", SecurityContext: &api.SecurityContext{Privileged: &privileged}}, }, }, } err := kubelet.syncPod(pod, nil, container.Pod{}, SyncPodUpdate) if err == nil { t.Errorf("expected pod infra creation to fail") } } func TestFilterOutTerminatedPods(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet pods := newTestPods(5) pods[0].Status.Phase = api.PodFailed pods[1].Status.Phase = api.PodSucceeded pods[2].Status.Phase = api.PodRunning pods[3].Status.Phase = api.PodPending expected := []*api.Pod{pods[2], pods[3], pods[4]} kubelet.podManager.SetPods(pods) actual := kubelet.filterOutTerminatedPods(pods) if !reflect.DeepEqual(expected, actual) { t.Errorf("expected %#v, got %#v", expected, actual) } } func TestRegisterExistingNodeWithApiserver(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet kubeClient := testKubelet.fakeKubeClient kubeClient.AddReactor("create", "nodes", func(action testclient.Action) (bool, runtime.Object, error) { // Return an error on create. return true, &api.Node{}, &apierrors.StatusError{ ErrStatus: api.Status{Reason: api.StatusReasonAlreadyExists}, } }) kubeClient.AddReactor("get", "nodes", func(action testclient.Action) (bool, runtime.Object, error) { // Return an existing (matching) node on get. return true, &api.Node{ ObjectMeta: api.ObjectMeta{Name: testKubeletHostname}, Spec: api.NodeSpec{ExternalID: testKubeletHostname}, }, nil }) kubeClient.AddReactor("*", "*", func(action testclient.Action) (bool, runtime.Object, error) { return true, nil, fmt.Errorf("no reaction implemented for %s", action) }) machineInfo := &cadvisorApi.MachineInfo{ MachineID: "123", SystemUUID: "abc", BootID: "1b3", NumCores: 2, MemoryCapacity: 1024, } mockCadvisor := testKubelet.fakeCadvisor mockCadvisor.On("MachineInfo").Return(machineInfo, nil) versionInfo := &cadvisorApi.VersionInfo{ KernelVersion: "3.16.0-0.bpo.4-amd64", ContainerOsVersion: "Debian GNU/Linux 7 (wheezy)", DockerVersion: "1.5.0", } mockCadvisor.On("VersionInfo").Return(versionInfo, nil) done := make(chan struct{}) go func() { kubelet.registerWithApiserver() done <- struct{}{} }() select { case <-time.After(5 * time.Second): t.Errorf("timed out waiting for registration") case <-done: return } } func TestMakePortMappings(t *testing.T) { tests := []struct { container *api.Container expectedPortMappings []kubecontainer.PortMapping }{ { &api.Container{ Name: "fooContainer", Ports: []api.ContainerPort{ { Protocol: api.ProtocolTCP, ContainerPort: 80, HostPort: 8080, HostIP: "127.0.0.1", }, { Protocol: api.ProtocolTCP, ContainerPort: 443, HostPort: 4343, HostIP: "192.168.0.1", }, { Name: "foo", Protocol: api.ProtocolUDP, ContainerPort: 555, HostPort: 5555, }, { Name: "foo", // Duplicated, should be ignored. Protocol: api.ProtocolUDP, ContainerPort: 888, HostPort: 8888, }, { Protocol: api.ProtocolTCP, // Duplicated, should be ignored. ContainerPort: 80, HostPort: 8888, }, }, }, []kubecontainer.PortMapping{ { Name: "fooContainer-TCP:80", Protocol: api.ProtocolTCP, ContainerPort: 80, HostPort: 8080, HostIP: "127.0.0.1", }, { Name: "fooContainer-TCP:443", Protocol: api.ProtocolTCP, ContainerPort: 443, HostPort: 4343, HostIP: "192.168.0.1", }, { Name: "fooContainer-foo", Protocol: api.ProtocolUDP, ContainerPort: 555, HostPort: 5555, HostIP: "", }, }, }, } for i, tt := range tests { actual := makePortMappings(tt.container) if !reflect.DeepEqual(tt.expectedPortMappings, actual) { t.Errorf("%d: Expected: %#v, saw: %#v", i, tt.expectedPortMappings, actual) } } } func TestIsPodPastActiveDeadline(t *testing.T) { testKubelet := newTestKubelet(t) kubelet := testKubelet.kubelet pods := newTestPods(5) exceededActiveDeadlineSeconds := int64(30) notYetActiveDeadlineSeconds := int64(120) now := util.Now() startTime := util.NewTime(now.Time.Add(-1 * time.Minute)) pods[0].Status.StartTime = &startTime pods[0].Spec.ActiveDeadlineSeconds = &exceededActiveDeadlineSeconds pods[1].Status.StartTime = &startTime pods[1].Spec.ActiveDeadlineSeconds = &notYetActiveDeadlineSeconds tests := []struct { pod *api.Pod expected bool }{{pods[0], true}, {pods[1], false}, {pods[2], false}, {pods[3], false}, {pods[4], false}} kubelet.podManager.SetPods(pods) for i, tt := range tests { actual := kubelet.pastActiveDeadline(tt.pod) if actual != tt.expected { t.Errorf("[%d] expected %#v, got %#v", i, tt.expected, actual) } } } func TestSyncPodsSetStatusToFailedForPodsThatRunTooLong(t *testing.T) { testKubelet := newTestKubelet(t) fakeRuntime := testKubelet.fakeRuntime testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) kubelet := testKubelet.kubelet now := util.Now() startTime := util.NewTime(now.Time.Add(-1 * time.Minute)) exceededActiveDeadlineSeconds := int64(30) pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "bar", Namespace: "new", }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "foo"}, }, ActiveDeadlineSeconds: &exceededActiveDeadlineSeconds, }, Status: api.PodStatus{ StartTime: &startTime, }, }, } fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "12345678", Name: "bar", Namespace: "new", Containers: []*kubecontainer.Container{ {Name: "foo"}, }, }, } // Let the pod worker sets the status to fail after this sync. kubelet.HandlePodUpdates(pods) status, found := kubelet.statusManager.GetPodStatus(pods[0].UID) if !found { t.Errorf("expected to found status for pod %q", pods[0].UID) } if status.Phase != api.PodFailed { t.Fatalf("expected pod status %q, ot %q.", api.PodFailed, status.Phase) } } func TestSyncPodsDoesNotSetPodsThatDidNotRunTooLongToFailed(t *testing.T) { testKubelet := newTestKubelet(t) fakeRuntime := testKubelet.fakeRuntime testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) kubelet := testKubelet.kubelet now := util.Now() startTime := util.NewTime(now.Time.Add(-1 * time.Minute)) exceededActiveDeadlineSeconds := int64(300) pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "bar", Namespace: "new", }, Spec: api.PodSpec{ Containers: []api.Container{ {Name: "foo"}, }, ActiveDeadlineSeconds: &exceededActiveDeadlineSeconds, }, Status: api.PodStatus{ StartTime: &startTime, }, }, } fakeRuntime.PodList = []*kubecontainer.Pod{ { ID: "12345678", Name: "bar", Namespace: "new", Containers: []*kubecontainer.Container{ {Name: "foo"}, }, }, } kubelet.podManager.SetPods(pods) kubelet.HandlePodUpdates(pods) status, found := kubelet.statusManager.GetPodStatus(pods[0].UID) if !found { t.Errorf("expected to found status for pod %q", pods[0].UID) } if status.Phase == api.PodFailed { t.Fatalf("expected pod status to not be %q", status.Phase) } } func TestDeletePodDirsForDeletedPods(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) kl := testKubelet.kubelet pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "pod1", Namespace: "ns", }, }, { ObjectMeta: api.ObjectMeta{ UID: "12345679", Name: "pod2", Namespace: "ns", }, }, } kl.podManager.SetPods(pods) // Sync to create pod directories. kl.HandlePodSyncs(kl.podManager.GetPods()) for i := range pods { if !dirExists(kl.getPodDir(pods[i].UID)) { t.Errorf("expected directory to exist for pod %d", i) } } // Pod 1 has been deleted and no longer exists. kl.podManager.SetPods([]*api.Pod{pods[0]}) kl.HandlePodCleanups() if !dirExists(kl.getPodDir(pods[0].UID)) { t.Errorf("expected directory to exist for pod 0") } if dirExists(kl.getPodDir(pods[1].UID)) { t.Errorf("expected directory to be deleted for pod 1") } } func syncAndVerifyPodDir(t *testing.T, testKubelet *TestKubelet, pods []*api.Pod, podsToCheck []*api.Pod, shouldExist bool) { kl := testKubelet.kubelet kl.podManager.SetPods(pods) kl.HandlePodSyncs(pods) kl.HandlePodCleanups() for i, pod := range podsToCheck { exist := dirExists(kl.getPodDir(pod.UID)) if shouldExist && !exist { t.Errorf("expected directory to exist for pod %d", i) } else if !shouldExist && exist { t.Errorf("expected directory to be removed for pod %d", i) } } } func TestDoesNotDeletePodDirsForTerminatedPods(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) kl := testKubelet.kubelet pods := []*api.Pod{ { ObjectMeta: api.ObjectMeta{ UID: "12345678", Name: "pod1", Namespace: "ns", }, }, { ObjectMeta: api.ObjectMeta{ UID: "12345679", Name: "pod2", Namespace: "ns", }, }, { ObjectMeta: api.ObjectMeta{ UID: "12345680", Name: "pod3", Namespace: "ns", }, }, } syncAndVerifyPodDir(t, testKubelet, pods, pods, true) // Pod 1 failed, and pod 2 succeeded. None of the pod directories should be // deleted. kl.statusManager.SetPodStatus(pods[1], api.PodStatus{Phase: api.PodFailed}) kl.statusManager.SetPodStatus(pods[2], api.PodStatus{Phase: api.PodSucceeded}) syncAndVerifyPodDir(t, testKubelet, pods, pods, true) } func TestDoesNotDeletePodDirsIfContainerIsRunning(t *testing.T) { testKubelet := newTestKubelet(t) testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorApi.MachineInfo{}, nil) testKubelet.fakeCadvisor.On("DockerImagesFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) testKubelet.fakeCadvisor.On("RootFsInfo").Return(cadvisorApiv2.FsInfo{}, nil) runningPod := &kubecontainer.Pod{ ID: "12345678", Name: "pod1", Namespace: "ns", } apiPod := &api.Pod{ ObjectMeta: api.ObjectMeta{ UID: runningPod.ID, Name: runningPod.Name, Namespace: runningPod.Namespace, }, } // Sync once to create pod directory; confirm that the pod directory has // already been created. pods := []*api.Pod{apiPod} syncAndVerifyPodDir(t, testKubelet, pods, []*api.Pod{apiPod}, true) // Pretend the pod is deleted from apiserver, but is still active on the node. // The pod directory should not be removed. pods = []*api.Pod{} testKubelet.fakeRuntime.PodList = []*kubecontainer.Pod{runningPod} syncAndVerifyPodDir(t, testKubelet, pods, []*api.Pod{apiPod}, true) // The pod is deleted and also not active on the node. The pod directory // should be removed. pods = []*api.Pod{} testKubelet.fakeRuntime.PodList = []*kubecontainer.Pod{} syncAndVerifyPodDir(t, testKubelet, pods, []*api.Pod{apiPod}, false) } func TestCleanupBandwidthLimits(t *testing.T) { tests := []struct { status *api.PodStatus pods []*api.Pod inputCIDRs []string expectResetCIDRs []string cacheStatus bool expectedCalls []string name string }{ { status: &api.PodStatus{ PodIP: "1.2.3.4", Phase: api.PodRunning, }, pods: []*api.Pod{ { ObjectMeta: api.ObjectMeta{ Name: "foo", Annotations: map[string]string{ "kubernetes.io/ingress-bandwidth": "10M", }, }, }, { ObjectMeta: api.ObjectMeta{ Name: "bar", }, }, }, inputCIDRs: []string{"1.2.3.4/32", "2.3.4.5/32", "5.6.7.8/32"}, expectResetCIDRs: []string{"2.3.4.5/32", "5.6.7.8/32"}, expectedCalls: []string{"GetPodStatus"}, name: "pod running", }, { status: &api.PodStatus{ PodIP: "1.2.3.4", Phase: api.PodRunning, }, pods: []*api.Pod{ { ObjectMeta: api.ObjectMeta{ Name: "foo", Annotations: map[string]string{ "kubernetes.io/ingress-bandwidth": "10M", }, }, }, { ObjectMeta: api.ObjectMeta{ Name: "bar", }, }, }, inputCIDRs: []string{"1.2.3.4/32", "2.3.4.5/32", "5.6.7.8/32"}, expectResetCIDRs: []string{"2.3.4.5/32", "5.6.7.8/32"}, expectedCalls: []string{}, cacheStatus: true, name: "pod running with cache", }, { status: &api.PodStatus{ PodIP: "1.2.3.4", Phase: api.PodFailed, }, pods: []*api.Pod{ { ObjectMeta: api.ObjectMeta{ Name: "foo", Annotations: map[string]string{ "kubernetes.io/ingress-bandwidth": "10M", }, }, }, { ObjectMeta: api.ObjectMeta{ Name: "bar", }, }, }, inputCIDRs: []string{"1.2.3.4/32", "2.3.4.5/32", "5.6.7.8/32"}, expectResetCIDRs: []string{"1.2.3.4/32", "2.3.4.5/32", "5.6.7.8/32"}, expectedCalls: []string{"GetPodStatus"}, name: "pod not running", }, { status: &api.PodStatus{ PodIP: "1.2.3.4", Phase: api.PodFailed, }, pods: []*api.Pod{ { ObjectMeta: api.ObjectMeta{ Name: "foo", Annotations: map[string]string{ "kubernetes.io/ingress-bandwidth": "10M", }, }, }, { ObjectMeta: api.ObjectMeta{ Name: "bar", }, }, }, inputCIDRs: []string{"1.2.3.4/32", "2.3.4.5/32", "5.6.7.8/32"}, expectResetCIDRs: []string{"1.2.3.4/32", "2.3.4.5/32", "5.6.7.8/32"}, expectedCalls: []string{}, cacheStatus: true, name: "pod not running with cache", }, { status: &api.PodStatus{ PodIP: "1.2.3.4", Phase: api.PodRunning, }, pods: []*api.Pod{ { ObjectMeta: api.ObjectMeta{ Name: "foo", }, }, { ObjectMeta: api.ObjectMeta{ Name: "bar", }, }, }, inputCIDRs: []string{"1.2.3.4/32", "2.3.4.5/32", "5.6.7.8/32"}, expectResetCIDRs: []string{"1.2.3.4/32", "2.3.4.5/32", "5.6.7.8/32"}, name: "no bandwidth limits", }, } for _, test := range tests { shaper := &bandwidth.FakeShaper{ CIDRs: test.inputCIDRs, } testKube := newTestKubelet(t) testKube.kubelet.shaper = shaper testKube.fakeRuntime.PodStatus = *test.status if test.cacheStatus { for _, pod := range test.pods { testKube.kubelet.statusManager.SetPodStatus(pod, *test.status) } } err := testKube.kubelet.cleanupBandwidthLimits(test.pods) if err != nil { t.Errorf("unexpected error: %v (%s)", test.name) } if !reflect.DeepEqual(shaper.ResetCIDRs, test.expectResetCIDRs) { t.Errorf("[%s]\nexpected: %v, saw: %v", test.name, test.expectResetCIDRs, shaper.ResetCIDRs) } if test.cacheStatus { if len(testKube.fakeRuntime.CalledFunctions) != 0 { t.Errorf("unexpected function calls: %v", testKube.fakeRuntime.CalledFunctions) } } else if !reflect.DeepEqual(testKube.fakeRuntime.CalledFunctions, test.expectedCalls) { t.Errorf("[%s], expected %v, saw %v", test.name, test.expectedCalls, testKube.fakeRuntime.CalledFunctions) } } } func TestExtractBandwidthResources(t *testing.T) { four, _ := resource.ParseQuantity("4M") ten, _ := resource.ParseQuantity("10M") twenty, _ := resource.ParseQuantity("20M") tests := []struct { pod *api.Pod expectedIngress *resource.Quantity expectedEgress *resource.Quantity expectError bool }{ { pod: &api.Pod{}, }, { pod: &api.Pod{ ObjectMeta: api.ObjectMeta{ Annotations: map[string]string{ "kubernetes.io/ingress-bandwidth": "10M", }, }, }, expectedIngress: ten, }, { pod: &api.Pod{ ObjectMeta: api.ObjectMeta{ Annotations: map[string]string{ "kubernetes.io/egress-bandwidth": "10M", }, }, }, expectedEgress: ten, }, { pod: &api.Pod{ ObjectMeta: api.ObjectMeta{ Annotations: map[string]string{ "kubernetes.io/ingress-bandwidth": "4M", "kubernetes.io/egress-bandwidth": "20M", }, }, }, expectedIngress: four, expectedEgress: twenty, }, { pod: &api.Pod{ ObjectMeta: api.ObjectMeta{ Annotations: map[string]string{ "kubernetes.io/ingress-bandwidth": "foo", }, }, }, expectError: true, }, } for _, test := range tests { ingress, egress, err := extractBandwidthResources(test.pod) if test.expectError { if err == nil { t.Errorf("unexpected non-error") } continue } if err != nil { t.Errorf("unexpected error: %v", err) continue } if !reflect.DeepEqual(ingress, test.expectedIngress) { t.Errorf("expected: %v, saw: %v", ingress, test.expectedIngress) } if !reflect.DeepEqual(egress, test.expectedEgress) { t.Errorf("expected: %v, saw: %v", egress, test.expectedEgress) } } }
Java
package com.doglandia.animatingtextviewlib; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
Java
# Involutinidae Butschli, 1880 FAMILY #### Status ACCEPTED #### According to Integrated Taxonomic Information System #### Published in null #### Original name null ### Remarks null
Java
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.seongil.mvplife.fragment; import android.os.Bundle; import android.view.View; import com.seongil.mvplife.base.MvpPresenter; import com.seongil.mvplife.base.MvpView; import com.seongil.mvplife.delegate.MvpDelegateCallback; import com.seongil.mvplife.delegate.fragment.MvpFragmentDelegate; import com.seongil.mvplife.delegate.fragment.MvpFragmentDelegateImpl; /** * Abstract class for the fragment which is holding a reference of the {@link MvpPresenter} * Also, holding a {@link MvpFragmentDelegate} which is handling the lifecycle of the fragment. * * @param <V> The type of {@link MvpView} * @param <P> The type of {@link MvpPresenter} * * @author seong-il, kim * @since 17. 1. 6 */ public abstract class BaseMvpFragment<V extends MvpView, P extends MvpPresenter<V>> extends CoreFragment implements MvpView, MvpDelegateCallback<V, P> { // ======================================================================== // Constants // ======================================================================== // ======================================================================== // Fields // ======================================================================== private MvpFragmentDelegate mFragmentDelegate; private P mPresenter; // ======================================================================== // Constructors // ======================================================================== // ======================================================================== // Getter & Setter // ======================================================================== // ======================================================================== // Methods for/from SuperClass/Interfaces // ======================================================================== @Override public abstract P createPresenter(); @Override public P getPresenter() { return mPresenter; } @Override public void setPresenter(P presenter) { mPresenter = presenter; } @Override @SuppressWarnings("unchecked") public V getMvpView() { return (V) this; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); getMvpDelegate().onViewCreated(view, savedInstanceState); } @Override public void onDestroyView() { getMvpDelegate().onDestroyView(); super.onDestroyView(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getMvpDelegate().onCreate(savedInstanceState); } @Override public void onDestroy() { super.onDestroy(); getMvpDelegate().onDestroy(); } // ======================================================================== // Methods // ======================================================================== protected MvpFragmentDelegate getMvpDelegate() { if (mFragmentDelegate == null) { mFragmentDelegate = new MvpFragmentDelegateImpl<>(this); } return mFragmentDelegate; } // ======================================================================== // Inner and Anonymous Classes // ======================================================================== }
Java
@media (min-width: 980px) { /*-----*/ .custom-bar-chart { margin-bottom: 40px; } } @media (min-width: 768px) and (max-width: 979px) { /*-----*/ .custom-bar-chart { margin-bottom: 40px; } /*chat room*/ } @media (max-width: 768px) { .header { position: absolute; } /*sidebar*/ #sidebar { height: auto; overflow: hidden; position: absolute; width: 100%; z-index: 1001; } /* body container */ #main-content { margin: 0px !important; position: none !important; } #sidebar > ul > li > a > span { line-height: 35px; } #sidebar > ul > li { margin: 0 10px 5px 10px; } #sidebar > ul > li > a { height: 35px; line-height: 35px; padding: 0 10px; text-align: left; } #sidebar > ul > li > a i { /*display: none !important;*/ } #sidebar ul > li > a .arrow, #sidebar > ul > li > a .arrow.open { margin-right: 10px; margin-top: 15px; } #sidebar ul > li.active > a .arrow, #sidebar ul > li > a:hover .arrow, #sidebar ul > li > a:focus .arrow, #sidebar > ul > li.active > a .arrow.open, #sidebar > ul > li > a:hover .arrow.open, #sidebar > ul > li > a:focus .arrow.open { margin-top: 15px; } #sidebar > ul > li > a, #sidebar > ul > li > ul.sub > li { width: 100%; } #sidebar > ul > li > ul.sub > li > a { background: transparent !important; } #sidebar > ul > li > ul.sub > li > a:hover { } /* sidebar */ #sidebar { margin: 0px !important; } /* sidebar collabler */ #sidebar .btn-navbar.collapsed .arrow { display: none; } #sidebar .btn-navbar .arrow { position: absolute; right: 35px; width: 0; height: 0; top: 48px; border-bottom: 15px solid #282e36; border-left: 15px solid transparent; border-right: 15px solid transparent; } /*---------*/ .modal-footer .btn { margin-bottom: 0px !important; } .btn { margin-bottom: 5px; } /* full calendar fix */ .fc-header-right { left: 25px; position: absolute; } .fc-header-left .fc-button { margin: 0px !important; top: -10px !important; } .fc-header-right .fc-button { margin: 0px !important; top: -50px !important; } .fc-state-active, .fc-state-active .fc-button-inner, .fc-state-hover, .fc-state-hover .fc-button-inner { background: none !important; color: #FFFFFF !important; } .fc-state-default, .fc-state-default .fc-button-inner { background: none !important; } .fc-button { border: none !important; margin-right: 2px; } .fc-view { top: 0px !important; } .fc-button .fc-button-inner { margin: 0px !important; padding: 2px !important; border: none !important; margin-right: 2px !important; background-color: #fafafa !important; background-image: -moz-linear-gradient(top, #fafafa, #efefef) !important; background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fafafa), to(#efefef)) !important; background-image: -webkit-linear-gradient(top, #fafafa, #efefef) !important; background-image: -o-linear-gradient(top, #fafafa, #efefef) !important; background-image: linear-gradient(to bottom, #fafafa, #efefef) !important; filter: progid:dximagetransform.microsoft.gradient(startColorstr='#fafafa', endColorstr='#efefef', GradientType=0) !important; -webkit-box-shadow: 0 1px 0px rgba(255, 255, 255, .8) !important; -moz-box-shadow: 0 1px 0px rgba(255, 255, 255, .8) !important; box-shadow: 0 1px 0px rgba(255, 255, 255, .8) !important; -webkit-border-radius: 3px !important; -moz-border-radius: 3px !important; border-radius: 3px !important; color: #646464 !important; border: 1px solid #ddd !important; text-shadow: 0 1px 0px rgba(255, 255, 255, .6) !important; text-align: center; } .fc-button.fc-state-disabled .fc-button-inner { color: #bcbbbb !important; } .fc-button.fc-state-active .fc-button-inner { background-color: #e5e4e4 !important; background-image: -moz-linear-gradient(top, #e5e4e4, #dddcdc) !important; background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#e5e4e4), to(#dddcdc)) !important; background-image: -webkit-linear-gradient(top, #e5e4e4, #dddcdc) !important; background-image: -o-linear-gradient(top, #e5e4e4, #dddcdc) !important; background-image: linear-gradient(to bottom, #e5e4e4, #dddcdc) !important; filter: progid:dximagetransform.microsoft.gradient(startColorstr='#e5e4e4', endColorstr='#dddcdc', GradientType=0) !important; } .fc-content { margin-top: 50px; } .fc-header-title h2 { line-height: 40px !important; font-size: 12px !important; } .fc-header { margin-bottom: 0px !important; } /*--*/ /*.chart-position {*/ /*margin-top: 0px;*/ /*}*/ .stepy-titles li { margin: 10px 3px; } /*-----*/ .custom-bar-chart { margin-bottom: 40px; } /*menu icon plus minus*/ .dcjq-icon { top: 10px; } ul.sidebar-menu li ul.sub li a { padding: 0; } /*---*/ .img-responsive { width: 100%; } } @media (max-width: 480px) { .notify-row, .search, .dont-show, .inbox-head .sr-input, .inbox-head .sr-btn { display: none; } #top_menu .nav > li, ul.top-menu > li { float: right; } .hidden-phone { display: none !important; } .chart-position { margin-top: 0px; } .navbar-inverse .navbar-toggle:hover, .navbar-inverse .navbar-toggle:focus { background-color: #ccc; border-color: #ccc; } } @media (max-width: 320px) { .login-social-link a { padding: 15px 17px !important; } .notify-row, .search, .dont-show, .inbox-head .sr-input, .inbox-head .sr-btn { display: none; } #top_menu .nav > li, ul.top-menu > li { float: right; } .hidden-phone { display: none !important; } .chart-position { margin-top: 0px; } .lock-wrapper { margin: 10% auto; max-width: 310px; } .lock-input { width: 82%; } .cmt-form { display: inline-block; width: 75%; } }
Java
import React from 'react' import { StyleSheet, View, processColor } from 'react-native' import { BubbleChart } from 'react-native-charts-wrapper' class BubbleChartScreen extends React.Component<any, any> { constructor(props) { super(props) const { modeInfo } = props const temp = props.value.weekLoc.sort((a, b) => { const day = a.x - b.x return day || (a.y - b.y) }) const valueFormatter = props.value.daysMapper.slice() valueFormatter.unshift() valueFormatter.push(props.value.daysMapper[0]) const isX = item => item.x === 6 const values = [...temp.filter(isX), ...temp.filter(item => item.x !== 6)] this.state = { data: { dataSets: [{ values, label: '奖杯数比例', config: { color: processColor(modeInfo.deepColor), highlightCircleWidth: 2, drawValues: false, valueTextColor: processColor(modeInfo.titleTextColor) } }] }, legend: { enabled: true, textSize: 14, form: 'CIRCLE', wordWrapEnabled: true, textColor: processColor(props.modeInfo.standardTextColor) }, xAxis: { valueFormatter, position: 'BOTTOM', drawGridLines: false, granularityEnabled: true, granularity: 1, textColor: processColor(props.modeInfo.standardTextColor) // avoidFirstLastClipping: true // labelCountForce: true, // labelCount: 12 }, yAxis: { left: { axisMinimum: 0, axisMaximum: 23, textColor: processColor(props.modeInfo.standardTextColor) }, right: { axisMinimum: 0, axisMaximum: 23, textColor: processColor(props.modeInfo.standardTextColor) } } } } handleSelect = () => { } render() { // console.log(this.state.data.dataSets[0].values.filter(item => item.x === 6)) return ( <View style={{ height: 250 }}> <BubbleChart style={styles.chart} data={this.state.data} legend={this.state.legend} chartDescription={{text: ''}} xAxis={this.state.xAxis} yAxis={this.state.yAxis} entryLabelColor={processColor(this.props.modeInfo.titleTextColor)} onSelect={this.handleSelect} /> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#F5FCFF' }, chart: { flex: 1 } }) export default BubbleChartScreen
Java
name 'neo4j' maintainer 'YOUR_COMPANY_NAME' maintainer_email 'YOUR_EMAIL' license 'All rights reserved' description 'Installs/Configures neo4j' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.1.0'
Java
# -*- coding: utf-8 -*- """Template shortcut & filters""" import os import datetime from jinja2 import Environment, FileSystemLoader from uwsgi_sloth.settings import ROOT from uwsgi_sloth import settings, __VERSION__ template_path = os.path.join(ROOT, 'templates') env = Environment(loader=FileSystemLoader(template_path)) # Template filters def friendly_time(msecs): secs, msecs = divmod(msecs, 1000) mins, secs = divmod(secs, 60) hours, mins = divmod(mins, 60) if hours: return '%dh%dm%ds' % (hours, mins, secs) elif mins: return '%dm%ds' % (mins, secs) elif secs: return '%ds%dms' % (secs, msecs) else: return '%.2fms' % msecs env.filters['friendly_time'] = friendly_time def render_template(template_name, context={}): template = env.get_template(template_name) context.update( SETTINGS=settings, now=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), version='.'.join(map(str, __VERSION__))) return template.render(**context)
Java
# Fagopyrum odontopterum Gross SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
# Polemonium confertum var. mellitum A.Gray VARIETY #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
package org.openstack.atlas.service.domain.exception; public class UniqueLbPortViolationException extends PersistenceServiceException { private final String message; public UniqueLbPortViolationException(final String message) { this.message = message; } @Override public String getMessage() { return message; } }
Java
#!/bin/bash -xe # 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. source /usr/local/jenkins/slave_scripts/common_translation_update.sh setup_git setup_review setup_translation setup_horizon # Download new files that are at least 75 % translated. # Also downloads updates for existing files that are at least 75 % # translated. tx pull -a -f --minimum-perc=75 # Pull upstream translations of all downloaded files but do not # download new files. tx pull -f # Invoke run_tests.sh to update the po files # Or else, "../manage.py makemessages" can be used. ./run_tests.sh --makemessages -V # Compress downloaded po files compress_non_en_po_files "horizon" compress_non_en_po_files "openstack_dashboard" # Add all changed files to git git add horizon/locale/* openstack_dashboard/locale/* filter_commits send_patch
Java
# Eriosema ×woodii C.H.Stirt. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
<?xml version="1.0" encoding="UTF-8" ?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <html xmlns:wicket="http://wicket.apache.org"> <body> <wicket:panel> <ul class="pagination pagination-sm"> <li><a wicket:id="first">&lt;&lt;</a></li> <li><a wicket:id="prev">&lt;</a></li> <li wicket:id="navigation"> <a wicket:id="pageLink" href="#"><wicket:container wicket:id="pageNumber"></wicket:container></a> </li> <li><a wicket:id="next">&gt;</a></li> <li><a wicket:id="last">&gt;&gt;</a></li> </ul> </wicket:panel> </body> </html>
Java
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver13; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import org.jboss.netty.buffer.ChannelBuffer; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFOxmBsnUdf4MaskedVer13 implements OFOxmBsnUdf4Masked { private static final Logger logger = LoggerFactory.getLogger(OFOxmBsnUdf4MaskedVer13.class); // version: 1.3 final static byte WIRE_VERSION = 4; final static int LENGTH = 12; private final static UDF DEFAULT_VALUE = UDF.ZERO; private final static UDF DEFAULT_VALUE_MASK = UDF.ZERO; // OF message fields private final UDF value; private final UDF mask; // // Immutable default instance final static OFOxmBsnUdf4MaskedVer13 DEFAULT = new OFOxmBsnUdf4MaskedVer13( DEFAULT_VALUE, DEFAULT_VALUE_MASK ); // package private constructor - used by readers, builders, and factory OFOxmBsnUdf4MaskedVer13(UDF value, UDF mask) { if(value == null) { throw new NullPointerException("OFOxmBsnUdf4MaskedVer13: property value cannot be null"); } if(mask == null) { throw new NullPointerException("OFOxmBsnUdf4MaskedVer13: property mask cannot be null"); } this.value = value; this.mask = mask; } // Accessors for OF message fields @Override public long getTypeLen() { return 0x31908L; } @Override public UDF getValue() { return value; } @Override public UDF getMask() { return mask; } @Override public MatchField<UDF> getMatchField() { return MatchField.BSN_UDF4; } @Override public boolean isMasked() { return true; } public OFOxm<UDF> getCanonical() { if (UDF.NO_MASK.equals(mask)) { return new OFOxmBsnUdf4Ver13(value); } else if(UDF.FULL_MASK.equals(mask)) { return null; } else { return this; } } @Override public OFVersion getVersion() { return OFVersion.OF_13; } public OFOxmBsnUdf4Masked.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFOxmBsnUdf4Masked.Builder { final OFOxmBsnUdf4MaskedVer13 parentMessage; // OF message fields private boolean valueSet; private UDF value; private boolean maskSet; private UDF mask; BuilderWithParent(OFOxmBsnUdf4MaskedVer13 parentMessage) { this.parentMessage = parentMessage; } @Override public long getTypeLen() { return 0x31908L; } @Override public UDF getValue() { return value; } @Override public OFOxmBsnUdf4Masked.Builder setValue(UDF value) { this.value = value; this.valueSet = true; return this; } @Override public UDF getMask() { return mask; } @Override public OFOxmBsnUdf4Masked.Builder setMask(UDF mask) { this.mask = mask; this.maskSet = true; return this; } @Override public MatchField<UDF> getMatchField() { return MatchField.BSN_UDF4; } @Override public boolean isMasked() { return true; } @Override public OFOxm<UDF> getCanonical()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property canonical not supported in version 1.3"); } @Override public OFVersion getVersion() { return OFVersion.OF_13; } @Override public OFOxmBsnUdf4Masked build() { UDF value = this.valueSet ? this.value : parentMessage.value; if(value == null) throw new NullPointerException("Property value must not be null"); UDF mask = this.maskSet ? this.mask : parentMessage.mask; if(mask == null) throw new NullPointerException("Property mask must not be null"); // return new OFOxmBsnUdf4MaskedVer13( value, mask ); } } static class Builder implements OFOxmBsnUdf4Masked.Builder { // OF message fields private boolean valueSet; private UDF value; private boolean maskSet; private UDF mask; @Override public long getTypeLen() { return 0x31908L; } @Override public UDF getValue() { return value; } @Override public OFOxmBsnUdf4Masked.Builder setValue(UDF value) { this.value = value; this.valueSet = true; return this; } @Override public UDF getMask() { return mask; } @Override public OFOxmBsnUdf4Masked.Builder setMask(UDF mask) { this.mask = mask; this.maskSet = true; return this; } @Override public MatchField<UDF> getMatchField() { return MatchField.BSN_UDF4; } @Override public boolean isMasked() { return true; } @Override public OFOxm<UDF> getCanonical()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property canonical not supported in version 1.3"); } @Override public OFVersion getVersion() { return OFVersion.OF_13; } // @Override public OFOxmBsnUdf4Masked build() { UDF value = this.valueSet ? this.value : DEFAULT_VALUE; if(value == null) throw new NullPointerException("Property value must not be null"); UDF mask = this.maskSet ? this.mask : DEFAULT_VALUE_MASK; if(mask == null) throw new NullPointerException("Property mask must not be null"); return new OFOxmBsnUdf4MaskedVer13( value, mask ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFOxmBsnUdf4Masked> { @Override public OFOxmBsnUdf4Masked readFrom(ChannelBuffer bb) throws OFParseError { // fixed value property typeLen == 0x31908L int typeLen = bb.readInt(); if(typeLen != 0x31908) throw new OFParseError("Wrong typeLen: Expected=0x31908L(0x31908L), got="+typeLen); UDF value = UDF.read4Bytes(bb); UDF mask = UDF.read4Bytes(bb); OFOxmBsnUdf4MaskedVer13 oxmBsnUdf4MaskedVer13 = new OFOxmBsnUdf4MaskedVer13( value, mask ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", oxmBsnUdf4MaskedVer13); return oxmBsnUdf4MaskedVer13; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFOxmBsnUdf4MaskedVer13Funnel FUNNEL = new OFOxmBsnUdf4MaskedVer13Funnel(); static class OFOxmBsnUdf4MaskedVer13Funnel implements Funnel<OFOxmBsnUdf4MaskedVer13> { private static final long serialVersionUID = 1L; @Override public void funnel(OFOxmBsnUdf4MaskedVer13 message, PrimitiveSink sink) { // fixed value property typeLen = 0x31908L sink.putInt(0x31908); message.value.putTo(sink); message.mask.putTo(sink); } } public void writeTo(ChannelBuffer bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFOxmBsnUdf4MaskedVer13> { @Override public void write(ChannelBuffer bb, OFOxmBsnUdf4MaskedVer13 message) { // fixed value property typeLen = 0x31908L bb.writeInt(0x31908); message.value.write4Bytes(bb); message.mask.write4Bytes(bb); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFOxmBsnUdf4MaskedVer13("); b.append("value=").append(value); b.append(", "); b.append("mask=").append(mask); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFOxmBsnUdf4MaskedVer13 other = (OFOxmBsnUdf4MaskedVer13) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; if (mask == null) { if (other.mask != null) return false; } else if (!mask.equals(other.mask)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); result = prime * result + ((mask == null) ? 0 : mask.hashCode()); return result; } }
Java
# Copyright 2017,2018 IBM Corp. # # 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 json import mock import unittest from zvmsdk.sdkwsgi.handlers import version from zvmsdk import version as sdk_version class HandlersRootTest(unittest.TestCase): def setUp(self): pass def test_version(self): req = mock.Mock() ver_str = {"rc": 0, "overallRC": 0, "errmsg": "", "modID": None, "output": {"api_version": version.APIVERSION, "min_version": version.APIVERSION, "version": sdk_version.__version__, "max_version": version.APIVERSION, }, "rs": 0} res = version.version(req) self.assertEqual('application/json', req.response.content_type) # version_json = json.dumps(ver_res) # version_str = utils.to_utf8(version_json) ver_res = json.loads(req.response.body.decode('utf-8')) self.assertEqual(ver_str, ver_res) self.assertEqual('application/json', res.content_type)
Java
# # Copyright (C) 2015 # Andy Warner # This file is part of the aft package. # # 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. # Simple makefile for the aft package TOP = ../../.. INCDIR = $(TOP)/src #AR = ar CC = g++ #CCFLAGS = -Wall -g -O2 -I$(TOP) -I$(INCDIR) CCFLAGS = -std=c++14 -Wall -g -fPIC -I$(TOP) -I$(INCDIR) DEPCPPFLAGS = -std=c++14 -I$(TOP) -I$(INCDIR) # OBJS := nativepluginloader.o nativethread.o OBJS := nativethread.o SRCS := $(OBJS:.o=.cpp) INCS = $(OBJS:.o=.h) LIBR = libaftnative.a .cpp.o: ; $(CC) $(CCFLAGS) -c $< all: $(LIBR) $(LIBR): $(OBJS) $(AR) rsv $@ $(OBJS) .PHONY: clean clean: rm -f $(OBJS) $(LIBR) .PHONY: depends depends: $(SRCS) $(INCS) $(CC) $(DEPCPPFLAGS) -MM $(SRCS) > .makedepends touch .mkdep-timestamp .makedepends: include .makedepends
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="ro"> <head> <!-- Generated by javadoc (version 1.7.0_07) on Tue May 27 14:37:24 EEST 2014 --> <title>Uses of Class net.sf.jasperreports.components.list.HorizontalFillList (JasperReports 5.6.0 API)</title> <meta name="date" content="2014-05-27"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class net.sf.jasperreports.components.list.HorizontalFillList (JasperReports 5.6.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../net/sf/jasperreports/components/list/HorizontalFillList.html" title="class in net.sf.jasperreports.components.list">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?net/sf/jasperreports/components/list/class-use/HorizontalFillList.html" target="_top">Frames</a></li> <li><a href="HorizontalFillList.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class net.sf.jasperreports.components.list.HorizontalFillList" class="title">Uses of Class<br>net.sf.jasperreports.components.list.HorizontalFillList</h2> </div> <div class="classUseContainer">No usage of net.sf.jasperreports.components.list.HorizontalFillList</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../net/sf/jasperreports/components/list/HorizontalFillList.html" title="class in net.sf.jasperreports.components.list">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?net/sf/jasperreports/components/list/class-use/HorizontalFillList.html" target="_top">Frames</a></li> <li><a href="HorizontalFillList.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color:#000000;">&copy; 2001-2010 Jaspersoft Corporation <a href="http://www.jaspersoft.com" target="_blank" style="color:#000000;">www.jaspersoft.com</a></span> </small></p> </body> </html>
Java
package com.tamirhassan.pdfxtk.comparators; /** * pdfXtk - PDF Extraction Toolkit * Copyright (c) by the authors/contributors. All rights reserved. * This project includes code from PDFBox and TouchGraph. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the names pdfXtk or PDF Extraction Toolkit; 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 REGENTS 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. * * http://pdfxtk.sourceforge.net * */ import java.util.Comparator; import com.tamirhassan.pdfxtk.model.GenericSegment; /** * @author Tamir Hassan, pdfanalyser@tamirhassan.com * @version PDF Analyser 0.9 * * Sorts on Xmid coordinate ((x1+x2)/2) */ public class XmidComparator implements Comparator<GenericSegment> { public int compare(GenericSegment obj1, GenericSegment obj2) { // sorts in x order double x1 = obj1.getXmid(); double x2 = obj2.getXmid(); // causes a contract violation (rounding?) // return (int) (x1 - x2); if (x2 > x1) return -1; else if (x2 == x1) return 0; else return 1; } public boolean equals(Object obj) { return obj.equals(this); } }
Java
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/ids/v1/ids.proto #ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_IDS_IDS_OPTIONS_H #define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_IDS_IDS_OPTIONS_H #include "google/cloud/ids/ids_connection.h" #include "google/cloud/ids/ids_connection_idempotency_policy.h" #include "google/cloud/backoff_policy.h" #include "google/cloud/options.h" #include "google/cloud/version.h" #include <memory> namespace google { namespace cloud { namespace ids { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN /// Option to use with `google::cloud::Options`. struct IDSRetryPolicyOption { using Type = std::shared_ptr<IDSRetryPolicy>; }; /// Option to use with `google::cloud::Options`. struct IDSBackoffPolicyOption { using Type = std::shared_ptr<BackoffPolicy>; }; /// Option to use with `google::cloud::Options`. struct IDSPollingPolicyOption { using Type = std::shared_ptr<PollingPolicy>; }; /// Option to use with `google::cloud::Options`. struct IDSConnectionIdempotencyPolicyOption { using Type = std::shared_ptr<IDSConnectionIdempotencyPolicy>; }; using IDSPolicyOptionList = OptionList<IDSRetryPolicyOption, IDSBackoffPolicyOption, IDSPollingPolicyOption, IDSConnectionIdempotencyPolicyOption>; GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace ids } // namespace cloud } // namespace google #endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_IDS_IDS_OPTIONS_H
Java
# Bartramia nothostricta Catcheside, 1987 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
/** * Copyright (C) 2015 meltmedia (christian.trimble@meltmedia.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.meltmedia.dropwizard.etcd.json; import java.util.concurrent.ScheduledExecutorService; import java.util.function.Function; import java.util.function.Supplier; import com.codahale.metrics.MetricRegistry; import mousio.etcd4j.EtcdClient; import io.dropwizard.Configuration; import io.dropwizard.ConfiguredBundle; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; public class EtcdJsonBundle<C extends Configuration> implements ConfiguredBundle<C> { public static class Builder<C extends Configuration> { private Supplier<EtcdClient> client; private Supplier<ScheduledExecutorService> executor; private Function<C, String> directoryAccessor; public Builder<C> withClient(Supplier<EtcdClient> client) { this.client = client; return this; } public Builder<C> withExecutor(Supplier<ScheduledExecutorService> executor) { this.executor = executor; return this; } public Builder<C> withDirectory(Function<C, String> directoryAccessor) { this.directoryAccessor = directoryAccessor; return this; } public EtcdJsonBundle<C> build() { return new EtcdJsonBundle<C>(client, executor, directoryAccessor); } } public static <C extends Configuration> Builder<C> builder() { return new Builder<C>(); } Supplier<EtcdClient> clientSupplier; EtcdJson factory; private Supplier<ScheduledExecutorService> executor; private Function<C, String> directoryAccessor; public EtcdJsonBundle(Supplier<EtcdClient> client, Supplier<ScheduledExecutorService> executor, Function<C, String> directoryAccessor) { this.clientSupplier = client; this.executor = executor; this.directoryAccessor = directoryAccessor; } @Override public void initialize(Bootstrap<?> bootstrap) { } @Override public void run(C configuration, Environment environment) throws Exception { factory = EtcdJson.builder().withClient(clientSupplier).withExecutor(executor.get()) .withBaseDirectory(directoryAccessor.apply(configuration)) .withMapper(environment.getObjectMapper()) .withMetricRegistry(environment.metrics()).build(); environment.lifecycle().manage(new EtcdJsonManager(factory)); environment.healthChecks().register("etcd-watch", new WatchServiceHealthCheck(factory.getWatchService())); } public EtcdJson getFactory() { return this.factory; } }
Java
# Cryptococcus cylindricus Á. Fonseca, Scorzetti & Fell SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Can. J. Microbiol. 46(1): 22 (2000) #### Original name Cryptococcus cylindricus Á. Fonseca, Scorzetti & Fell ### Remarks null
Java
# BOESG-website Public facing website for British Open Educational Software Group at http://www.boesg.org.uk. ### Note for Contributors Deployment is automated upon merge to the master branch via CI. Please raise PRs against the dev branch.
Java
import com.google.common.base.Function; import javax.annotation.Nullable; /** * Created by ckale on 10/29/14. */ public class DateValueSortFunction implements Function<PojoDTO, Long>{ @Nullable @Override public Long apply(@Nullable final PojoDTO input) { return input.getDateTime().getMillis(); } }
Java
package ru.stqa.javacourse.mantis.tests; import org.testng.annotations.Test; import ru.stqa.javacourse.mantis.model.Issue; import ru.stqa.javacourse.mantis.model.Project; import javax.xml.rpc.ServiceException; import java.net.MalformedURLException; import java.rmi.RemoteException; import java.util.Set; import static org.testng.Assert.assertEquals; public class SoapTest extends TestBase { @Test public void testGetProjects() throws MalformedURLException, ServiceException, RemoteException { Set<Project> projects = app.soap().getProjects(); System.out.println(projects.size()); for (Project project : projects) { System.out.println(project.getName()); } } @Test public void testCreateIssue() throws RemoteException, ServiceException, MalformedURLException { Set<Project> projects = app.soap().getProjects(); Issue issue=new Issue().withSummary("test issue") .withDescription("test issue description").withProject(projects.iterator().next()); Issue created = app.soap().addIssue(issue); assertEquals(issue.getSummary(),created.getSummary()); } }
Java
# Belonidium tremulae var. ulmaceum Velen. VARIETY #### Status ACCEPTED #### According to Index Fungorum #### Published in Monogr. Discom. Bohem. (Prague) 404 (1934) #### Original name Belonidium tremulae var. ulmaceum Velen. ### Remarks null
Java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v10/services/customer_conversion_goal_service.proto package com.google.ads.googleads.v10.services; /** * <pre> * A single operation (update) on a customer conversion goal. * </pre> * * Protobuf type {@code google.ads.googleads.v10.services.CustomerConversionGoalOperation} */ public final class CustomerConversionGoalOperation extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v10.services.CustomerConversionGoalOperation) CustomerConversionGoalOperationOrBuilder { private static final long serialVersionUID = 0L; // Use CustomerConversionGoalOperation.newBuilder() to construct. private CustomerConversionGoalOperation(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CustomerConversionGoalOperation() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new CustomerConversionGoalOperation(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private CustomerConversionGoalOperation( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder subBuilder = null; if (operationCase_ == 1) { subBuilder = ((com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_).toBuilder(); } operation_ = input.readMessage(com.google.ads.googleads.v10.resources.CustomerConversionGoal.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_); operation_ = subBuilder.buildPartial(); } operationCase_ = 1; break; } case 18: { com.google.protobuf.FieldMask.Builder subBuilder = null; if (updateMask_ != null) { subBuilder = updateMask_.toBuilder(); } updateMask_ = input.readMessage(com.google.protobuf.FieldMask.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(updateMask_); updateMask_ = subBuilder.buildPartial(); } break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.class, com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.Builder.class); } private int operationCase_ = 0; private java.lang.Object operation_; public enum OperationCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { UPDATE(1), OPERATION_NOT_SET(0); private final int value; private OperationCase(int value) { this.value = value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static OperationCase valueOf(int value) { return forNumber(value); } public static OperationCase forNumber(int value) { switch (value) { case 1: return UPDATE; case 0: return OPERATION_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public OperationCase getOperationCase() { return OperationCase.forNumber( operationCase_); } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return updateMask_ != null; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return getUpdateMask(); } public static final int UPDATE_FIELD_NUMBER = 1; /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> * @return Whether the update field is set. */ @java.lang.Override public boolean hasUpdate() { return operationCase_ == 1; } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> * @return The update. */ @java.lang.Override public com.google.ads.googleads.v10.resources.CustomerConversionGoal getUpdate() { if (operationCase_ == 1) { return (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_; } return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance(); } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder getUpdateOrBuilder() { if (operationCase_ == 1) { return (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_; } return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (operationCase_ == 1) { output.writeMessage(1, (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_); } if (updateMask_ != null) { output.writeMessage(2, getUpdateMask()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (operationCase_ == 1) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_); } if (updateMask_ != null) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, getUpdateMask()); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v10.services.CustomerConversionGoalOperation)) { return super.equals(obj); } com.google.ads.googleads.v10.services.CustomerConversionGoalOperation other = (com.google.ads.googleads.v10.services.CustomerConversionGoalOperation) obj; if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask() .equals(other.getUpdateMask())) return false; } if (!getOperationCase().equals(other.getOperationCase())) return false; switch (operationCase_) { case 1: if (!getUpdate() .equals(other.getUpdate())) return false; break; case 0: default: } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } switch (operationCase_) { case 1: hash = (37 * hash) + UPDATE_FIELD_NUMBER; hash = (53 * hash) + getUpdate().hashCode(); break; case 0: default: } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v10.services.CustomerConversionGoalOperation prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * A single operation (update) on a customer conversion goal. * </pre> * * Protobuf type {@code google.ads.googleads.v10.services.CustomerConversionGoalOperation} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v10.services.CustomerConversionGoalOperation) com.google.ads.googleads.v10.services.CustomerConversionGoalOperationOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.class, com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.Builder.class); } // Construct using com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); if (updateMaskBuilder_ == null) { updateMask_ = null; } else { updateMask_ = null; updateMaskBuilder_ = null; } operationCase_ = 0; operation_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_descriptor; } @java.lang.Override public com.google.ads.googleads.v10.services.CustomerConversionGoalOperation getDefaultInstanceForType() { return com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v10.services.CustomerConversionGoalOperation build() { com.google.ads.googleads.v10.services.CustomerConversionGoalOperation result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v10.services.CustomerConversionGoalOperation buildPartial() { com.google.ads.googleads.v10.services.CustomerConversionGoalOperation result = new com.google.ads.googleads.v10.services.CustomerConversionGoalOperation(this); if (updateMaskBuilder_ == null) { result.updateMask_ = updateMask_; } else { result.updateMask_ = updateMaskBuilder_.build(); } if (operationCase_ == 1) { if (updateBuilder_ == null) { result.operation_ = operation_; } else { result.operation_ = updateBuilder_.build(); } } result.operationCase_ = operationCase_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v10.services.CustomerConversionGoalOperation) { return mergeFrom((com.google.ads.googleads.v10.services.CustomerConversionGoalOperation)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v10.services.CustomerConversionGoalOperation other) { if (other == com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.getDefaultInstance()) return this; if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } switch (other.getOperationCase()) { case UPDATE: { mergeUpdate(other.getUpdate()); break; } case OPERATION_NOT_SET: { break; } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v10.services.CustomerConversionGoalOperation) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int operationCase_ = 0; private java.lang.Object operation_; public OperationCase getOperationCase() { return OperationCase.forNumber( operationCase_); } public Builder clearOperation() { operationCase_ = 0; operation_ = null; onChanged(); return this; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return updateMaskBuilder_ != null || updateMask_ != null; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; onChanged(); } else { updateMaskBuilder_.setMessage(value); } return this; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask( com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); onChanged(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } return this; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (updateMask_ != null) { updateMask_ = com.google.protobuf.FieldMask.newBuilder(updateMask_).mergeFrom(value).buildPartial(); } else { updateMask_ = value; } onChanged(); } else { updateMaskBuilder_.mergeFrom(value); } return this; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder clearUpdateMask() { if (updateMaskBuilder_ == null) { updateMask_ = null; onChanged(); } else { updateMask_ = null; updateMaskBuilder_ = null; } return this; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v10.resources.CustomerConversionGoal, com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder, com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder> updateBuilder_; /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> * @return Whether the update field is set. */ @java.lang.Override public boolean hasUpdate() { return operationCase_ == 1; } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> * @return The update. */ @java.lang.Override public com.google.ads.googleads.v10.resources.CustomerConversionGoal getUpdate() { if (updateBuilder_ == null) { if (operationCase_ == 1) { return (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_; } return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance(); } else { if (operationCase_ == 1) { return updateBuilder_.getMessage(); } return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance(); } } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> */ public Builder setUpdate(com.google.ads.googleads.v10.resources.CustomerConversionGoal value) { if (updateBuilder_ == null) { if (value == null) { throw new NullPointerException(); } operation_ = value; onChanged(); } else { updateBuilder_.setMessage(value); } operationCase_ = 1; return this; } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> */ public Builder setUpdate( com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder builderForValue) { if (updateBuilder_ == null) { operation_ = builderForValue.build(); onChanged(); } else { updateBuilder_.setMessage(builderForValue.build()); } operationCase_ = 1; return this; } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> */ public Builder mergeUpdate(com.google.ads.googleads.v10.resources.CustomerConversionGoal value) { if (updateBuilder_ == null) { if (operationCase_ == 1 && operation_ != com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance()) { operation_ = com.google.ads.googleads.v10.resources.CustomerConversionGoal.newBuilder((com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_) .mergeFrom(value).buildPartial(); } else { operation_ = value; } onChanged(); } else { if (operationCase_ == 1) { updateBuilder_.mergeFrom(value); } updateBuilder_.setMessage(value); } operationCase_ = 1; return this; } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> */ public Builder clearUpdate() { if (updateBuilder_ == null) { if (operationCase_ == 1) { operationCase_ = 0; operation_ = null; onChanged(); } } else { if (operationCase_ == 1) { operationCase_ = 0; operation_ = null; } updateBuilder_.clear(); } return this; } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> */ public com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder getUpdateBuilder() { return getUpdateFieldBuilder().getBuilder(); } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder getUpdateOrBuilder() { if ((operationCase_ == 1) && (updateBuilder_ != null)) { return updateBuilder_.getMessageOrBuilder(); } else { if (operationCase_ == 1) { return (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_; } return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance(); } } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v10.resources.CustomerConversionGoal, com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder, com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder> getUpdateFieldBuilder() { if (updateBuilder_ == null) { if (!(operationCase_ == 1)) { operation_ = com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance(); } updateBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v10.resources.CustomerConversionGoal, com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder, com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder>( (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_, getParentForChildren(), isClean()); operation_ = null; } operationCase_ = 1; onChanged();; return updateBuilder_; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v10.services.CustomerConversionGoalOperation) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v10.services.CustomerConversionGoalOperation) private static final com.google.ads.googleads.v10.services.CustomerConversionGoalOperation DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v10.services.CustomerConversionGoalOperation(); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CustomerConversionGoalOperation> PARSER = new com.google.protobuf.AbstractParser<CustomerConversionGoalOperation>() { @java.lang.Override public CustomerConversionGoalOperation parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new CustomerConversionGoalOperation(input, extensionRegistry); } }; public static com.google.protobuf.Parser<CustomerConversionGoalOperation> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CustomerConversionGoalOperation> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v10.services.CustomerConversionGoalOperation getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
Java
.container { clear: both; } body { font-family: Verdana, Arial, sans-serif; } h3 { font-family: Verdana, Arial, sans-serif; font-size: 18px; line-height: normal; } a.button, span.button { margin-left:10px; height:36px; } #sides{ margin:0; height:144px; width: 100%; } #left{ float:left; width:144px; overflow:hidden; } #right{ float:left; width:50%; overflow:hidden; } #image-data { margin: 20px 0px; width: 300px !important; height: auto; } .inst_table, .inst_table th, .inst_table td { border: 1px solid black; border-collapse: collapse; text-align: center; } .bottom { margin-top: 10px; margin-left: 20px; margin-bottom: 40px; float: left; } label.error { margin-left: 10px; } select.error, textarea.error, input.error { outline-style: solid; outline-width: 2px; outline-color: #FF0000; } .ui-dialog { position: fixed !important; }
Java
/* * Copyright 2017-2022 John Snow Labs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.johnsnowlabs.nlp import org.apache.spark.ml.param.BooleanParam trait HasCaseSensitiveProperties extends ParamsAndFeaturesWritable { /** Whether to ignore case in index lookups (Default depends on model) * * @group param */ val caseSensitive = new BooleanParam(this, "caseSensitive", "Whether to ignore case in index lookups") setDefault(caseSensitive, false) /** @group getParam */ def getCaseSensitive: Boolean = $(caseSensitive) /** @group setParam */ def setCaseSensitive(value: Boolean): this.type = set(this.caseSensitive, value) }
Java
package org.openjava.upay.web.domain; import java.util.List; public class TablePage<T> { private long start; private int length; private long recordsTotal; private long recordsFiltered; private List<T> data; public TablePage() { } public long getStart() { return start; } public void setStart(long start) { this.start = start; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public long getRecordsTotal() { return recordsTotal; } public void setRecordsTotal(long recordsTotal) { this.recordsTotal = recordsTotal; } public long getRecordsFiltered() { return recordsFiltered; } public void setRecordsFiltered(long recordsFiltered) { this.recordsFiltered = recordsFiltered; } public List<T> getData() { return data; } public void setData(List<T> data) { this.data = data; } public TablePage wrapData(long total, List<T> data) { this.recordsTotal = total; this.recordsFiltered = total; this.data = data; return this; } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_24) on Tue Apr 26 20:40:28 CST 2011 --> <TITLE> com.numericalmethod.suanshu.optimization.constrained.linearprogramming.simplex.standard (SuanShu 1.3.1 API Documentation) </TITLE> <META NAME="date" CONTENT="2011-04-26"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../../../../../../com/numericalmethod/suanshu/optimization/constrained/linearprogramming/simplex/standard/package-summary.html" target="classFrame">com.numericalmethod.suanshu.optimization.constrained.linearprogramming.simplex.standard</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="LpBoundedSolution.html" title="class in com.numericalmethod.suanshu.optimization.constrained.linearprogramming.simplex.standard" target="classFrame">LpBoundedSolution</A> <BR> <A HREF="LpUnboundedSolution.html" title="class in com.numericalmethod.suanshu.optimization.constrained.linearprogramming.simplex.standard" target="classFrame">LpUnboundedSolution</A> <BR> <A HREF="Phase2ByFerrisMangasarianWright.html" title="class in com.numericalmethod.suanshu.optimization.constrained.linearprogramming.simplex.standard" target="classFrame">Phase2ByFerrisMangasarianWright</A> <BR> <A HREF="StandardSimplex.html" title="class in com.numericalmethod.suanshu.optimization.constrained.linearprogramming.simplex.standard" target="classFrame">StandardSimplex</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
Java
# Eleocharis submersa Miq. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
// This header file is deprecated in 3ds Max 2011. // Please use header file listed below. #include "..\maxscript\protocols\time.h"
Java
# 10乡党 我们还有一篇没有讲的第十篇《乡党》。这一篇不补讲了。《乡党》这一篇,以现在观念来说,都是描述孔子的生活形态,以现代新闻报道的方式来看,也可以说是孔子生活的“花絮”,中间提到了孔子办外交的时候什么态度,对人的时候什么态度,上班的时候什么态度,开会的时候什么态度。这篇书过去的读书人看得很严重,现在看来是生活的艺术。孔子的学生们要为孔子立一个塑像,或演一出孔子的戏,就要拿这一篇好好研究了。 孔子于乡党,恂恂如也,似不能言者。其在宗庙朝廷,便便言,唯谨尔。 朝,与下大夫言,侃侃如也。与上大夫言,訚訚如也。君在,踧踖如也,与与如也。 君召使摈,色勃如也,足躩如也。揖所与立,左右手,衣前后,襜如也。趋进,翼如也。宾退,必复命,曰:宾不顾矣。 入公门,鞠躬如也,如不容。立不中门,行不履阈。过位,色勃如也,足躩如也,其言似不足者。摄齐升堂,鞠躬如也,屏气似不息者。出,降一等,逞颜色,怡怡如也。没阶,趋进,翼如也。复其位,踧踖如也。 执圭,鞠躬如也,如不胜,上如楫,下如授,勃如战色。足蹜蹜如有循。享礼,有容色。私觌,愉愉如也。 君子不以绀緅饰,红紫不以为亵服。当暑,袗絺绤,必表而出之。缁衣羔裘,素衣麂裘,黄衣狐裘,亵裘长,短右袂。必有寝衣,长一身有半。狐貉之厚以居。去丧,无所不佩。非惟裳,必杀之。羔裘亥冠,不以吊。吉月,必朝服而朝。 齐必有明衣,布。齐必变食,居必迁坐。 食不厌精,脍不厌细。食饐而餲,鱼馁而肉败,不食。色恶不食,臭恶不食。失饪不食,不时不食。割不正不食。不得其酱不食。肉虽多,不使胜食气。惟酒无量,不及乱。沽酒市脯不食。不撤姜食,不多食。祭于公,不宿肉。祭肉不出三日,出三日,不食之矣。食不语,寝不言。虽疏食菜羹瓜祭,必齐如也。 席不正不坐。 乡人饮酒,杖者出,斯出矣。乡人傩,朝服而立于阼阶。 问人于他邦。再拜而送之。康子馈药,拜而受之。曰:丘未达,不敢尝。 厩焚,子退朝,曰:伤人乎?不问马。 君赐食,必正席先尝之。君赐腥,必熟而荐之。君赐生,必畜之。侍食于君,君祭,先饭。疾,君视之,东首,加朝服拖绅。君命召,不俟驾行矣。 入太庙,每事问。 朋友死,无所归。曰:于我殡。朋友之馈,虽车马,非祭肉,不拜。 寝不尸,居不容。见齐衰者,虽狎必变。见冕者与瞽者,虽亵必以貌。凶服者式之。式负版者。有盛馔,必变色而作。迅雷,风烈必变。 升车,必正立执绥。车中不内顾,不疾言,不亲指。 色斯举矣。翔而后集。曰:山梁雌雉,时哉!时哉!子路共之,三嗅而作。 《乡党》的歇后语 现在讲这一篇书很难讲,要想讲得好,除非由人扮演出一个孔子,拍成电影。但能担任这角色的演员则很难,就像电影上的耶稣,很少出现他的正面,很难传神。有一个笑话,以前有一个老迂夫子,认为一个人只要做到《论语》里面一两句话,就终身受用无穷。当下就有一个年轻人说,我就做到了两句,老夫子马上改容相敬,立刻请教他做到了哪两句,年轻人说“食不厌精,脍不厌细”,我就完全照做了。这只是一个笑话。这些生活上的描写,都放在《乡党》篇中,这是说孔子的生活习惯,代表了他学问的精神,表示他的言行一致,这是《乡党》篇的第一个观念。而第二个观念,在以前看不出这篇的道理,现在我们看到年轻人,穿衣服不会穿,讲话不会讲,吃东西不会吃,走路也不会走,才知道《乡党》这一篇,把孔子的生活形态记下来,的确有道理。还有第三点,我们可以看到的,孔子是讲仁、讲孝、讲忠的,这也就反映出春秋战国时代,社会的人心太坏,不忠不孝,不仁不义的人太多了。同样的一个道理来看《乡党》,为什么把孔子的生活形态,记载得这么多?就是那个时代的青年和现在一样,生活的礼仪不知道,有学问的不一定处得合适,待人处世之间,什么立场应该什么态度?应该怎样说话?都不知道。就是现在,一般人以为美国人生活形态很随便,其实他们的上流社会、领导阶层,还是端端正正的打领带,服装整齐,还是非常讲礼。所以真正的学问,还是要自己用智慧去发掘。《乡党》这一篇,我们就不讨论了,全部《论语》就到此结束。 总之,万事都从作人开始,一个人生,无论做什么事业——做官、经商、做学者、做平民,都是要作人。事业的升沉成败,各有变化不同。但无论如何,总要作人。《乡党》一篇,记载孔子如何作人。后世的人们,敬重他的成就便尊称他所谓“圣人”。人人都可成圣,只看自己如何做到圣地的成就。
Java
package com.jy.controller.workflow.online.apply; import com.jy.common.ajax.AjaxRes; import com.jy.common.utils.DateUtils; import com.jy.common.utils.base.Const; import com.jy.common.utils.security.AccountShiroUtil; import com.jy.controller.base.BaseController; import com.jy.entity.attendance.WorkRecord; import com.jy.entity.oa.overtime.Overtime; import com.jy.entity.oa.patch.Patch; import com.jy.entity.oa.task.TaskInfo; import com.jy.service.oa.activiti.ActivitiDeployService; import com.jy.service.oa.overtime.OvertimeService; import com.jy.service.oa.patch.PatchService; import com.jy.service.oa.task.TaskInfoService; import org.activiti.engine.IdentityService; import org.activiti.engine.RuntimeService; import org.activiti.engine.TaskService; import org.activiti.engine.impl.persistence.entity.ExecutionEntity; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Task; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 补卡页面 */ @Controller @RequestMapping(value = "/backstage/workflow/online/patch/") public class PatchController extends BaseController<Object> { private static final String SECURITY_URL = "/backstage/workflow/online/patch/index"; @Autowired private RuntimeService runtimeService; @Autowired private TaskService taskService; @Autowired private TaskInfoService taskInfoService; @Autowired private IdentityService identityService; @Autowired private PatchService patchService; @Autowired private ActivitiDeployService activitiDeployService; /** * 补卡列表 */ @RequestMapping(value = "index") public String index(org.springframework.ui.Model model) { if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) { model.addAttribute("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION)); return "/system/workflow/online/apply/patch"; } return Const.NO_AUTHORIZED_URL; } /** * 启动流程 */ @RequestMapping(value = "start", method = RequestMethod.POST) @ResponseBody public AjaxRes startWorkflow(Patch o) { AjaxRes ar = getAjaxRes(); if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_MENU, SECURITY_URL))) { try { String currentUserId = AccountShiroUtil.getCurrentUser().getAccountId(); String[] approvers = o.getApprover().split(","); Map<String, Object> variables = new HashMap<String, Object>(); for (int i = 0; i < approvers.length; i++) { variables.put("approver" + (i + 1), approvers[i]); } String workflowKey = "patch"; identityService.setAuthenticatedUserId(currentUserId); Date now = new Date(); ProcessInstance processInstance = runtimeService.startProcessInstanceByKeyAndTenantId(workflowKey, variables, getCompany()); String pId = processInstance.getId(); String leaveID = get32UUID(); o.setPid(pId); o.setAccountId(currentUserId); o.setCreatetime(now); o.setIsvalid(0); o.setName(AccountShiroUtil.getCurrentUser().getName()); o.setId(leaveID); patchService.insert(o); Task task = taskService.createTaskQuery().processInstanceId(pId).singleResult(); String processDefinitionName = ((ExecutionEntity) processInstance).getProcessInstance().getProcessDefinition().getName(); String subkect = processDefinitionName + "-" + AccountShiroUtil.getCurrentUser().getName() + "-" + DateUtils.formatDate(now, "yyyy-MM-dd HH:mm"); //开始流程 TaskInfo taskInfo = new TaskInfo(); taskInfo.setId(get32UUID()); taskInfo.setBusinesskey(leaveID); taskInfo.setCode("start"); taskInfo.setName("发起申请"); taskInfo.setStatus(0); taskInfo.setPresentationsubject(subkect); taskInfo.setAttr1(processDefinitionName); taskInfo.setCreatetime(DateUtils.addSeconds(now, -1)); taskInfo.setCompletetime(DateUtils.addSeconds(now, -1)); taskInfo.setCreator(currentUserId); taskInfo.setAssignee(currentUserId); taskInfo.setTaskid("0"); taskInfo.setPkey(workflowKey); taskInfo.setExecutionid("0"); taskInfo.setProcessinstanceid(processInstance.getId()); taskInfo.setProcessdefinitionid(processInstance.getProcessDefinitionId()); taskInfoService.insert(taskInfo); //第一级审批流程 taskInfo.setId(get32UUID()); taskInfo.setCode(processInstance.getActivityId()); taskInfo.setName(task.getName()); taskInfo.setStatus(1); taskInfo.setTaskid(task.getId()); taskInfo.setCreatetime(now); taskInfo.setCompletetime(null); taskInfo.setAssignee(approvers[0]); taskInfoService.insert(taskInfo); ar.setSucceedMsg("发起补卡申请成功!"); } catch (Exception e) { logger.error(e.toString(), e); ar.setFailMsg("启动流程失败"); } finally { identityService.setAuthenticatedUserId(null); } } return ar; } }
Java
# grunt-tslint [![NPM version](https://badge.fury.io/js/grunt-tslint.svg)](https://www.npmjs.com/package/grunt-tslint) [![Downloads](http://img.shields.io/npm/dm/grunt-tslint.svg)](https://npmjs.org/package/grunt-tslint) > A grunt plugin for [tslint](https://github.com/palantir/tslint). ## Getting Started This plugin requires [Grunt](http://gruntjs.com/) `~0.4.1` and [tslint](https://github.com/palantir/tslint) `~4.0.0` ``` npm install grunt-tslint --save-dev ``` Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript: ``` grunt.loadNpmTasks("grunt-tslint"); ``` ## The "tslint" task ### Overview In your project's `Gruntfile.js`, add a section named `tslint` to the data object passed into `grunt.initConfig()`: ```js grunt.initConfig({ tslint: { options: { // Task-specific options go here. }, your_target: { // Target-specific file lists and/or options go here. }, }, }) ``` ### Options * `options.configuration: Object | string` - A TSLint configuration; can either be a JSON configuration object or a path to a tslint.json config file. * `options.project: string` - `tsconfig.json` file location. If provided type checking will be enabled. * `options.force: boolean` - If `true`, the task will suceed even if lint failures are found. Defaults to `false`. * `options.fix: boolean` - If `true`, fixes linting errors for select rules. This may overwrite linted files. Defaults to `false`. ### Usage Example ```js grunt.initConfig({ tslint: { options: { // can be a configuration object or a filepath to tslint.json configuration: "tslint.json", // If set to true, tslint errors will be reported, but not fail the task // If set to false, tslint errors will be reported, and the task will fail force: false, fix: false }, files: { src: [ "src/file1.ts", "src/file2.ts" ] } } }) ``` ## Contributing In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).
Java
<!DOCTYPE html> <html> <head> <title>try chat(JAX-RS)</title> <meta charset="UTF-8"> <link rel="stylesheet" href="../webjars/bootstrap/3.3.1/css/bootstrap.min.css" /> <link rel="stylesheet" href="../resources/css/style.css" /> <script type='text/javascript' src="../webjars/jquery/2.1.1/jquery.min.js"></script> <script type='text/javascript' src="../webjars/bootstrap/3.3.1/js/bootstrap.min.js"></script> <script type='text/javascript' src="../webjars/vue/0.11.0/vue.min.js"></script> <script type='text/javascript' src="../resources/js/common.js"></script> </head> <body> <div class="container"> <div class="jumbotron"> <h1>サンプルチャット JAX-RS</h1> <form id="form" class="login" v-on="submit:join"> <span id="error" >{{error_message}}</span> <div id="nameFg" class="form-group {{name_error_css}}"> <label for="name" class="control-label">名前 <span>{{name_message}}</span></label> <input id="name" name="name" placeholder="表示名を入力" type="text" class="form-control" v-model="name" /> </div> <div id="emailFg" class="form-group {{email_error_css}}"> <label for="email" class="control-label ">Gravatarメールアドレス <span>{{email_message}}</span></label> <input id="email" name="email" placeholder="Gravatarのイメージを使用する場合入力" type="email" class="form-control" v-model="email" /> </div> <input type="submit" value="join" class="btn btn-default" /> </form> <div> <a href="../" class="btn btn-link">JSF版へ</a> </div> </div> </div> <script type='text/javascript' src="../resources/js/vm_index.js"></script> </body> </html>
Java
var searchData= [ ['interactiontype',['InteractionType',['../class_student_record.html#a00e060bc8aa9829e5db087e2cba21009',1,'StudentRecord']]] ];
Java
/* * Copyright 2010-2011 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.metrics.eventtracker; import com.google.inject.Guice; import com.google.inject.Injector; import com.ning.metrics.serialization.event.ThriftToThriftEnvelopeEvent; import com.ning.metrics.serialization.writer.SyncType; import org.joda.time.DateTime; import org.skife.config.ConfigurationObjectFactory; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.io.File; import java.util.UUID; @Test(enabled = false) public class TestIntegration { private final File tmpDir = new File(System.getProperty("java.io.tmpdir"), "collector"); @SuppressWarnings("unused") @BeforeTest(alwaysRun = true) private void setupTmpDir() { if (!tmpDir.exists() && !tmpDir.mkdirs()) { throw new RuntimeException("Failed to create: " + tmpDir); } if (!tmpDir.isDirectory()) { throw new RuntimeException("Path points to something that's not a directory: " + tmpDir); } } @SuppressWarnings("unused") @AfterTest(alwaysRun = true) private void cleanupTmpDir() { tmpDir.delete(); } @Test(groups = "slow", enabled = false) public void testGuiceThrift() throws Exception { System.setProperty("eventtracker.type", "SCRIBE"); System.setProperty("eventtracker.directory", tmpDir.getAbsolutePath()); System.setProperty("eventtracker.scribe.host", "127.0.0.1"); System.setProperty("eventtracker.scribe.port", "7911"); final Injector injector = Guice.createInjector(new CollectorControllerModule()); final CollectorController controller = injector.getInstance(CollectorController.class); final ScribeSender sender = (ScribeSender) injector.getInstance(EventSender.class); sender.createConnection(); fireThriftEvents(controller); sender.close(); } @Test(groups = "slow", enabled = false) public void testScribeFactory() throws Exception { System.setProperty("eventtracker.type", "COLLECTOR"); System.setProperty("eventtracker.directory", tmpDir.getAbsolutePath()); System.setProperty("eventtracker.collector.host", "127.0.0.1"); System.setProperty("eventtracker.collector.port", "8080"); final EventTrackerConfig config = new ConfigurationObjectFactory(System.getProperties()).build(EventTrackerConfig.class); final CollectorController controller = ScribeCollectorFactory.createScribeController( config.getScribeHost(), config.getScribePort(), config.getScribeRefreshRate(), config.getScribeMaxIdleTimeInMinutes(), config.getSpoolDirectoryName(), config.isFlushEnabled(), config.getFlushIntervalInSeconds(), SyncType.valueOf(config.getSyncType()), config.getSyncBatchSize(), config.getMaxUncommittedWriteCount(), config.getMaxUncommittedPeriodInSeconds() ); fireThriftEvents(controller); } private void fireThriftEvents(final CollectorController controller) throws Exception { controller.offerEvent(ThriftToThriftEnvelopeEvent.extractEvent("thrift", new DateTime(), new Click(UUID.randomUUID().toString(), new DateTime().getMillis(), "user agent"))); Assert.assertEquals(controller.getEventsReceived().get(), 1); Assert.assertEquals(controller.getEventsLost().get(), 0); controller.commit(); controller.flush(); Thread.sleep(5000); } }
Java
// Copyright (c) 2008, Google Inc. // 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 Google Inc. 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 // OWNER 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 <base.h> #include "client/windows/crash_generation/minidump_generator.h" #include <cassert> #include "client/windows/common/auto_critical_section.h" #include "common/windows/guid_string.h" using std::wstring; namespace google_breakpad { MinidumpGenerator::MinidumpGenerator(const wstring& dump_path) : dbghelp_module_(NULL), rpcrt4_module_(NULL), dump_path_(dump_path), write_dump_(NULL), create_uuid_(NULL) { InitializeCriticalSection(&module_load_sync_); InitializeCriticalSection(&get_proc_address_sync_); } MinidumpGenerator::~MinidumpGenerator() { if (dbghelp_module_) { FreeLibrary(dbghelp_module_); } if (rpcrt4_module_) { FreeLibrary(rpcrt4_module_); } DeleteCriticalSection(&get_proc_address_sync_); DeleteCriticalSection(&module_load_sync_); } bool MinidumpGenerator::WriteMinidump(HANDLE process_handle, DWORD process_id, DWORD thread_id, DWORD requesting_thread_id, EXCEPTION_POINTERS* exception_pointers, MDRawAssertionInfo* assert_info, MINIDUMP_TYPE dump_type, bool is_client_pointers, wstring* dump_path) { MiniDumpWriteDumpType write_dump = GetWriteDump(); if (!write_dump) { return false; } wstring dump_file_path; if (!GenerateDumpFilePath(&dump_file_path)) { return false; } // If the client requests a full memory dump, we will write a normal mini // dump and a full memory dump. Both dump files use the same uuid as file // name prefix. bool full_memory_dump = (dump_type & MiniDumpWithFullMemory) != 0; wstring full_dump_file_path; if (full_memory_dump) { full_dump_file_path.assign(dump_file_path); full_dump_file_path.resize(full_dump_file_path.size() - 4); // strip .dmp full_dump_file_path.append(TEXT("-full.dmp")); } HANDLE dump_file = CreateFile(dump_file_path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (dump_file == INVALID_HANDLE_VALUE) { return false; } HANDLE full_dump_file = INVALID_HANDLE_VALUE; if (full_memory_dump) { full_dump_file = CreateFile(full_dump_file_path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (full_dump_file == INVALID_HANDLE_VALUE) { CloseHandle(dump_file); return false; } } MINIDUMP_EXCEPTION_INFORMATION* dump_exception_pointers = NULL; MINIDUMP_EXCEPTION_INFORMATION dump_exception_info; // Setup the exception information object only if it's a dump // due to an exception. if (exception_pointers) { dump_exception_pointers = &dump_exception_info; dump_exception_info.ThreadId = thread_id; dump_exception_info.ExceptionPointers = exception_pointers; dump_exception_info.ClientPointers = is_client_pointers; } // Add an MDRawBreakpadInfo stream to the minidump, to provide additional // information about the exception handler to the Breakpad processor. // The information will help the processor determine which threads are // relevant. The Breakpad processor does not require this information but // can function better with Breakpad-generated dumps when it is present. // The native debugger is not harmed by the presence of this information. MDRawBreakpadInfo breakpad_info = {0}; if (!is_client_pointers) { // Set the dump thread id and requesting thread id only in case of // in-process dump generation. breakpad_info.validity = MD_BREAKPAD_INFO_VALID_DUMP_THREAD_ID | MD_BREAKPAD_INFO_VALID_REQUESTING_THREAD_ID; breakpad_info.dump_thread_id = thread_id; breakpad_info.requesting_thread_id = requesting_thread_id; } // Leave room in user_stream_array for a possible assertion info stream. MINIDUMP_USER_STREAM user_stream_array[2]; user_stream_array[0].Type = MD_BREAKPAD_INFO_STREAM; user_stream_array[0].BufferSize = sizeof(breakpad_info); user_stream_array[0].Buffer = &breakpad_info; MINIDUMP_USER_STREAM_INFORMATION user_streams; user_streams.UserStreamCount = 1; user_streams.UserStreamArray = user_stream_array; MDRawAssertionInfo* actual_assert_info = assert_info; MDRawAssertionInfo client_assert_info = {0}; if (assert_info) { // If the assertion info object lives in the client process, // read the memory of the client process. if (is_client_pointers) { SIZE_T bytes_read = 0; if (!ReadProcessMemory(process_handle, assert_info, &client_assert_info, sizeof(client_assert_info), &bytes_read)) { CloseHandle(dump_file); if (full_dump_file != INVALID_HANDLE_VALUE) CloseHandle(full_dump_file); return false; } if (bytes_read != sizeof(client_assert_info)) { CloseHandle(dump_file); if (full_dump_file != INVALID_HANDLE_VALUE) CloseHandle(full_dump_file); return false; } actual_assert_info = &client_assert_info; } user_stream_array[1].Type = MD_ASSERTION_INFO_STREAM; user_stream_array[1].BufferSize = sizeof(MDRawAssertionInfo); user_stream_array[1].Buffer = actual_assert_info; ++user_streams.UserStreamCount; } bool result_minidump = write_dump( process_handle, process_id, dump_file, static_cast<MINIDUMP_TYPE>((dump_type & (~MiniDumpWithFullMemory)) | MiniDumpNormal), exception_pointers ? &dump_exception_info : NULL, &user_streams, NULL) != FALSE; bool result_full_memory = true; if (full_memory_dump) { result_full_memory = write_dump( process_handle, process_id, full_dump_file, static_cast<MINIDUMP_TYPE>(dump_type & (~MiniDumpNormal)), exception_pointers ? &dump_exception_info : NULL, &user_streams, NULL) != FALSE; } bool result = result_minidump && result_full_memory; CloseHandle(dump_file); if (full_dump_file != INVALID_HANDLE_VALUE) CloseHandle(full_dump_file); // Store the path of the dump file in the out parameter if dump generation // succeeded. if (result && dump_path) { *dump_path = dump_file_path; } return result; } HMODULE MinidumpGenerator::GetDbghelpModule() { AutoCriticalSection lock(&module_load_sync_); if (!dbghelp_module_) { dbghelp_module_ = LoadLibrary(TEXT("dbghelp.dll")); } return dbghelp_module_; } MinidumpGenerator::MiniDumpWriteDumpType MinidumpGenerator::GetWriteDump() { AutoCriticalSection lock(&get_proc_address_sync_); if (!write_dump_) { HMODULE module = GetDbghelpModule(); if (module) { FARPROC proc = GetProcAddress(module, "MiniDumpWriteDump"); write_dump_ = reinterpret_cast<MiniDumpWriteDumpType>(proc); } } return write_dump_; } HMODULE MinidumpGenerator::GetRpcrt4Module() { AutoCriticalSection lock(&module_load_sync_); if (!rpcrt4_module_) { rpcrt4_module_ = LoadLibrary(TEXT("rpcrt4.dll")); } return rpcrt4_module_; } MinidumpGenerator::UuidCreateType MinidumpGenerator::GetCreateUuid() { AutoCriticalSection lock(&module_load_sync_); if (!create_uuid_) { HMODULE module = GetRpcrt4Module(); if (module) { FARPROC proc = GetProcAddress(module, "UuidCreate"); create_uuid_ = reinterpret_cast<UuidCreateType>(proc); } } return create_uuid_; } bool MinidumpGenerator::GenerateDumpFilePath(wstring* file_path) { UUID id = {0}; UuidCreateType create_uuid = GetCreateUuid(); if(!create_uuid) { return false; } create_uuid(&id); wstring id_str = GUIDString::GUIDToWString(&id); *file_path = dump_path_ + TEXT("\\") + id_str + TEXT(".dmp"); return true; } } // namespace google_breakpad
Java
package com.nosolojava.fsm.impl.runtime.executable.basic; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.nosolojava.fsm.runtime.Context; import com.nosolojava.fsm.runtime.executable.Elif; import com.nosolojava.fsm.runtime.executable.Else; import com.nosolojava.fsm.runtime.executable.Executable; import com.nosolojava.fsm.runtime.executable.If; public class BasicIf extends BasicConditional implements If { private static final long serialVersionUID = -415238773021486012L; private final List<Elif> elifs = new ArrayList<Elif>(); private final Else elseOperation; public BasicIf(String condition) { this(condition, null, null, null); } public BasicIf(String condition, List<Executable> executables) { this(condition, null, null, executables); } public BasicIf(String condition, Else elseOperation, List<Executable> executables) { this(condition, null, elseOperation, executables); } public BasicIf(String condition, List<Elif> elifs, Else elseOperation, List<Executable> executables) { super(condition, executables); if (elifs != null) { this.elifs.addAll(elifs); } this.elseOperation = elseOperation; } @Override public boolean runIf(Context context) { boolean result = false; // if condition fails if (super.runIf(context)) { result = true; } else { // try with elifs boolean enterElif = false; Iterator<Elif> iterElif = elifs.iterator(); Elif elif; while (!enterElif && iterElif.hasNext()) { elif = iterElif.next(); enterElif = elif.runIf(context); } // if no elif and else if (!enterElif && this.elseOperation != null) { elseOperation.run(context); } } return result; } public List<Elif> getElifs() { return this.elifs; } public void addElif(Elif elif) { this.elifs.add(elif); } public void addElifs(List<Elif> elifs) { this.elifs.addAll(elifs); } public void clearAndSetElifs(List<Elif> elifs) { this.elifs.clear(); addElifs(elifs); } }
Java
/** * Copyright 2015 Santhosh Kumar Tekuri * * The JLibs authors license this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package jlibs.wamp4j.spi; import java.io.InputStream; public interface Listener{ public void onMessage(WAMPSocket socket, MessageType type, InputStream is); public void onReadComplete(WAMPSocket socket); public void readyToWrite(WAMPSocket socket); public void onError(WAMPSocket socket, Throwable error); public void onClose(WAMPSocket socket); }
Java
package me.littlepanda.dadbear.core.queue; import java.util.Queue; /** * @author 张静波 myplaylife@icloud.com * */ public interface DistributedQueue<T> extends Queue<T> { /** * <p>如果使用无参构造函数,需要先调用这个方法,队列才能使用</p> * @param queue_name * @param clazz */ abstract public void init(String queue_name, Class<T> clazz); }
Java
# Changelog [![GitHub commits since latest release](https://img.shields.io/github/commits-since/ligato/vpp-agent/latest.svg?style=flat-square)](https://github.com/ligato/vpp-agent/compare/v3.2.0...master) ## Release Notes - [v3.2.0](#v3.2.0) - [v3.1.0](#v3.1.0) - [v3.0.0](#v3.0.0) - [v3.0.1](#v3.0.1) - [v2.5.0](#v2.5.0) - [v2.5.1](#v2.5.1) - [v2.4.0](#v2.4.0) - [v2.3.0](#v2.3.0) - [v2.2.0](#v2.2.0) - [v2.2.0-beta](#v2.2.0-beta) - [v2.1.0](#v2.1.0) - [v2.1.1](#v2.1.1) - [v2.0.0](#v2.0.0) - [v2.0.1](#v2.0.1) - [v2.0.2](#v2.0.2) - [v1.8.0](#v1.8.0) - [v1.8.1](#v1.8.1) - [v1.7.0](#v1.7.0) - [v1.6.0](#v1.6.0) - [v1.5.0](#v1.5.0) - [v1.5.1](#v1.5.1) - [v1.5.2](#v1.5.2) - [v1.4.0](#v1.4.0) - [v1.4.1](#v1.4.1) - [v1.3.0](#v1.3.0) - [v1.2.0](#v1.2.0) - [v1.1.0](#v1.1.0) - [v1.0.8](#v1.0.8) - [v1.0.7](#v1.0.7) - [v1.0.6](#v1.0.6) - [v1.0.5](#v1.0.5) - [v1.0.4](#v1.0.4) - [v1.0.3](#v1.0.3) - [v1.0.2](#v1.0.2) <!--- RELEASE CHANGELOG TEMPLATE: <a name="vX.Y.Z"></a> # [X.Y.Z](https://github.com/ligato/vpp-agent/compare/vX-1.Y-1.Z-1...vX.Y.Z) (YYYY-MM-DD) ### COMPATIBILITY ### KNOWN ISSUES ### BREAKING CHANGES ### Bug Fixes ### Features ### Improvements ### Docker Images ### Documentation --> <a name="v3.2.0"></a> # [3.2.0](https://github.com/ligato/vpp-agent/compare/v3.1.0...v3.2.0) (2020-10-XX) ### COMPATIBILITY - VPP 20.09 (compatible) - VPP 20.05 (default) - VPP 20.01 (backwards compatible) - VPP 19.08 (backwards compatible) - ~~VPP 19.04~~ (no longer supported) ### Bug Fixes - Fixes and improvements for agentctl and models [#1643](https://github.com/ligato/vpp-agent/pull/1643) - Fix creation of multiple ipip tunnels [#1650](https://github.com/ligato/vpp-agent/pull/1650) - Fix IPSec tun protect + add IPSec e2e test [#1654](https://github.com/ligato/vpp-agent/pull/1654) - Fix bridge domain dump for VPP 20.05 [#1663](https://github.com/ligato/vpp-agent/pull/1663) - Fix IPSec SA add/del in VPP 20.05 [#1664](https://github.com/ligato/vpp-agent/pull/1664) - Update expected output of agentctl status command [#1673](https://github.com/ligato/vpp-agent/pull/1673) - vpp/ifplugin: Recognize interface name prefix "tun" as TAP [#1674](https://github.com/ligato/vpp-agent/pull/1674) - Fix IPv4 link-local IP address handling [#1715](https://github.com/ligato/vpp-agent/pull/1715) - maps caching prometheus gauges weren't really used [#1741](https://github.com/ligato/vpp-agent/pull/1741) - Permit agent to run even when VPP stats are unavailable [#1712](https://github.com/ligato/vpp-agent/pull/1712) - Fix grpc context timeout for agentctl import command [#1718](https://github.com/ligato/vpp-agent/pull/1718) - Changed nat44 pool key to prevent possible key collisions [#1725](https://github.com/ligato/vpp-agent/pull/1725) - Remove forced delay for linux interface notifications [#1742](https://github.com/ligato/vpp-agent/pull/1742) ### Features - agentctl: Add config get/update commands [#1709](https://github.com/ligato/vpp-agent/pull/1709) - agentctl: Support specific history seq num and improve layout [#1717](https://github.com/ligato/vpp-agent/pull/1717) - agentctl: Add config.resync subcommand (with resync) [#1642](https://github.com/ligato/vpp-agent/pull/1642) - IP Flow Information eXport (IPFIX) plugin [#1649](https://github.com/ligato/vpp-agent/pull/1649) - Add IPIP & IPSec point-to-multipoint support [#1669](https://github.com/ligato/vpp-agent/pull/1669) - Wireguard plugin support [#1731](https://github.com/ligato/vpp-agent/pull/1731) - Add tunnel mode support for VPP TAP interfaces [#1671](https://github.com/ligato/vpp-agent/pull/1671) - New REST endpoint for retrieving version of Agent [#1670](https://github.com/ligato/vpp-agent/pull/1670) - Add support for IPv6 ND address autoconfig [#1676](https://github.com/ligato/vpp-agent/pull/1676) - Add VRF field to proxy ARP range [#1672](https://github.com/ligato/vpp-agent/pull/1672) - Switch to new proto v2 (google.golang.org/protobuf) [#1691](https://github.com/ligato/vpp-agent/pull/1691) - ipsec: allow configuring salt for encryption algorithm [#1698](https://github.com/ligato/vpp-agent/pull/1698) - gtpu: Add RemoteTeid to GTPU interface [#1719](https://github.com/ligato/vpp-agent/pull/1719) - Added support for NAT44 static mapping twice-NAT pool IP address reference [#1728](https://github.com/ligato/vpp-agent/pull/1728) - add IP protocol number to ACL model [#1726](https://github.com/ligato/vpp-agent/pull/1726) - gtpu: Add support for arbitrary DecapNextNode [#1721](https://github.com/ligato/vpp-agent/pull/1721) - configurator: Add support for waiting until config update is done [#1734](https://github.com/ligato/vpp-agent/pull/1734) - telemetry: Add reading VPP threads to the telemetry plugin [#1753](https://github.com/ligato/vpp-agent/pull/1753) - linux: Add support for Linux VRFs [#1744](https://github.com/ligato/vpp-agent/pull/1744) - VRRP support [#1744](https://github.com/ligato/vpp-agent/pull/1744) ### Improvements - perf: Performance enhancement for adding many rules to Linux IP… [#1644](https://github.com/ligato/vpp-agent/pull/1644) - Improve testing process for e2e/integration tests [#1757](https://github.com/ligato/vpp-agent/pull/1757) ### Documentation - docs: Add example for developing agents with custom VPP plugins [#1665](https://github.com/ligato/vpp-agent/pull/1665) ### Other - Delete unused REST handler for VPP commands [#1677](https://github.com/ligato/vpp-agent/pull/1677) - separate model for IPSec Security Policies [#1679](https://github.com/ligato/vpp-agent/pull/1679) - do not mark host_if_name for AF_PACKET as deprecated [#1745](https://github.com/ligato/vpp-agent/pull/1745) - Store interface internal name & dev type as metadata [#1706](https://github.com/ligato/vpp-agent/pull/1706) - Check if HostIfName contains non-printable characters [#1662](https://github.com/ligato/vpp-agent/pull/1662) - Fix error message for duplicate keys [#1659](https://github.com/ligato/vpp-agent/pull/1659) <a name="v3.1.0"></a> # [3.1.0](https://github.com/ligato/vpp-agent/compare/v3.0.0...v3.1.0) (2020-03-13) ### BREAKING CHANGES * Switch cn-infra dependency to using vanity import path [#1620](https://github.com/ligato/vpp-agent/pull/1620) To migrate, replace all cn-infra import paths (`github.com/ligato/cn-infra` -> `go.ligato.io/cn-infra/v2`) To update cn-infra dependency, run `go get -u go.ligato.io/cn-infra/v2@master`. ### Bug Fixes * Add missing models to ConfigData [#1625](https://github.com/ligato/vpp-agent/pull/1625) * Fix watching VPP events [#1640](https://github.com/ligato/vpp-agent/pull/1640) ### Features * Allow customizing polling from stats poller [#1634](https://github.com/ligato/vpp-agent/pull/1634) * IPIP tunnel + IPSec tunnel protection support [#1638](https://github.com/ligato/vpp-agent/pull/1638) * Add prometheus metrics to govppmux [#1626](https://github.com/ligato/vpp-agent/pull/1626) * Add prometheus metrics to kvscheduler [#1630](https://github.com/ligato/vpp-agent/pull/1630) ### Improvements * Improve performance testing suite [#1630](https://github.com/ligato/vpp-agent/pull/1630) <a name="v3.0.1"></a> # [3.0.1](https://github.com/ligato/vpp-agent/compare/v3.0.0...v3.0.1) (2020-02-20) ### Bug Fixes * Add missing models to ConfigData (https://github.com/ligato/vpp-agent/pull/1625) <a name="v3.0.0"></a> # [3.0.0](https://github.com/ligato/vpp-agent/compare/v2.5.0...master) (2020-02-10) ### COMPATIBILITY - **VPP 20.01** (default) - **VPP 19.08.1** (recommended) - **VPP 19.04.4** ### KNOWN ISSUES - VPP L3 plugin: `IPScanNeighbor` was disabled for VPP 20.01 due to VPP API changes (will be implemented later using new model) - VPP NAT plugin: `VirtualReassembly` in `Nat44Global` was disabled for VPP 20.01 due to VPP API changes (will be implemented later in VPP L3 plugin using new model) ### BREAKING CHANGES - migrate from dep to Go modules for dependency management and remove vendor directory [#1599](https://github.com/ligato/vpp-agent/pull/1599) - use vanity import path `go.ligato.io/vpp-agent/v3` in Go files [#1599](https://github.com/ligato/vpp-agent/pull/1599) - move all _.proto_ files into `proto/ligato` directory and add check for breaking changes [#1599](https://github.com/ligato/vpp-agent/pull/1599) ### Bug Fixes - check for duplicate Linux interface IP address [#1586](https://github.com/ligato/vpp-agent/pull/1586) ### New Features - VPP interface plugin: Allow AF-PACKET to reference target Linux interface via logical name [#1616](https://github.com/ligato/vpp-agent/pull/1616) - VPP L3 plugin: add support for L3 cross-connects [#1602](https://github.com/ligato/vpp-agent/pull/1602) - VPP L3 plugin: IP flow hash settings support [#1610](https://github.com/ligato/vpp-agent/pull/1610) - VPP NAT plugin: NAT interface and AddressPool API changes [#1595](https://github.com/ligato/vpp-agent/pull/1595) - VPP plugins: support disabling VPP plugins [#1593](https://github.com/ligato/vpp-agent/pull/1593) - VPP client: add support for govpp proxy [#1593](https://github.com/ligato/vpp-agent/pull/1593) ### Improvements - optimize getting model keys, with up to 20% faster transactions [#1615](https://github.com/ligato/vpp-agent/pull/1615) - agentctl output formatting improvements (#1581, #1582, #1589) - generated VPP binary API now imports common types from `*_types` packages - development docker images now have smaller size (~400MB less) - start using Github Workflows for CI/CD pipeline - add gRPC reflection service <a name="v2.5.1"></a> # [2.5.1](https://github.com/ligato/vpp-agent/compare/v2.5.0...v2.5.1) (2019-12-06) ### COMPATIBILITY - **VPP 20.01-379** (`20.01-rc0~379-ga6b93eac5`) - **VPP 20.01-324** (`20.01-rc0~324-g66a332cf1`) - **VPP 19.08.1** (default) - **VPP 19.04** (backward compatible) - cn-infra v2.2 ### Bug Fixes * Fix linux interface dump ([#1577](https://github.com/ligato/vpp-agent/pull/1577)) * Fix VRF for SR policy ([#1578](https://github.com/ligato/vpp-agent/pull/1578)) <a name="v2.5.0"></a> # [2.5.0](https://github.com/ligato/vpp-agent/compare/v2.4.0...v2.5.0) (2019-11-29) ### Compatibility - **VPP 20.01-379** (`20.01-rc0~379-ga6b93eac5`) - **VPP 20.01-324** (`20.01-rc0~324-g66a332cf1`) - **VPP 19.08.1** (default) - **VPP 19.04** (backward compatible) - cn-infra v2.2 ### New Features * SRv6 global config (encap source address) * Support for Linux configuration dumping ### Bug Fixes * Update GoVPP with fix for stats conversion panic <a name="v2.4.0"></a> # [2.4.0](https://github.com/ligato/vpp-agent/compare/v2.3.0...v2.4.0) (2019-10-21) ### Compatibility - **VPP 20.01-379** (`20.01-rc0~379-ga6b93eac5`) - **VPP 20.01-324** (`20.01-rc0~324-g66a332cf1`) - **VPP 19.08.1** (default) - **VPP 19.04** (backward compatible) - cn-infra v2.2 ### New Features This release introduces compatibility with two different commits of the VPP 20.01. Previously compatible version was updated to commit `324-g66a332cf1`, and support for `379-ga6b93eac5` was added. Other previous versions remained. * [Telemetry][vpp-telemetry] - Added `StatsPoller` service periodically retrieving VPP stats. <a name="v2.3.0"></a> # [2.3.0](https://github.com/ligato/vpp-agent/compare/v2.2.0...v2.3.0) (2019-10-04) ### Compatibility - **VPP 20.01** (`20.01-rc0~161-ge5948fb49~b3570`) - **VPP 19.08.1** (default) - **VPP 19.04** (backward compatible) - cn-infra v2.2 VPP support for version 19.08 was updated to 19.08.1. Support for 19.01 was dropped in this release. ### Bug Fixes * Linux interfaces with 'EXISTING' type should be resynced properly. * Resolved issue with SRv6 removal. * AgentCTL dump command fixed. * ACL ICMP rule is now properly configured and data can be obtained using the ACL dump. * Missing dependency for SRv6 L2 steering fixed. * Fixed issue with possible division by zero and missing interface MTU. * Namespace plugin uses a Docker event listener instead of periodical polling. This should prevent cases where quickly started microservice container was not detected. ### New Features * [netalloc-plugin][netalloc-plugin] - A new plugin called netalloc which allows disassociating topology from addressing in the network configuration. Interfaces, routes and other network objects' addresses can be symbolic references into the pool of allocated addresses known to netalloc plugin. See [model][netalloc-plugin-model] for more information. * [if-plugin][vpp-interface-plugin] - Added support for GRE tunnel interfaces. Choose the `GRE_TUNNEL` interface type with appropriate link data. * [agentctl][agentctl] - Many new features and enhancements added to the AgentCTL: * version is defined as a parameter for root command instead of the separate command * ETCD endpoints can be defined via the `ETCD_ENDPOINTS` environment variable * sub-command `config` supports `get/put/del` commands * `model` sub-commands improved * added VPP command to manage VPP instance Additionally, starting with this release the AgentCTL is a VPP-Agent main control tool and the vpp-agent-ctl was definitely removed. ### Improvements Many end-to-end tests introduced, gradually increasing VPP-Agent stability. * [if-plugin][vpp-interface-plugin] - IP addresses assigned by the DHCP are excluded from the interface address descriptor. - VPP-Agent now processes status change notifications labeled by the VPP as UNKNOWN. * [ns-plugin][linux-ns-plugin] - Dockerclient microservice polling replaced with an event listener. * [sr-plugin][sr-plugin] - SRv6 dynamic proxy routing now can be connected to a non-zero VRF table. <a name="v2.2.0"></a> # [2.2.0](https://github.com/ligato/vpp-agent/compare/v2.2.0-beta...v2.2.0) (2019-08-26) ### Compatibility - **VPP 19.08** (rc1) - **VPP 19.04** (default) - **VPP 19.01** (backward compatible) - cn-infra v2.2 ### Bug Fixes - CN-infra version updated to 2.2 contains a supervisor fix which should prevent the issue where the supervisor logging occasionally caused the agent to crash during large outputs. ### New Features * [if-plugin][vpp-interface-plugin] - Added option to configure SPAN records. Northbound data are formatted by the [SPAN model][span-model]. ### Improvements * [orchestrator][orchestrator-plugin] - Clientv2 is now recognized as separate data source by the orchestrator plugin. This feature allows to use the localclient together with other data sources. ### Documentation - Updated documentation comments in the protobuf API. <a name="v2.2.0-beta"></a> # [2.2.0-beta](https://github.com/ligato/vpp-agent/compare/v2.1.1...v2.2.0-beta) (2019-08-09) ### Compatibility - **VPP 19.08** (rc1) - **VPP 19.04** (default) - **VPP 19.01** (backward compatible) ### Bug Fixes * Fixed SRv6 localsid delete case for non-zero VRF tables. * Fixed interface IPv6 detection in the descriptor. * Various bugs fixed in KV scheduler TXN post-processing. * Interface plugin config names fixed, no stats publishers are now used by default. Instead, datasync is used (by default ETCD, Redis and Consul). * Rx-placement and rx-mode is now correctly dependent on interface link state. * Fixed crash for iptables rulechain with default microservice. * Punt dump fixed in all supported VPP versions. * Removal of registered punt sockets fixed after a resync. * Punt socket paths should no longer be unintentionally recreated. * IP redirect is now correctly dependent on RX interface. * Fixed IPSec security association configuration for tunnel mode. * Fixed URL for VPP metrics in telemetry plugin * Routes are now properly dependent on VRF. ### New Features * Defined new environment variable `DISABLE_INTERFACE_STATS` to generally disable interface plugin stats. * Defined new environment variable `RESYNC_TIMEOU` to override default resync timeout. * Added [ETCD ansible python plugin][ansible] with example playbook. Consult [readme](ansible/README.md) for more information. ### Improvements * [govppmux-plugin][govppmux-plugin] - GoVPPMux stats can be read with rest under path `/govppmux/stats`. - Added disabling of interface stats via the environment variable `DISABLE_INTERFACE_STATS`. - Added disabling of interface status publishing via environment variable `DISABLE_STATUS_PUBLISHING`. * [kv-scheduler][kv-scheduler] - Added some more performance improvements. - The same key can be no more matched by multiple descriptors. * [abf-plugin][vpp-abf-plugin] - ABF plugin was added to config data model and is now initialized in configurator. * [if-plugin][vpp-interface-plugin] - Interface rx-placement and rx-mode was enhanced and now allows per-queue configuration. - Added [examples](examples/kvscheduler/rxplacement) for rx-placement and rx-mode. * [nat-plugin][vpp-nat-plugin] - NAT example updated for VPP 19.04 * [l3-plugin][vpp-l3-plugin] - Route keys were changed to prevent collisions with some types of configuration. Route with outgoing interface now contains the interface name in the key. - Added support for DHCP proxy. A new descriptor allows calling CRUD operations to VPP DHCP proxy servers. * [punt-plugin][vpp-punt-plugin] - Added support for Punt exceptions. - IP redirect dump was implemented for VPP 19.08. * [Telemetry][vpp-telemetry] - Interface metrics added to telemetry plugin. Note that the URL for prometheus export was changed to `/metrics/vpp`. - Plugin configuration file now has an option to skip certain metrics. * [rest-plugin][rest-plugin] - Added support for IPSec plugin - Added support for punt plugin * [agentctl][agentctl] - We continuously update the new CTL tool. Various bugs were fixed some new features added. - Added new command `import` which can import configuration from file. ### Docker Images * The supervisor was replaced with VPP-Agent init plugin. * Images now use pre-built VPP images from [ligato/vpp-base](https://github.com/ligato/vpp-base) <a name="v2.1.1"></a> # [2.1.1](https://github.com/ligato/vpp-agent/compare/v2.1.0...v2.1.1) (2019-04-05) ### Compatibility - **VPP 19.04** (`stable/1904`, recommended) - **VPP 19.01** (backward compatible) ### Bug Fixes * Fixed IPv6 detection for Linux interfaces [#1355](https://github.com/ligato/vpp-agent/pull/1355). * Fixed config file names for ifplugin in VPP & Linux [#1341](https://github.com/ligato/vpp-agent/pull/1341). * Fixed setting status publishers from env var: `VPP_STATUS_PUBLISHERS`. ### Improvements * The start/stop timeouts for agent can be configured using env vars: `START_TIMEOUT=15s` and `STOP_TIMEOUT=5s`, with values parsed as duration. * ABF was added to the `ConfigData` message for VPP [#1356](https://github.com/ligato/vpp-agent/pull/1356). ### Docker Images * Images now install all compiled .deb packages from VPP (including `vpp-plugin-dpdk`). <a name="v2.1.0"></a> # [2.1.0](https://github.com/ligato/vpp-agent/compare/v2.0.2...v2.1.0) (2019-05-09) ### Compatibility - **VPP 19.04** (`stable/1904`, recommended) - **VPP 19.01** (backward compatible) - cn-infra v2.1 - Go 1.11 The VPP 18.10 was deprecated and is no longer compatible. ### BREAKING CHANGES * All non-zero VRF tables now must be explicitly created, providing a VRF proto-modeled data to the VPP-Agent. Otherwise, some configuration items will not be created as before (for example interface IP addresses). ### Bug Fixes * VPP ARP `retrieve` now also returns IPv6 entries. ### New Features * [govppmux-plugin][govppmux-plugin] - The GoVPPMux plugin configuration file contains a new option `ConnectViaShm`, which when set to `true` forces connecting to the VPP via shared memory prefix. This is an alternative to environment variable `GOVPPMUX_NOSOCK`. * [configurator][configurator-plugin] - The configurator plugin now collects statistics which are available via the `GetStats()` function or via REST on URL `/stats/configurator`. * [kv-scheduler][kv-scheduler] - Added transaction statistics. * [abf-plugin][vpp-abf-plugin] - Added new plugin ABF - ACL-based forwarding, providing an option to configure routing based on matching ACL rules. An ABF entry configures interfaces which will be attached, list of forwarding paths and associated access control list. * [if-plugin][vpp-interface-plugin] - Added support for Generic Segmentation Offload (GSO) for TAP interfaces. * [l3-plugin][vpp-l3-plugin] - A new model for VRF tables was introduced. Every VRF is defined by an index and an IP version, a new optional label was added. Configuration types using non-zero VRF now require it to be created, since the VRF is considered a dependency. VRFs with zero-index are present in the VPP by default and do not need to be configured (applies for both, IPv4 and IPv6). * [agentctl][agentctl] - This tool becomes obsolete and was completely replaced with a new implementation. Please note that the development of this tool is in the early stages, and functionality is quite limited now. New and improved functionality is planned for the next couple of releases since our goal is to have a single vpp-agent control utility. Because of this, we have also deprecated the vpp-agent-ctl tool which will be most likely removed in the next release. ### Improvements * [kv-scheduler][kv-scheduler] - The KV Scheduler received another performance improvements. * [if-plugin][vpp-interface-plugin] - Attempt to configure a Bond interface with already existing ID returns a non-retriable error. * [linux-if-plugin][linux-interface-plugin] - Before adding an IPv6 address to the Linux interface, the plugins will use `sysctl` to ensure the IPv6 is enabled in the target OS. ### Docker Images - Supervisord is started as a process with PID 1 ### Documentation - The ligato.io webpage is finally available, check out it [here][ligato.io]! We have also released a [new documentation site][ligato-docs] with a lot of new or updated articles, guides, tutorials and many more. Most of the README.md files scattered across the code were removed or updated and moved to the site. <a name="v2.0.2"></a> # [2.0.2](https://github.com/ligato/vpp-agent/compare/v2.0.1...v2.0.2) (2019-04-19) ### Compatibility - **VPP 19.01** (updated to `v19.01.1-14-g0f36ef60d`) - **VPP 18.10** (backward compatible) - cn-infra v2.0 - Go 1.11 This minor release brought compatibility with updated version of the VPP 19.01. <a name="v2.0.1"></a> # [2.0.1](https://github.com/ligato/vpp-agent/compare/v2.0.0...v2.0.1) (2019-04-05) ### Compatibility - **VPP 19.01** (compatible by default, recommended) - **VPP 18.10** (backward compatible) - cn-infra v2.0 - Go 1.11 ### Bug Fixes * Fixed bug where Linux network namespace was not reverted in some cases. * The VPP socketclient connection checks (and waits) for the socket file in the same manner as for the shared memory, giving the GoVPPMux more time to connect in case the VPP startup is delayed. Also errors occurred during the shm/socket file watch are now properly handled. * Fixed wrong dependency for SRv6 end functions referencing VRF tables (DT6,DT4,T). ### Improvements * [GoVPPMux][govppmux-plugin] - Added option to adjust the number of connection attempts and time delay between them. Seek `retry-connect-count` and `retry-connect-timeout` fields in [govpp.conf][govppmux-conf]. Also keep in mind the total time in which plugins can be initialized when using these fields. * [linux-if-plugin][linux-interface-plugin] - Default loopback MTU was set to 65536. * [ns-plugin][linux-ns-plugin] - Plugin descriptor returns `ErrEscapedNetNs` if Linux namespace was changed but not reverted back before returned to scheduler. ### Docker Images * Supervisord process is now started with PID=1 <a name="v2.0.0"></a> # [2.0.0](https://github.com/ligato/vpp-agent/compare/v1.8...v2.0.0) (2019-04-02) ### Compatibility - **VPP 19.01** (compatible by default, recommended) - **VPP 18.10** (backward compatible) - cn-infra v2.0 - Go 1.11 ### BREAKING CHANGES * All northbound models were re-written and simplified and most of them are no longer compatible with model data from v1. * The `v1` label from all vpp-agent keys was updated to `v2`. * Plugins using some kind of dependency on other VPP/Linux plugin (for example required interface) should be updated and handled by the KVScheduler. ### Bug Fixes * We expect a lot of known and unknown race-condition and plugin dependency related issues to be solved by the KV Scheduler. * MTU is omitted for the sub-interface type. * If linux plugin attempts to switch to non-existing namespace, it prints appropriate log message as warning, and continues with execution instead of interrupt it with error. * Punt socket path string is cleaned from unwanted characters. * Added VPE compatibility check for L3 plugin vppcalls. * The MAC address assigned to an af-packet interface is used from the host only if not provided from the configuration. * Fixed bug causing the agent to crash in an attempt to 'update' rx-placement with empty value. * Switch interface from zero to non-zero VRF causes VPP issues - this limitation was now restricted only to unnumbered interfaces. * IPSec tunnel dump now also retrieves integ/crypto keys. * Errored operation should no more publish to the index mapping. * Some obsolete Retval checks were removed. * Error caused by missing DPDK interface is no longer retryable. * Linux interface IP address without mask is now handled properly. * Fixed bug causing agent to crash when some VPP plugin we support was not loaded. * Fixed metrics retrieval in telemetry plugin. ### Known Issues * The bidirectional forwarding detection (aka BFD plugin) was removed. We plan to add it in one of the future releases. * The L4 plugin (application namespaces) was removed. * We experienced problems with the VPP with some messages while using socket client connection. The issue kind was that the reply message was not returned (GoVPP could not decode it). If you encounter similar error, please try to setup VPP connection using shared memory (see below). ### Features * Performance - The vpp-agent now supports connection via socket client (in addition to shared memory). The socket client connection provides higher performance and message throughput, thus it was set as default connection type. The shared memory is still available via the environment variable `GOVPPMUX_NOSOCK`. - Many other changes, benchmarking and profiling was done to improve vpp-agent experience. * Multi-VPP support - The VPP-agent can connect to multiple versions of the VPP with the same binary file without any additional building or code changes. See compatibility part to know which versions are supported. The list will be extended in the future. * Models - All vpp-agent models were reviewed and cleaned up. Various changes were done, like simple renaming (in order to have more meaningful fields, avoid duplicated names in types, etc.), improved model convenience (interface type-specific fields are now defined as `oneof`, preventing to set multiple or incorrect data) and other. All models were also moved to the common [api][models] folder. * [KVScheduler][kv-scheduler] - Added new component called KVScheduler, as a reaction to various flaws and issues with race conditions between Vpp/Linux plugins, poor readability and poorly readable logging. Also the system of notifications between plugins was unreliable and hard to debug or even understand. Based on this experience, a new framework offers improved generic mechanisms to handle dependencies between configuration items and creates clean and readable transaction-based logging. Since this component significantly changed the way how plugins are defined, we recommend to learn more about it on the [VPP-Agent wiki page][wiki]. * [orchestrator][orchestrator-plugin] - The orchestrator is a new component which long-term added value will be a support for multiple northbound data sources (KVDB, GRPC, ...). The current implementation handles combination of GRPC + KVDB, which includes data changes and resync. In the future, any combination of sources will be supported. * [GoVPPMux][govppmux-plugin] - Added `Ping()` method to the VPE vppcalls usable to test the VPP connection. * [if-plugin][vpp-interface-plugin] - UDP encapsulation can be configured to an IPSec tunnel interface - Support for new Bond-type interfaces. - Support for L2 tag rewrite (currently present in the interface plugin because of the inconsistent VPP API) * [nat-plugin][vpp-nat-plugin] - Added support for session affinity in NAT44 static mapping with load balancer. * [sr-plugin][sr-plugin] - Support for Dynamic segment routing proxy with L2 segment routing unaware services. - Added support for SRv6 end function End.DT4 and End.DT6. * [linux-if-plugin][linux-interface-plugin] - Added support for new Linux interface type - loopback. - Attempt to assign already existing IP address to the interface does not cause an error. * [linux-iptables][linux-iptables-plugin] - Added new linux IP tables plugin able to configure IP tables chain in the specified table, manage chain rules and set default chain policy. ### Improvements * [KVScheduler][kv-scheduler] - Performance improvements related to memory management. * [GoVPPMux][govppmux-plugin] - Need for config file was removed, GoVPP is now set with default values if the startup config is not provided. - `DefaultReplyTimeout` is now configured globally, instead of set for every request separately. - Tolerated default health check timeout is now set to 250ms (up from 100ms). The old value had not provide enough time in some cases. * [acl-plugin][vpp-acl-plugin] - Model moved to the [api/models][models] * [if-plugin][vpp-interface-plugin] - Model reviewed, updated and moved to the [api/models][models]. - Interface plugin now handles IPSec tunnel interfaces (previously done in IPSec plugin). - NAT related configuration was moved to its own plugin. - New interface stats (added in 1.8.1) use new GoVPP API, and publishing frequency was significantly decreased to handle creation of multiple interfaces in short period of time. * [IPSec-plugin][vpp-ipsec-plugin] - Model moved to the [api/models][models] - The IPSec interface is no longer processed by the IPSec plugin (moved to interface plugin). - The ipsec link in interface model now uses the enum definitions from IPSec model. Also some missing crypto algorithms were added. * [l2-plugin][vpp-l2-plugin] - Model moved to the [api/models][models] and split to three separate models for bridge domains, FIBs and cross connects. * [l3-plugin][vpp-l3-plugin] - Model moved to the [api/models][models] and split to three separate models for ARPs, Proxy ARPs including IP neighbor and Routes. * [nat-plugin][vpp-nat-plugin] - Defined new plugin to handle NAT-related configuration and its own [model][nat-proto] (before a part of interface plugin). * [punt-plugin][vpp-punt-plugin] - Model moved to the [api/models][models]. - Added retrieve support for punt socket. The current implementation is not final - plugin uses local cache (it will be enhanced when the appropriate VPP binary API call will be added). * [stn-plugin][vpp-stn-plugin] - Model moved to the [api/models][models]. * [linux-if-plugin][linux-interface-plugin] - Model reviewed, updated and moved to the [api/models][models]. * [linux-l3-plugin][linux-l3-plugin] - Model moved to the [api/models][models] and split to separate models for ARPs and Routes. - Linux routes and ARPs have a new dependency - the target interface is required to contain an IP address. * [ns-plugin][ns-plugin] - New auxiliary plugin to handle linux namespaces and microservices (evolved from ns-handler). Also defines [model][ns-proto] for generic linux namespace definition. ### Docker Images * Configuration file for GoVPP was removed, forcing to use default values (which are the same as they were in the file). * Fixes for installing ARM64 debugger. * Kafka is no longer required in order to run vpp-agent from the image. ### Documentation * Added documentation for the punt plugin, describing main features and usage of the punt plugin. * Added documentation for the [IPSec plugin][vpp-ipsec-plugin], describing main and usage of the IPSec plugin. * Added documentation for the [interface plugin][vpp-interface-plugin]. The document is only available on [wiki page][wiki]. * Description improved in various proto files. * Added a lot of new documentation for the KVScheduler (examples, troubleshooting, debugging guides, diagrams, ...) * Added tutorial for KV Scheduler. * Added many new documentation articles to the [wiki page][wiki]. However, most of is there only temporary since we are preparing new ligato.io website with all the documentation and other information about the Ligato project. Also majority of readme files from the vpp-agent repository will be removed in the future. <a name="v1.8.1"></a> # [1.8.1](https://github.com/ligato/vpp-agent/compare/v1.8..v1.8.1) (2019-03-04) Motive for this minor release was updated VPP with several fixed bugs from the previous version. The VPP version also introduced new interface statistics mechanism, thus the stats processing was updated in the interface plugin. ### Compatibility - v19.01-16~gd30202244 - cn-infra v1.7 - GO 1.11 ### Bug Fixes - VPP bug: fixed crash when attempting to run in kubernetes pod - VPP bug: fixed crash in barrier sync when vlib_worker_threads is zero ### Features - [vpp-ifplugin][vpp-interface-plugin] * Support for new VPP stats (the support for old ones were deprecated by the VPP, thus removed from the vpp-agent as well). <a name="v1.8.0"></a> # [1.8.0](https://github.com/ligato/vpp-agent/compare/v1.7...v1.8) (2018-12-12) ### Compatibility - VPP v19.01-rc0~394-g6b4a32de - cn-infra v1.7 - Go 1.11 ### Bug Fixes * Pre-existing VETH-type interfaces are now read from the default OS namespace during resync if the Linux interfaces were dumped. * The Linux interface dump method does not return an error if some interface namespace becomes suddenly unavailable at the read-time. Instead, this case is logged and all the other interfaces are returned as usual. * The Linux localclient's delete case for Linux interfaces now works properly. * The Linux interface dump now uses OS link name (instead of vpp-agent specific name) to read the interface attributes. This sometimes caused errors where an incorrect or even none interface was read. * Fixed bug where the unsuccessful namespace switch left the namespace file opened. * Fixed crash if the Linux plugin was disabled. * Fixed occasional crash in vpp-agent interface notifications. * Corrected interface counters for TX packets. * Access list with created TCP/UDP/ICMP rule, which remained as empty struct no longer causes vpp-agent to crash ### Features - [vpp-ifplugin][vpp-interface-plugin] * Rx-mode and Rx-placement now support dump via the respective binary API call - vpp-rpc-plugin * GRPC now supports also IPSec configuration. * All currently supported configuration items can be also dumped/read via GRPC (similar to rest) * GRPC now allows to automatically persist configuration to the data store. The desired DB has to be defined in the new GRPC config file (see [readme][readme] for additional information). - [vpp-punt][punt-model] * Added simple new punt plugin. The plugin allows to register/unregister punt to host via Unix domain socket. The new [model][punt-model] was added for this configuration type. Since the VPP API is incomplete, the configuration does not support dump. ### Improvements - [vpp-ifplugin][vpp-interface-plugin] * The VxLAN interface now support IPv4/IPv6 virtual routing and forwarding (VRF tables). * Support for new interface type: VmxNet3. The VmxNet3 virtual network adapter has no physical counterpart since it is optimized for performance in a virtual machine. Because built-in drivers for this card are not provided by default in the OS, the user must install VMware Tools. The interface model was updated for the VmxNet3 specific configuration. - [ipsec-plugin][vpp-ipsec-plugin] * IPSec resync processing for security policy databases (SPD) and security associations (SA) was improved. Data are properly read from northbound and southbound, compared and partially configured/removed, instead of complete cleanup and re-configuration. This does not appeal to IPSec tunnel interfaces. * IPSec tunnel can be now set as an unnumbered interface. - [rest-plugin][rest-plugin] * In case of error, the output returns correct error code with cause (parsed from JSON) instead of an empty body <a name="v1.7.0"></a> # [1.7.0](https://github.com/ligato/vpp-agent/compare/v1.6...v1.7) (2018-10-02) ### Compatibility - VPP 18.10-rc0~505-ge23edac - cn-infra v1.6 - Go 1.11 ### Bug Fixes * Corrected several cases where various errors were silently ignored * GRPC registration is now done in Init() phase, ensuring that it finishes before GRPC server is started * Removed occasional cases where Linux tap interface was not configured correctly * Fixed FIB configuration failures caused by wrong updating of the metadata after several modifications * No additional characters are added to NAT tag and can be now configured with the full length without index out of range errors * Linux interface resync registers all VETH-type interfaces, despite the peer is not known * Status publishing to ETCD/Consul now should work properly * Fixed occasional failure caused by concurrent map access inside Linux plugin interface configurator * VPP route dump now correctly recognizes route type ### Features - [vpp-ifplugin][vpp-interface-plugin] * It is now possible to dump unnumbered interface data * Rx-placement now uses specific binary API to configure instead of generic CLI API - [vpp-l2plugin][vpp-l2-plugin] * Bridge domain ARP termination table can now be dumped - [linux-ifplugin][linux-interface-plugin] * Linux interface watcher was reintroduced. * Linux interfaces can be now dumped. - [linux-l3plugin][linux-l3-plugin] * Linux ARP entries and routes can be dumped. ### Improvements - [vpp-plugins][vpp-plugins] * Improved error propagation in all the VPP plugins. Majority of errors now print the stack trace to the log output allowing better error tracing and debugging. * Stopwatch was removed from all vppcalls - [linux-plugins][linux-plugins] * Improved error propagation in all Linux plugins (same way as for VPP) * Stopwatch was removed from all linuxcalls - [govpp-plugn][govppmux-plugin] * Tracer (introduced in cn-infra 1.6) added to VPP message processing, replacing stopwatch. The measurement should be more precise and logged for all binary API calls. Also the rest plugin now allows showing traced entries. ### Docker Images * The image can now be built on ARM64 platform <a name="v1.6.0"></a> # [1.6.0](https://github.com/ligato/vpp-agent/compare/v1.5.2...v1.6) (2018-08-24) ### Compatibility - VPP 18.10-rc0~169-gb11f903a - cn-infra v1.5 ### BREAKING CHANGES - Flavors were replaced with new way of managing plugins. - REST interface URLs were changed, see [readme][readme] for complete list. ### Bug Fixes * if VPP routes are dumped, all paths are returned * NAT load-balanced static mappings should be resynced correctly * telemetry plugin now correctly parses parentheses for `show node counters` * telemetry plugin will not hide an error caused by value loading if the config file is not present * Linux plugin namespace handler now correctly handles namespace switching for interfaces with IPv6 addresses. Default IPv6 address (link local) will not be moved to the new namespace if there are no more IPv6 addresses configured within the interface. This should prevent failures in some cases where IPv6 is not enabled in the destination namespace. * VxLAN with non-zero VRF can be successfully removed * Lint is now working again * VPP route resync works correctly if next hop IP address is not defined ### Features * Deprecating flavors - CN-infra 1.5 brought new replacement for flavors and it would be a shame not to implement it in the vpp-agent. The old flavors package was removed and replaced with this new concept, visible in app package vpp-agent. - [rest plugin][rest-plugin] * All VPP configuration types are now supported to be dumped using REST. The output consists of two parts; data formatted as NB proto model, and metadata with VPP specific configuration (interface indexes, different counters, etc.). * REST prefix was changed. The new URL now contains API version and purpose (dump, put). The list of all URLs can be found in the [readme][readme] - [ifplugin][vpp-interface-plugin] * Added support for NAT virtual reassembly for both, IPv4 and IPv6. See change in [nat proto file][nat-proto] - [l3plugin][vpp-l3-plugin] * Vpp-agent now knows about DROP-type routes. They can be configured and also dumped. VPP default routes, which are DROP-type is recognized and registered. Currently, resync does not remove or correlate such a route type automatically, so no default routes are unintentionally removed. * New configurator for L3 IP scan neighbor was added, allowing to set/unset IP scan neigh parameters to the VPP. ### Improvements - [vpp plugins][vpp-plugins] * all vppcalls were unified under API defined for every configuration type (e.g. interfaces, l2, l3, ...). Configurators now use special handler object to access vppcalls. This should prevent duplicates and make vppcalls cleaner and more understandable. - [ifplugin][vpp-interface-plugin] * VPP interface DHCP configuration can now be dumped and added to resync processing * Interfaces and also L3 routes can be configured for non-zero VRF table if IPv6 is used. - [examples][examples] * All examples were reworked to use new flavors concept. The purpose was not changed. ### Docker Images - using Ubuntu 18.04 as the base image <a name="v1.5.2"></a> ## [1.5.2](https://github.com/ligato/vpp-agent/compare/v1.5.1...v1.5.2) (2018-07-23) ### Compatibility - VPP 18.07-rc0~358-ga5ee900 - cn-infra v1.4.1 (minor version fixes bug in Consul) ### Bug Fixes - [Telemetry][vpp-telemetry] * Fixed bug where lack of config file could cause continuous polling. The interval now also cannot be changed to a value less than 5 seconds. * Telemetry plugin is now closed properly <a name="v1.5.1"></a> ## 1.5.1 (2018-07-20) ### Compatibility - VPP 18.07-rc0~358-ga5ee900 - cn-infra v1.4 ### Features - [Telemetry][vpp-telemetry] * Default polling interval was raised to 30s. * Added option to use telemetry config file to change polling interval, or turn the polling off, disabling the telemetry plugin. The change was added due to several reports where often polling is suspicious of interrupting VPP worker threads and causing packet drops and/or other negative impacts. More information how to use the config file can be found in the [readme][readme]. <a name="v1.5.0"></a> # [1.5.0](https://github.com/ligato/vpp-agent/compare/v1.4.1...v1.5) (2018-07-16) ### Compatibility - VPP 18.07-rc0~358-ga5ee900 - cn-infra v1.4 ### BREAKING CHANGES - The package `etcdv3` was renamed to `etcd`, along with its flag and configuration file. - The package `defaultplugins` was renamed to `vpp` to make the purpose of the package clear ### Bug Fixes - Fixed a few issues with parsing VPP metrics from CLI for [Telemetry][vpp-telemetry]. - Fixed bug in GoVPP occurring after some request timed out, causing the channel to receive replies from the previous request and always returning an error. - Fixed issue which prevented setting interface to non-existing VRF. - Fixed bug where removal of an af-packet interface caused attached Veth to go DOWN. - Fixed NAT44 address pool resolution which was not correct in some cases. - Fixed bug with adding SR policies causing incomplete configuration. ### Features - [LinuxPlugin][linux-interface-plugin] * Is now optional and can be disabled via configuration file. - [ifplugin][vpp-interface-plugin] * Added support for VxLAN multicast * Rx-placement can be configured on VPP interfaces - [IPsec][vpp-ipsec-plugin] * IPsec UDP encapsulation can now be set (NAT traversal) ### Docker Images - Replace `START_AGENT` with `OMIT_AGENT` to match `RETAIN_SUPERVISOR` and keep both unset by default. - Refactored and cleaned up execute scripts and remove unused scripts. - Fixed some issues with `RETAIN_SUPERVISOR` option. - Location of supervisord pid file is now explicitly set to `/run/supervisord.pid` in *supervisord.conf* file. - The vpp-agent is now started with single flag `--config-dir=/opt/vpp-agent/dev`, and will automatically load all configuration from that directory. <a name="v1.4.1"></a> ## [1.4.1](https://github.com/ligato/vpp-agent/compare/v1.4.0...v1.4.1) (2018-06-11) A minor release using newer VPP v18.04 version. ### Compatibility - VPP v18.04 (2302d0d) - cn-infra v1.3 ### Bug Fixes - VPP submodule was removed from the project. It should prevent various problems with dependency resolution. - Fixed known bug present in the previous version of the VPP, issued as [VPP-1280][vpp-issue-1280]. Current version contains appropriate fix. <a name="v1.4.0"></a> # [1.4.0](https://github.com/ligato/vpp-agent/compare/v1.3...v1.4.0) (2018-05-24) ### Compatibility - VPP v18.04 (ac2b736) - cn-infra v1.3 ### Bug Fixes * Fixed case where the creation of the Linux route with unreachable gateway threw an error. The route is now appropriately cached and created when possible. * Fixed issue with GoVPP channels returning errors after a timeout. * Fixed various issues related to caching and resync in L2 cross-connect * Split horizon group is now correctly assigned if an interface is created after bridge domain * Fixed issue where the creation of FIB while the interface was not a part of the bridge domain returned an error. ### Known issues * VPP crash may occur if there is interface with non-default VRF (>0). There is an [VPP-1280][vpp-issue-1280] issue created with more details ### Features - [Consul][consul] * Consul is now supported as a key-value store alternative to ETCD. More information in the [readme][readme]. - [Telemetry][vpp-telemetry] * New plugin for collecting telemetry data about VPP metrics and serving them via HTTP server for Prometheus. More information in the [readme][readme]. - [Ipsecplugin][vpp-ipsec-plugin] * Now supports tunnel interface for encrypting all the data passing through that interface. - GRPC * Vpp-agent itself can act as a GRPC server (no need for external executable) * All configuration types are supported (incl. Linux interfaces, routes and ARP) * Client can read VPP notifications via vpp-agent. - [SR plugin][sr-plugin] * New plugin with support for Segment Routing. More information in the [readme][readme]. ### Improvements - [ifplugin][vpp-interface-plugin] * Added support for self-twice-NAT - __vpp-agent-grpc__ executable merged with [vpp-agent][vpp-agent] command. - [govppmux][govppmux-plugin] * `configure reply timeout` can be configured. * Support for VPP started with custom shared memory prefix. SHM may be configured via the GoVPP plugin config file. More info in the [readme][readme] * Overall redundancy cleanup and corrected naming for all proto models. * Added more unit tests for increased coverage and code stability. ### Documentation - [localclient_linux][examples-vpp-local] now contains two examples, the old one demonstrating basic plugin functionality was moved to plugin package, and specialised example for [NAT][examples-nat] was added. - [localclient_linux][examples-linux-local] now contains two examples, the old one demonstrating [veth][examples-veth] interface usage was moved to package and new example for linux [tap][examples-tap] was added. <a name="v1.3.0"></a> # [1.3.0](https://github.com/ligato/vpp-agent/compare/v1.2...v1.3) (2018-03-22) The vpp-agent is now using custom VPP branch [stable-1801-contiv][contiv-vpp1810]. ### Compatibility - VPP v18.01-rc0~605-g954d437 - cn-infra v1.2 ### Bug Fixes * Resync of ifplugin in both, VPP and Linux, was improved. Interfaces with the same configuration data are not recreated during resync. * STN does not fail if IP address with a mask is provided. * Fixed ingress/egress interface resolution in ACL. * Linux routes now check network reachability for gateway address before configuration. It should prevent "network unreachable" errors during config. * Corrected bridge domain crash in case non-bvi interface was added to another non-bvi interface. * Fixed several bugs related to VETH and AF-PACKET configuration and resync. ### Features - [ipsecplugin][vpp-ipsec-plugin]: * New plugin for IPSec added. The IPSec is supported for VPP only with Linux set manually for now. IKEv2 is not yet supported. More information in the [readme][readme]. - [nsplugin][linux-ns-plugin] * New namespace plugin added. The configurator handles common namespace and microservice processing and communication with other Linux plugins. - [ifplugin][vpp-interface-plugin] * Added support for Network address translation. NAT plugin supports a configuration of NAT44 interfaces, address pools and DNAT. More information in the [readme][readme]. * DHCP can now be configured for the interface - [l2plugin][vpp-l2-plugin] * Split-horizon group can be configured for bridge domain interface. - [l3plugin][vpp-l3-plugin] * Added support for proxy ARP. For more information and configuration example, please see [readme][readme]. - [linux ifplugin][linux-interface-plugin] * Support for automatic interface configuration (currently only TAP). ### Improvements - [aclplugin][agentctl] * Removed configuration order of interfaces. The access list can be now configured even if interfaces do not exist yet, and add them later. - vpp-agent-ctl * The vpp-agent-ctl was refactored and command info was updated. ### Docker Images * VPP can be built and run in the release or debug mode. Read more information in the [readme][readme]. * Production image is now smaller by roughly 40% (229MB). <a name="v1.2.0"></a> # [1.2.0](https://github.com/ligato/vpp-agent/compare/v1.1...v1.2) (2018-02-07) ### Compatibility - VPP v18.04-rc0~90-gd95c39e - cn-infra v1.1 ### Bug Fixes - Fixed interface assignment in ACLs - Fixed bridge domain BVI modification resolution - vpp-agent-grpc (removed in 1.4 release, since then it is a part of the vpp-agent) now compiles properly together with other commands. ### Known Issues - VPP can occasionally cause a deadlock during checksum calculation (https://jira.fd.io/browse/VPP-1134) - VPP-Agent might not properly handle initialization across plugins (this is not occurring currently, but needs to be tested more) ### Improvements - [aclplugin][vpp-acl-plugin] * Improved resync of ACL entries. Every new ACL entry is correctly configured in the VPP and all obsolete entries are read and removed. - [ifplugin][vpp-interface-plugin] * Improved resync of interfaces, BFD sessions, authentication keys, echo functions and STN. Better resolution of persistence config for interfaces. - [l2plugin][vpp-l2-plugin] * Improved resync of bridge domains, FIB entries, and xConnect pairs. Resync now better correlates configuration present on the VPP with the NB setup. - [linux-ifplugin][linux-interface-plugin] * ARP does not need the interface to be present on the VPP. Configuration is cached and put to the VPP if requirements are fulfilled. - Dependencies * Migrated from glide to dep ### Docker Images * VPP compilation now skips building of Java/C++ APIs, this saves build time and final image size. * Development image now runs VPP in debug mode with various debug options added in [VPP config file][vpp-conf-file]. <a name="v1.1.0"></a> # [1.1.0](https://github.com/ligato/vpp-agent/compare/v1.0.8...v1.1) (2018-01-22) ### Compatibility - VPP version v18.04-rc0~33-gb59bd65 - cn-infra v1.0.8 ### Bug Fixes - fixed skip-resync parameter if vpp-plugin.conf is not provided. - corrected af_packet type interface behavior if veth interface is created/removed. - several fixes related to the af_packet and veth interface type configuration. - microservice and veth-interface related events are synchronized. ### Known Issues - VPP can occasionally cause a deadlock during checksum calculation (https://jira.fd.io/browse/VPP-1134) - VPP-Agent might not properly handle initialization across plugins (this is not occurring currently, but needs to be tested more) ### Features - [ifplugin][vpp-interface-plugin] - added support for un-numbered interfaces. The nterface can be marked as un-numbered with information about another interface containing required IP address. A un-numbered interface does not need to have IP address set. - added support for virtio-based TAPv2 interfaces. - interface status is no longer stored in the ETCD by default and it can be turned on using the appropriate setting in vpp-plugin.conf. See [readme][readme] for more details. - [l2plugin][vpp-l2-plugin] - bridge domain status is no longer stored in the ETCD by default and it can be turned on using the appropriate setting in vpp-plugin.conf. See [readme][readme] for more details. ### Improvements - [ifplugin][vpp-interface-plugin] - default MTU value was removed in order to be able to just pass empty MTU field. MTU now can be set only in interface configuration (preferred) or defined in vpp-plugin.conf. If none of them is set, MTU value will be empty. - interface state data are stored in statuscheck readiness probe - [l3plugin][vpp-l3-plugin] - removed strict configuration order for VPP ARP entries and routes. Both ARP entry or route can be configured without interface already present. - l4plugin (removed in v2.0) - removed strict configuration order for application namespaces. Application namespace can be configured without interface already present. - localclient - added API for ARP entries, L4 features, Application namespaces, and STN rules. - logging - consolidated and improved logging in vpp and Linux plugins. <a name="v1.0.8"></a> ## [1.0.8](https://github.com/ligato/vpp-agent/compare/v1.0.7...v1.0.8) (2017-11-21) ### Compatibility - VPP v18.01-rc0-309-g70bfcaf - cn-infra v1.0.7 ### Features - [ifplugin][vpp-interface-plugin] - ability to configure STN rules. See respective [readme][readme] in interface plugin for more details. - rx-mode settings can be set on interface. Ethernet-type interface can be set to POLLING mode, other types of interfaces supports also INTERRUPT and ADAPTIVE. Fields to set QueueID/QueueIDValid are also available - added possibility to add interface to any VRF table. - added defaultplugins API. - API contains new Method `DisableResync(keyPrefix ...string)`. One or more ETCD key prefixes can be used as a parameter to disable resync for that specific key(s). - l4plugin (removed in v2.0) - added new l4 plugin to the VPP plugins. It can be used to enable/disable L4 features and configure application namespaces. See respective [readme][readme] in L4 plugin for more details. - support for VPP plugins/l3plugin ARP configuration. The configurator can perform the basic CRUD operation with ARP config. - resync - resync error propagation improved. If any resynced configuration fails, rest of the resync completes and will not be interrupted. All errors which appear during resync are logged after. - [linux l3plugin][linux-l3-plugin] - route configuration does not return an error if the required interface is missing. Instead, the route data are internally stored and configured when the interface appears. - GoVPP - delay flag removed from GoVPP plugin ### Improvements - removed dead links from README files ### Documentation - improved in multiple vpp-agent packages <a name="v1.0.7"></a> ## [1.0.7](https://github.com/ligato/vpp-agent/compare/v1.0.6...v1.0.7) (2017-10-30) ### Compatibility - VPP version v18.01-rc0~154-gfc1c612 - cn-infra v1.0.6 ### Features - [Default VPP plugin][vpp-interface-plugin] - added resync strategies. Resync of VPP plugins can be set using defaultpluigns config file; Resync can be set to full (always resync everything) or dependent on VPP configuration (if there is none, skip resync). Resync can be also forced to skip using the parameter. - [Linuxplugins L3Plugin][linux-l3-plugin] - added support for basic CRUD operations with the static Address resolution protocol entries and static Routes. <a name="v1.0.6"></a> ## [1.0.6](https://github.com/ligato/vpp-agent/compare/v1.0.5...v1.0.6) (2017-10-17) ### Compatibility - cn-infra v1.0.5 ### Features - [LinuxPlugin][linux-interface-plugin] - The configuration of vEth interfaces modified. Veth configuration defines two names: symbolic used internally and the one used in host OS. `HostIfName` field is optional. If it is not defined, the name in the host OS will be the same as the symbolic one - defined by `Name` field. <a name="v1.0.5"></a> ## [1.0.5](https://github.com/ligato/vpp-agent/compare/v1.0.4...v1.0.5) (2017-09-26) ### Compatibility - VPP version v17.10-rc0~334-gce41a5c - cn-infra v1.0.4 ### Features - [GoVppMux][govppmux-plugin] - configuration file for govpp added - Kafka Partitions - Changes in offset handling, only automatically partitioned messages (hash, random) have their offset marked. Manually partitioned messages are not marked. - Implemented post-init consumer (for manual partitioner only) which allows starting consuming after kafka-plugin Init() - Minimalistic examples & documentation for Kafka API will be improved in a later release. <a name="v1.0.4"></a> ## [1.0.4](https://github.com/ligato/vpp-agent/compare/v1.0.3...v1.0.4) (2017-09-08) ### Features - Kafka Partitions - Implemented new methods that allow to specify partitions & offset parameters: * publish: Mux.NewSyncPublisherToPartition() & Mux.NewAsyncPublisherToPartition() * watch: ProtoWatcher.WatchPartition() - Minimalistic examples & documentation for Kafka API will be improved in a later release. - Flavors - reduced to only local.FlavorVppLocal & vpp.Flavor - GoVPP - updated version waits until the VPP is ready to accept a new connection <a name="v1.0.3"></a> ## [1.0.3](https://github.com/ligato/vpp-agent/compare/v1.0.2...v1.0.3) (2017-09-05) ### Compatibility - VPP version v17.10-rc0~265-g809bc74 (upgraded because of VPP MEMIF fixes) ### Features Enabled support for wathing data store `OfDifferentAgent()` - see: * examples/idx_iface_cache (removed in v2.0) * examples/examples/idx_bd_cache (removed in v2.0) * examples/idx_veth_cache (removed in v2.0) Preview of new Kafka client API methods that allows to fill also partition and offset argument. New methods implementation ignores these new parameters for now (fallback to existing implementation based on `github.com/bsm/sarama-cluster` and `github.com/Shopify/sarama`). <a name="v1.0.2"></a> ## [1.0.2](https://github.com/ligato/vpp-agent/compare/v1.0.1...v1.0.2) (2017-08-28) ### Compatibility - VPP version v17.10-rc0~203 ### Known Issues A rarely occurring problem during startup with binary API connectivity. VPP rejects binary API connectivity when VPP Agent tries to connect too early (plan fix this behavior in next release). ### Features Algorithms for applying northbound configuration (stored in ETCD key-value data store) to VPP in the proper order of VPP binary API calls implemented in [Default VPP plugin][vpp-interface-plugin]: - network interfaces, especially: - MEMIFs (optimized data plane network interface tailored for a container to container network connectivity) - VETHs (standard Linux Virtual Ethernet network interface) - AF_Packets (for accessing VETHs and similar type of interface) - VXLANs, Physical Network Interfaces, loopbacks ... - L2 BD & X-Connects - L3 IP Routes & VRFs - ACL (Access Control List) Support for Linux VETH northbound configuration implemented in [Linux Plugin][linux-interface-plugin] applied in proper order with VPP AF_Packet configuration. Data Synchronization during startup for network interfaces & L2 BD (support for the situation when ETCD contain configuration before VPP Agent starts). Data replication and events: - Updating operational data in ETCD (VPP indexes such as sw_if_index) and statistics (port counters). - Updating statistics in Redis (optional once redis.conf available - see flags). - Publishing links up/down events to Kafka message bus. - [Examples][examples] - Tools: - [agentctl CLI tool][agentctl] that show state & configuration of VPP agents - [docker][docker]: container-based development environment for the VPP agent - other features inherited from cn-infra: - health: status check & k8s HTTP/REST probes - logging: changing log level at runtime - Ability to extend the behavior of the VPP Agent by creating new plugins on top of VPP Agent flavor (removed with CN-Infra v1.5). New plugins can access API for configured: - VPP Network interfaces, - Bridge domains and VETHs based on [idxvpp][idx-vpp] threadsafe map tailored for VPP data with advanced features (multiple watchers, secondary indexes). - VPP Agent is embeddable in different software projects and with different systems by using Local Flavor (removed with CN-Infra v1.5) to reuse VPP Agent algorithms. For doing this there is VPP Agent client version 1 (removed in v2.0): - local client - for embedded VPP Agent (communication inside one operating system process, VPP Agent effectively used as a library) - remote client - for remote configuration of VPP Agent (while integrating for example with control plane) [agentctl]: cmd/agentctl [ansible]: ansible [configurator-plugin]: plugins/configurator [consul]: https://www.consul.io/ [contiv-vpp1810]: https://github.com/vpp-dev/vpp/tree/stable-1801-contiv [docker]: docker [examples]: examples [examples-linux-local]: examples/localclient_linux [examples-nat]: examples/localclient_vpp/nat [examples-tap]: examples/localclient_linux/tap [examples-veth]: examples/localclient_linux/veth [examples-vpp-local]: examples/localclient_vpp [govppmux-plugin]: plugins/govppmux [govppmux-conf]: plugins/govppmux/govpp.conf [idx-vpp]: pkg/idxvpp [kv-scheduler]: plugins/kvscheduler [ligato.io]: https://ligato.io/ [ligato-docs]: https://docs.ligato.io/en/latest/ [linux-interface-plugin]: plugins/linux/ifplugin [linux-iptables-plugin]: plugins/linux/iptablesplugin [linux-l3-plugin]: plugins/linux/l3plugin [linux-ns-plugin]: plugins/linux/nsplugin [linux-plugins]: plugins/linux [nat-proto]: api/models/vpp/nat/nat.proto [netalloc-plugin]: plugins/netalloc [netalloc-plugin-model]: api/models/netalloc/netalloc.proto [ns-plugin]: plugins/linux/nsplugin [ns-proto]: api/models/linux/namespace/namespace.proto [models]: api/models [orchestrator-plugin]: plugins/orchestrator [punt-model]: api/models/vpp/punt/punt.proto [readme]: README.md [rest-plugin]: plugins/restapi [span-model]: api/models/vpp/interfaces/span.proto [sr-plugin]: plugins/vpp/srplugin [vpp-abf-plugin]: plugins/vpp/abfplugin [vpp-acl-plugin]: plugins/vpp/aclplugin [vpp-agent]: cmd/vpp-agent [vpp-conf-file]: docker/dev/vpp.conf [vpp-interface-plugin]: plugins/vpp/ifplugin [vpp-issue-1280]: https://jira.fd.io/browse/VPP-1280 [vpp-ipsec-plugin]: plugins/vpp/ipsecplugin [vpp-l2-plugin]: plugins/vpp/l2plugin [vpp-l3-plugin]: plugins/vpp/l3plugin [vpp-nat-plugin]: plugins/vpp/natplugin [vpp-plugins]: plugins/vpp [vpp-punt-plugin]: plugins/vpp/puntplugin [vpp-stn-plugin]: plugins/vpp/stnplugin [vpp-telemetry]: plugins/telemetry [wiki]: https://github.com/ligato/vpp-agent/wiki
Java
<?php require 'common.php'; require Sc::$rootDir.'/driver/file.php'; class Test{ static public $d = NULL; static public function testAdd(){ if(empty(self::$d)){ self::$d = new Sc_Driver_File(); } self::$d->add(array( 'hash'=>'hash1', 'node'=>'192.168.1.1', 'fhash'=>'hashfile1' )); self::$d->add(array( 'hash'=>'hash1', 'node'=>'192.168.1.2', 'fhash'=>'hashfile2' )); } static public function testGet(){ if(empty(self::$d)){ self::$d = new Sc_Driver_File(); } var_dump(self::$d->get('hash1')); } static public function testDel(){ if(empty(self::$d)){ self::$d = new Sc_Driver_File(); } var_dump(self::$d->delete('82341a6c6f03e3af261a95ba81050c0a')); } } //$a = 1/0; Test::testDel();
Java
package debop4s.data.orm.hibernate.repository import com.mysema.query.jpa.hibernate._ import com.mysema.query.types.EntityPath import debop4s.data.orm.ReadOnlyConnection import debop4s.data.orm.model.HConnectPageImpl import org.hibernate.{LockOptions, Session, SessionFactory} import org.slf4j.LoggerFactory import org.springframework.data.domain.PageRequest import scala.annotation.varargs import scala.util.control.NonFatal /** * HibernateQueryDslDao * @author debop created at 2014. 5. 20. */ class HibernateQueryDslDao(val sessionFactory: SessionFactory) { private lazy val log = LoggerFactory.getLogger(getClass) private def session: Session = sessionFactory.getCurrentSession private def sessionStateless = sessionFactory.openStatelessSession() def getQuery: HibernateQuery = new HibernateQuery(session) def from(path: EntityPath[_]): HibernateQuery = getQuery.from(path) @varargs def from(paths: EntityPath[_]*): HibernateQuery = getQuery.from(paths: _*) def deleteFrom(path: EntityPath[_]): HibernateDeleteClause = new HibernateDeleteClause(session, path) def updateFrom(path: EntityPath[_]): HibernateUpdateClause = new HibernateUpdateClause(session, path) def deleteStateless(path: EntityPath[_])(action: HibernateDeleteClause => Unit): Long = { try { val stateless = sessionFactory.openStatelessSession() val deleteClause = new HibernateDeleteClause(stateless, path) action(deleteClause) deleteClause.execute() } catch { case NonFatal(e) => log.error(s"삭제 작업 시 예외가 발생했습니다.", e) -1L } } def updateStateless(path: EntityPath[_])(action: HibernateUpdateClause => Unit): Long = { try { val stateless = sessionFactory.openStatelessSession() val updateStateless = new HibernateUpdateClause(stateless, path) action(updateStateless) updateStateless.execute() } catch { case NonFatal(e) => log.error(s"삭제 작업 시 예외가 발생했습니다.", e) -1L } } @ReadOnlyConnection def load[T](clazz: Class[T], id: java.io.Serializable): T = session.load(clazz, id).asInstanceOf[T] @ReadOnlyConnection def load[T](clazz: Class[T], id: java.io.Serializable, lockOptions: LockOptions) = session.load(clazz, id, lockOptions) @ReadOnlyConnection def get[T](clazz: Class[T], id: java.io.Serializable) = session.get(clazz, id) @ReadOnlyConnection def get[T](clazz: Class[T], id: java.io.Serializable, lockOptions: LockOptions) = session.get(clazz, id, lockOptions) @ReadOnlyConnection def findAll[T](path: EntityPath[T]) = getQuery.from(path).list(path) @ReadOnlyConnection def findAll[T](path: EntityPath[T], query: HibernateQuery, offset: Int, limit: Int) = query.offset(offset).limit(limit).list(path) @ReadOnlyConnection def getPage[T](path: EntityPath[T], query: HibernateQuery, pageNo: Int, pageSize: Int) = { val total = query.count() val offset = (pageNo - 1) * pageSize val limit = pageSize val items = findAll(path, query, offset, limit) new HConnectPageImpl(items, new PageRequest(pageNo, pageSize), total) } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package jp.eisbahn.oauth2.server.spi.servlet; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.junit.Test; public class HttpServletRequestAdapterTest { @Test public void test() { HttpServletRequest request = createMock(HttpServletRequest.class); expect(request.getParameter("name1")).andReturn("value1"); expect(request.getHeader("name2")).andReturn("value2"); @SuppressWarnings("serial") Map<String, String[]> map = new HashMap<String, String[]>() { { put("k1", new String[]{"v1"}); put("k2", new String[]{"v2"}); } }; expect(request.getParameterMap()).andReturn(map); replay(request); HttpServletRequestAdapter target = new HttpServletRequestAdapter(request); assertEquals("value1", target.getParameter("name1")); assertEquals("value2", target.getHeader("name2")); Map<String, String[]> parameterMap = target.getParameterMap(); assertEquals(2, parameterMap.size()); assertEquals("v1", parameterMap.get("k1")[0]); assertEquals("v2", parameterMap.get("k2")[0]); verify(request); } }
Java
/** * Autogenerated by Thrift Compiler (0.10.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package lizard.api.TLZ; @SuppressWarnings("all") @javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2018-06-17") public class TLZ_Patch implements org.apache.thrift.TBase<TLZ_Patch, TLZ_Patch._Fields>, java.io.Serializable, Cloneable, Comparable<TLZ_Patch> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TLZ_Patch"); private static final org.apache.thrift.protocol.TField ENTITIES_FIELD_DESC = new org.apache.thrift.protocol.TField("entities", org.apache.thrift.protocol.TType.LIST, (short)1); private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new TLZ_PatchStandardSchemeFactory(); private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new TLZ_PatchTupleSchemeFactory(); public java.util.List<TLZ_PatchEntry> entities; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ENTITIES((short)1, "entities"); private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>(); static { for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // ENTITIES return ENTITIES; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(java.lang.String name) { return byName.get(name); } private final short _thriftId; private final java.lang.String _fieldName; _Fields(short thriftId, java.lang.String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public java.lang.String getFieldName() { return _fieldName; } } // isset id assignments public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ENTITIES, new org.apache.thrift.meta_data.FieldMetaData("entities", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TLZ_PatchEntry.class)))); metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TLZ_Patch.class, metaDataMap); } public TLZ_Patch() { } public TLZ_Patch( java.util.List<TLZ_PatchEntry> entities) { this(); this.entities = entities; } /** * Performs a deep copy on <i>other</i>. */ public TLZ_Patch(TLZ_Patch other) { if (other.isSetEntities()) { java.util.List<TLZ_PatchEntry> __this__entities = new java.util.ArrayList<TLZ_PatchEntry>(other.entities.size()); for (TLZ_PatchEntry other_element : other.entities) { __this__entities.add(new TLZ_PatchEntry(other_element)); } this.entities = __this__entities; } } public TLZ_Patch deepCopy() { return new TLZ_Patch(this); } @Override public void clear() { this.entities = null; } public int getEntitiesSize() { return (this.entities == null) ? 0 : this.entities.size(); } public java.util.Iterator<TLZ_PatchEntry> getEntitiesIterator() { return (this.entities == null) ? null : this.entities.iterator(); } public void addToEntities(TLZ_PatchEntry elem) { if (this.entities == null) { this.entities = new java.util.ArrayList<TLZ_PatchEntry>(); } this.entities.add(elem); } public java.util.List<TLZ_PatchEntry> getEntities() { return this.entities; } public TLZ_Patch setEntities(java.util.List<TLZ_PatchEntry> entities) { this.entities = entities; return this; } public void unsetEntities() { this.entities = null; } /** Returns true if field entities is set (has been assigned a value) and false otherwise */ public boolean isSetEntities() { return this.entities != null; } public void setEntitiesIsSet(boolean value) { if (!value) { this.entities = null; } } public void setFieldValue(_Fields field, java.lang.Object value) { switch (field) { case ENTITIES: if (value == null) { unsetEntities(); } else { setEntities((java.util.List<TLZ_PatchEntry>)value); } break; } } public java.lang.Object getFieldValue(_Fields field) { switch (field) { case ENTITIES: return getEntities(); } throw new java.lang.IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new java.lang.IllegalArgumentException(); } switch (field) { case ENTITIES: return isSetEntities(); } throw new java.lang.IllegalStateException(); } @Override public boolean equals(java.lang.Object that) { if (that == null) return false; if (that instanceof TLZ_Patch) return this.equals((TLZ_Patch)that); return false; } public boolean equals(TLZ_Patch that) { if (that == null) return false; if (this == that) return true; boolean this_present_entities = true && this.isSetEntities(); boolean that_present_entities = true && that.isSetEntities(); if (this_present_entities || that_present_entities) { if (!(this_present_entities && that_present_entities)) return false; if (!this.entities.equals(that.entities)) return false; } return true; } @Override public int hashCode() { int hashCode = 1; hashCode = hashCode * 8191 + ((isSetEntities()) ? 131071 : 524287); if (isSetEntities()) hashCode = hashCode * 8191 + entities.hashCode(); return hashCode; } @Override public int compareTo(TLZ_Patch other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = java.lang.Boolean.valueOf(isSetEntities()).compareTo(other.isSetEntities()); if (lastComparison != 0) { return lastComparison; } if (isSetEntities()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.entities, other.entities); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { scheme(iprot).read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { scheme(oprot).write(oprot, this); } @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("TLZ_Patch("); boolean first = true; sb.append("entities:"); if (this.entities == null) { sb.append("null"); } else { sb.append(this.entities); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields if (entities == null) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'entities' was not present! Struct: " + toString()); } // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class TLZ_PatchStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public TLZ_PatchStandardScheme getScheme() { return new TLZ_PatchStandardScheme(); } } private static class TLZ_PatchStandardScheme extends org.apache.thrift.scheme.StandardScheme<TLZ_Patch> { public void read(org.apache.thrift.protocol.TProtocol iprot, TLZ_Patch struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // ENTITIES if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list8 = iprot.readListBegin(); struct.entities = new java.util.ArrayList<TLZ_PatchEntry>(_list8.size); TLZ_PatchEntry _elem9; for (int _i10 = 0; _i10 < _list8.size; ++_i10) { _elem9 = new TLZ_PatchEntry(); _elem9.read(iprot); struct.entities.add(_elem9); } iprot.readListEnd(); } struct.setEntitiesIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, TLZ_Patch struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.entities != null) { oprot.writeFieldBegin(ENTITIES_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.entities.size())); for (TLZ_PatchEntry _iter11 : struct.entities) { _iter11.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class TLZ_PatchTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public TLZ_PatchTupleScheme getScheme() { return new TLZ_PatchTupleScheme(); } } private static class TLZ_PatchTupleScheme extends org.apache.thrift.scheme.TupleScheme<TLZ_Patch> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, TLZ_Patch struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; { oprot.writeI32(struct.entities.size()); for (TLZ_PatchEntry _iter12 : struct.entities) { _iter12.write(oprot); } } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, TLZ_Patch struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; { org.apache.thrift.protocol.TList _list13 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.entities = new java.util.ArrayList<TLZ_PatchEntry>(_list13.size); TLZ_PatchEntry _elem14; for (int _i15 = 0; _i15 < _list13.size; ++_i15) { _elem14 = new TLZ_PatchEntry(); _elem14.read(iprot); struct.entities.add(_elem14); } } struct.setEntitiesIsSet(true); } } private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) { return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); } }
Java
/* * Copyright 2013 Gunnar Kappei. * * 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 net.opengis.gml; /** * An XML MultiSurfaceType(@http://www.opengis.net/gml). * * This is a complex type. */ public interface MultiSurfaceType extends net.opengis.gml.AbstractGeometricAggregateType { public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(MultiSurfaceType.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s6E28D279B6C224D74769DB8B98AF1665").resolveHandle("multisurfacetypeb44dtype"); /** * Gets a List of "surfaceMember" elements */ java.util.List<net.opengis.gml.SurfacePropertyType> getSurfaceMemberList(); /** * Gets array of all "surfaceMember" elements * @deprecated */ @Deprecated net.opengis.gml.SurfacePropertyType[] getSurfaceMemberArray(); /** * Gets ith "surfaceMember" element */ net.opengis.gml.SurfacePropertyType getSurfaceMemberArray(int i); /** * Returns number of "surfaceMember" element */ int sizeOfSurfaceMemberArray(); /** * Sets array of all "surfaceMember" element */ void setSurfaceMemberArray(net.opengis.gml.SurfacePropertyType[] surfaceMemberArray); /** * Sets ith "surfaceMember" element */ void setSurfaceMemberArray(int i, net.opengis.gml.SurfacePropertyType surfaceMember); /** * Inserts and returns a new empty value (as xml) as the ith "surfaceMember" element */ net.opengis.gml.SurfacePropertyType insertNewSurfaceMember(int i); /** * Appends and returns a new empty value (as xml) as the last "surfaceMember" element */ net.opengis.gml.SurfacePropertyType addNewSurfaceMember(); /** * Removes the ith "surfaceMember" element */ void removeSurfaceMember(int i); /** * Gets the "surfaceMembers" element */ net.opengis.gml.SurfaceArrayPropertyType getSurfaceMembers(); /** * True if has "surfaceMembers" element */ boolean isSetSurfaceMembers(); /** * Sets the "surfaceMembers" element */ void setSurfaceMembers(net.opengis.gml.SurfaceArrayPropertyType surfaceMembers); /** * Appends and returns a new empty "surfaceMembers" element */ net.opengis.gml.SurfaceArrayPropertyType addNewSurfaceMembers(); /** * Unsets the "surfaceMembers" element */ void unsetSurfaceMembers(); /** * A factory class with static methods for creating instances * of this type. */ public static final class Factory { public static net.opengis.gml.MultiSurfaceType newInstance() { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); } public static net.opengis.gml.MultiSurfaceType newInstance(org.apache.xmlbeans.XmlOptions options) { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); } /** @param xmlAsString the string value to parse */ public static net.opengis.gml.MultiSurfaceType parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); } public static net.opengis.gml.MultiSurfaceType parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); } /** @param file the file from which to load an xml document */ public static net.opengis.gml.MultiSurfaceType parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); } public static net.opengis.gml.MultiSurfaceType parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); } public static net.opengis.gml.MultiSurfaceType parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); } public static net.opengis.gml.MultiSurfaceType parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); } public static net.opengis.gml.MultiSurfaceType parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); } public static net.opengis.gml.MultiSurfaceType parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); } public static net.opengis.gml.MultiSurfaceType parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); } public static net.opengis.gml.MultiSurfaceType parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); } public static net.opengis.gml.MultiSurfaceType parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); } public static net.opengis.gml.MultiSurfaceType parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); } public static net.opengis.gml.MultiSurfaceType parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); } public static net.opengis.gml.MultiSurfaceType parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ @Deprecated public static net.opengis.gml.MultiSurfaceType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ @Deprecated public static net.opengis.gml.MultiSurfaceType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ @Deprecated public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ @Deprecated public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } private Factory() { } // No instance of this class allowed } }
Java
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.redshift.model.transform; import org.w3c.dom.Node; import javax.annotation.Generated; import com.amazonaws.AmazonServiceException; import com.amazonaws.transform.StandardErrorUnmarshaller; import com.amazonaws.services.redshift.model.AuthenticationProfileNotFoundException; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AuthenticationProfileNotFoundExceptionUnmarshaller extends StandardErrorUnmarshaller { public AuthenticationProfileNotFoundExceptionUnmarshaller() { super(AuthenticationProfileNotFoundException.class); } @Override public AmazonServiceException unmarshall(Node node) throws Exception { // Bail out if this isn't the right error code that this // marshaller understands String errorCode = parseErrorCode(node); if (errorCode == null || !errorCode.equals("AuthenticationProfileNotFoundFault")) return null; AuthenticationProfileNotFoundException e = (AuthenticationProfileNotFoundException) super.unmarshall(node); return e; } }
Java
package ru.job4j.pro.collections.list; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * NodeListTest class. * * @author Vladimir Ivanov * @version 0.1 * @since 30.08.2017 */ public class NodeListTest { /** * Test list is not cycled. */ @Test public void whenListIsNotCycledThenGetFalse() { Node<Integer> first = new Node<>(1); Node<Integer> two = new Node<>(2); Node<Integer> third = new Node<>(3); Node<Integer> four = new Node<>(4); Node<Integer> five = new Node<>(5); first.next = two; two.next = third; third.next = four; four.next = five; NodeList<Integer> list = new NodeList<>(first); boolean result = list.hasCycle(); assertThat(result, is(false)); } /** * Test list is cycled. */ @Test public void whenListIsCycledThenGetTrue() { Node<Integer> first = new Node<>(1); Node<Integer> two = new Node<>(2); Node<Integer> third = new Node<>(3); Node<Integer> four = new Node<>(4); first.next = two; two.next = third; third.next = four; four.next = first; NodeList<Integer> list = new NodeList<>(first); boolean result = list.hasCycle(); assertThat(result, is(true)); } /** * Test list is cycled. */ @Test public void whenBigListIsCycledThenGetTrue() { Node<Integer> node = new Node<>(0); Node<Integer> cycleFrom = null; Node<Integer> cycleTo = null; NodeList<Integer> list = new NodeList<>(node); for (int value = 1; value < 10000000; value++) { node.next = new Node<>(value); node = node.next; if (value == 900000) { cycleTo = node; } else if (value == 9990000) { cycleFrom = node; } } cycleFrom.next = cycleTo; boolean result = list.hasCycle(); assertThat(result, is(true)); } }
Java
# Amomum macrospermum Sm. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
'use strict'; /** * @ngdoc function * @name lubriApp.controller:MembersCtrl * @description * # MembersCtrl * Controller of the lubriApp */ angular.module('lubriApp') .config(function($stateProvider) { $stateProvider.state('app.members', { abstract: true, url: '/members', templateUrl: 'views/members/main.html', controller: 'MembersCtrl' }) .state('app.members.list', { url: '', templateUrl: 'views/members/list.html', controller: 'MembersCtrl' }) .state('app.members.add', { url: '/add', templateUrl: 'views/members/form.html', controller: 'MembersCtrl' }) .state('app.members.import', { url: '/import', templateUrl: 'views/members/import.html', controller: 'MembersCtrl' }) .state('app.members.edit', { url: '/:id/edit', templateUrl: 'views/members/form.html', controller: 'MembersCtrl' }) .state('app.members.view', { url: '/:id', templateUrl: 'views/members/view.html', controller: 'MembersCtrl' }); }) .controller('MembersCtrl', function($scope, $state, $stateParams, $q, $interval, toasty, Member, SweetAlert, i18nService) { var memberId = $stateParams.id; i18nService.setCurrentLang('zh-cn'); $scope.importData = []; $scope.gridImportOptions = { enableGridMenu: true, importerDataAddCallback: function( grid, newObjects ) { $scope.importData = $scope.importData.concat( newObjects ); }, onRegisterApi: function(gridApi){ $scope.gridImportApi = gridApi; gridApi.rowEdit.on.saveRow($scope, $scope.saveRow); }, data: 'importData' }; $scope.saveRow = function( rowEntity ) { // create a fake promise - normally you'd use the promise returned by $http or $resource var promise = $q.defer(); $scope.gridImportApi.rowEdit.setSavePromise( $scope.gridImportApi.grid, rowEntity, promise.promise ); $interval( function() { promise.resolve(); }, 1000, 1); }; $scope.saveImport = function () { if ($scope.importData.length > 0) { var members = $scope.importData; for (var i=0;i<members.length;i++) { var member = members[i]; member.created = new Date(); delete member.$$hashKey; Member.upsert(member, function() { }, function(err) { console.log(err); }); }; toasty.pop.success({title: '组员导入成功', msg: members.length + '个组员成功导入到系统中!', sound: false}); loadItems(); $state.go('^.list'); }; }; if (memberId) { $scope.member = Member.findById({ id: memberId }, function() {}, function(err) { console.log(err); }); } else { $scope.member = {}; } $scope.gridOptions = { data: 'members', enableFiltering: true, paginationPageSizes: [5, 10, 15], paginationPageSize: 10, headerRowHeight: 39, rowHeight: 39, columnFooterHeight: 39, gridFooterHeight: 39, selectionRowHeaderWidth: 39, columnDefs: [ { name: 'Edit', width: 80, displayName: '编辑', enableSorting: false, enableFiltering: false, cellTemplate: '<a href="" class="ui-state-hover" ui-sref="^.edit({id: row.entity.id})"> <i class="fa fa-pencil fa-lg blue"></i></a> <a href="" class="ui-state-hover" style="margin-left:5px;" ng-click="getExternalScopes().delete({id: row.entity.id})"><i class="fa fa-trash-o fa-lg red"></i></a>' }, { name: 'name', displayName: '全称', cellTemplate: '<div class="ui-grid-cell-contents"><a href="" ui-sref="^.view({id: row.entity.id})"> {{ COL_FIELD }} </a></div>'} ,{ name: 'firstName', displayName: '姓' } ,{ name: 'lastName', displayName: '名' } ,{ name: 'displayName', displayName: '显示名' } ,{ name: 'position', displayName: '职位' } , { name: 'priority', displayName: '排序号' } ], enableGridMenu: true, enableSelectAll: true, exporterCsvFilename: 'members.csv', exporterSuppressColumns: ['Edit'], exporterPdfDefaultStyle: {fontSize: 9}, exporterPdfTableStyle: {margin: [30, 30, 30, 30]}, exporterPdfTableHeaderStyle: {fontSize: 10, bold: true, italics: true, color: 'red'}, exporterPdfHeader: { text: "Meeting Member Information", style: 'headerStyle' }, exporterPdfFooter: function ( currentPage, pageCount ) { return { text: currentPage.toString() + ' of ' + pageCount.toString(), style: 'footerStyle' }; }, exporterPdfCustomFormatter: function ( docDefinition ) { docDefinition.styles.headerStyle = { fontSize: 22, bold: true }; docDefinition.styles.footerStyle = { fontSize: 10, bold: true }; return docDefinition; }, exporterPdfOrientation: 'portrait', exporterPdfPageSize: 'LETTER', exporterPdfMaxGridWidth: 500, exporterCsvLinkElement: angular.element(document.querySelectorAll(".custom-csv-link-location")) }; $scope.gridOptions.onRegisterApi = function (gridApi) { $scope.gridApi = gridApi; }; function loadItems() { $scope.members = Member.find(); } loadItems(); $scope.viewActions = { delete : $scope.delete }; $scope.delete = function(id) { SweetAlert.swal({ title: '您确定要删除吗?', type: 'warning', showCancelButton: true, confirmButtonColor: '#DD6B55' }, function(isConfirm){ if (isConfirm) { Member.deleteById(id, function() { toasty.pop.success({title: '组员被删除', msg: '您成功删除了组员!', sound: false}); loadItems(); $state.go($state.current, {}, {reload: true}); //$state.go('app.members.list'); }, function(err) { toasty.pop.error({title: '删除组员出错', msg: '删除组员发生错误:' + err, sound: false}); }); } else { return false; } }); }; $scope.formFields = [{ key: 'name', type: 'text', label: '全名', required: true }, { key: 'firstName', type: 'text', label: '姓', required: true }, { key: 'lastName', type: 'text', label: '名', required: true }, { key: 'displayName', type: 'text', label: '显示名', required: true }, { key: 'position', type: 'text', label: '职位', required: true }, { key: 'priority', type: 'number', label: '排序号', required: true }]; $scope.formOptions = { uniqueFormId: true, hideSubmit: false, submitCopy: '保存' }; $scope.onSubmit = function() { if (($scope.member.created === null) || ($scope.member.created === undefined)){ $scope.member.created = new Date(); }; Member.upsert($scope.member, function() { toasty.pop.success({title: '组员保存成功', msg: '组员已成功保存到系统中!', sound: false}); loadItems(); $state.go('^.list'); }, function(err) { console.log(err); }); }; });
Java
package com.intel.media.mts.dao.impl; import org.junit.Assert; import org.junit.Test; import com.intel.media.mts.dao.DaoTestSupport; import com.intel.media.mts.model.Software; public class SoftwareDaoImplTest extends DaoTestSupport { @Test public void test(){ Software s = new Software(); String name = "Ubuntu"; String desc = "OS type 12.04"; s.setName(name); s.setDescription(desc); softwareDao.doSave(s); System.out.println(s); Software s2 = softwareDao.findById(s.getId()); Assert.assertEquals(name, s2.getName()); Assert.assertEquals(desc, s2.getDescription()); } }
Java
# Pennisetum aureum Link SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
package com.thinkgem.jeesite.modules.purifier.dao; import com.thinkgem.jeesite.common.persistence.CrudDao; import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao; import com.thinkgem.jeesite.modules.purifier.entity.Ware; /** * 仓库管理dao * * @author addison * @since 2017年03月02日 */ @MyBatisDao public interface WareDao extends CrudDao<Ware> { int deleteByWare(Ware ware); }
Java
<form class="form-horizontal" role="form" name="form" ng-show="model" ng-submit="onFormSubmit()"> <div class="form-custom-alerts"> <alert ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</alert> </div> <div ng-form ng-repeat="field in fields" name="innerForm" ng-if="!field.hidden"> <div class="form-group" ng-class="{'has-feedback has-success': isSuccess(innerForm), 'has-feedback has-error': isError(innerForm)}"> <label class="col-sm-2 control-label">{{field.describe}}</label> <div class="col-sm-4" ng-switch="field.type"> <div class="checkbox" ng-switch-when='checkbox'> <label> <input type="checkbox" name="input" ng-model="model[field.name]"> {{field.checkBoxMessage != null ? field.checkBoxMessage : field.describe}} </label> </div> <div class="radio" ng-switch-when='radio'> <div class="radio" ng-repeat='option in field.options'> <label> <input type="radio" name="input" value="{{option.value}}" ng-model="model[field.name]" ng-required="true"> {{option.text}} </label> </div> </div> <div ng-switch-when='select'> <select class="form-control" name="input" ng-model="model[field.name]" ng-options="option.value as option.name for option in field.options" ng-required="field.required == null ? true : field.required"></select> </div> <div ng-switch-default> <input type="{{field.type || 'text'}}" class="form-control" placeholder="{{field.placeholder || ''}}" ng-disabled="!!field.disabled" ng-model="model[field.name]" name="input" ui-validate="validators" ng-required="field.required == null ? true : field.required" ng-pattern="patternForField(field)"> <span class="glyphicon glyphicon-ok form-control-feedback" ng-show="isSuccess(innerForm)"></span> <span class="glyphicon glyphicon-remove form-control-feedback" ng-show="isError(innerForm)"></span> </div> </div> <div class="help-block col-sm-6" ng-show='!hideError || attempted || innerForm.input.$dirty'> <p ng-show="innerForm.input.$error.required">{{field.describe}}不能为空!</p> <p ng-show="innerForm.input.$error.pattern">{{field.describe}}格式错误!</p> <p ng-show="innerForm.input.$error.minLength">{{field.describe}}最少需要{{field.minLength}}个字符!</p> <p ng-show="innerForm.input.$error.maxLength">{{field.describe}}的长度不能少于{{field.maxLength}}个字符!</p> <p ng-show="innerForm.input.$error.custom"> <span ng-show="!!field.validateMessage">{{field.validateMessage}}</span> <span ng-show="!field.validateMessage">{{field.describe}}填写有误!</span> </p> </div> </div> <div ng-if="field.type == 'password' && field.needConfirm == true" class="form-group" ng-class="{'has-feedback has-success': isSuccess(innerForm, 'confirm'), 'has-feedback has-error': isError(innerForm, 'confirm')}"> <label class="col-sm-2 control-label">确认密码</label> <div class="col-sm-4"> <input type="password" class="form-control" ng-model="extraModel[field.name]" name="confirm" ng-required="field.required == null || field.required || !!model[fieldname]" ui-validate="{passwordMatch: '$value==model[field.name]'}" ui-validate-watch=" 'model[field.name]' "> <span class="glyphicon glyphicon-ok form-control-feedback" ng-show="isSuccess(innerForm, 'confirm')"></span> <span class="glyphicon glyphicon-remove form-control-feedback" ng-show="isError(innerForm, 'confirm')"></span> </div> <div class="help-block col-sm-6" ng-show='!hideError || attempted || innerForm.confirm.$dirty'> <span ng-show="innerForm.confirm.$error.required">确认密码不能为空!</span> <span ng-show="!innerForm.confirm.$error.required && innerForm.confirm.$error.passwordMatch">两次密码输入不一致!</span> </div> </div> </div> <div class="form-group" ng-if="submitButton != 'none'"> <div class="col-sm-offset-2 col-sm-8"> <button type="submit" class="btn btn-primary">{{submitButton || '保存修改'}}</button> </div> </div> <div ng-transclude></div> </form>
Java
# Hyophila tortula (Schwaegr.) Hampe SPECIES #### Status SYNONYM #### According to Integrated Taxonomic Information System #### Published in null #### Original name null ### Remarks null
Java
# Artemisia glauca var. cernua (Nutt.) Bush VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Peperomia acuminata f. acuminata FORM #### Status ACCEPTED #### According to NUB Generator [autonym] #### Published in null #### Original name null ### Remarks null
Java
# Coburgia multiflora (W.T.Aiton) Herb. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Leucanthemum vulgare subsp. silvaticum (Brot.) Nyman SUBSPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java